text stringlengths 1 1.05M |
|---|
#!/bin/bash
python test_wiki_facts.py
|
var _tensor_test_8cpp =
[
[ "BOOST_AUTO_TEST_CASE", "_tensor_test_8cpp.xhtml#aa08fb9adf6eaf05fd4a3698880c1c292", null ],
[ "BOOST_AUTO_TEST_CASE", "_tensor_test_8cpp.xhtml#a67f451b173e1cea17e907085cb967184", null ],
[ "BOOST_AUTO_TEST_CASE", "_tensor_test_8cpp.xhtml#a60cf24873ff60e391417efc873e9c55e", null ],
[ "BOOST_AUTO_TEST_CASE", "_tensor_test_8cpp.xhtml#ad842127d839c39ea39e3c0f3ac219728", null ],
[ "BOOST_FIXTURE_TEST_CASE", "_tensor_test_8cpp.xhtml#ab7e46ed88187c63506b21f45abbabb13", null ],
[ "BOOST_FIXTURE_TEST_CASE", "_tensor_test_8cpp.xhtml#a37f7ffb280c544fe70e212e24fc5c2a7", null ],
[ "BOOST_FIXTURE_TEST_CASE", "_tensor_test_8cpp.xhtml#a3370241e4a543440e79a3d1842fe6f9f", null ],
[ "BOOST_FIXTURE_TEST_CASE", "_tensor_test_8cpp.xhtml#a8ff9749fd66d314c3c2bbef1eca00f09", null ],
[ "BOOST_FIXTURE_TEST_CASE", "_tensor_test_8cpp.xhtml#aa2d0d8c3d827fec2b96ff3ae2389550e", null ],
[ "BOOST_FIXTURE_TEST_CASE", "_tensor_test_8cpp.xhtml#a0c4119e76379387b984dbbbf998f2925", null ],
[ "boost_test_print_type", "_tensor_test_8cpp.xhtml#abe311824d11bad4e6f93c8f94a721052", null ],
[ "boost_test_print_type", "_tensor_test_8cpp.xhtml#af676ec7e9534bd6e6ac3072a2c0403f4", null ],
[ "CheckTensor", "_tensor_test_8cpp.xhtml#ad80e179ec400af9d2547f172f3ca05f3", null ]
]; |
package com.freud.db.derby;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import org.springframework.web.bind.annotation.RequestParam;
public class Test {
public static void main(@RequestParam("AA") String[] args) throws Exception {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection conn = DriverManager.getConnection("jdbc:derby:zk_admin;create=true");
try {
conn.prepareStatement("DROP TABLE ZK_INSTANCE").execute();
conn.prepareStatement(
"CREATE TABLE ZK_INSTANCE("
+ " ID INTEGER NOT NULL GENERATED BY DEFAULT AS IDENTITY (START WITH 0, INCREMENT BY 1),"
+ " NAME VARCHAR(128) NOT NULL," + " IP VARCHAR(15) NOT NULL," + " USE INT,"
+ " OPERATE_DATE TIMESTAMP," + " CONSTRAINT PK_T_ZK_INSTANCE PRIMARY KEY (ID)" + ")")
.execute();
} catch (Exception e) {
// e.printStackTrace();
System.out.println(1 + "--");
}
try {
conn.prepareStatement(
"INSERT INTO ZK_INSTANCE(NAME,IP,USE,OPERATE_DATE) VALUES('10.1.5.123','10.1.5.123',1,CURRENT_TIMESTAMP)")
.execute();
} catch (Exception e) {
// e.printStackTrace();
System.out.println(2 + "--");
}
try {
ResultSet rs = conn.prepareStatement("select * from ZK_INSTANCE").executeQuery();
rs.next();
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
System.out.println(rs.getInt(4));
System.out.println(rs.getTimestamp(5));
} catch (Exception e) {
// e.printStackTrace();
System.out.println(3 + "--");
}
conn.commit();
conn.close();
}
} |
// Backend code
const express = require('express');
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
const server = express();
const port = 8000;
// Parse requests with JSON
server.use(bodyParser.json());
// Connect to MongoDB
const mongoURL = 'mongodb://localhost:27017';
const dbName = 'itemlist';
MongoClient.connect(mongoURL, (err, client) => {
if(err)
console.log('Error connecting to MongoDB');
const db = client.db(dbName);
// Create a collection called 'items'
db.createCollection('items', (err, result) => {
if (err)
console.log('Error creating collection');
});
// Get all items
server.get('/items', (req, res) => {
db.collection('items').find({}).toArray((err, result) => {
if (err)
console.log('Error retrieving items');
res.send(result);
});
});
// Add a new item
server.post('/items', (req, res) => {
const item = req.body;
db.collection('items').insertOne(item, (err, result) => {
if (err)
console.log('Error inserting item');
res.send({message: 'Inserted item successfully'});
});
});
server.listen(port, () => {
console.log('Server listening on port ' + port);
});
});
// Frontend code
import React, {useState, useEffect} from 'react';
import axios from 'axios';
const App = () => {
const [items, setItems] = useState([]);
const getItems = async () => {
try {
const res = await axios.get('/items');
setItems(res.data);
} catch (error) {
console.log('Error retrieving items');
}
};
const addItem = async item => {
try {
const res = await axios.post('/items', item);
console.log(res.data.message);
getItems();
} catch (error) {
console.log('Error inserting item');
}
};
useEffect(() => {
getItems();
}, []);
return (
<div>
<h1>Item List</h1>
<ul>
{items.map(item => (
<li key={item._id}>{item.name}</li>
))}
</ul>
<form onSubmit={e => {
e.preventDefault();
addItem({name: e.target.item.value});
e.target.item.value = '';
}}>
<input type='text' name='item' />
<button type='submit'>Add Item</button>
</form>
</div>
);
};
export default App; |
<reponame>jinjuan-li/iot-suite-server
package com.tuya.iot.suite.web.Interceptor;
import com.alibaba.fastjson.JSON;
import com.tuya.iot.suite.core.constant.ErrorCode;
import com.tuya.iot.suite.core.constant.Response;
import com.tuya.iot.suite.core.model.UserToken;
import com.tuya.iot.suite.core.util.ContextUtil;
import com.tuya.iot.suite.web.i18n.I18nMessage;
import com.tuya.iot.suite.web.util.SessionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 登陆拦截器
*/
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
@Autowired
private I18nMessage i18nMessage;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
log.info("preHandle {}...", request.getRequestURI());
//获取session
HttpSession session = request.getSession(false);
if (session != null) {
UserToken token = SessionContext.getUserToken();
//判断session中是否有用户数据,如果有,则返回true,继续向下执行
if (token != null) {
ContextUtil.setUserToken(token);
return true;
}
}
response.setCharacterEncoding("UTF-8");
response.getWriter().write(JSON.toJSONString(Response.buildFailure(ErrorCode.NO_LOGIN.getCode(),
i18nMessage.getMessage(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg()))));
return false;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
ModelAndView modelAndView) throws Exception {
log.debug("postHandle {}.", httpServletRequest.getRequestURI());
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)
throws Exception {
log.debug("afterCompletion {}: exception = {}", httpServletRequest.getRequestURI(), e);
}
public LoginInterceptor(I18nMessage i18nMessage) {
this.i18nMessage = i18nMessage;
}
}
|
<reponame>SynthSys/BioDare2-BACK
/*
* 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 ed.biodare2.backend.security.dao.db;
import ed.biodare2.Fixtures;
import ed.biodare2.SimpleRepoTestConfig;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
//import org.springframework.transaction.annotation.Transactional;
/**
*
* @author tzielins
*/
@RunWith(SpringRunner.class)
@DataJpaTest
@Import({SimpleRepoTestConfig.class})
public class EntityACLTest {
//@MockBean // neede cause main apps needs it and JPA profile does not set it
//Jackson2ObjectMapperBuilder builder;
@Autowired
Fixtures fixtures;
//@Autowired
//UserAccountRep users;
//@Autowired
//UserGroupRep groups;
//@Autowired //@PersistenceContext
//TestEntityManager EM;
//@PersistenceContext
//EntityManager EM;
@Autowired
TestEntityManager testEM;
//@PersistenceUnit
//EntityManagerFactory EMF;
public EntityACLTest() {
}
@Test
//@Transactional
public void aclCanBeSaved() {
EntityACL acl = new EntityACL();
acl.setOwner(fixtures.user1);
acl.setSuperOwner(fixtures.user1.getSupervisor());
acl.getAllowedToRead().addAll(fixtures.user1.getDefaultToRead());
acl.getAllowedToWrite().add(fixtures.otherGroup);
//EM.persist(acl);
//EM.flush();
EntityACL s = testEM.persistFlushFind(acl);
assertNotNull(s);
assertTrue(true);
}
}
|
<filename>src/main/java/com/stylefeng/guns/modular/manage/service/IDispatchingService.java<gh_stars>0
package com.stylefeng.guns.modular.manage.service;
import com.stylefeng.guns.modular.manage.transfer.DispDto;
/**
* 配送管理Service
*
* @author nxj
* @Date 2018-01-30 09:04:41
*/
public interface IDispatchingService {
/**
* 添加配送
* @param dispDto
*/
void add(DispDto dispDto);
}
|
<reponame>Zhangoufei/NotePractice<gh_stars>100-1000
// 雪花特效
(function () {
var style = document.createElement("style");
style.innerText = "body .snow{position: fixed;color: #fff;line-height: 1;text-shadow: 0 0 .2em #ffffff;z-index: 2;}";
document.getElementsByTagName("head")[0].appendChild(style);
var dpr = ~~document.documentElement.getAttribute("data-dpr") || 1;
var wWidth = window.innerWidth;
var wHeight = window.innerHeight;
var maxNum = wWidth / 50;
var snowArr = [];
function createSnow(r) {
var size = Math.random() + .8;
var left = wWidth * Math.random();
var speed = (Math.random() * .5 + .6) * size * dpr;
var snow = document.createElement("div");
snow.innerText = "❅";
snow.className = "snow";
var text = "";
text += "font-size:";
text += size;
text += "em;left:";
text += left;
text += "px;bottom:100%;";
snow.style.cssText = text;
document.body.appendChild(snow);
var top = r ? wHeight * Math.random() : (-snow.offsetHeight);
snow.style.top = top + "px";
snow.style.bottom = "auto";
return {
snow: snow,
speed: speed,
top: top
}
}
function draw() {
for (var i = 0; i < maxNum; i++) {
if (!snowArr[i]) {
if (typeof snowArr[i] == "undefined") {
snowArr[i] = createSnow(true);
} else {
snowArr[i] = createSnow();
}
}
var data = snowArr[i];
data.top += data.speed;
data.snow.style.top = data.top + "px";
if (data.top > wHeight) {
document.body.removeChild(data.snow);
snowArr[i] = null;
}
}
requestAnimationFrame(draw);
}
draw();
})();
|
/*
Author: <NAME>
*/
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
AsyncStorage,
TouchableHighlight,
Image,
} from 'react-native';
import { Actions } from 'react-native-router-flux'
import {queryAll, deleteSurvey, queryAllSubscribers, deleteSubscriber} from '../databases/schemas'
import realm from '../databases/schemas'
export default class Side extends Component<{}> {
constructor (props) {
super (props)
this.state = {
translated:'',
surveys:[],
subscribers:[],
}
}
componentWillMount () {
this.checkInternet()
this.loadData()
}
loadData () {
queryAll().then((surveys)=>{
this.setState({surveys})
}).catch((error)=> {
alert(error)
})
}
async checkInternet () {
var status = await AsyncStorage.getItem('status')
if (status === 'true') {
this.setState({upload:true})
}
}
async uploadSurveys () {
try {
this.state.surveys.forEach(async (survey)=> {
let response = await fetch('https://afridash.com/enque/saveToMysql.php',{
method:'POST',
headers:{
'Accept': 'application/json',
},
body: JSON.stringify(survey)
});
let responseJson = await response.json();
if(responseJson.success === '1'){
deleteSurvey(survey.id).then().catch((error)=>{
alert(error)
})
}
})
}catch(error) {
alert(error)
}
this.uploadSubscribers()
}
async uploadSubscribers () {
this.state.subscribers.forEach( async (subscriber) => {
let response = await fetch('https://afridash.com/enque/saveSubscriber.php',{
method:'POST',
headers:{
'Accept': 'application/json',
},
body: JSON.stringify(subscriber)
});
let responseJson = await response.json();
if(responseJson.success === '1'){
deleteSubscriber(subscriber.id).then().catch((error)=>{
alert(error)
})
}
})
}
render() {
return (
<View style={styles.container}>
<View style={styles.sdg}>
<TouchableHighlight onPress={()=>Actions.replace('sustainable')} style={{flex:1.5, alignItems:'center', justifyContent:'center'}}>
<View style={{flex:1, flexDirection:'row', alignItems:'center', justifyContent:'center'}}>
<Image source={require('../assets/images/sus.png')} resizeMode={'contain'} style={styles.sdgImage} />
</View>
</TouchableHighlight>
</View>
<TouchableHighlight onPress={()=>Actions.replace('entryMethod')} style={styles.category}>
<Text style={styles.text}>Home</Text>
</TouchableHighlight>
<TouchableHighlight onPress={()=>Actions.replace('dashboard')} style={styles.category}>
<Text style={styles.text}>Surveys</Text>
</TouchableHighlight>
<TouchableHighlight onPress={()=>Actions.replace('myworld')} style={styles.category}>
<Text style={styles.text}>My World 2030</Text>
</TouchableHighlight>
<TouchableHighlight style={styles.category} onPress={()=>Actions.replace('login')}>
<Text style={styles.text}>Change Partner Id</Text>
</TouchableHighlight>
{this.state.upload &&
<TouchableHighlight onPress={()=>this.uploadSurveys()} style={styles.upload}>
<Text style={styles.uploadButton}>Upload Surveys</Text>
</TouchableHighlight>}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
sdg: {
flex:1,
borderColor:'#15354e',
borderTopWidth:25,
borderBottomWidth:1,
},
sdgImage:{
height:100,
flex:1,
},
text: {
fontSize:20,
flex:1,
fontWeight:'400',
},
category: {
flexDirection:'row',
borderColor:'#15354e',
padding:15,
borderBottomWidth: (Platform.OS === 'ios') ? 1 : 0.5,
},
enque: {
flex:1,
backgroundColor:'purple'
},
upload: {
flex:2,
flexDirection:'row',
justifyContent:'center',
alignItems:'flex-end'
},
uploadButton: {
backgroundColor:'#1eaaf1',
color:'white',
fontSize:20,
marginBottom:1,
alignItems:'center',
justifyContent:'center',
flex:1,
padding:10,
textAlign:'center',
height:50,
},
});
|
import random
def generate_random_nums(n,min_val,max_val):
output = []
for i in range(n):
output.append(random.randint(min_val,max_val))
return output
if __name__ == '__main__':
n = 10
min_val = 1
max_val = 100
print(generate_random_nums(n,min_val,max_val)) |
import React from 'react';
import SEO from '../components/SEO';
import Header from "../partials/header/Header";
import WelCome from '../container/Welcome/Welcome';
import Footer from '../container/Footer/Footer';
import ScrollToTop from '../components/ScrollToTop.jsx';
const Welcome = () => {
return (
<React.Fragment>
<SEO title="Exomac || Welcome" />
<Header />
<WelCome/>
<Footer />
<ScrollToTop />
</React.Fragment>
)
}
export default Welcome;
|
import scipy.signal as signal
from concurrent.futures import ProcessPoolExecutor
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from torch.distributions import Categorical
import cy_heuristics as cy_heu
import sched
INPUT_SIZE = 10
N_WORKERS = 8
executor = ProcessPoolExecutor(max_workers = N_WORKERS)
def get_return(rewards, discount=1.0):
r = rewards[::-1]
a = [1, -discount]
b = [1]
y = signal.lfilter(b, a, x=r)
return y[::-1]
def wrap(x):
(i, j), y = x
rets = []
for x in y:
_sample, num_proc, order, use_deadline = x
score, rews = cy_heu.test_RTA_LC(_sample, num_proc, order, use_deadline=use_deadline, ret_score=2)
if score < 0:
score = 0
rets.append(get_return(rews) + score)
return (i, j), rets
def wrap_np(x):
(i, j), y = x
rets = []
for x in y:
_sample, num_proc, order, use_deadline = x
score , ret = cy_heu.test_Lee(_sample, num_proc, order, use_deadline=use_deadline, ret_score=2)
rets.append(get_return(ret) + score)
return (i, j), rets
class LinearSolver (nn.Module):
def __init__(self, num_proc, seq_len, use_deadline=False,
use_cuda=True, hidden_size=256):
super(LinearSolver, self).__init__()
self.num_proc = num_proc
self.seq_len = seq_len
self.use_deadline = use_deadline
self.use_cuda = use_cuda
self.layer = nn.Linear(10, 1)
nn.init.uniform_(self.layer.weight, 0, 1)
if self.use_deadline:
print("EXPLICIT MODE")
else:
print("IMPLICIT MODE")
def input_transform(self, inputs):
"""
Args:¡
inputs: [batch_size, seq_len, 3]
"""
if self.use_deadline is False: # implicit
inputs[:, :, 2] = inputs[:, :, 0]
inputs = inputs.float()
div = torch.stack([
(inputs[:, :, 1] / inputs[:, :, 0]), # Utilization
(inputs[:, :, 2] / inputs[:, :, 0]),
(inputs[:, :, 0] - inputs[:, :, 1]) / 1000,
(inputs[:, :, 0] - inputs[:, :, 2]) / 1000,
torch.log(inputs[:, :, 0]) / np.log(2), # Log
torch.log(inputs[:, :, 1] / np.log(2)),
torch.log(inputs[:, :, 2] / np.log(2)),
], dim=-1)
tt = (inputs / 1000)
ret = torch.cat([div, tt], dim=-1).type(torch.FloatTensor)
if self.use_cuda:
ret = ret.cuda()
return ret
def forward(self, inputs, normalize=False):
"""
Args:
inputs : [batch_size, seq_len, 3] : Before the transformation.
Returns:
score : [batch_size, seq_len]
"""
batch_size, seq_len, _ = inputs.shape
inputs_tr = self.input_transform(inputs)
score = self.layer(inputs_tr).squeeze()
if normalize:
score = torch.log(torch.softmax(score, dim=-1))
# print(score)
return score
return score
def ranknet_loss(self, inputs, labels):
"""
:param inputs: [batch_size, seq_len, 3]
:param labels: [batch_size, seq_len]
"""
scores = self.forward(inputs)
pred_mtx, label_mtx = self.convert_to_matrix(scores, labels)
pred_mtx = F.sigmoid(pred_mtx)
loss = torch.sum(-label_mtx * torch.log(pred_mtx) - (1 - label_mtx) * torch.log(1 - pred_mtx))
return loss
def convert_to_matrix(self, scores, labels):
"""
:param scores: [batch_size, seq_len]
:param labels: [batch_size, seq_len]
"""
batch_size, seq_len = scores.size()
scores = nn.functional.normalize(scores, dim=1)
score_ret = torch.zeros((batch_size, seq_len, seq_len))
label_ret = torch.zeros((batch_size, seq_len, seq_len))
# scores /= 10000
for i in range(seq_len):
for j in range(seq_len):
score_ret[:, i, j] = scores[:, i] - scores[:, j]
label_ret[:, i, j] = labels[:, i] > labels[:, j]
return score_ret, label_ret
def listnet_loss(self, inputs, labels, phi="softmax"):
"""
:param inputs: [batch_size, seq_len, 3]
:param labels: [batch_size, seq_len]
"""
scores = self.forward(inputs) # [batch_size x seq_len]
labels = labels.float()
if phi == "softmax":
pred = torch.softmax(scores, -1) # [batch_size x seq_len]
target = torch.softmax(labels, -1)
elif phi == "log":
pred = torch.log(scores, -1) / torch.sum(torch.log(scores, -1))
target = torch.log(labels, -1) / torch.sum(torch.log(labels, -1))
elif phi.startswith("id"):
pred = scores / torch.sum(scores, -1)
target = labels / torch.sum(labels)
else:
raise LookupError("WHAT INCREASING FUNCTION YOU NEED")
# pred, target : [batch_size x seq_len]
loss = -torch.sum(target * torch.log(pred))
return loss
class LinearActor(nn.Module):
def __init__(self, input_dim, use_cuda=True):
super(LinearActor, self).__init__()
self.use_cuda = use_cuda
self.layer = nn.Linear(input_dim, 1)
def forward(self, inputs, argmax=False, guide=None):
"""
Args:
inputs : [batch_size x seq_len x input_dim]
"""
batch_size = inputs.shape[0]
seq_len = inputs.shape[1]
prev_chosen_indices = []
prev_chosen_logprobs = []
mask = torch.zeros(batch_size, seq_len, dtype = torch.bool)
for index in range(seq_len):
prob = self.pointer(inputs, mask)
cat = Categorical(prob)
if argmax:
_, chosen = torch.max(prob, -1)
elif guide is not None:
chosen = guide[:, index]
else:
chosen = cat.sample()
logprobs = cat.log_prob(chosen)
prev_chosen_logprobs.append(logprobs)
prev_chosen_indices.append(chosen)
mask[[i for i in range(batch_size)], chosen] = True
return torch.stack(prev_chosen_logprobs, 1), torch.stack(prev_chosen_indices, 1)
def pointer(self, inputs, mask):
"""
Args:
mask : [batch_size x seq_len]
"""
score = self.layer(inputs).squeeze()
score[mask] = -1e8
score = torch.softmax(score, dim=-1)
return score
class LinearRLSolver(nn.Module):
def __init__(self, num_proc,
use_deadline = False,
use_cuda = True):
super(LinearRLSolver, self).__init__()
self.num_proc = num_proc
self.use_deadline = use_deadline
self.use_cuda = use_cuda
print("use_deadline", self.use_deadline)
print("is_cuda", self.use_cuda)
self.actor = LinearActor(input_dim=10, use_cuda=use_cuda)
def reward(self, sample, chosen):
"""
Args:
sample_solution seq_len of [batch_size]
torch.LongTensor [batch_size x seq_len x INPUT_SIZE]
"""
batch_size, seq_len, _ = sample.size()
rewardarr = torch.FloatTensor(batch_size, seq_len)
tmp = np.arange(batch_size)
order = np.zeros_like(chosen)
for i in range(seq_len):
order[tmp, chosen[:, i]] = seq_len - i - 1
_sample = sample.cpu()
_samples = [(sample, self.num_proc, _order, self.use_deadline) for (sample, _order) in
zip(_sample.numpy(), order)]
tmps = []
step = (batch_size // N_WORKERS) + 1
chunks = []
for i in range(0, batch_size, step):
chunks.append(((i, min(i + step, batch_size)), _samples[i:min(i + step, batch_size)]))
for ((i, j), ret) in executor.map(wrap, chunks):
for q, _ in enumerate(range(i, j)):
rewardarr[_, :] = torch.from_numpy(ret[q])
if self.use_cuda:
rewardarr = rewardarr.cuda()
return rewardarr
def input_transform(self, inputs):
if self.use_deadline is False:
inputs[:, :, 2] = inputs[:, :, 0]
inputs = inputs.float()
div = torch.stack([
(inputs[:, :, 1] / inputs[:, :, 0]), # Utilization
(inputs[:, :, 2] / inputs[:, :, 0]),
(inputs[:, :, 0] - inputs[:, :, 1]) / 1000,
(inputs[:, :, 0] - inputs[:, :, 2]) / 1000,
torch.log(inputs[:, :, 0]) / np.log(2), # Log
torch.log(inputs[:, :, 1] / np.log(2)),
torch.log(inputs[:, :, 2] / np.log(2)),
], dim=-1)
tt = (inputs / 1000)
ret = torch.cat([div, tt], dim=-1).type(torch.FloatTensor)
if self.use_cuda:
ret = ret.cuda()
return ret
def forward(self, inputs, argmax=False, get_reward=True, guide=None):
"""
Args:
inputs: [batch_size, seq_len, 3] (T, C, D)
"""
batch_size, seq_len, _ = inputs.shape
_inputs = self.input_transform(inputs)
probs, actions = self.actor(_inputs, argmax, guide=guide)
if get_reward:
R = self.reward(inputs, actions.cpu().numpy())
return R, probs, actions
else:
return probs, actions
def sample_gumbel(score, sampling_number=5, eps=1e-10):
"""
Args:
score : [batch x num_tasks]
"""
tmax, _ = torch.max(score, dim=-1)
tmin, _ = torch.min(score, dim=-1)
score = score / (tmax - tmin).unsqueeze(1)
score = score * score.size(1)
batch_size = score.size(0)
num_tasks = score.size(1)
U = torch.rand([batch_size, sampling_number, num_tasks])
return score.unsqueeze(1) - torch.log(-torch.log(U + eps) + eps)
def get_rank(score):
"""
Args:
score: [batch_size x num_gumbel_sample x num_tasks]
"""
num_tasks = score.size(2)
arg = torch.argsort(-score, dim=-1).numpy() # [batch_size x num_gumbel_sample x num_tasks]
ret = np.zeros_like(arg)
for i in range(ret.shape[0]):
for j in range(ret.shape[1]):
for k in range(ret.shape[2]):
ret[i][j][arg[i, j, k]] = num_tasks - k - 1
return ret
|
#!/bin/sh
# Remove golangci-lint
DOT_DIR="${HOME}/wsl-dotfiles"
CACHE_DIR="${HOME}/.cache"
. "${DOT_DIR}/etc/lib/sh/has.sh"
if has "golangci-lint"; then
echo "Remove golangci-lint ..."
rm -f "${CACHE_DIR}/mygo/bin/golangci-lint"
else
echo "golangci-lint is already removed"
fi
|
package io.github.cottonmc.epicurean.block;
import net.fabricmc.fabric.api.block.FabricBlockSettings;
import net.fabricmc.fabric.api.container.ContainerProviderRegistry;
import net.fabricmc.fabric.api.tools.FabricToolTags;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Material;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.sound.BlockSoundGroup;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class CookingTableBlock extends Block {
public CookingTableBlock() {
super(FabricBlockSettings.of(Material.WOOD)
.breakByTool(FabricToolTags.PICKAXES)
.sounds(BlockSoundGroup.STONE)
.strength(2.0f, 6.0f)
.build());
}
@Override
public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {
if (world.isClient) return ActionResult.SUCCESS;
ContainerProviderRegistry.INSTANCE.openContainer(EpicureanBlocks.COOKING_CONTAINER, player, buf -> {
buf.writeBlockPos(pos);
});
// player.increaseStat(new Identifier(EpicureanGastronomy.MOD_ID, "open_cooking_table"));
return ActionResult.SUCCESS;
}
}
|
#!/bin/sh
# This is a generated file; do not edit or check into version control.
export "FLUTTER_ROOT=/Users/albertm/Development/SDK/flutter"
export "FLUTTER_APPLICATION_PATH=/Users/albertm/Development/Projects/flutter_course/dicee-flutter"
export "FLUTTER_TARGET=lib/main.dart"
export "FLUTTER_BUILD_DIR=build"
export "SYMROOT=${SOURCE_ROOT}/../build/ios"
export "FLUTTER_FRAMEWORK_DIR=/Users/albertm/Development/SDK/flutter/bin/cache/artifacts/engine/ios"
export "FLUTTER_BUILD_NAME=1.0.0"
export "FLUTTER_BUILD_NUMBER=1"
|
<reponame>yenbekbay/anvilabs-scripts
const {hasAnyDep} = require('anvilabs-scripts-core/utils');
module.exports = {
presets: [
[
'env',
{
targets: {
node: '8.8.0',
},
},
],
],
plugins: [
hasAnyDep(['lodash', 'ramda'])
? ['lodash', {id: ['lodash', 'ramda']}]
: null,
[
'module-resolver',
{
alias: {
src: './src',
},
extensions: ['.js', '.ts', '.json'],
},
],
].filter(plugin => !!plugin),
};
|
#!/bin/bash
# Function to list all available chaincodes
listChaincodes() {
# Add code to list all available chaincodes
echo "Available chaincodes: chaincode1, chaincode2, chaincode3"
}
# Verify the specified chaincode
verifyChaincode() {
chaincode=$1
version=$2
channel=$3
cli=$4
peer=$5
# Add code to verify the chaincode on the specified channel using the designated CLI and peer
# For demonstration purposes, assume the verification process here
verificationResult="success" # Replace with actual verification logic
if [ "$verificationResult" = "success" ]; then
echo "✅ success: Chaincode $chaincode/$version verified on $channel/$cli/$peer"
else
echo "❌ failed: Failed to verify chaincode $chaincode/$version on $channel/$cli/$peer"
listChaincodes
exit 1
fi
}
# Main script
verifyChaincode "$1" "$2" "$3" "$4" "$5" |
from flask import Flask
import requests
app = Flask(__name__)
@app.route('/currency/<string:iso_code>', methods=['GET'])
def get_currency(iso_code):
url = 'http://data.fixer.io/api/latest?access_key={key}&base={base}'
currency_data = requests.get(url.format(key='yourkey', base=iso_code)).json()
return currency_data
if __name__ == '__main__':
app.run(debug=True) |
package com.acmvit.acm_app.pref;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.acmvit.acm_app.model.AuthToken;
import com.acmvit.acm_app.model.User;
import com.google.gson.Gson;
public class SessionManager {
private static final String TAG = "SessionManager";
private final Gson gson = new Gson();
private static final int PRIVATE_MODE = 0;
private static final String PREF_NAME = "UserSession";
private static final String AUTH_TOKEN = "AuthToken";
private static final String USER = "User";
private final SharedPreferences pref;
private final SharedPreferences.Editor editor;
private final MutableLiveData<Boolean> authStateNotifier = new MutableLiveData<>();
@SuppressLint("CommitPrefEdits")
@MainThread
public SessionManager(Context context) {
Log.d(TAG, "SessionManager:");
pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
authStateNotifier.setValue(getAuthState());
editor = pref.edit();
}
public LiveData<Boolean> getAuthStateNotifier() {
return authStateNotifier;
}
public void addUserDetails(User user) {
String json = gson.toJson(user);
editor.putString(USER, json);
editor.commit();
if (user == null) {
addToken(null);
}
}
public void addToken(AuthToken token) {
String json = gson.toJson(token);
editor.putString(AUTH_TOKEN, json);
editor.commit();
authStateNotifier.postValue(token != null && !token.isNull());
}
public User getUserDetails() {
String json = pref.getString(USER, "");
User user = gson.fromJson(json, User.class);
if (user == null) {
addToken(null);
}
return user;
}
public AuthToken getToken() {
AuthToken token = getParsedAuthToken();
if (token == null) {
authStateNotifier.postValue(false);
}
return token;
}
private AuthToken getParsedAuthToken() {
String json = pref.getString(AUTH_TOKEN, "");
return gson.fromJson(json, AuthToken.class);
}
public boolean getAuthState() {
AuthToken authToken = getParsedAuthToken();
return authToken != null && !authToken.isNull();
}
public void truncateSession() {
editor.clear();
editor.commit();
authStateNotifier.postValue(false);
}
}
|
# Copy Node Exporter to Pods
kubectl cp prometheus/node_exporter-0.17.0-rc.0.linux-amd64/ flume-0:/
kubectl cp prometheus/node_exporter-0.17.0-rc.0.linux-amd64/ kafka-0:/
kubectl cp prometheus/node_exporter-0.17.0-rc.0.linux-amd64/ zk-0:/
kubectl cp prometheus/node_exporter-0.17.0-rc.0.linux-amd64/ monitor-server-0:/
# Run Node Exporter inside pods
kubectl exec -ti flume-0 -- /node_exporter-0.17.0-rc.0.linux-amd64/node_exporter &
kubectl exec -ti kafka-0 -- /node_exporter-0.17.0-rc.0.linux-amd64/node_exporter &
kubectl exec -ti zk-0 -- /node_exporter-0.17.0-rc.0.linux-amd64/node_exporter &
kubectl exec -ti monitor-server-0 -- /node_exporter-0.17.0-rc.0.linux-amd64/node_exporter &
# Deploy Prometheus
# Deploy Prometheus permissions
kubectl create -f prometheus/permissions.yaml
# Deploy Prometheus
kubectl create -f prometheus/prometheus-deployment.yaml
# Wait until Prometheus pod is ready
getPrometheusState () {
prometheusState=$(kubectl get pods -n default prometheus-0 -o jsonpath="{.status.phase}")
}
getPrometheusState
while [ $prometheusState != "Running" ]
do
getPrometheusState
sleep 1
done
# Deploy probe
kubectl create -f probe-k8s-network.yaml
|
#ifndef STRF_DETAIL_SINGLE_BYTE_CHARSETS_HPP
#define STRF_DETAIL_SINGLE_BYTE_CHARSETS_HPP
// Copyright (C) (See commit logs on github.com/robhz786/strf)
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <strf/detail/facets/charset.hpp>
// References
// https://www.compart.com/en/unicode/charsets/
// http://www.unicode.org/Public/MAPPINGS/ISO8859/
// https://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WindowsBestFit/
// https://www.fileformat.info/info/charset/ISO-8859-8/
#if ! defined(STRF_CHECK_DEST)
#define STRF_CHECK_DEST \
STRF_IF_UNLIKELY (dest_it == dest_end) { \
dest.advance_to(dest_it); \
dest.recycle(); \
STRF_IF_UNLIKELY (!dest.good()) { \
return; \
} \
dest_it = dest.buffer_ptr(); \
dest_end = dest.buffer_end(); \
}
#define STRF_CHECK_DEST_SIZE(SIZE) \
STRF_IF_UNLIKELY (dest_it + SIZE > dest_end) { \
dest.advance_to(dest_it); \
dest.recycle(); \
STRF_IF_UNLIKELY (!dest.good()) { \
return; \
} \
dest_it = dest.buffer_ptr(); \
dest_end = dest.buffer_end(); \
}
#endif // ! defined(STRF_CHECK_DEST)
#define STRF_DEF_SINGLE_BYTE_CHARSET_(CHARSET) \
template <typename CharT> \
class static_charset<CharT, strf::csid_ ## CHARSET> \
: public strf::detail::single_byte_charset \
< CharT, strf::detail::impl_ ## CHARSET > \
{ }; \
\
template <typename SrcCharT, typename DestCharT> \
class static_transcoder \
< SrcCharT, DestCharT, strf::csid_ ## CHARSET, strf::csid_ ## CHARSET > \
: public strf::detail::single_byte_charset_sanitizer \
< SrcCharT, DestCharT, strf::detail::impl_ ## CHARSET > \
{}; \
\
template <typename SrcCharT, typename DestCharT> \
class static_transcoder \
< SrcCharT, DestCharT, strf::csid_utf32, strf::csid_ ## CHARSET > \
: public strf::detail::utf32_to_single_byte_charset \
< SrcCharT, DestCharT, strf::detail::impl_ ## CHARSET > \
{}; \
\
template <typename SrcCharT, typename DestCharT> \
class static_transcoder \
< SrcCharT, DestCharT, strf::csid_ ## CHARSET, strf::csid_utf32 > \
: public strf::detail::single_byte_charset_to_utf32 \
< SrcCharT, DestCharT, strf::detail::impl_ ## CHARSET > \
{}; \
\
template <typename CharT> \
using CHARSET ## _t = \
strf::static_charset<CharT, strf::csid_ ## CHARSET>;
#if defined(STRF_HAS_VARIABLE_TEMPLATES)
#define STRF_DEF_SINGLE_BYTE_CHARSET(CHARSET) \
STRF_DEF_SINGLE_BYTE_CHARSET_(CHARSET) \
template <typename CharT> STRF_DEVICE CHARSET ## _t<CharT> CHARSET = {};
#else
#define STRF_DEF_SINGLE_BYTE_CHARSET(CHARSET) STRF_DEF_SINGLE_BYTE_CHARSET_(CHARSET)
#endif // defined(STRF_HAS_VARIABLE_TEMPLATE)
namespace strf {
namespace detail {
template<size_t SIZE, class T>
constexpr STRF_HD size_t array_size(T (&)[SIZE]) {
return SIZE;
}
struct ch32_to_char
{
char32_t key;
unsigned value;
};
struct cmp_ch32_to_char
{
STRF_HD bool operator()(ch32_to_char a, ch32_to_char b) const
{
return a.key < b.key;
}
};
struct impl_ascii
{
static STRF_HD const char* name() noexcept
{
return "ASCII";
};
static constexpr strf::charset_id id = strf::csid_ascii;
static STRF_HD bool is_valid(std::uint8_t ch)
{
return (ch & 0x80) == 0;
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
if ((ch & 0x80) == 0)
return ch;
return 0xFFFD;
}
static STRF_HD unsigned encode(char32_t ch)
{
return ch < 0x80 ? ch : 0x100;
}
};
struct impl_iso_8859_1
{
static STRF_HD const char* name() noexcept
{
return "ISO-8859-1";
};
static constexpr strf::charset_id id = strf::csid_iso_8859_1;
static STRF_HD bool is_valid(std::uint8_t)
{
return true;
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
return ch;
}
static STRF_HD unsigned encode(char32_t ch)
{
return ch;
}
};
struct impl_iso_8859_2
{
static STRF_HD const char* name() noexcept
{
return "ISO-8859-2";
};
static constexpr strf::charset_id id = strf::csid_iso_8859_2;
static STRF_HD bool is_valid(std::uint8_t)
{
return true;
}
static STRF_HD unsigned encode(char32_t ch)
{
if (ch <= 0xA0) {
return ch;
}
return encode_ext(ch);
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
STRF_IF_LIKELY (ch <= 0xA0) {
return ch;
}
static const char32_t ext[] =
{ /*A0 */ 0x0104, 0x02D8, 0x0141, 0x00A4, 0x013D, 0x015A, 0x00A7
, 0x00A8, 0x0160, 0x015E, 0x0164, 0x0179, 0x00AD, 0x017D, 0x017B
, 0x00B0, 0x0105, 0x02DB, 0x0142, 0x00B4, 0x013E, 0x015B, 0x02C7
, 0x00B8, 0x0161, 0x015F, 0x0165, 0x017A, 0x02DD, 0x017E, 0x017C
, 0x0154, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x0139, 0x0106, 0x00C7
, 0x010C, 0x00C9, 0x0118, 0x00CB, 0x011A, 0x00CD, 0x00CE, 0x010E
, 0x0110, 0x0143, 0x0147, 0x00D3, 0x00D4, 0x0150, 0x00D6, 0x00D7
, 0x0158, 0x016E, 0x00DA, 0x0170, 0x00DC, 0x00DD, 0x0162, 0x00DF
, 0x0155, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x013A, 0x0107, 0x00E7
, 0x010D, 0x00E9, 0x0119, 0x00EB, 0x011B, 0x00ED, 0x00EE, 0x010F
, 0x0111, 0x0144, 0x0148, 0x00F3, 0x00F4, 0x0151, 0x00F6, 0x00F7
, 0x0159, 0x016F, 0x00FA, 0x0171, 0x00FC, 0x00FD, 0x0163, 0x02D9 };
return ext[ch - 0xA1];
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_iso_8859_2::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x00A4, 0xA4}, {0x00A7, 0xA7}, {0x00A8, 0xA8}, {0x00AD, 0xAD}
, {0x00B0, 0xB0}, {0x00B4, 0xB4}, {0x00B8, 0xB8}, {0x00C1, 0xC1}
, {0x00C2, 0xC2}, {0x00C4, 0xC4}, {0x00C7, 0xC7}, {0x00C9, 0xC9}
, {0x00CB, 0xCB}, {0x00CD, 0xCD}, {0x00CE, 0xCE}, {0x00D3, 0xD3}
, {0x00D4, 0xD4}, {0x00D6, 0xD6}, {0x00D7, 0xD7}, {0x00DA, 0xDA}
, {0x00DC, 0xDC}, {0x00DD, 0xDD}, {0x00DF, 0xDF}, {0x00E1, 0xE1}
, {0x00E2, 0xE2}, {0x00E4, 0xE4}, {0x00E7, 0xE7}, {0x00E9, 0xE9}
, {0x00EB, 0xEB}, {0x00ED, 0xED}, {0x00EE, 0xEE}, {0x00F3, 0xF3}
, {0x00F4, 0xF4}, {0x00F6, 0xF6}, {0x00F7, 0xF7}, {0x00FA, 0xFA}
, {0x00FC, 0xFC}, {0x00FD, 0xFD}, {0x0102, 0xC3}, {0x0103, 0xE3}
, {0x0104, 0xA1}, {0x0105, 0xB1}, {0x0106, 0xC6}, {0x0107, 0xE6}
, {0x010C, 0xC8}, {0x010D, 0xE8}, {0x010E, 0xCF}, {0x010F, 0xEF}
, {0x0110, 0xD0}, {0x0111, 0xF0}, {0x0118, 0xCA}, {0x0119, 0xEA}
, {0x011A, 0xCC}, {0x011B, 0xEC}, {0x0139, 0xC5}, {0x013A, 0xE5}
, {0x013D, 0xA5}, {0x013E, 0xB5}, {0x0141, 0xA3}, {0x0142, 0xB3}
, {0x0143, 0xD1}, {0x0144, 0xF1}, {0x0147, 0xD2}, {0x0148, 0xF2}
, {0x0150, 0xD5}, {0x0151, 0xF5}, {0x0154, 0xC0}, {0x0155, 0xE0}
, {0x0158, 0xD8}, {0x0159, 0xF8}, {0x015A, 0xA6}, {0x015B, 0xB6}
, {0x015E, 0xAA}, {0x015F, 0xBA}, {0x0160, 0xA9}, {0x0161, 0xB9}
, {0x0162, 0xDE}, {0x0163, 0xFE}, {0x0164, 0xAB}, {0x0165, 0xBB}
, {0x016E, 0xD9}, {0x016F, 0xF9}, {0x0170, 0xDB}, {0x0171, 0xFB}
, {0x0179, 0xAC}, {0x017A, 0xBC}, {0x017B, 0xAF}, {0x017C, 0xBF}
, {0x017D, 0xAE}, {0x017E, 0xBE}, {0x02C7, 0xB7}, {0x02D8, 0xA2}
, {0x02D9, 0xFF}, {0x02DB, 0xB2}, {0x02DD, 0xBD} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif // ! defined(STRF_OMIT_IMPL)
struct impl_iso_8859_3
{
static STRF_HD const char* name() noexcept
{
return "ISO-8859-3";
};
static constexpr strf::charset_id id = strf::csid_iso_8859_3;
static STRF_HD bool is_valid(std::uint8_t ch)
{
return ch != 0xA5
&& ch != 0xAE
&& ch != 0xBE
&& ch != 0xC3
&& ch != 0xD0
&& ch != 0xE3
&& ch != 0xF0;
}
static STRF_HD unsigned encode(char32_t ch)
{
if (ch <= 0xA0) {
return ch;
}
return encode_ext(ch);
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
if (ch <= 0xA0) {
return ch;
}
constexpr unsigned short undef = 0xFFFD;
static const unsigned short ext[] =
{ /* A0*/ 0x0126, 0x02D8, 0x00A3, 0x00A4, undef, 0x0124, 0x00A7
, 0x00A8, 0x0130, 0x015E, 0x011E, 0x0134, 0x00AD, undef, 0x017B
, 0x00B0, 0x0127, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x0125, 0x00B7
, 0x00B8, 0x0131, 0x015F, 0x011F, 0x0135, 0x00BD, undef, 0x017C
, 0x00C0, 0x00C1, 0x00C2, undef, 0x00C4, 0x010A, 0x0108, 0x00C7
, 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF
, undef, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x0120, 0x00D6, 0x00D7
, 0x011C, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x016C, 0x015C, 0x00DF
, 0x00E0, 0x00E1, 0x00E2, undef, 0x00E4, 0x010B, 0x0109, 0x00E7
, 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF
, undef, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x0121, 0x00F6, 0x00F7
, 0x011D, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x016D, 0x015D, 0x02D9 };
return ext[ch - 0xA1];
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_iso_8859_3::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x00A3, 0xA3}, {0x00A4, 0xA4}, {0x00A7, 0xA7}, {0x00A8, 0xA8}
, {0x00AD, 0xAD}, {0x00B0, 0xB0}, {0x00B2, 0xB2}, {0x00B3, 0xB3}
, {0x00B4, 0xB4}, {0x00B5, 0xB5}, {0x00B7, 0xB7}, {0x00B8, 0xB8}
, {0x00BD, 0xBD}, {0x00C0, 0xC0}, {0x00C1, 0xC1}, {0x00C2, 0xC2}
, {0x00C4, 0xC4}, {0x00C7, 0xC7}, {0x00C8, 0xC8}, {0x00C9, 0xC9}
, {0x00CA, 0xCA}, {0x00CB, 0xCB}, {0x00CC, 0xCC}, {0x00CD, 0xCD}
, {0x00CE, 0xCE}, {0x00CF, 0xCF}, {0x00D1, 0xD1}, {0x00D2, 0xD2}
, {0x00D3, 0xD3}, {0x00D4, 0xD4}, {0x00D6, 0xD6}, {0x00D7, 0xD7}
, {0x00D9, 0xD9}, {0x00DA, 0xDA}, {0x00DB, 0xDB}, {0x00DC, 0xDC}
, {0x00DF, 0xDF}, {0x00E0, 0xE0}, {0x00E1, 0xE1}, {0x00E2, 0xE2}
, {0x00E4, 0xE4}, {0x00E7, 0xE7}, {0x00E8, 0xE8}, {0x00E9, 0xE9}
, {0x00EA, 0xEA}, {0x00EB, 0xEB}, {0x00EC, 0xEC}, {0x00ED, 0xED}
, {0x00EE, 0xEE}, {0x00EF, 0xEF}, {0x00F1, 0xF1}, {0x00F2, 0xF2}
, {0x00F3, 0xF3}, {0x00F4, 0xF4}, {0x00F6, 0xF6}, {0x00F7, 0xF7}
, {0x00F9, 0xF9}, {0x00FA, 0xFA}, {0x00FB, 0xFB}, {0x00FC, 0xFC}
, {0x0108, 0xC6}, {0x0109, 0xE6}, {0x010A, 0xC5}, {0x010B, 0xE5}
, {0x011C, 0xD8}, {0x011D, 0xF8}, {0x011E, 0xAB}, {0x011F, 0xBB}
, {0x0120, 0xD5}, {0x0121, 0xF5}, {0x0124, 0xA6}, {0x0125, 0xB6}
, {0x0126, 0xA1}, {0x0127, 0xB1}, {0x0130, 0xA9}, {0x0131, 0xB9}
, {0x0134, 0xAC}, {0x0135, 0xBC}, {0x015C, 0xDE}, {0x015D, 0xFE}
, {0x015E, 0xAA}, {0x015F, 0xBA}, {0x016C, 0xDD}, {0x016D, 0xFD}
, {0x017B, 0xAF}, {0x017C, 0xBF}, {0x02D8, 0xA2}, {0x02D9, 0xFF} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif // ! defined(STRF_OMIT_IMPL)
struct impl_iso_8859_4
{
static STRF_HD const char* name() noexcept
{
return "ISO-8859-4";
};
static constexpr strf::charset_id id = strf::csid_iso_8859_4;
static STRF_HD bool is_valid(std::uint8_t)
{
return true;
}
static STRF_HD unsigned encode(char32_t ch)
{
if (ch <= 0xA0) {
return ch;
}
return encode_ext(ch);
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
if (ch <= 0xA0) {
return ch;
}
static const char32_t ext[] =
{ /*A0 */ 0x0104, 0x0138, 0x0156, 0x00A4, 0x0128, 0x013B, 0x00A7
, 0x00A8, 0x0160, 0x0112, 0x0122, 0x0166, 0x00AD, 0x017D, 0x00AF
, 0x00B0, 0x0105, 0x02DB, 0x0157, 0x00B4, 0x0129, 0x013C, 0x02C7
, 0x00B8, 0x0161, 0x0113, 0x0123, 0x0167, 0x014A, 0x017E, 0x014B
, 0x0100, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x012E
, 0x010C, 0x00C9, 0x0118, 0x00CB, 0x0116, 0x00CD, 0x00CE, 0x012A
, 0x0110, 0x0145, 0x014C, 0x0136, 0x00D4, 0x00D5, 0x00D6, 0x00D7
, 0x00D8, 0x0172, 0x00DA, 0x00DB, 0x00DC, 0x0168, 0x016A, 0x00DF
, 0x0101, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x012F
, 0x010D, 0x00E9, 0x0119, 0x00EB, 0x0117, 0x00ED, 0x00EE, 0x012B
, 0x0111, 0x0146, 0x014D, 0x0137, 0x00F4, 0x00F5, 0x00F6, 0x00F7
, 0x00F8, 0x0173, 0x00FA, 0x00FB, 0x00FC, 0x0169, 0x016B, 0x02D9 };
return ext[ch - 0xA1];
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_iso_8859_4::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x00A4, 0xA4}, {0x00A7, 0xA7}, {0x00A8, 0xA8}, {0x00AD, 0xAD}
, {0x00AF, 0xAF}, {0x00B0, 0xB0}, {0x00B4, 0xB4}, {0x00B8, 0xB8}
, {0x00C1, 0xC1}, {0x00C2, 0xC2}, {0x00C3, 0xC3}, {0x00C4, 0xC4}
, {0x00C5, 0xC5}, {0x00C6, 0xC6}, {0x00C9, 0xC9}, {0x00CB, 0xCB}
, {0x00CD, 0xCD}, {0x00CE, 0xCE}, {0x00D4, 0xD4}, {0x00D5, 0xD5}
, {0x00D6, 0xD6}, {0x00D7, 0xD7}, {0x00D8, 0xD8}, {0x00DA, 0xDA}
, {0x00DB, 0xDB}, {0x00DC, 0xDC}, {0x00DF, 0xDF}, {0x00E1, 0xE1}
, {0x00E2, 0xE2}, {0x00E3, 0xE3}, {0x00E4, 0xE4}, {0x00E5, 0xE5}
, {0x00E6, 0xE6}, {0x00E9, 0xE9}, {0x00EB, 0xEB}, {0x00ED, 0xED}
, {0x00EE, 0xEE}, {0x00F4, 0xF4}, {0x00F5, 0xF5}, {0x00F6, 0xF6}
, {0x00F7, 0xF7}, {0x00F8, 0xF8}, {0x00FA, 0xFA}, {0x00FB, 0xFB}
, {0x00FC, 0xFC}, {0x0100, 0xC0}, {0x0101, 0xE0}, {0x0104, 0xA1}
, {0x0105, 0xB1}, {0x010C, 0xC8}, {0x010D, 0xE8}, {0x0110, 0xD0}
, {0x0111, 0xF0}, {0x0112, 0xAA}, {0x0113, 0xBA}, {0x0116, 0xCC}
, {0x0117, 0xEC}, {0x0118, 0xCA}, {0x0119, 0xEA}, {0x0122, 0xAB}
, {0x0123, 0xBB}, {0x0128, 0xA5}, {0x0129, 0xB5}, {0x012A, 0xCF}
, {0x012B, 0xEF}, {0x012E, 0xC7}, {0x012F, 0xE7}, {0x0136, 0xD3}
, {0x0137, 0xF3}, {0x0138, 0xA2}, {0x013B, 0xA6}, {0x013C, 0xB6}
, {0x0145, 0xD1}, {0x0146, 0xF1}, {0x014A, 0xBD}, {0x014B, 0xBF}
, {0x014C, 0xD2}, {0x014D, 0xF2}, {0x0156, 0xA3}, {0x0157, 0xB3}
, {0x0160, 0xA9}, {0x0161, 0xB9}, {0x0166, 0xAC}, {0x0167, 0xBC}
, {0x0168, 0xDD}, {0x0169, 0xFD}, {0x016A, 0xDE}, {0x016B, 0xFE}
, {0x0172, 0xD9}, {0x0173, 0xF9}, {0x017D, 0xAE}, {0x017E, 0xBE}
, {0x02C7, 0xB7}, {0x02D9, 0xFF}, {0x02DB, 0xB2} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif // ! defined(STRF_OMIT_IMPL)
struct impl_iso_8859_5
{
static STRF_HD const char* name() noexcept
{
return "ISO-8859-5";
};
static constexpr strf::charset_id id = strf::csid_iso_8859_5;
static STRF_HD bool is_valid(std::uint8_t)
{
return true;
}
static STRF_HD unsigned encode(char32_t ch)
{
if (ch <= 0xA0) {
return ch;
}
return encode_ext(ch);
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
if (ch <= 0xA0) {
return ch;
}
static const char32_t ext[] =
{ /*A0 */ 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0406, 0x0407
, 0x0408, 0x0409, 0x040A, 0x040B, 0x040C, 0x00AD, 0x040E, 0x040F
, 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417
, 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F
, 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427
, 0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F
, 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437
, 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F
, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447
, 0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D, 0x044E, 0x044F
, 0x2116, 0x0451, 0x0452, 0x0453, 0x0454, 0x0455, 0x0456, 0x0457
, 0x0458, 0x0459, 0x045A, 0x045B, 0x045C, 0x00A7, 0x045E, 0x045F };
return ext[ch - 0xA1];
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_iso_8859_5::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x00A7, 0xFD}, {0x00AD, 0xAD}, {0x0401, 0xA1}, {0x0402, 0xA2}
, {0x0403, 0xA3}, {0x0404, 0xA4}, {0x0405, 0xA5}, {0x0406, 0xA6}
, {0x0407, 0xA7}, {0x0408, 0xA8}, {0x0409, 0xA9}, {0x040A, 0xAA}
, {0x040B, 0xAB}, {0x040C, 0xAC}, {0x040E, 0xAE}, {0x040F, 0xAF}
, {0x0410, 0xB0}, {0x0411, 0xB1}, {0x0412, 0xB2}, {0x0413, 0xB3}
, {0x0414, 0xB4}, {0x0415, 0xB5}, {0x0416, 0xB6}, {0x0417, 0xB7}
, {0x0418, 0xB8}, {0x0419, 0xB9}, {0x041A, 0xBA}, {0x041B, 0xBB}
, {0x041C, 0xBC}, {0x041D, 0xBD}, {0x041E, 0xBE}, {0x041F, 0xBF}
, {0x0420, 0xC0}, {0x0421, 0xC1}, {0x0422, 0xC2}, {0x0423, 0xC3}
, {0x0424, 0xC4}, {0x0425, 0xC5}, {0x0426, 0xC6}, {0x0427, 0xC7}
, {0x0428, 0xC8}, {0x0429, 0xC9}, {0x042A, 0xCA}, {0x042B, 0xCB}
, {0x042C, 0xCC}, {0x042D, 0xCD}, {0x042E, 0xCE}, {0x042F, 0xCF}
, {0x0430, 0xD0}, {0x0431, 0xD1}, {0x0432, 0xD2}, {0x0433, 0xD3}
, {0x0434, 0xD4}, {0x0435, 0xD5}, {0x0436, 0xD6}, {0x0437, 0xD7}
, {0x0438, 0xD8}, {0x0439, 0xD9}, {0x043A, 0xDA}, {0x043B, 0xDB}
, {0x043C, 0xDC}, {0x043D, 0xDD}, {0x043E, 0xDE}, {0x043F, 0xDF}
, {0x0440, 0xE0}, {0x0441, 0xE1}, {0x0442, 0xE2}, {0x0443, 0xE3}
, {0x0444, 0xE4}, {0x0445, 0xE5}, {0x0446, 0xE6}, {0x0447, 0xE7}
, {0x0448, 0xE8}, {0x0449, 0xE9}, {0x044A, 0xEA}, {0x044B, 0xEB}
, {0x044C, 0xEC}, {0x044D, 0xED}, {0x044E, 0xEE}, {0x044F, 0xEF}
, {0x0451, 0xF1}, {0x0452, 0xF2}, {0x0453, 0xF3}, {0x0454, 0xF4}
, {0x0455, 0xF5}, {0x0456, 0xF6}, {0x0457, 0xF7}, {0x0458, 0xF8}
, {0x0459, 0xF9}, {0x045A, 0xFA}, {0x045B, 0xFB}, {0x045C, 0xFC}
, {0x045E, 0xFE}, {0x045F, 0xFF}, {0x2116, 0xF0} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif // ! defined(STRF_OMIT_IMPL)
struct impl_iso_8859_6
{
static STRF_HD const char* name() noexcept
{
return "ISO-8859-6";
};
static constexpr strf::charset_id id = strf::csid_iso_8859_6;
static STRF_HD bool is_valid(std::uint8_t ch)
{
return ch <= 0xA0 || ch == 0xA4 || ch == 0xAC || ch == 0xAD
|| ch == 0xBB || ch == 0xBF || (0xC1 <= ch && ch <= 0xDA)
|| (0xE0 <= ch && ch <= 0xF2);
}
static STRF_HD unsigned encode(char32_t ch)
{
if (ch <= 0xA0) {
return ch;
}
return encode_ext(ch);
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
if (ch <= 0xA0) {
return ch;
}
static const char32_t ext[] =
{ /*A0 */ 0xFFFD, 0xFFFD, 0xFFFD, 0x00A4, 0xFFFD, 0xFFFD, 0xFFFD
, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x060C, 0x00AD, 0xFFFD, 0xFFFD
, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD
, 0xFFFD, 0xFFFD, 0xFFFD, 0x061B, 0xFFFD, 0xFFFD, 0xFFFD, 0x061F
, 0xFFFD, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627
, 0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F
, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x0637
, 0x0638, 0x0639, 0x063A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD
, 0x0640, 0x0641, 0x0642, 0x0643, 0x0644, 0x0645, 0x0646, 0x0647
, 0x0648, 0x0649, 0x064A, 0x064B, 0x064C, 0x064D, 0x064E, 0x064F
, 0x0650, 0x0651, 0x0652, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD
, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD };
return ext[ch - 0xA1];
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_iso_8859_6::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x00A4, 0xA4}, {0x00AD, 0xAD}, {0x060C, 0xAC}, {0x061B, 0xBB}
, {0x061F, 0xBF}, {0x0621, 0xC1}, {0x0622, 0xC2}, {0x0623, 0xC3}
, {0x0624, 0xC4}, {0x0625, 0xC5}, {0x0626, 0xC6}, {0x0627, 0xC7}
, {0x0628, 0xC8}, {0x0629, 0xC9}, {0x062A, 0xCA}, {0x062B, 0xCB}
, {0x062C, 0xCC}, {0x062D, 0xCD}, {0x062E, 0xCE}, {0x062F, 0xCF}
, {0x0630, 0xD0}, {0x0631, 0xD1}, {0x0632, 0xD2}, {0x0633, 0xD3}
, {0x0634, 0xD4}, {0x0635, 0xD5}, {0x0636, 0xD6}, {0x0637, 0xD7}
, {0x0638, 0xD8}, {0x0639, 0xD9}, {0x063A, 0xDA}, {0x0640, 0xE0}
, {0x0641, 0xE1}, {0x0642, 0xE2}, {0x0643, 0xE3}, {0x0644, 0xE4}
, {0x0645, 0xE5}, {0x0646, 0xE6}, {0x0647, 0xE7}, {0x0648, 0xE8}
, {0x0649, 0xE9}, {0x064A, 0xEA}, {0x064B, 0xEB}, {0x064C, 0xEC}
, {0x064D, 0xED}, {0x064E, 0xEE}, {0x064F, 0xEF}, {0x0650, 0xF0}
, {0x0651, 0xF1}, {0x0652, 0xF2} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif // ! defined(STRF_OMIT_IMPL)
struct impl_iso_8859_7
{
static STRF_HD const char* name() noexcept
{
return "ISO-8859-7";
};
static constexpr strf::charset_id id = strf::csid_iso_8859_7;
static STRF_HD bool is_valid(std::uint8_t ch)
{
return ch != 0xAE && ch != 0xD2 && ch != 0xFF;
}
static STRF_HD unsigned encode(char32_t ch)
{
if (ch <= 0xA0) {
return ch;
}
return encode_ext(ch);
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
if (ch <= 0xA0) {
return ch;
}
static const char32_t ext[] =
{ /*A0 */ 0x2018, 0x2019, 0x00A3, 0x20AC, 0x20AF, 0x00A6, 0x00A7
, 0x00A8, 0x00A9, 0x037A, 0x00AB, 0x00AC, 0x00AD, 0xFFFD, 0x2015
, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x0384, 0x0385, 0x0386, 0x00B7
, 0x0388, 0x0389, 0x038A, 0x00BB, 0x038C, 0x00BD, 0x038E, 0x038F
, 0x0390, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397
, 0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F
, 0x03A0, 0x03A1, 0xFFFD, 0x03A3, 0x03A4, 0x03A5, 0x03A6, 0x03A7
, 0x03A8, 0x03A9, 0x03AA, 0x03AB, 0x03AC, 0x03AD, 0x03AE, 0x03AF
, 0x03B0, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7
, 0x03B8, 0x03B9, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BE, 0x03BF
, 0x03C0, 0x03C1, 0x03C2, 0x03C3, 0x03C4, 0x03C5, 0x03C6, 0x03C7
, 0x03C8, 0x03C9, 0x03CA, 0x03CB, 0x03CC, 0x03CD, 0x03CE, 0xFFFD };
return ext[ch - 0xA1];
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_iso_8859_7::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x00A3, 0xA3}, {0x00A6, 0xA6}, {0x00A7, 0xA7}, {0x00A8, 0xA8}
, {0x00A9, 0xA9}, {0x00AB, 0xAB}, {0x00AC, 0xAC}, {0x00AD, 0xAD}
, {0x00B0, 0xB0}, {0x00B1, 0xB1}, {0x00B2, 0xB2}, {0x00B3, 0xB3}
, {0x00B7, 0xB7}, {0x00BB, 0xBB}, {0x00BD, 0xBD}, {0x037A, 0xAA}
, {0x0384, 0xB4}, {0x0385, 0xB5}, {0x0386, 0xB6}, {0x0388, 0xB8}
, {0x0389, 0xB9}, {0x038A, 0xBA}, {0x038C, 0xBC}, {0x038E, 0xBE}
, {0x038F, 0xBF}, {0x0390, 0xC0}, {0x0391, 0xC1}, {0x0392, 0xC2}
, {0x0393, 0xC3}, {0x0394, 0xC4}, {0x0395, 0xC5}, {0x0396, 0xC6}
, {0x0397, 0xC7}, {0x0398, 0xC8}, {0x0399, 0xC9}, {0x039A, 0xCA}
, {0x039B, 0xCB}, {0x039C, 0xCC}, {0x039D, 0xCD}, {0x039E, 0xCE}
, {0x039F, 0xCF}, {0x03A0, 0xD0}, {0x03A1, 0xD1}, {0x03A3, 0xD3}
, {0x03A4, 0xD4}, {0x03A5, 0xD5}, {0x03A6, 0xD6}, {0x03A7, 0xD7}
, {0x03A8, 0xD8}, {0x03A9, 0xD9}, {0x03AA, 0xDA}, {0x03AB, 0xDB}
, {0x03AC, 0xDC}, {0x03AD, 0xDD}, {0x03AE, 0xDE}, {0x03AF, 0xDF}
, {0x03B0, 0xE0}, {0x03B1, 0xE1}, {0x03B2, 0xE2}, {0x03B3, 0xE3}
, {0x03B4, 0xE4}, {0x03B5, 0xE5}, {0x03B6, 0xE6}, {0x03B7, 0xE7}
, {0x03B8, 0xE8}, {0x03B9, 0xE9}, {0x03BA, 0xEA}, {0x03BB, 0xEB}
, {0x03BC, 0xEC}, {0x03BD, 0xED}, {0x03BE, 0xEE}, {0x03BF, 0xEF}
, {0x03C0, 0xF0}, {0x03C1, 0xF1}, {0x03C2, 0xF2}, {0x03C3, 0xF3}
, {0x03C4, 0xF4}, {0x03C5, 0xF5}, {0x03C6, 0xF6}, {0x03C7, 0xF7}
, {0x03C8, 0xF8}, {0x03C9, 0xF9}, {0x03CA, 0xFA}, {0x03CB, 0xFB}
, {0x03CC, 0xFC}, {0x03CD, 0xFD}, {0x03CE, 0xFE}, {0x2015, 0xAF}
, {0x2018, 0xA1}, {0x2019, 0xA2}, {0x20AC, 0xA4}, {0x20AF, 0xA5} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif // ! defined(STRF_OMIT_IMPL)
struct impl_iso_8859_8
{
static STRF_HD const char* name() noexcept
{
return "ISO-8859-8";
};
static constexpr strf::charset_id id = strf::csid_iso_8859_8;
static STRF_HD bool is_valid(std::uint8_t ch)
{
return (ch <= 0xBE && ch != 0xA1) || (0xDF <= ch && ch <= 0xFA)
|| ch == 0xFD || ch == 0xFE;
}
static STRF_HD unsigned encode(char32_t ch)
{
if (ch <= 0xA0) {
return ch;
}
return encode_ext(ch);
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
if (ch <= 0xA0) {
return ch;
}
static const char32_t ext[] =
{ /*A0 */ 0xFFFD, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7
, 0x00A8, 0x00A9, 0x00D7, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF
, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7
, 0x00B8, 0x00B9, 0x00F7, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0xFFFD
, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD
, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD
, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD
, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2017
, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7
, 0x05D8, 0x05D9, 0x05DA, 0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF
, 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7
, 0x05E8, 0x05E9, 0x05EA, 0xFFFD, 0xFFFD, 0x200E, 0x200F, 0xFFFD };
return ext[ch - 0xA1];
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_iso_8859_8::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x00A2, 0xA2}, {0x00A3, 0xA3}, {0x00A4, 0xA4}, {0x00A5, 0xA5}
, {0x00A6, 0xA6}, {0x00A7, 0xA7}, {0x00A8, 0xA8}, {0x00A9, 0xA9}
, {0x00AB, 0xAB}, {0x00AC, 0xAC}, {0x00AD, 0xAD}, {0x00AE, 0xAE}
, {0x00AF, 0xAF}, {0x00B0, 0xB0}, {0x00B1, 0xB1}, {0x00B2, 0xB2}
, {0x00B3, 0xB3}, {0x00B4, 0xB4}, {0x00B5, 0xB5}, {0x00B6, 0xB6}
, {0x00B7, 0xB7}, {0x00B8, 0xB8}, {0x00B9, 0xB9}, {0x00BB, 0xBB}
, {0x00BC, 0xBC}, {0x00BD, 0xBD}, {0x00BE, 0xBE}, {0x00D7, 0xAA}
, {0x00F7, 0xBA}, {0x05D0, 0xE0}, {0x05D1, 0xE1}, {0x05D2, 0xE2}
, {0x05D3, 0xE3}, {0x05D4, 0xE4}, {0x05D5, 0xE5}, {0x05D6, 0xE6}
, {0x05D7, 0xE7}, {0x05D8, 0xE8}, {0x05D9, 0xE9}, {0x05DA, 0xEA}
, {0x05DB, 0xEB}, {0x05DC, 0xEC}, {0x05DD, 0xED}, {0x05DE, 0xEE}
, {0x05DF, 0xEF}, {0x05E0, 0xF0}, {0x05E1, 0xF1}, {0x05E2, 0xF2}
, {0x05E3, 0xF3}, {0x05E4, 0xF4}, {0x05E5, 0xF5}, {0x05E6, 0xF6}
, {0x05E7, 0xF7}, {0x05E8, 0xF8}, {0x05E9, 0xF9}, {0x05EA, 0xFA}
, {0x200E, 0xFD}, {0x200F, 0xFE}, {0x2017, 0xDF} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif // ! defined(STRF_OMIT_IMPL)
struct impl_iso_8859_9
{
static STRF_HD const char* name() noexcept
{
return "ISO-8859-9";
};
static constexpr strf::charset_id id = strf::csid_iso_8859_9;
static STRF_HD bool is_valid(std::uint8_t)
{
return true;
}
static STRF_HD unsigned encode(char32_t ch)
{
STRF_IF_LIKELY (ch <= 0xCF) {
return ch;
}
switch (ch) {
case 0x011E: return 0xD0;
case 0x0130: return 0xDD;
case 0x015E: return 0xDE;
case 0x011F: return 0xF0;
case 0x0131: return 0xFD;
case 0x015F: return 0xFE;
case 0xD0:
case 0xDD:
case 0xDE:
case 0xF0:
case 0xFD:
case 0xFE:
return 0x100;
}
return ch;
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
STRF_IF_LIKELY (ch <= 0xCF) {
return ch;
}
switch (ch) {
case 0xD0: return 0x011E;
case 0xDD: return 0x0130;
case 0xDE: return 0x015E;
case 0xF0: return 0x011F;
case 0xFD: return 0x0131;
case 0xFE: return 0x015F;
}
return ch;
}
};
struct impl_iso_8859_10
{
static STRF_HD const char* name() noexcept
{
return "ISO-8859-10";
};
static constexpr strf::charset_id id = strf::csid_iso_8859_10;
static STRF_HD bool is_valid(std::uint8_t)
{
return true;
}
static STRF_HD unsigned encode(char32_t ch)
{
if (ch <= 0xA0) {
return ch;
}
return encode_ext(ch);
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
if (ch <= 0xA0) {
return ch;
}
static const char32_t ext[] =
{ /*A0 */ 0x0104, 0x0112, 0x0122, 0x012A, 0x0128, 0x0136, 0x00A7
, 0x013B, 0x0110, 0x0160, 0x0166, 0x017D, 0x00AD, 0x016A, 0x014A
, 0x00B0, 0x0105, 0x0113, 0x0123, 0x012B, 0x0129, 0x0137, 0x00B7
, 0x013C, 0x0111, 0x0161, 0x0167, 0x017E, 0x2015, 0x016B, 0x014B
, 0x0100, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x012E
, 0x010C, 0x00C9, 0x0118, 0x00CB, 0x0116, 0x00CD, 0x00CE, 0x00CF
, 0x00D0, 0x0145, 0x014C, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x0168
, 0x00D8, 0x0172, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DE, 0x00DF
, 0x0101, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x012F
, 0x010D, 0x00E9, 0x0119, 0x00EB, 0x0117, 0x00ED, 0x00EE, 0x00EF
, 0x00F0, 0x0146, 0x014D, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x0169
, 0x00F8, 0x0173, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FE, 0x0138 };
return ext[ch - 0xA1];
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_iso_8859_10::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x00A7, 0xA7}, {0x00AD, 0xAD}, {0x00B0, 0xB0}, {0x00B7, 0xB7}
, {0x00C1, 0xC1}, {0x00C2, 0xC2}, {0x00C3, 0xC3}, {0x00C4, 0xC4}
, {0x00C5, 0xC5}, {0x00C6, 0xC6}, {0x00C9, 0xC9}, {0x00CB, 0xCB}
, {0x00CD, 0xCD}, {0x00CE, 0xCE}, {0x00CF, 0xCF}, {0x00D0, 0xD0}
, {0x00D3, 0xD3}, {0x00D4, 0xD4}, {0x00D5, 0xD5}, {0x00D6, 0xD6}
, {0x00D8, 0xD8}, {0x00DA, 0xDA}, {0x00DB, 0xDB}, {0x00DC, 0xDC}
, {0x00DD, 0xDD}, {0x00DE, 0xDE}, {0x00DF, 0xDF}, {0x00E1, 0xE1}
, {0x00E2, 0xE2}, {0x00E3, 0xE3}, {0x00E4, 0xE4}, {0x00E5, 0xE5}
, {0x00E6, 0xE6}, {0x00E9, 0xE9}, {0x00EB, 0xEB}, {0x00ED, 0xED}
, {0x00EE, 0xEE}, {0x00EF, 0xEF}, {0x00F0, 0xF0}, {0x00F3, 0xF3}
, {0x00F4, 0xF4}, {0x00F5, 0xF5}, {0x00F6, 0xF6}, {0x00F8, 0xF8}
, {0x00FA, 0xFA}, {0x00FB, 0xFB}, {0x00FC, 0xFC}, {0x00FD, 0xFD}
, {0x00FE, 0xFE}, {0x0100, 0xC0}, {0x0101, 0xE0}, {0x0104, 0xA1}
, {0x0105, 0xB1}, {0x010C, 0xC8}, {0x010D, 0xE8}, {0x0110, 0xA9}
, {0x0111, 0xB9}, {0x0112, 0xA2}, {0x0113, 0xB2}, {0x0116, 0xCC}
, {0x0117, 0xEC}, {0x0118, 0xCA}, {0x0119, 0xEA}, {0x0122, 0xA3}
, {0x0123, 0xB3}, {0x0128, 0xA5}, {0x0129, 0xB5}, {0x012A, 0xA4}
, {0x012B, 0xB4}, {0x012E, 0xC7}, {0x012F, 0xE7}, {0x0136, 0xA6}
, {0x0137, 0xB6}, {0x0138, 0xFF}, {0x013B, 0xA8}, {0x013C, 0xB8}
, {0x0145, 0xD1}, {0x0146, 0xF1}, {0x014A, 0xAF}, {0x014B, 0xBF}
, {0x014C, 0xD2}, {0x014D, 0xF2}, {0x0160, 0xAA}, {0x0161, 0xBA}
, {0x0166, 0xAB}, {0x0167, 0xBB}, {0x0168, 0xD7}, {0x0169, 0xF7}
, {0x016A, 0xAE}, {0x016B, 0xBE}, {0x0172, 0xD9}, {0x0173, 0xF9}
, {0x017D, 0xAC}, {0x017E, 0xBC}, {0x2015, 0xBD} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif // ! defined(STRF_OMIT_IMPL)
struct impl_iso_8859_11
{
static STRF_HD const char* name() noexcept
{
return "ISO-8859-11";
};
static constexpr strf::charset_id id = strf::csid_iso_8859_11;
static STRF_HD bool is_valid(std::uint8_t ch)
{
return ch <= 0xDA || (ch >= 0xDF && ch <= 0xFB);
}
static STRF_HD unsigned encode(char32_t ch)
{
if (ch <= 0xA0) {
return ch;
}
return encode_ext(ch);
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
if (ch <= 0xA0) {
return ch;
}
static const char32_t ext[] =
{ /*A0 */ 0x0E01, 0x0E02, 0x0E03, 0x0E04, 0x0E05, 0x0E06, 0x0E07
, 0x0E08, 0x0E09, 0x0E0A, 0x0E0B, 0x0E0C, 0x0E0D, 0x0E0E, 0x0E0F
, 0x0E10, 0x0E11, 0x0E12, 0x0E13, 0x0E14, 0x0E15, 0x0E16, 0x0E17
, 0x0E18, 0x0E19, 0x0E1A, 0x0E1B, 0x0E1C, 0x0E1D, 0x0E1E, 0x0E1F
, 0x0E20, 0x0E21, 0x0E22, 0x0E23, 0x0E24, 0x0E25, 0x0E26, 0x0E27
, 0x0E28, 0x0E29, 0x0E2A, 0x0E2B, 0x0E2C, 0x0E2D, 0x0E2E, 0x0E2F
, 0x0E30, 0x0E31, 0x0E32, 0x0E33, 0x0E34, 0x0E35, 0x0E36, 0x0E37
, 0x0E38, 0x0E39, 0x0E3A, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x0E3F
, 0x0E40, 0x0E41, 0x0E42, 0x0E43, 0x0E44, 0x0E45, 0x0E46, 0x0E47
, 0x0E48, 0x0E49, 0x0E4A, 0x0E4B, 0x0E4C, 0x0E4D, 0x0E4E, 0x0E4F
, 0x0E50, 0x0E51, 0x0E52, 0x0E53, 0x0E54, 0x0E55, 0x0E56, 0x0E57
, 0x0E58, 0x0E59, 0x0E5A, 0x0E5B, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD };
return ext[ch - 0xA1];
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_iso_8859_11::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x0E01, 0xA1}, {0x0E02, 0xA2}, {0x0E03, 0xA3}, {0x0E04, 0xA4}
, {0x0E05, 0xA5}, {0x0E06, 0xA6}, {0x0E07, 0xA7}, {0x0E08, 0xA8}
, {0x0E09, 0xA9}, {0x0E0A, 0xAA}, {0x0E0B, 0xAB}, {0x0E0C, 0xAC}
, {0x0E0D, 0xAD}, {0x0E0E, 0xAE}, {0x0E0F, 0xAF}, {0x0E10, 0xB0}
, {0x0E11, 0xB1}, {0x0E12, 0xB2}, {0x0E13, 0xB3}, {0x0E14, 0xB4}
, {0x0E15, 0xB5}, {0x0E16, 0xB6}, {0x0E17, 0xB7}, {0x0E18, 0xB8}
, {0x0E19, 0xB9}, {0x0E1A, 0xBA}, {0x0E1B, 0xBB}, {0x0E1C, 0xBC}
, {0x0E1D, 0xBD}, {0x0E1E, 0xBE}, {0x0E1F, 0xBF}, {0x0E20, 0xC0}
, {0x0E21, 0xC1}, {0x0E22, 0xC2}, {0x0E23, 0xC3}, {0x0E24, 0xC4}
, {0x0E25, 0xC5}, {0x0E26, 0xC6}, {0x0E27, 0xC7}, {0x0E28, 0xC8}
, {0x0E29, 0xC9}, {0x0E2A, 0xCA}, {0x0E2B, 0xCB}, {0x0E2C, 0xCC}
, {0x0E2D, 0xCD}, {0x0E2E, 0xCE}, {0x0E2F, 0xCF}, {0x0E30, 0xD0}
, {0x0E31, 0xD1}, {0x0E32, 0xD2}, {0x0E33, 0xD3}, {0x0E34, 0xD4}
, {0x0E35, 0xD5}, {0x0E36, 0xD6}, {0x0E37, 0xD7}, {0x0E38, 0xD8}
, {0x0E39, 0xD9}, {0x0E3A, 0xDA}, {0x0E3F, 0xDF}, {0x0E40, 0xE0}
, {0x0E41, 0xE1}, {0x0E42, 0xE2}, {0x0E43, 0xE3}, {0x0E44, 0xE4}
, {0x0E45, 0xE5}, {0x0E46, 0xE6}, {0x0E47, 0xE7}, {0x0E48, 0xE8}
, {0x0E49, 0xE9}, {0x0E4A, 0xEA}, {0x0E4B, 0xEB}, {0x0E4C, 0xEC}
, {0x0E4D, 0xED}, {0x0E4E, 0xEE}, {0x0E4F, 0xEF}, {0x0E50, 0xF0}
, {0x0E51, 0xF1}, {0x0E52, 0xF2}, {0x0E53, 0xF3}, {0x0E54, 0xF4}
, {0x0E55, 0xF5}, {0x0E56, 0xF6}, {0x0E57, 0xF7}, {0x0E58, 0xF8}
, {0x0E59, 0xF9}, {0x0E5A, 0xFA}, {0x0E5B, 0xFB} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif // ! defined(STRF_OMIT_IMPL)
struct impl_iso_8859_13
{
static STRF_HD const char* name() noexcept
{
return "ISO-8859-13";
};
static constexpr strf::charset_id id = strf::csid_iso_8859_13;
static STRF_HD bool is_valid(std::uint8_t)
{
return true;
}
static STRF_HD unsigned encode(char32_t ch)
{
if (ch <= 0xA0) {
return ch;
}
return encode_ext(ch);
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
if (ch <= 0xA0) {
return ch;
}
static const char32_t ext[] =
{ /*A0 */ 0x201D, 0x00A2, 0x00A3, 0x00A4, 0x201E, 0x00A6, 0x00A7
, 0x00D8, 0x00A9, 0x0156, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00C6
, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x201C, 0x00B5, 0x00B6, 0x00B7
, 0x00F8, 0x00B9, 0x0157, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00E6
, 0x0104, 0x012E, 0x0100, 0x0106, 0x00C4, 0x00C5, 0x0118, 0x0112
, 0x010C, 0x00C9, 0x0179, 0x0116, 0x0122, 0x0136, 0x012A, 0x013B
, 0x0160, 0x0143, 0x0145, 0x00D3, 0x014C, 0x00D5, 0x00D6, 0x00D7
, 0x0172, 0x0141, 0x015A, 0x016A, 0x00DC, 0x017B, 0x017D, 0x00DF
, 0x0105, 0x012F, 0x0101, 0x0107, 0x00E4, 0x00E5, 0x0119, 0x0113
, 0x010D, 0x00E9, 0x017A, 0x0117, 0x0123, 0x0137, 0x012B, 0x013C
, 0x0161, 0x0144, 0x0146, 0x00F3, 0x014D, 0x00F5, 0x00F6, 0x00F7
, 0x0173, 0x0142, 0x015B, 0x016B, 0x00FC, 0x017C, 0x017E, 0x2019 };
return ext[ch - 0xA1];
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_iso_8859_13::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x00A2, 0xA2}, {0x00A3, 0xA3}, {0x00A4, 0xA4}, {0x00A6, 0xA6}
, {0x00A7, 0xA7}, {0x00A9, 0xA9}, {0x00AB, 0xAB}, {0x00AC, 0xAC}
, {0x00AD, 0xAD}, {0x00AE, 0xAE}, {0x00B0, 0xB0}, {0x00B1, 0xB1}
, {0x00B2, 0xB2}, {0x00B3, 0xB3}, {0x00B5, 0xB5}, {0x00B6, 0xB6}
, {0x00B7, 0xB7}, {0x00B9, 0xB9}, {0x00BB, 0xBB}, {0x00BC, 0xBC}
, {0x00BD, 0xBD}, {0x00BE, 0xBE}, {0x00C4, 0xC4}, {0x00C5, 0xC5}
, {0x00C6, 0xAF}, {0x00C9, 0xC9}, {0x00D3, 0xD3}, {0x00D5, 0xD5}
, {0x00D6, 0xD6}, {0x00D7, 0xD7}, {0x00D8, 0xA8}, {0x00DC, 0xDC}
, {0x00DF, 0xDF}, {0x00E4, 0xE4}, {0x00E5, 0xE5}, {0x00E6, 0xBF}
, {0x00E9, 0xE9}, {0x00F3, 0xF3}, {0x00F5, 0xF5}, {0x00F6, 0xF6}
, {0x00F7, 0xF7}, {0x00F8, 0xB8}, {0x00FC, 0xFC}, {0x0100, 0xC2}
, {0x0101, 0xE2}, {0x0104, 0xC0}, {0x0105, 0xE0}, {0x0106, 0xC3}
, {0x0107, 0xE3}, {0x010C, 0xC8}, {0x010D, 0xE8}, {0x0112, 0xC7}
, {0x0113, 0xE7}, {0x0116, 0xCB}, {0x0117, 0xEB}, {0x0118, 0xC6}
, {0x0119, 0xE6}, {0x0122, 0xCC}, {0x0123, 0xEC}, {0x012A, 0xCE}
, {0x012B, 0xEE}, {0x012E, 0xC1}, {0x012F, 0xE1}, {0x0136, 0xCD}
, {0x0137, 0xED}, {0x013B, 0xCF}, {0x013C, 0xEF}, {0x0141, 0xD9}
, {0x0142, 0xF9}, {0x0143, 0xD1}, {0x0144, 0xF1}, {0x0145, 0xD2}
, {0x0146, 0xF2}, {0x014C, 0xD4}, {0x014D, 0xF4}, {0x0156, 0xAA}
, {0x0157, 0xBA}, {0x015A, 0xDA}, {0x015B, 0xFA}, {0x0160, 0xD0}
, {0x0161, 0xF0}, {0x016A, 0xDB}, {0x016B, 0xFB}, {0x0172, 0xD8}
, {0x0173, 0xF8}, {0x0179, 0xCA}, {0x017A, 0xEA}, {0x017B, 0xDD}
, {0x017C, 0xFD}, {0x017D, 0xDE}, {0x017E, 0xFE}, {0x2019, 0xFF}
, {0x201C, 0xB4}, {0x201D, 0xA1}, {0x201E, 0xA5} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif // ! defined(STRF_OMIT_IMPL)
struct impl_iso_8859_14
{
static STRF_HD const char* name() noexcept
{
return "ISO-8859-14";
};
static constexpr strf::charset_id id = strf::csid_iso_8859_14;
static STRF_HD bool is_valid(std::uint8_t)
{
return true;
}
static STRF_HD unsigned encode(char32_t ch)
{
if (ch <= 0xA0) {
return ch;
}
return encode_ext(ch);
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
if (ch <= 0xA0) {
return ch;
}
static const char32_t ext[] =
{ /*A0 */ 0x1E02, 0x1E03, 0x00A3, 0x010A, 0x010B, 0x1E0A, 0x00A7
, 0x1E80, 0x00A9, 0x1E82, 0x1E0B, 0x1EF2, 0x00AD, 0x00AE, 0x0178
, 0x1E1E, 0x1E1F, 0x0120, 0x0121, 0x1E40, 0x1E41, 0x00B6, 0x1E56
, 0x1E81, 0x1E57, 0x1E83, 0x1E60, 0x1EF3, 0x1E84, 0x1E85, 0x1E61
, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7
, 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF
, 0x0174, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x1E6A
, 0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x0176, 0x00DF
, 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7
, 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF
, 0x0175, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x1E6B
, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x0177, 0x00FF };
return ext[ch - 0xA1];
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_iso_8859_14::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x00A3, 0xA3}, {0x00A7, 0xA7}, {0x00A9, 0xA9}, {0x00AD, 0xAD}
, {0x00AE, 0xAE}, {0x00B6, 0xB6}, {0x00C0, 0xC0}, {0x00C1, 0xC1}
, {0x00C2, 0xC2}, {0x00C3, 0xC3}, {0x00C4, 0xC4}, {0x00C5, 0xC5}
, {0x00C6, 0xC6}, {0x00C7, 0xC7}, {0x00C8, 0xC8}, {0x00C9, 0xC9}
, {0x00CA, 0xCA}, {0x00CB, 0xCB}, {0x00CC, 0xCC}, {0x00CD, 0xCD}
, {0x00CE, 0xCE}, {0x00CF, 0xCF}, {0x00D1, 0xD1}, {0x00D2, 0xD2}
, {0x00D3, 0xD3}, {0x00D4, 0xD4}, {0x00D5, 0xD5}, {0x00D6, 0xD6}
, {0x00D8, 0xD8}, {0x00D9, 0xD9}, {0x00DA, 0xDA}, {0x00DB, 0xDB}
, {0x00DC, 0xDC}, {0x00DD, 0xDD}, {0x00DF, 0xDF}, {0x00E0, 0xE0}
, {0x00E1, 0xE1}, {0x00E2, 0xE2}, {0x00E3, 0xE3}, {0x00E4, 0xE4}
, {0x00E5, 0xE5}, {0x00E6, 0xE6}, {0x00E7, 0xE7}, {0x00E8, 0xE8}
, {0x00E9, 0xE9}, {0x00EA, 0xEA}, {0x00EB, 0xEB}, {0x00EC, 0xEC}
, {0x00ED, 0xED}, {0x00EE, 0xEE}, {0x00EF, 0xEF}, {0x00F1, 0xF1}
, {0x00F2, 0xF2}, {0x00F3, 0xF3}, {0x00F4, 0xF4}, {0x00F5, 0xF5}
, {0x00F6, 0xF6}, {0x00F8, 0xF8}, {0x00F9, 0xF9}, {0x00FA, 0xFA}
, {0x00FB, 0xFB}, {0x00FC, 0xFC}, {0x00FD, 0xFD}, {0x00FF, 0xFF}
, {0x010A, 0xA4}, {0x010B, 0xA5}, {0x0120, 0xB2}, {0x0121, 0xB3}
, {0x0174, 0xD0}, {0x0175, 0xF0}, {0x0176, 0xDE}, {0x0177, 0xFE}
, {0x0178, 0xAF}, {0x1E02, 0xA1}, {0x1E03, 0xA2}, {0x1E0A, 0xA6}
, {0x1E0B, 0xAB}, {0x1E1E, 0xB0}, {0x1E1F, 0xB1}, {0x1E40, 0xB4}
, {0x1E41, 0xB5}, {0x1E56, 0xB7}, {0x1E57, 0xB9}, {0x1E60, 0xBB}
, {0x1E61, 0xBF}, {0x1E6A, 0xD7}, {0x1E6B, 0xF7}, {0x1E80, 0xA8}
, {0x1E81, 0xB8}, {0x1E82, 0xAA}, {0x1E83, 0xBA}, {0x1E84, 0xBD}
, {0x1E85, 0xBE}, {0x1EF2, 0xAC}, {0x1EF3, 0xBC} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif // ! defined(STRF_OMIT_IMPL)
class impl_iso_8859_15
{
public:
static STRF_HD const char* name() noexcept
{
return "ISO-8859-15";
};
static constexpr strf::charset_id id = strf::csid_iso_8859_15;
static STRF_HD bool is_valid(std::uint8_t)
{
return true;
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
static const unsigned short ext[] = {
/* */ 0x20AC, 0x00A5, 0x0160, 0x00A7,
0x0161, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,
0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x017D, 0x00B5, 0x00B6, 0x00B7,
0x017E, 0x00B9, 0x00BA, 0x00BB, 0x0152, 0x0153, 0x0178
};
STRF_IF_LIKELY (ch <= 0xA3 || 0xBF <= ch)
return ch;
return ext[ch - 0xA4];
}
static STRF_HD unsigned encode(char32_t ch)
{
return (ch < 0xA0 || (0xBE < ch && ch < 0x100)) ? ch : encode_ext(ch);
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_iso_8859_15::encode_ext(char32_t ch)
{
switch(ch) {
case 0x20AC: return 0xA4;
case 0x0160: return 0xA6;
case 0x0161: return 0xA8;
case 0x017D: return 0xB4;
case 0x017E: return 0xB8;
case 0x0152: return 0xBC;
case 0x0153: return 0xBD;
case 0x0178: return 0xBE;
case 0xA4:
case 0xA6:
case 0xA8:
case 0xB4:
case 0xB8:
case 0xBC:
case 0xBD:
case 0xBE:
return 0x100;
}
return ch;
}
#endif // ! defined(STRF_OMIT_IMPL)
struct impl_iso_8859_16
{
static STRF_HD const char* name() noexcept
{
return "ISO-8859-16";
};
static constexpr strf::charset_id id = strf::csid_iso_8859_16;
static STRF_HD bool is_valid(std::uint8_t)
{
return true;
}
static STRF_HD unsigned encode(char32_t ch)
{
if (ch <= 0xA0) {
return ch;
}
return encode_ext(ch);
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
if (ch <= 0xA0) {
return ch;
}
static const char32_t ext[] =
{ /*A0 */ 0x0104, 0x0105, 0x0141, 0x20AC, 0x201E, 0x0160, 0x00A7
, 0x0161, 0x00A9, 0x0218, 0x00AB, 0x0179, 0x00AD, 0x017A, 0x017B
, 0x00B0, 0x00B1, 0x010C, 0x0142, 0x017D, 0x201D, 0x00B6, 0x00B7
, 0x017E, 0x010D, 0x0219, 0x00BB, 0x0152, 0x0153, 0x0178, 0x017C
, 0x00C0, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x0106, 0x00C6, 0x00C7
, 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF
, 0x0110, 0x0143, 0x00D2, 0x00D3, 0x00D4, 0x0150, 0x00D6, 0x015A
, 0x0170, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x0118, 0x021A, 0x00DF
, 0x00E0, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x0107, 0x00E6, 0x00E7
, 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF
, 0x0111, 0x0144, 0x00F2, 0x00F3, 0x00F4, 0x0151, 0x00F6, 0x015B
, 0x0171, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x0119, 0x021B, 0x00FF };
return ext[ch - 0xA1];
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_iso_8859_16::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x00A7, 0xA7}, {0x00A9, 0xA9}, {0x00AB, 0xAB}, {0x00AD, 0xAD}
, {0x00B0, 0xB0}, {0x00B1, 0xB1}, {0x00B6, 0xB6}, {0x00B7, 0xB7}
, {0x00BB, 0xBB}, {0x00C0, 0xC0}, {0x00C1, 0xC1}, {0x00C2, 0xC2}
, {0x00C4, 0xC4}, {0x00C6, 0xC6}, {0x00C7, 0xC7}, {0x00C8, 0xC8}
, {0x00C9, 0xC9}, {0x00CA, 0xCA}, {0x00CB, 0xCB}, {0x00CC, 0xCC}
, {0x00CD, 0xCD}, {0x00CE, 0xCE}, {0x00CF, 0xCF}, {0x00D2, 0xD2}
, {0x00D3, 0xD3}, {0x00D4, 0xD4}, {0x00D6, 0xD6}, {0x00D9, 0xD9}
, {0x00DA, 0xDA}, {0x00DB, 0xDB}, {0x00DC, 0xDC}, {0x00DF, 0xDF}
, {0x00E0, 0xE0}, {0x00E1, 0xE1}, {0x00E2, 0xE2}, {0x00E4, 0xE4}
, {0x00E6, 0xE6}, {0x00E7, 0xE7}, {0x00E8, 0xE8}, {0x00E9, 0xE9}
, {0x00EA, 0xEA}, {0x00EB, 0xEB}, {0x00EC, 0xEC}, {0x00ED, 0xED}
, {0x00EE, 0xEE}, {0x00EF, 0xEF}, {0x00F2, 0xF2}, {0x00F3, 0xF3}
, {0x00F4, 0xF4}, {0x00F6, 0xF6}, {0x00F9, 0xF9}, {0x00FA, 0xFA}
, {0x00FB, 0xFB}, {0x00FC, 0xFC}, {0x00FF, 0xFF}, {0x0102, 0xC3}
, {0x0103, 0xE3}, {0x0104, 0xA1}, {0x0105, 0xA2}, {0x0106, 0xC5}
, {0x0107, 0xE5}, {0x010C, 0xB2}, {0x010D, 0xB9}, {0x0110, 0xD0}
, {0x0111, 0xF0}, {0x0118, 0xDD}, {0x0119, 0xFD}, {0x0141, 0xA3}
, {0x0142, 0xB3}, {0x0143, 0xD1}, {0x0144, 0xF1}, {0x0150, 0xD5}
, {0x0151, 0xF5}, {0x0152, 0xBC}, {0x0153, 0xBD}, {0x015A, 0xD7}
, {0x015B, 0xF7}, {0x0160, 0xA6}, {0x0161, 0xA8}, {0x0170, 0xD8}
, {0x0171, 0xF8}, {0x0178, 0xBE}, {0x0179, 0xAC}, {0x017A, 0xAE}
, {0x017B, 0xAF}, {0x017C, 0xBF}, {0x017D, 0xB4}, {0x017E, 0xB8}
, {0x0218, 0xAA}, {0x0219, 0xBA}, {0x021A, 0xDE}, {0x021B, 0xFE}
, {0x201D, 0xB5}, {0x201E, 0xA5}, {0x20AC, 0xA4} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif // ! defined(STRF_OMIT_IMPL)
class impl_windows_1250
{
public:
static STRF_HD const char* name() noexcept
{
return "windows-1250";
};
static constexpr strf::charset_id id = strf::csid_windows_1250;
static STRF_HD bool is_valid(std::uint8_t)
{
return true;
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
STRF_IF_LIKELY (ch < 0x80) {
return ch;
} else {
static const char32_t ext[] =
{ 0x20AC, 0x0081, 0x201A, 0x0083, 0x201E, 0x2026, 0x2020, 0x2021
, 0x0088, 0x2030, 0x0160, 0x2039, 0x015A, 0x0164, 0x017D, 0x0179
, 0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014
, 0x0098, 0x2122, 0x0161, 0x203A, 0x015B, 0x0165, 0x017E, 0x017A
, 0x00A0, 0x02C7, 0x02D8, 0x0141, 0x00A4, 0x0104, 0x00A6, 0x00A7
, 0x00A8, 0x00A9, 0x015E, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x017B
, 0x00B0, 0x00B1, 0x02DB, 0x0142, 0x00B4, 0x00B5, 0x00B6, 0x00B7
, 0x00B8, 0x0105, 0x015F, 0x00BB, 0x013D, 0x02DD, 0x013E, 0x017C
, 0x0154, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x0139, 0x0106, 0x00C7
, 0x010C, 0x00C9, 0x0118, 0x00CB, 0x011A, 0x00CD, 0x00CE, 0x010E
, 0x0110, 0x0143, 0x0147, 0x00D3, 0x00D4, 0x0150, 0x00D6, 0x00D7
, 0x0158, 0x016E, 0x00DA, 0x0170, 0x00DC, 0x00DD, 0x0162, 0x00DF
, 0x0155, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x013A, 0x0107, 0x00E7
, 0x010D, 0x00E9, 0x0119, 0x00EB, 0x011B, 0x00ED, 0x00EE, 0x010F
, 0x0111, 0x0144, 0x0148, 0x00F3, 0x00F4, 0x0151, 0x00F6, 0x00F7
, 0x0159, 0x016F, 0x00FA, 0x0171, 0x00FC, 0x00FD, 0x0163, 0x02D9 };
return ext[ch - 0x80];
}
}
static STRF_HD unsigned encode(char32_t ch)
{
return ch < 0x80 ? ch : encode_ext(ch);
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_windows_1250::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x0081, 0x81}, {0x0083, 0x83}, {0x0088, 0x88}, {0x0090, 0x90}
, {0x0098, 0x98}, {0x00A0, 0xA0}, {0x00A4, 0xA4}, {0x00A6, 0xA6}
, {0x00A7, 0xA7}, {0x00A8, 0xA8}, {0x00A9, 0xA9}, {0x00AB, 0xAB}
, {0x00AC, 0xAC}, {0x00AD, 0xAD}, {0x00AE, 0xAE}, {0x00B0, 0xB0}
, {0x00B1, 0xB1}, {0x00B4, 0xB4}, {0x00B5, 0xB5}, {0x00B6, 0xB6}
, {0x00B7, 0xB7}, {0x00B8, 0xB8}, {0x00BB, 0xBB}, {0x00C1, 0xC1}
, {0x00C2, 0xC2}, {0x00C4, 0xC4}, {0x00C7, 0xC7}, {0x00C9, 0xC9}
, {0x00CB, 0xCB}, {0x00CD, 0xCD}, {0x00CE, 0xCE}, {0x00D3, 0xD3}
, {0x00D4, 0xD4}, {0x00D6, 0xD6}, {0x00D7, 0xD7}, {0x00DA, 0xDA}
, {0x00DC, 0xDC}, {0x00DD, 0xDD}, {0x00DF, 0xDF}, {0x00E1, 0xE1}
, {0x00E2, 0xE2}, {0x00E4, 0xE4}, {0x00E7, 0xE7}, {0x00E9, 0xE9}
, {0x00EB, 0xEB}, {0x00ED, 0xED}, {0x00EE, 0xEE}, {0x00F3, 0xF3}
, {0x00F4, 0xF4}, {0x00F6, 0xF6}, {0x00F7, 0xF7}, {0x00FA, 0xFA}
, {0x00FC, 0xFC}, {0x00FD, 0xFD}, {0x0102, 0xC3}, {0x0103, 0xE3}
, {0x0104, 0xA5}, {0x0105, 0xB9}, {0x0106, 0xC6}, {0x0107, 0xE6}
, {0x010C, 0xC8}, {0x010D, 0xE8}, {0x010E, 0xCF}, {0x010F, 0xEF}
, {0x0110, 0xD0}, {0x0111, 0xF0}, {0x0118, 0xCA}, {0x0119, 0xEA}
, {0x011A, 0xCC}, {0x011B, 0xEC}, {0x0139, 0xC5}, {0x013A, 0xE5}
, {0x013D, 0xBC}, {0x013E, 0xBE}, {0x0141, 0xA3}, {0x0142, 0xB3}
, {0x0143, 0xD1}, {0x0144, 0xF1}, {0x0147, 0xD2}, {0x0148, 0xF2}
, {0x0150, 0xD5}, {0x0151, 0xF5}, {0x0154, 0xC0}, {0x0155, 0xE0}
, {0x0158, 0xD8}, {0x0159, 0xF8}, {0x015A, 0x8C}, {0x015B, 0x9C}
, {0x015E, 0xAA}, {0x015F, 0xBA}, {0x0160, 0x8A}, {0x0161, 0x9A}
, {0x0162, 0xDE}, {0x0163, 0xFE}, {0x0164, 0x8D}, {0x0165, 0x9D}
, {0x016E, 0xD9}, {0x016F, 0xF9}, {0x0170, 0xDB}, {0x0171, 0xFB}
, {0x0179, 0x8F}, {0x017A, 0x9F}, {0x017B, 0xAF}, {0x017C, 0xBF}
, {0x017D, 0x8E}, {0x017E, 0x9E}, {0x02C7, 0xA1}, {0x02D8, 0xA2}
, {0x02D9, 0xFF}, {0x02DB, 0xB2}, {0x02DD, 0xBD}, {0x2013, 0x96}
, {0x2014, 0x97}, {0x2018, 0x91}, {0x2019, 0x92}, {0x201A, 0x82}
, {0x201C, 0x93}, {0x201D, 0x94}, {0x201E, 0x84}, {0x2020, 0x86}
, {0x2021, 0x87}, {0x2022, 0x95}, {0x2026, 0x85}, {0x2030, 0x89}
, {0x2039, 0x8B}, {0x203A, 0x9B}, {0x20AC, 0x80}, {0x2122, 0x99} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
};
#endif // ! defined(STRF_OMIT_IMPL)
class impl_windows_1251
{
public:
static STRF_HD const char* name() noexcept
{
return "windows-1251";
};
static constexpr strf::charset_id id = strf::csid_windows_1251;
static STRF_HD bool is_valid(std::uint8_t)
{
return true;
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
STRF_IF_LIKELY (ch < 0x80) {
return ch;
}
else {
static const unsigned short ext[] =
{ 0x0402, 0x0403, 0x201A, 0x0453, 0x201E, 0x2026, 0x2020, 0x2021
, 0x20AC, 0x2030, 0x0409, 0x2039, 0x040A, 0x040C, 0x040B, 0x040F
, 0x0452, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014
, 0x0098, 0x2122, 0x0459, 0x203A, 0x045A, 0x045C, 0x045B, 0x045F
, 0x00A0, 0x040E, 0x045E, 0x0408, 0x00A4, 0x0490, 0x00A6, 0x00A7
, 0x0401, 0x00A9, 0x0404, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x0407
, 0x00B0, 0x00B1, 0x0406, 0x0456, 0x0491, 0x00B5, 0x00B6, 0x00B7
, 0x0451, 0x2116, 0x0454, 0x00BB, 0x0458, 0x0405, 0x0455, 0x0457
, 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417
, 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F
, 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427
, 0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F
, 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437
, 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F
, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447
, 0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D, 0x044E, 0x044F };
return ext[ch - 0x80];
}
}
static STRF_HD unsigned encode(char32_t ch)
{
return ch < 0x80 ? ch : encode_ext(ch);
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_windows_1251::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x0098, 0x98}, {0x00A0, 0xA0}, {0x00A4, 0xA4}, {0x00A6, 0xA6}
, {0x00A7, 0xA7}, {0x00A9, 0xA9}, {0x00AB, 0xAB}, {0x00AC, 0xAC}
, {0x00AD, 0xAD}, {0x00AE, 0xAE}, {0x00B0, 0xB0}, {0x00B1, 0xB1}
, {0x00B5, 0xB5}, {0x00B6, 0xB6}, {0x00B7, 0xB7}, {0x00BB, 0xBB}
, {0x0401, 0xA8}, {0x0402, 0x80}, {0x0403, 0x81}, {0x0404, 0xAA}
, {0x0405, 0xBD}, {0x0406, 0xB2}, {0x0407, 0xAF}, {0x0408, 0xA3}
, {0x0409, 0x8A}, {0x040A, 0x8C}, {0x040B, 0x8E}, {0x040C, 0x8D}
, {0x040E, 0xA1}, {0x040F, 0x8F}, {0x0410, 0xC0}, {0x0411, 0xC1}
, {0x0412, 0xC2}, {0x0413, 0xC3}, {0x0414, 0xC4}, {0x0415, 0xC5}
, {0x0416, 0xC6}, {0x0417, 0xC7}, {0x0418, 0xC8}, {0x0419, 0xC9}
, {0x041A, 0xCA}, {0x041B, 0xCB}, {0x041C, 0xCC}, {0x041D, 0xCD}
, {0x041E, 0xCE}, {0x041F, 0xCF}, {0x0420, 0xD0}, {0x0421, 0xD1}
, {0x0422, 0xD2}, {0x0423, 0xD3}, {0x0424, 0xD4}, {0x0425, 0xD5}
, {0x0426, 0xD6}, {0x0427, 0xD7}, {0x0428, 0xD8}, {0x0429, 0xD9}
, {0x042A, 0xDA}, {0x042B, 0xDB}, {0x042C, 0xDC}, {0x042D, 0xDD}
, {0x042E, 0xDE}, {0x042F, 0xDF}, {0x0430, 0xE0}, {0x0431, 0xE1}
, {0x0432, 0xE2}, {0x0433, 0xE3}, {0x0434, 0xE4}, {0x0435, 0xE5}
, {0x0436, 0xE6}, {0x0437, 0xE7}, {0x0438, 0xE8}, {0x0439, 0xE9}
, {0x043A, 0xEA}, {0x043B, 0xEB}, {0x043C, 0xEC}, {0x043D, 0xED}
, {0x043E, 0xEE}, {0x043F, 0xEF}, {0x0440, 0xF0}, {0x0441, 0xF1}
, {0x0442, 0xF2}, {0x0443, 0xF3}, {0x0444, 0xF4}, {0x0445, 0xF5}
, {0x0446, 0xF6}, {0x0447, 0xF7}, {0x0448, 0xF8}, {0x0449, 0xF9}
, {0x044A, 0xFA}, {0x044B, 0xFB}, {0x044C, 0xFC}, {0x044D, 0xFD}
, {0x044E, 0xFE}, {0x044F, 0xFF}, {0x0451, 0xB8}, {0x0452, 0x90}
, {0x0453, 0x83}, {0x0454, 0xBA}, {0x0455, 0xBE}, {0x0456, 0xB3}
, {0x0457, 0xBF}, {0x0458, 0xBC}, {0x0459, 0x9A}, {0x045A, 0x9C}
, {0x045B, 0x9E}, {0x045C, 0x9D}, {0x045E, 0xA2}, {0x045F, 0x9F}
, {0x0490, 0xA5}, {0x0491, 0xB4}, {0x2013, 0x96}, {0x2014, 0x97}
, {0x2018, 0x91}, {0x2019, 0x92}, {0x201A, 0x82}, {0x201C, 0x93}
, {0x201D, 0x94}, {0x201E, 0x84}, {0x2020, 0x86}, {0x2021, 0x87}
, {0x2022, 0x95}, {0x2026, 0x85}, {0x2030, 0x89}, {0x2039, 0x8B}
, {0x203A, 0x9B}, {0x20AC, 0x88}, {0x2116, 0xB9}, {0x2122, 0x99} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif //! defined(STRF_OMIT_IMPL)
class impl_windows_1252
{
public:
static STRF_HD const char* name() noexcept
{
return "windows-1252";
};
static constexpr strf::charset_id id = strf::csid_windows_1252;
static STRF_HD bool is_valid(std::uint8_t)
{
return true;
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
STRF_IF_LIKELY (ch < 0x80 || 0x9F < ch) {
return ch;
}
else {
static const unsigned short ext[] = {
0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,
0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F,
0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,
0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178,
};
return ext[ch - 0x80];
}
}
static STRF_HD unsigned encode(char32_t ch)
{
return (ch < 0x80 || (0x9F < ch && ch < 0x100)) ? ch : encode_ext(ch);
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_windows_1252::encode_ext(char32_t ch)
{
switch(ch) {
case 0x81: return 0x81;
case 0x8D: return 0x8D;
case 0x8F: return 0x8F;
case 0x90: return 0x90;
case 0x9D: return 0x9D;
case 0x20AC: return 0x80;
case 0x201A: return 0x82;
case 0x0192: return 0x83;
case 0x201E: return 0x84;
case 0x2026: return 0x85;
case 0x2020: return 0x86;
case 0x2021: return 0x87;
case 0x02C6: return 0x88;
case 0x2030: return 0x89;
case 0x0160: return 0x8A;
case 0x2039: return 0x8B;
case 0x0152: return 0x8C;
case 0x017D: return 0x8E;
case 0x2018: return 0x91;
case 0x2019: return 0x92;
case 0x201C: return 0x93;
case 0x201D: return 0x94;
case 0x2022: return 0x95;
case 0x2013: return 0x96;
case 0x2014: return 0x97;
case 0x02DC: return 0x98;
case 0x2122: return 0x99;
case 0x0161: return 0x9A;
case 0x203A: return 0x9B;
case 0x0153: return 0x9C;
case 0x017E: return 0x9E;
case 0x0178: return 0x9F;
}
return 0x100;
}
#endif // ! defined(STRF_OMIT_IMPL)
class impl_windows_1253
{
public:
static STRF_HD const char* name() noexcept
{
return "windows-1253";
};
static constexpr strf::charset_id id = strf::csid_windows_1253;
static STRF_HD bool is_valid(std::uint8_t ch)
{
return ch != 0xAA && ch != 0xD2 && ch != 0xFF ;
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
STRF_IF_LIKELY (ch < 0x80) {
return ch;
}
else {
static const unsigned short ext[] =
{ 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021
, 0x0088, 0x2030, 0x008A, 0x2039, 0x008C, 0x008D, 0x008E, 0x008F
, 0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014
, 0x0098, 0x2122, 0x009A, 0x203A, 0x009C, 0x009D, 0x009E, 0x009F
, 0x00A0, 0x0385, 0x0386, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7
, 0x00A8, 0x00A9, 0xFFFD, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x2015
, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x0384, 0x00B5, 0x00B6, 0x00B7
, 0x0388, 0x0389, 0x038A, 0x00BB, 0x038C, 0x00BD, 0x038E, 0x038F
, 0x0390, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397
, 0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F
, 0x03A0, 0x03A1, 0xFFFD, 0x03A3, 0x03A4, 0x03A5, 0x03A6, 0x03A7
, 0x03A8, 0x03A9, 0x03AA, 0x03AB, 0x03AC, 0x03AD, 0x03AE, 0x03AF
, 0x03B0, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7
, 0x03B8, 0x03B9, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BE, 0x03BF
, 0x03C0, 0x03C1, 0x03C2, 0x03C3, 0x03C4, 0x03C5, 0x03C6, 0x03C7
, 0x03C8, 0x03C9, 0x03CA, 0x03CB, 0x03CC, 0x03CD, 0x03CE, 0xFFFD };
return ext[ch - 0x80];
}
}
static STRF_HD unsigned encode(char32_t ch)
{
return (ch < 0x80) ? ch : encode_ext(ch);
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_windows_1253::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x0081, 0x81}, {0x0088, 0x88}, {0x008A, 0x8A}, {0x008C, 0x8C}
, {0x008D, 0x8D}, {0x008E, 0x8E}, {0x008F, 0x8F}, {0x0090, 0x90}
, {0x0098, 0x98}, {0x009A, 0x9A}, {0x009C, 0x9C}, {0x009D, 0x9D}
, {0x009E, 0x9E}, {0x009F, 0x9F}, {0x00A0, 0xA0}, {0x00A3, 0xA3}
, {0x00A4, 0xA4}, {0x00A5, 0xA5}, {0x00A6, 0xA6}, {0x00A7, 0xA7}
, {0x00A8, 0xA8}, {0x00A9, 0xA9}, {0x00AB, 0xAB}, {0x00AC, 0xAC}
, {0x00AD, 0xAD}, {0x00AE, 0xAE}, {0x00B0, 0xB0}, {0x00B1, 0xB1}
, {0x00B2, 0xB2}, {0x00B3, 0xB3}, {0x00B5, 0xB5}, {0x00B6, 0xB6}
, {0x00B7, 0xB7}, {0x00BB, 0xBB}, {0x00BD, 0xBD}, {0x0192, 0x83}
, {0x0384, 0xB4}, {0x0385, 0xA1}, {0x0386, 0xA2}, {0x0388, 0xB8}
, {0x0389, 0xB9}, {0x038A, 0xBA}, {0x038C, 0xBC}, {0x038E, 0xBE}
, {0x038F, 0xBF}, {0x0390, 0xC0}, {0x0391, 0xC1}, {0x0392, 0xC2}
, {0x0393, 0xC3}, {0x0394, 0xC4}, {0x0395, 0xC5}, {0x0396, 0xC6}
, {0x0397, 0xC7}, {0x0398, 0xC8}, {0x0399, 0xC9}, {0x039A, 0xCA}
, {0x039B, 0xCB}, {0x039C, 0xCC}, {0x039D, 0xCD}, {0x039E, 0xCE}
, {0x039F, 0xCF}, {0x03A0, 0xD0}, {0x03A1, 0xD1}, {0x03A3, 0xD3}
, {0x03A4, 0xD4}, {0x03A5, 0xD5}, {0x03A6, 0xD6}, {0x03A7, 0xD7}
, {0x03A8, 0xD8}, {0x03A9, 0xD9}, {0x03AA, 0xDA}, {0x03AB, 0xDB}
, {0x03AC, 0xDC}, {0x03AD, 0xDD}, {0x03AE, 0xDE}, {0x03AF, 0xDF}
, {0x03B0, 0xE0}, {0x03B1, 0xE1}, {0x03B2, 0xE2}, {0x03B3, 0xE3}
, {0x03B4, 0xE4}, {0x03B5, 0xE5}, {0x03B6, 0xE6}, {0x03B7, 0xE7}
, {0x03B8, 0xE8}, {0x03B9, 0xE9}, {0x03BA, 0xEA}, {0x03BB, 0xEB}
, {0x03BC, 0xEC}, {0x03BD, 0xED}, {0x03BE, 0xEE}, {0x03BF, 0xEF}
, {0x03C0, 0xF0}, {0x03C1, 0xF1}, {0x03C2, 0xF2}, {0x03C3, 0xF3}
, {0x03C4, 0xF4}, {0x03C5, 0xF5}, {0x03C6, 0xF6}, {0x03C7, 0xF7}
, {0x03C8, 0xF8}, {0x03C9, 0xF9}, {0x03CA, 0xFA}, {0x03CB, 0xFB}
, {0x03CC, 0xFC}, {0x03CD, 0xFD}, {0x03CE, 0xFE}, {0x2013, 0x96}
, {0x2014, 0x97}, {0x2015, 0xAF}, {0x2018, 0x91}, {0x2019, 0x92}
, {0x201A, 0x82}, {0x201C, 0x93}, {0x201D, 0x94}, {0x201E, 0x84}
, {0x2020, 0x86}, {0x2021, 0x87}, {0x2022, 0x95}, {0x2026, 0x85}
, {0x2030, 0x89}, {0x2039, 0x8B}, {0x203A, 0x9B}, {0x20AC, 0x80}
, {0x2122, 0x99} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif //! defined(STRF_OMIT_IMPL)
class impl_windows_1254
{
public:
static STRF_HD const char* name() noexcept
{
return "windows-1254";
};
static constexpr strf::charset_id id = strf::csid_windows_1254;
static STRF_HD bool is_valid(std::uint8_t)
{
return true;
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
if (ch <= 0x7F) {
return ch;
}
else if (ch <= 0x9F) {
static const unsigned short ext[] =
{ 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021
, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x008E, 0x008F
, 0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014
, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x009E, 0x0178 };
return ext[ch - 0x80];
}
switch (ch) {
case 0xD0: return 0x011E;
case 0xDD: return 0x0130;
case 0xDE: return 0x015E;
case 0xF0: return 0x011F;
case 0xFD: return 0x0131;
case 0xFE: return 0x015F;
}
return ch;
}
static STRF_HD unsigned encode(char32_t ch)
{
return ch < 0x80 ? ch : encode_ext(ch);
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_windows_1254::encode_ext(char32_t ch)
{
switch(ch) {
case 0x81: return 0x81;
case 0x8D: return 0x8D;
case 0x8E: return 0x8E;
case 0x8F: return 0x8F;
case 0x90: return 0x90;
case 0x9D: return 0x9D;
case 0x9E: return 0x9E;
case 0x011E: return 0xD0;
case 0x011F: return 0xF0;
case 0x0130: return 0xDD;
case 0x0131: return 0xFD;
case 0x0152: return 0x8C;
case 0x0153: return 0x9C;
case 0x015E: return 0xDE;
case 0x015F: return 0xFE;
case 0x0160: return 0x8A;
case 0x0161: return 0x9A;
case 0x0178: return 0x9F;
case 0x0192: return 0x83;
case 0x02C6: return 0x88;
case 0x02DC: return 0x98;
case 0x2013: return 0x96;
case 0x2014: return 0x97;
case 0x2018: return 0x91;
case 0x2019: return 0x92;
case 0x201A: return 0x82;
case 0x201C: return 0x93;
case 0x201D: return 0x94;
case 0x201E: return 0x84;
case 0x2020: return 0x86;
case 0x2021: return 0x87;
case 0x2022: return 0x95;
case 0x2026: return 0x85;
case 0x2030: return 0x89;
case 0x2039: return 0x8B;
case 0x203A: return 0x9B;
case 0x20AC: return 0x80;
case 0x2122: return 0x99;
}
return 0xA0 <= ch && ch <= 0xFF ? ch : 0x100;
}
#endif //! defined(STRF_OMIT_IMPL)
class impl_windows_1255
{
public:
static STRF_HD const char* name() noexcept
{
return "windows-1255";
};
static constexpr strf::charset_id id = strf::csid_windows_1255;
static STRF_HD bool is_valid(std::uint8_t ch)
{
return ch != 0xD9 && ch != 0xDA && ch != 0xDB && ch != 0xDC
&& ch != 0xDD && ch != 0xDE && ch != 0xDF && ch != 0xFB
&& ch != 0xFC && ch != 0xFF;
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
STRF_IF_LIKELY (ch < 0x80) {
return ch;
}
else {
static const unsigned short ext[] =
{ 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021
, 0x02C6, 0x2030, 0x008A, 0x2039, 0x008C, 0x008D, 0x008E, 0x008F
, 0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014
, 0x02DC, 0x2122, 0x009A, 0x203A, 0x009C, 0x009D, 0x009E, 0x009F
, 0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x20AA, 0x00A5, 0x00A6, 0x00A7
, 0x00A8, 0x00A9, 0x00D7, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF
, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7
, 0x00B8, 0x00B9, 0x00F7, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF
, 0x05B0, 0x05B1, 0x05B2, 0x05B3, 0x05B4, 0x05B5, 0x05B6, 0x05B7
, 0x05B8, 0x05B9, 0x05BA, 0x05BB, 0x05BC, 0x05BD, 0x05BE, 0x05BF
, 0x05C0, 0x05C1, 0x05C2, 0x05C3, 0x05F0, 0x05F1, 0x05F2, 0x05F3
, 0x05F4, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD
, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7
, 0x05D8, 0x05D9, 0x05DA, 0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF
, 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7
, 0x05E8, 0x05E9, 0x05EA, 0xFFFD, 0xFFFD, 0x200E, 0x200F, 0xFFFD
};
return ext[ch - 0x80];
}
}
static STRF_HD unsigned encode(char32_t ch)
{
return (ch < 0x80) ? ch : encode_ext(ch);
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_windows_1255::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x0081, 0x81}, {0x008A, 0x8A}, {0x008C, 0x8C}, {0x008D, 0x8D}
, {0x008E, 0x8E}, {0x008F, 0x8F}, {0x0090, 0x90}, {0x009A, 0x9A}
, {0x009C, 0x9C}, {0x009D, 0x9D}, {0x009E, 0x9E}, {0x009F, 0x9F}
, {0x00A0, 0xA0}, {0x00A1, 0xA1}, {0x00A2, 0xA2}, {0x00A3, 0xA3}
, {0x00A5, 0xA5}, {0x00A6, 0xA6}, {0x00A7, 0xA7}, {0x00A8, 0xA8}
, {0x00A9, 0xA9}, {0x00AB, 0xAB}, {0x00AC, 0xAC}, {0x00AD, 0xAD}
, {0x00AE, 0xAE}, {0x00AF, 0xAF}, {0x00B0, 0xB0}, {0x00B1, 0xB1}
, {0x00B2, 0xB2}, {0x00B3, 0xB3}, {0x00B4, 0xB4}, {0x00B5, 0xB5}
, {0x00B6, 0xB6}, {0x00B7, 0xB7}, {0x00B8, 0xB8}, {0x00B9, 0xB9}
, {0x00BB, 0xBB}, {0x00BC, 0xBC}, {0x00BD, 0xBD}, {0x00BE, 0xBE}
, {0x00BF, 0xBF}, {0x00D7, 0xAA}, {0x00F7, 0xBA}, {0x0192, 0x83}
, {0x02C6, 0x88}, {0x02DC, 0x98}, {0x05B0, 0xC0}, {0x05B1, 0xC1}
, {0x05B2, 0xC2}, {0x05B3, 0xC3}, {0x05B4, 0xC4}, {0x05B5, 0xC5}
, {0x05B6, 0xC6}, {0x05B7, 0xC7}, {0x05B8, 0xC8}, {0x05B9, 0xC9}
, {0x05BA, 0xCA}, {0x05BB, 0xCB}, {0x05BC, 0xCC}, {0x05BD, 0xCD}
, {0x05BE, 0xCE}, {0x05BF, 0xCF}, {0x05C0, 0xD0}, {0x05C1, 0xD1}
, {0x05C2, 0xD2}, {0x05C3, 0xD3}, {0x05D0, 0xE0}, {0x05D1, 0xE1}
, {0x05D2, 0xE2}, {0x05D3, 0xE3}, {0x05D4, 0xE4}, {0x05D5, 0xE5}
, {0x05D6, 0xE6}, {0x05D7, 0xE7}, {0x05D8, 0xE8}, {0x05D9, 0xE9}
, {0x05DA, 0xEA}, {0x05DB, 0xEB}, {0x05DC, 0xEC}, {0x05DD, 0xED}
, {0x05DE, 0xEE}, {0x05DF, 0xEF}, {0x05E0, 0xF0}, {0x05E1, 0xF1}
, {0x05E2, 0xF2}, {0x05E3, 0xF3}, {0x05E4, 0xF4}, {0x05E5, 0xF5}
, {0x05E6, 0xF6}, {0x05E7, 0xF7}, {0x05E8, 0xF8}, {0x05E9, 0xF9}
, {0x05EA, 0xFA}, {0x05F0, 0xD4}, {0x05F1, 0xD5}, {0x05F2, 0xD6}
, {0x05F3, 0xD7}, {0x05F4, 0xD8}, {0x200E, 0xFD}, {0x200F, 0xFE}
, {0x2013, 0x96}, {0x2014, 0x97}, {0x2018, 0x91}, {0x2019, 0x92}
, {0x201A, 0x82}, {0x201C, 0x93}, {0x201D, 0x94}, {0x201E, 0x84}
, {0x2020, 0x86}, {0x2021, 0x87}, {0x2022, 0x95}, {0x2026, 0x85}
, {0x2030, 0x89}, {0x2039, 0x8B}, {0x203A, 0x9B}, {0x20AA, 0xA4}
, {0x20AC, 0x80}, {0x2122, 0x99}};
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif //! defined(STRF_OMIT_IMPL)
class impl_windows_1256
{
public:
static STRF_HD const char* name() noexcept
{
return "windows-1256";
};
static constexpr strf::charset_id id = strf::csid_windows_1256;
static STRF_HD bool is_valid(std::uint8_t)
{
return true;
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
STRF_IF_LIKELY (ch < 0x80) {
return ch;
}
else {
static const unsigned short ext[] =
{ 0x20AC, 0x067E, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021
, 0x02C6, 0x2030, 0x0679, 0x2039, 0x0152, 0x0686, 0x0698, 0x0688
, 0x06AF, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014
, 0x06A9, 0x2122, 0x0691, 0x203A, 0x0153, 0x200C, 0x200D, 0x06BA
, 0x00A0, 0x060C, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7
, 0x00A8, 0x00A9, 0x06BE, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF
, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7
, 0x00B8, 0x00B9, 0x061B, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x061F
, 0x06C1, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627
, 0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F
, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x00D7
, 0x0637, 0x0638, 0x0639, 0x063A, 0x0640, 0x0641, 0x0642, 0x0643
, 0x00E0, 0x0644, 0x00E2, 0x0645, 0x0646, 0x0647, 0x0648, 0x00E7
, 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x0649, 0x064A, 0x00EE, 0x00EF
, 0x064B, 0x064C, 0x064D, 0x064E, 0x00F4, 0x064F, 0x0650, 0x00F7
, 0x0651, 0x00F9, 0x0652, 0x00FB, 0x00FC, 0x200E, 0x200F, 0x06D2 };
return ext[ch - 0x80];
}
}
static STRF_HD unsigned encode(char32_t ch)
{
return (ch < 0x80) ? ch : encode_ext(ch);
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_windows_1256::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x00A0, 0xA0}, {0x00A2, 0xA2}, {0x00A3, 0xA3}, {0x00A4, 0xA4}
, {0x00A5, 0xA5}, {0x00A6, 0xA6}, {0x00A7, 0xA7}, {0x00A8, 0xA8}
, {0x00A9, 0xA9}, {0x00AB, 0xAB}, {0x00AC, 0xAC}, {0x00AD, 0xAD}
, {0x00AE, 0xAE}, {0x00AF, 0xAF}, {0x00B0, 0xB0}, {0x00B1, 0xB1}
, {0x00B2, 0xB2}, {0x00B3, 0xB3}, {0x00B4, 0xB4}, {0x00B5, 0xB5}
, {0x00B6, 0xB6}, {0x00B7, 0xB7}, {0x00B8, 0xB8}, {0x00B9, 0xB9}
, {0x00BB, 0xBB}, {0x00BC, 0xBC}, {0x00BD, 0xBD}, {0x00BE, 0xBE}
, {0x00D7, 0xD7}, {0x00E0, 0xE0}, {0x00E2, 0xE2}, {0x00E7, 0xE7}
, {0x00E8, 0xE8}, {0x00E9, 0xE9}, {0x00EA, 0xEA}, {0x00EB, 0xEB}
, {0x00EE, 0xEE}, {0x00EF, 0xEF}, {0x00F4, 0xF4}, {0x00F7, 0xF7}
, {0x00F9, 0xF9}, {0x00FB, 0xFB}, {0x00FC, 0xFC}, {0x0152, 0x8C}
, {0x0153, 0x9C}, {0x0192, 0x83}, {0x02C6, 0x88}, {0x060C, 0xA1}
, {0x061B, 0xBA}, {0x061F, 0xBF}, {0x0621, 0xC1}, {0x0622, 0xC2}
, {0x0623, 0xC3}, {0x0624, 0xC4}, {0x0625, 0xC5}, {0x0626, 0xC6}
, {0x0627, 0xC7}, {0x0628, 0xC8}, {0x0629, 0xC9}, {0x062A, 0xCA}
, {0x062B, 0xCB}, {0x062C, 0xCC}, {0x062D, 0xCD}, {0x062E, 0xCE}
, {0x062F, 0xCF}, {0x0630, 0xD0}, {0x0631, 0xD1}, {0x0632, 0xD2}
, {0x0633, 0xD3}, {0x0634, 0xD4}, {0x0635, 0xD5}, {0x0636, 0xD6}
, {0x0637, 0xD8}, {0x0638, 0xD9}, {0x0639, 0xDA}, {0x063A, 0xDB}
, {0x0640, 0xDC}, {0x0641, 0xDD}, {0x0642, 0xDE}, {0x0643, 0xDF}
, {0x0644, 0xE1}, {0x0645, 0xE3}, {0x0646, 0xE4}, {0x0647, 0xE5}
, {0x0648, 0xE6}, {0x0649, 0xEC}, {0x064A, 0xED}, {0x064B, 0xF0}
, {0x064C, 0xF1}, {0x064D, 0xF2}, {0x064E, 0xF3}, {0x064F, 0xF5}
, {0x0650, 0xF6}, {0x0651, 0xF8}, {0x0652, 0xFA}, {0x0679, 0x8A}
, {0x067E, 0x81}, {0x0686, 0x8D}, {0x0688, 0x8F}, {0x0691, 0x9A}
, {0x0698, 0x8E}, {0x06A9, 0x98}, {0x06AF, 0x90}, {0x06BA, 0x9F}
, {0x06BE, 0xAA}, {0x06C1, 0xC0}, {0x06D2, 0xFF}, {0x200C, 0x9D}
, {0x200D, 0x9E}, {0x200E, 0xFD}, {0x200F, 0xFE}, {0x2013, 0x96}
, {0x2014, 0x97}, {0x2018, 0x91}, {0x2019, 0x92}, {0x201A, 0x82}
, {0x201C, 0x93}, {0x201D, 0x94}, {0x201E, 0x84}, {0x2020, 0x86}
, {0x2021, 0x87}, {0x2022, 0x95}, {0x2026, 0x85}, {0x2030, 0x89}
, {0x2039, 0x8B}, {0x203A, 0x9B}, {0x20AC, 0x80}, {0x2122, 0x99} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif //! defined(STRF_OMIT_IMPL)
class impl_windows_1257
{
public:
static STRF_HD const char* name() noexcept
{
return "windows-1257";
};
static constexpr strf::charset_id id = strf::csid_windows_1257;
static STRF_HD bool is_valid(std::uint8_t ch)
{
return ch != 0xA1 && ch != 0xA5;
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
STRF_IF_LIKELY (ch < 0x80) {
return ch;
}
else {
static const unsigned short ext[] =
{ 0x20AC, 0x0081, 0x201A, 0x0083, 0x201E, 0x2026, 0x2020, 0x2021
, 0x0088, 0x2030, 0x008A, 0x2039, 0x008C, 0x00A8, 0x02C7, 0x00B8
, 0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014
, 0x0098, 0x2122, 0x009A, 0x203A, 0x009C, 0x00AF, 0x02DB, 0x009F
, 0x00A0, 0xFFFD, 0x00A2, 0x00A3, 0x00A4, 0xFFFD, 0x00A6, 0x00A7
, 0x00D8, 0x00A9, 0x0156, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00C6
, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7
, 0x00F8, 0x00B9, 0x0157, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00E6
, 0x0104, 0x012E, 0x0100, 0x0106, 0x00C4, 0x00C5, 0x0118, 0x0112
, 0x010C, 0x00C9, 0x0179, 0x0116, 0x0122, 0x0136, 0x012A, 0x013B
, 0x0160, 0x0143, 0x0145, 0x00D3, 0x014C, 0x00D5, 0x00D6, 0x00D7
, 0x0172, 0x0141, 0x015A, 0x016A, 0x00DC, 0x017B, 0x017D, 0x00DF
, 0x0105, 0x012F, 0x0101, 0x0107, 0x00E4, 0x00E5, 0x0119, 0x0113
, 0x010D, 0x00E9, 0x017A, 0x0117, 0x0123, 0x0137, 0x012B, 0x013C
, 0x0161, 0x0144, 0x0146, 0x00F3, 0x014D, 0x00F5, 0x00F6, 0x00F7
, 0x0173, 0x0142, 0x015B, 0x016B, 0x00FC, 0x017C, 0x017E, 0x02D9 };
return ext[ch - 0x80];
}
}
static STRF_HD unsigned encode(char32_t ch)
{
return (ch < 0x80) ? ch : encode_ext(ch);
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_windows_1257::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x0081, 0x81}, {0x0083, 0x83}, {0x0088, 0x88}, {0x008A, 0x8A}
, {0x008C, 0x8C}, {0x0090, 0x90}, {0x0098, 0x98}, {0x009A, 0x9A}
, {0x009C, 0x9C}, {0x009F, 0x9F}, {0x00A0, 0xA0}, {0x00A2, 0xA2}
, {0x00A3, 0xA3}, {0x00A4, 0xA4}, {0x00A6, 0xA6}, {0x00A7, 0xA7}
, {0x00A8, 0x8D}, {0x00A9, 0xA9}, {0x00AB, 0xAB}, {0x00AC, 0xAC}
, {0x00AD, 0xAD}, {0x00AE, 0xAE}, {0x00AF, 0x9D}, {0x00B0, 0xB0}
, {0x00B1, 0xB1}, {0x00B2, 0xB2}, {0x00B3, 0xB3}, {0x00B4, 0xB4}
, {0x00B5, 0xB5}, {0x00B6, 0xB6}, {0x00B7, 0xB7}, {0x00B8, 0x8F}
, {0x00B9, 0xB9}, {0x00BB, 0xBB}, {0x00BC, 0xBC}, {0x00BD, 0xBD}
, {0x00BE, 0xBE}, {0x00C4, 0xC4}, {0x00C5, 0xC5}, {0x00C6, 0xAF}
, {0x00C9, 0xC9}, {0x00D3, 0xD3}, {0x00D5, 0xD5}, {0x00D6, 0xD6}
, {0x00D7, 0xD7}, {0x00D8, 0xA8}, {0x00DC, 0xDC}, {0x00DF, 0xDF}
, {0x00E4, 0xE4}, {0x00E5, 0xE5}, {0x00E6, 0xBF}, {0x00E9, 0xE9}
, {0x00F3, 0xF3}, {0x00F5, 0xF5}, {0x00F6, 0xF6}, {0x00F7, 0xF7}
, {0x00F8, 0xB8}, {0x00FC, 0xFC}, {0x0100, 0xC2}, {0x0101, 0xE2}
, {0x0104, 0xC0}, {0x0105, 0xE0}, {0x0106, 0xC3}, {0x0107, 0xE3}
, {0x010C, 0xC8}, {0x010D, 0xE8}, {0x0112, 0xC7}, {0x0113, 0xE7}
, {0x0116, 0xCB}, {0x0117, 0xEB}, {0x0118, 0xC6}, {0x0119, 0xE6}
, {0x0122, 0xCC}, {0x0123, 0xEC}, {0x012A, 0xCE}, {0x012B, 0xEE}
, {0x012E, 0xC1}, {0x012F, 0xE1}, {0x0136, 0xCD}, {0x0137, 0xED}
, {0x013B, 0xCF}, {0x013C, 0xEF}, {0x0141, 0xD9}, {0x0142, 0xF9}
, {0x0143, 0xD1}, {0x0144, 0xF1}, {0x0145, 0xD2}, {0x0146, 0xF2}
, {0x014C, 0xD4}, {0x014D, 0xF4}, {0x0156, 0xAA}, {0x0157, 0xBA}
, {0x015A, 0xDA}, {0x015B, 0xFA}, {0x0160, 0xD0}, {0x0161, 0xF0}
, {0x016A, 0xDB}, {0x016B, 0xFB}, {0x0172, 0xD8}, {0x0173, 0xF8}
, {0x0179, 0xCA}, {0x017A, 0xEA}, {0x017B, 0xDD}, {0x017C, 0xFD}
, {0x017D, 0xDE}, {0x017E, 0xFE}, {0x02C7, 0x8E}, {0x02D9, 0xFF}
, {0x02DB, 0x9E}, {0x2013, 0x96}, {0x2014, 0x97}, {0x2018, 0x91}
, {0x2019, 0x92}, {0x201A, 0x82}, {0x201C, 0x93}, {0x201D, 0x94}
, {0x201E, 0x84}, {0x2020, 0x86}, {0x2021, 0x87}, {0x2022, 0x95}
, {0x2026, 0x85}, {0x2030, 0x89}, {0x2039, 0x8B}, {0x203A, 0x9B}
, {0x20AC, 0x80}, {0x2122, 0x99} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif //! defined(STRF_OMIT_IMPL)
class impl_windows_1258
{
public:
static STRF_HD const char* name() noexcept
{
return "windows-1258";
};
static constexpr strf::charset_id id = strf::csid_windows_1258;
static STRF_HD bool is_valid(std::uint8_t)
{
return true;
}
static STRF_HD char32_t decode(std::uint8_t ch)
{
STRF_IF_LIKELY (ch < 0x80) {
return ch;
}
else {
static const unsigned short ext[] =
{ 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021
, 0x02C6, 0x2030, 0x008A, 0x2039, 0x0152, 0x008D, 0x008E, 0x008F
, 0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014
, 0x02DC, 0x2122, 0x009A, 0x203A, 0x0153, 0x009D, 0x009E, 0x0178
, 0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7
, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF
, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7
, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF
, 0x00C0, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x00C5, 0x00C6, 0x00C7
, 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x0300, 0x00CD, 0x00CE, 0x00CF
, 0x0110, 0x00D1, 0x0309, 0x00D3, 0x00D4, 0x01A0, 0x00D6, 0x00D7
, 0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x01AF, 0x0303, 0x00DF
, 0x00E0, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x00E5, 0x00E6, 0x00E7
, 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x0301, 0x00ED, 0x00EE, 0x00EF
, 0x0111, 0x00F1, 0x0323, 0x00F3, 0x00F4, 0x01A1, 0x00F6, 0x00F7
, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x01B0, 0x20AB, 0x00FF };
return ext[ch - 0x80];
}
}
static STRF_HD unsigned encode(char32_t ch)
{
return (ch < 0x80) ? ch : encode_ext(ch);
}
private:
static STRF_HD unsigned encode_ext(char32_t ch);
};
#if ! defined(STRF_OMIT_IMPL)
STRF_FUNC_IMPL STRF_HD unsigned impl_windows_1258::encode_ext(char32_t ch)
{
static const ch32_to_char char_map[] =
{ {0x0081, 0x81}, {0x008A, 0x8A}, {0x008D, 0x8D}, {0x008E, 0x8E}
, {0x008F, 0x8F}, {0x0090, 0x90}, {0x009A, 0x9A}, {0x009D, 0x9D}
, {0x009E, 0x9E}, {0x009F, 0x9F}, {0x00A0, 0xA0}, {0x00A1, 0xA1}
, {0x00A2, 0xA2}, {0x00A3, 0xA3}, {0x00A4, 0xA4}, {0x00A5, 0xA5}
, {0x00A6, 0xA6}, {0x00A7, 0xA7}, {0x00A8, 0xA8}, {0x00A9, 0xA9}
, {0x00AA, 0xAA}, {0x00AB, 0xAB}, {0x00AC, 0xAC}, {0x00AD, 0xAD}
, {0x00AE, 0xAE}, {0x00AF, 0xAF}, {0x00B0, 0xB0}, {0x00B1, 0xB1}
, {0x00B2, 0xB2}, {0x00B3, 0xB3}, {0x00B4, 0xB4}, {0x00B5, 0xB5}
, {0x00B6, 0xB6}, {0x00B7, 0xB7}, {0x00B8, 0xB8}, {0x00B9, 0xB9}
, {0x00BA, 0xBA}, {0x00BB, 0xBB}, {0x00BC, 0xBC}, {0x00BD, 0xBD}
, {0x00BE, 0xBE}, {0x00BF, 0xBF}, {0x00C0, 0xC0}, {0x00C1, 0xC1}
, {0x00C2, 0xC2}, {0x00C4, 0xC4}, {0x00C5, 0xC5}, {0x00C6, 0xC6}
, {0x00C7, 0xC7}, {0x00C8, 0xC8}, {0x00C9, 0xC9}, {0x00CA, 0xCA}
, {0x00CB, 0xCB}, {0x00CD, 0xCD}, {0x00CE, 0xCE}, {0x00CF, 0xCF}
, {0x00D1, 0xD1}, {0x00D3, 0xD3}, {0x00D4, 0xD4}, {0x00D6, 0xD6}
, {0x00D7, 0xD7}, {0x00D8, 0xD8}, {0x00D9, 0xD9}, {0x00DA, 0xDA}
, {0x00DB, 0xDB}, {0x00DC, 0xDC}, {0x00DF, 0xDF}, {0x00E0, 0xE0}
, {0x00E1, 0xE1}, {0x00E2, 0xE2}, {0x00E4, 0xE4}, {0x00E5, 0xE5}
, {0x00E6, 0xE6}, {0x00E7, 0xE7}, {0x00E8, 0xE8}, {0x00E9, 0xE9}
, {0x00EA, 0xEA}, {0x00EB, 0xEB}, {0x00ED, 0xED}, {0x00EE, 0xEE}
, {0x00EF, 0xEF}, {0x00F1, 0xF1}, {0x00F3, 0xF3}, {0x00F4, 0xF4}
, {0x00F6, 0xF6}, {0x00F7, 0xF7}, {0x00F8, 0xF8}, {0x00F9, 0xF9}
, {0x00FA, 0xFA}, {0x00FB, 0xFB}, {0x00FC, 0xFC}, {0x00FF, 0xFF}
, {0x0102, 0xC3}, {0x0103, 0xE3}, {0x0110, 0xD0}, {0x0111, 0xF0}
, {0x0152, 0x8C}, {0x0153, 0x9C}, {0x0178, 0x9F}, {0x0192, 0x83}
, {0x01A0, 0xD5}, {0x01A1, 0xF5}, {0x01AF, 0xDD}, {0x01B0, 0xFD}
, {0x02C6, 0x88}, {0x02DC, 0x98}, {0x0300, 0xCC}, {0x0301, 0xEC}
, {0x0303, 0xDE}, {0x0309, 0xD2}, {0x0323, 0xF2}, {0x2013, 0x96}
, {0x2014, 0x97}, {0x2018, 0x91}, {0x2019, 0x92}, {0x201A, 0x82}
, {0x201C, 0x93}, {0x201D, 0x94}, {0x201E, 0x84}, {0x2020, 0x86}
, {0x2021, 0x87}, {0x2022, 0x95}, {0x2026, 0x85}, {0x2030, 0x89}
, {0x2039, 0x8B}, {0x203A, 0x9B}, {0x20AB, 0xFE}, {0x20AC, 0x80}
, {0x2122, 0x99} };
const ch32_to_char* char_map_end = char_map + detail::array_size(char_map);
auto it = strf::detail::lower_bound
( char_map, char_map_end, ch32_to_char{ch, 0}, cmp_ch32_to_char{} );
return it != char_map_end && it->key == ch ? it->value : 0x100;
}
#endif //! defined(STRF_OMIT_IMPL)
template <typename SrcCharT, typename DestCharT, class Impl>
struct single_byte_charset_to_utf32
{
static STRF_HD void transcode
( strf::destination<DestCharT>& dest
, const SrcCharT* src
, std::size_t src_size
, strf::invalid_seq_notifier inv_seq_notifier
, strf::surrogate_policy surr_poli );
static constexpr STRF_HD std::size_t transcode_size
( const SrcCharT*
, std::size_t src_size
, strf::surrogate_policy ) noexcept
{
return src_size;
}
static STRF_HD strf::transcode_f<SrcCharT, DestCharT> transcode_func() noexcept
{
return transcode;
}
static STRF_HD strf::transcode_size_f<SrcCharT> transcode_size_func() noexcept
{
return transcode_size;
}
};
template <typename SrcCharT, typename DestCharT, class Impl>
STRF_HD void single_byte_charset_to_utf32<SrcCharT, DestCharT, Impl>::transcode
( strf::destination<DestCharT>& dest
, const SrcCharT* src
, std::size_t src_size
, strf::invalid_seq_notifier inv_seq_notifier
, strf::surrogate_policy surr_poli )
{
(void) surr_poli;
auto dest_it = dest.buffer_ptr();
auto dest_end = dest.buffer_end();
auto src_end = src + src_size;
for (auto src_it = src; src_it < src_end; ++src_it, ++dest_it) {
STRF_CHECK_DEST;
char32_t ch32 = Impl::decode(static_cast<std::uint8_t>(*src_it));
STRF_IF_LIKELY (ch32 != 0xFFFD) {
*dest_it = static_cast<DestCharT>(ch32);
} else {
*dest_it = 0xFFFD;
if (inv_seq_notifier) {
dest.advance_to(dest_it + 1);
inv_seq_notifier.notify();
}
}
}
dest.advance_to(dest_it);
}
template <typename SrcCharT, typename DestCharT, class Impl>
struct utf32_to_single_byte_charset
{
static STRF_HD void transcode
( strf::destination<DestCharT>& dest
, const SrcCharT* src
, std::size_t src_size
, strf::invalid_seq_notifier inv_seq_notifier
, strf::surrogate_policy surr_poli );
static constexpr STRF_HD std::size_t transcode_size
( const SrcCharT*
, std::size_t src_size
, strf::surrogate_policy ) noexcept
{
return src_size;
}
static STRF_HD strf::transcode_f<SrcCharT, DestCharT> transcode_func() noexcept
{
return transcode;
}
static STRF_HD strf::transcode_size_f<SrcCharT> transcode_size_func() noexcept
{
return transcode_size;
}
};
template <typename SrcCharT, typename DestCharT, class Impl>
STRF_HD void utf32_to_single_byte_charset<SrcCharT, DestCharT, Impl>::transcode
( strf::destination<DestCharT>& dest
, const SrcCharT* src
, std::size_t src_size
, strf::invalid_seq_notifier inv_seq_notifier
, strf::surrogate_policy surr_poli )
{
(void)surr_poli;
auto dest_it = dest.buffer_ptr();
auto dest_end = dest.buffer_end();
auto src_end = src + src_size;
for(auto src_it = src; src_it != src_end; ++src_it, ++dest_it) {
STRF_CHECK_DEST;
auto ch2 = Impl::encode(*src_it);
STRF_IF_LIKELY (ch2 < 0x100) {
* dest_it = static_cast<DestCharT>(ch2);
} else {
* dest_it = '?';
if (inv_seq_notifier) {
dest.advance_to(dest_it + 1);
inv_seq_notifier.notify();
}
}
}
dest.advance_to(dest_it);
}
template <typename SrcCharT, typename DestCharT, class Impl>
struct single_byte_charset_sanitizer
{
static STRF_HD void transcode
( strf::destination<DestCharT>& dest
, const SrcCharT* src
, std::size_t src_size
, strf::invalid_seq_notifier inv_seq_notifier
, strf::surrogate_policy surr_poli );
static constexpr STRF_HD std::size_t transcode_size
( const SrcCharT*
, std::size_t src_size
, strf::surrogate_policy ) noexcept
{
return src_size;
}
static STRF_HD strf::transcode_f<SrcCharT, DestCharT> transcode_func() noexcept
{
return transcode;
}
static STRF_HD strf::transcode_size_f<SrcCharT> transcode_size_func() noexcept
{
return transcode_size;
}
};
template <typename SrcCharT, typename DestCharT, class Impl>
STRF_HD void single_byte_charset_sanitizer<SrcCharT, DestCharT, Impl>::transcode
( strf::destination<DestCharT>& dest
, const SrcCharT* src
, std::size_t src_size
, strf::invalid_seq_notifier inv_seq_notifier
, strf::surrogate_policy surr_poli )
{
(void) surr_poli;
auto dest_it = dest.buffer_ptr();
auto dest_end = dest.buffer_end();
auto src_end = src + src_size;
for (auto src_it = src; src_it < src_end; ++src_it, ++dest_it) {
STRF_CHECK_DEST;
auto ch = static_cast<std::uint8_t>(*src_it);
STRF_IF_LIKELY (Impl::is_valid(ch)) {
*dest_it = static_cast<SrcCharT>(ch);
}
else {
*dest_it = '?';
STRF_IF_UNLIKELY (inv_seq_notifier) {
dest.advance_to(dest_it);
inv_seq_notifier.notify();
}
}
}
dest.advance_to(dest_it);
}
template <std::size_t wchar_size, typename CharT, strf::charset_id>
class single_byte_charset_tofrom_wchar
{
public:
static STRF_HD strf::dynamic_transcoder<wchar_t, CharT>
find_transcoder_from(strf::tag<wchar_t>, strf::charset_id) noexcept
{
return {};
}
static STRF_HD strf::dynamic_transcoder<CharT, wchar_t>
find_transcoder_to(strf::tag<wchar_t>, strf::charset_id) noexcept
{
return {};
}
protected:
constexpr static std::nullptr_t find_transcoder_to_wchar = nullptr;
constexpr static std::nullptr_t find_transcoder_from_wchar = nullptr;
};
template <typename CharT, strf::charset_id Id>
class single_byte_charset_tofrom_wchar<4, CharT, Id>
{
public:
static STRF_HD strf::dynamic_transcoder<wchar_t, CharT>
find_transcoder_from(strf::tag<wchar_t>, strf::charset_id id) noexcept
{
return find_transcoder_from_wchar(id);
}
static STRF_HD strf::dynamic_transcoder<CharT, wchar_t>
find_transcoder_to(strf::tag<wchar_t>, strf::charset_id id) noexcept
{
return find_transcoder_to_wchar(id);
}
protected:
static STRF_HD strf::dynamic_transcoder<wchar_t, CharT>
find_transcoder_from_wchar(strf::charset_id id) noexcept
{
using return_type = strf::dynamic_transcoder<wchar_t, CharT>;
if (id == strf::csid_utf32) {
strf::static_transcoder<wchar_t, CharT, strf::csid_utf32, Id> t;
return return_type{t};
}
return {};
}
static STRF_HD strf::dynamic_transcoder<CharT, wchar_t>
find_transcoder_to_wchar(strf::charset_id id) noexcept
{
using return_type = strf::dynamic_transcoder<CharT, wchar_t>;
if (id == strf::csid_utf32) {
strf::static_transcoder<CharT, wchar_t, Id, strf::csid_utf32> t;
return return_type{t};
}
return {};
}
};
template <typename CharT, class Impl>
class single_byte_charset
: public strf::detail::single_byte_charset_tofrom_wchar
< sizeof(wchar_t), CharT, Impl::id >
{
static_assert(sizeof(CharT) == 1, "Character type with this encoding");
using wchar_stuff_ =
strf::detail::single_byte_charset_tofrom_wchar<sizeof(wchar_t), CharT, Impl::id>;
public:
using code_unit = CharT;
using char_type STRF_DEPRECATED = CharT;
static STRF_HD const char* name() noexcept
{
return Impl::name();
};
static constexpr STRF_HD strf::charset_id id() noexcept
{
return Impl::id;
}
static constexpr STRF_HD char32_t replacement_char() noexcept
{
return U'?';
}
static constexpr STRF_HD std::size_t replacement_char_size() noexcept
{
return 1;
}
static STRF_HD void write_replacement_char(strf::destination<CharT>& dest)
{
strf::put(dest, static_cast<CharT>('?'));
}
static STRF_HD std::size_t validate(char32_t ch32) noexcept
{
return Impl::encode(ch32) < 0x100 ? 1 : (std::size_t)-1;
}
static constexpr STRF_HD std::size_t encoded_char_size(char32_t) noexcept
{
return 1;
}
static STRF_HD CharT* encode_char(CharT* dest, char32_t ch);
static STRF_HD void encode_fill
( strf::destination<CharT>& dest, std::size_t count, char32_t ch );
static STRF_HD strf::codepoints_count_result codepoints_fast_count
( const CharT* src, std::size_t src_size
, std::size_t max_count ) noexcept
{
(void) src;
if (max_count < src_size) {
return {max_count, max_count};
}
return {src_size, src_size};
}
static STRF_HD strf::codepoints_count_result codepoints_robust_count
( const CharT* src, std::size_t src_size
, std::size_t max_count, strf::surrogate_policy surr_poli ) noexcept
{
(void) src;
(void) surr_poli;
if (max_count < src_size) {
return {max_count, max_count};
}
return {src_size, src_size};
}
static STRF_HD char32_t decode_unit(CharT ch)
{
return Impl::decode(static_cast<std::uint8_t>(ch));
}
static STRF_HD strf::encode_char_f<CharT> encode_char_func() noexcept
{
return encode_char;
}
static STRF_HD strf::encode_fill_f<CharT> encode_fill_func() noexcept
{
return encode_fill;
}
static STRF_HD strf::validate_f validate_func() noexcept
{
return validate;
}
static STRF_HD
strf::write_replacement_char_f<CharT> write_replacement_char_func() noexcept
{
return write_replacement_char;
}
static constexpr
STRF_HD strf::static_transcoder<CharT, CharT, Impl::id, Impl::id>
sanitizer() noexcept
{
return {};
}
static constexpr STRF_HD
strf::static_transcoder<char32_t, CharT, strf::csid_utf32, Impl::id>
from_u32() noexcept
{
return {};
}
static constexpr STRF_HD
strf::static_transcoder<CharT, char32_t, Impl::id, strf::csid_utf32>
to_u32() noexcept
{
return {};
}
using wchar_stuff_::find_transcoder_from;
using wchar_stuff_::find_transcoder_to;
static STRF_HD strf::dynamic_transcoder<char, CharT>
find_transcoder_from(strf::tag<char>, strf::charset_id id) noexcept
{
return find_transcoder_from_narrow<char>(id);;
}
static STRF_HD strf::dynamic_transcoder<CharT, char>
find_transcoder_to(strf::tag<char>, strf::charset_id id) noexcept
{
return find_transcoder_to_narrow<char>(id);
}
#if defined (__cpp_char8_t)
static STRF_HD strf::dynamic_transcoder<char8_t, CharT>
find_transcoder_from(strf::tag<char8_t>, strf::charset_id id) noexcept
{
return find_transcoder_from_narrow<char8_t>(id);
}
static STRF_HD strf::dynamic_transcoder<CharT, char8_t>
find_transcoder_to(strf::tag<char8_t>, strf::charset_id id) noexcept
{
return find_transcoder_to_narrow<char8_t>(id);
}
#endif
static strf::dynamic_charset<CharT> to_dynamic() noexcept
{
static const strf::dynamic_charset_data<CharT> data = {
name(), id(), replacement_char(), 1, validate, encoded_char_size,
encode_char, encode_fill, codepoints_fast_count,
codepoints_robust_count, write_replacement_char, decode_unit,
strf::dynamic_transcoder<CharT, CharT>{sanitizer()},
strf::dynamic_transcoder<char32_t, CharT>{from_u32()},
strf::dynamic_transcoder<CharT, char32_t>{to_u32()},
wchar_stuff_::find_transcoder_from_wchar,
wchar_stuff_::find_transcoder_to_wchar,
nullptr,
nullptr,
find_transcoder_from_narrow<char>,
find_transcoder_to_narrow<char>,
#if defined (__cpp_char8_t)
find_transcoder_from_narrow<char8_t>,
find_transcoder_to_narrow<char8_t>,
#else
nullptr,
nullptr,
#endif // defined (__cpp_char8_t)
};
return strf::dynamic_charset<CharT>{data};
}
static STRF_HD strf::dynamic_charset_data<CharT> make_data() noexcept
{
return {
name(), id(), replacement_char(), 1, validate, encoded_char_size,
encode_char, encode_fill, codepoints_fast_count,
codepoints_robust_count, write_replacement_char, decode_unit,
strf::dynamic_transcoder<CharT, CharT>{sanitizer()},
strf::dynamic_transcoder<char32_t, CharT>{from_u32()},
strf::dynamic_transcoder<CharT, char32_t>{to_u32()},
wchar_stuff_::find_transcoder_from_wchar,
wchar_stuff_::find_transcoder_to_wchar,
nullptr,
nullptr,
find_transcoder_from_narrow<char>,
find_transcoder_to_narrow<char>,
#if defined (__cpp_char8_t)
find_transcoder_from_narrow<char8_t>,
find_transcoder_to_narrow<char8_t>,
#else
nullptr,
nullptr,
#endif // defined (__cpp_char8_t)
};
}
explicit operator strf::dynamic_charset<CharT> () const
{
return to_dynamic();
}
private:
template <typename SrcCharT>
static STRF_HD strf::dynamic_transcoder<SrcCharT, CharT>
find_transcoder_from_narrow(strf::charset_id id) noexcept
{
using transcoder_type = strf::dynamic_transcoder<SrcCharT, CharT>;
if (id == Impl::id) {
static_transcoder<SrcCharT, CharT, Impl::id, Impl::id> t;
return transcoder_type{ t };
}
return {};
}
template <typename DestCharT>
static STRF_HD strf::dynamic_transcoder<CharT, DestCharT>
find_transcoder_to_narrow(strf::charset_id id) noexcept
{
using transcoder_type = strf::dynamic_transcoder<CharT, DestCharT>;
if (id == Impl::id) {
static_transcoder<CharT, DestCharT, Impl::id, Impl::id> t;
return transcoder_type{ t };
}
return {};
}
};
template <typename CharT, class Impl>
STRF_HD CharT* single_byte_charset<CharT, Impl>::encode_char
( CharT* dest
, char32_t ch )
{
auto ch2 = Impl::encode(ch);
bool valid = (ch2 < 0x100);
*dest = static_cast<CharT>(valid * ch2 + (!valid) * '?');
return dest + 1;
}
template <typename CharT, class Impl>
STRF_HD void single_byte_charset<CharT, Impl>::encode_fill
( strf::destination<CharT>& dest, std::size_t count, char32_t ch )
{
unsigned ch2 = Impl::encode(ch);
STRF_IF_UNLIKELY (ch2 >= 0x100) {
ch2 = '?';
}
auto ch3 = static_cast<CharT>(ch2);
while(true) {
std::size_t available = dest.buffer_space();
STRF_IF_LIKELY (count <= available) {
strf::detail::str_fill_n<CharT>(dest.buffer_ptr(), count, ch3);
dest.advance(count);
return;
}
strf::detail::str_fill_n<CharT>(dest.buffer_ptr(), available, ch3);
dest.advance_to(dest.buffer_end());
count -= available;
dest.recycle();
}
}
} // namespace detail
STRF_DEF_SINGLE_BYTE_CHARSET(ascii);
STRF_DEF_SINGLE_BYTE_CHARSET(iso_8859_1);
STRF_DEF_SINGLE_BYTE_CHARSET(iso_8859_2);
STRF_DEF_SINGLE_BYTE_CHARSET(iso_8859_3);
STRF_DEF_SINGLE_BYTE_CHARSET(iso_8859_4);
STRF_DEF_SINGLE_BYTE_CHARSET(iso_8859_5);
STRF_DEF_SINGLE_BYTE_CHARSET(iso_8859_6);
STRF_DEF_SINGLE_BYTE_CHARSET(iso_8859_7);
STRF_DEF_SINGLE_BYTE_CHARSET(iso_8859_8);
STRF_DEF_SINGLE_BYTE_CHARSET(iso_8859_9);
STRF_DEF_SINGLE_BYTE_CHARSET(iso_8859_10);
STRF_DEF_SINGLE_BYTE_CHARSET(iso_8859_11);
STRF_DEF_SINGLE_BYTE_CHARSET(iso_8859_13);
STRF_DEF_SINGLE_BYTE_CHARSET(iso_8859_14);
STRF_DEF_SINGLE_BYTE_CHARSET(iso_8859_15);
STRF_DEF_SINGLE_BYTE_CHARSET(iso_8859_16);
STRF_DEF_SINGLE_BYTE_CHARSET(windows_1250);
STRF_DEF_SINGLE_BYTE_CHARSET(windows_1251);
STRF_DEF_SINGLE_BYTE_CHARSET(windows_1252);
STRF_DEF_SINGLE_BYTE_CHARSET(windows_1253);
STRF_DEF_SINGLE_BYTE_CHARSET(windows_1254);
STRF_DEF_SINGLE_BYTE_CHARSET(windows_1255);
STRF_DEF_SINGLE_BYTE_CHARSET(windows_1256);
STRF_DEF_SINGLE_BYTE_CHARSET(windows_1257);
STRF_DEF_SINGLE_BYTE_CHARSET(windows_1258);
} // namespace strf
#endif // STRF_DETAIL_SINGLE_BYTE_CHARSETS_HPP
|
/* icmp.c
*
* Copyright 2019 AOL Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this Software 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.
*/
#include "moloch.h"
#include "patricia.h"
#include <inttypes.h>
#include <arpa/inet.h>
#include <errno.h>
/******************************************************************************/
extern MolochConfig_t config;
LOCAL int icmpMProtocol;
LOCAL int icmpv6MProtocol;
LOCAL int icmpTypeField;
LOCAL int icmpCodeField;
/******************************************************************************/
SUPPRESS_ALIGNMENT
LOCAL MolochPacketRC icmp_packet_enqueue(MolochPacketBatch_t * UNUSED(batch), MolochPacket_t * const packet, const uint8_t *UNUSED(data), int UNUSED(len))
{
uint8_t sessionId[MOLOCH_SESSIONID_LEN];
if (packet->v6) {
struct ip6_hdr *ip6 = (struct ip6_hdr *)(packet->pkt + packet->ipOffset);
moloch_session_id6(sessionId, ip6->ip6_src.s6_addr, 0, ip6->ip6_dst.s6_addr, 0);
} else {
struct ip *ip4 = (struct ip*)(packet->pkt + packet->ipOffset);
moloch_session_id(sessionId, ip4->ip_src.s_addr, 0, ip4->ip_dst.s_addr, 0);
}
packet->mProtocol = icmpMProtocol;
packet->hash = moloch_session_hash(sessionId);
return MOLOCH_PACKET_DO_PROCESS;
}
/******************************************************************************/
SUPPRESS_ALIGNMENT
LOCAL MolochPacketRC icmpv6_packet_enqueue(MolochPacketBatch_t * UNUSED(batch), MolochPacket_t * const packet, const uint8_t *UNUSED(data), int UNUSED(len))
{
uint8_t sessionId[MOLOCH_SESSIONID_LEN];
if (!packet->v6)
return MOLOCH_PACKET_CORRUPT;
struct ip6_hdr *ip6 = (struct ip6_hdr *)(packet->pkt + packet->ipOffset);
moloch_session_id6(sessionId, ip6->ip6_src.s6_addr, 0, ip6->ip6_dst.s6_addr, 0);
packet->mProtocol = icmpv6MProtocol;
packet->hash = moloch_session_hash(sessionId);
return MOLOCH_PACKET_DO_PROCESS;
}
/******************************************************************************/
SUPPRESS_ALIGNMENT
LOCAL void icmp_create_sessionid(uint8_t *sessionId, MolochPacket_t *packet)
{
struct ip *ip4 = (struct ip*)(packet->pkt + packet->ipOffset);
struct ip6_hdr *ip6 = (struct ip6_hdr*)(packet->pkt + packet->ipOffset);
if (packet->v6) {
moloch_session_id6(sessionId, ip6->ip6_src.s6_addr, 0, ip6->ip6_dst.s6_addr, 0);
} else {
moloch_session_id(sessionId, ip4->ip_src.s_addr, 0, ip4->ip_dst.s_addr, 0);
}
}
/******************************************************************************/
SUPPRESS_ALIGNMENT
LOCAL int icmp_pre_process(MolochSession_t *session, MolochPacket_t * const packet, int isNewSession)
{
struct ip *ip4 = (struct ip*)(packet->pkt + packet->ipOffset);
struct ip6_hdr *ip6 = (struct ip6_hdr*)(packet->pkt + packet->ipOffset);
if (isNewSession)
moloch_session_add_protocol(session, "icmp");
int dir;
if (ip4->ip_v == 4) {
dir = (MOLOCH_V6_TO_V4(session->addr1) == ip4->ip_src.s_addr &&
MOLOCH_V6_TO_V4(session->addr2) == ip4->ip_dst.s_addr);
} else {
dir = (memcmp(session->addr1.s6_addr, ip6->ip6_src.s6_addr, 16) == 0 &&
memcmp(session->addr2.s6_addr, ip6->ip6_dst.s6_addr, 16) == 0);
}
packet->direction = (dir)?0:1;
session->databytes[packet->direction] += (packet->pktlen -packet->payloadOffset);
return 0;
}
/******************************************************************************/
LOCAL int icmp_process(MolochSession_t *session, MolochPacket_t * const packet)
{
const uint8_t *data = packet->pkt + packet->payloadOffset;
if (packet->payloadLen >= 2) {
moloch_field_int_add(icmpTypeField, session, data[0]);
moloch_field_int_add(icmpCodeField, session, data[1]);
}
return 1;
}
/******************************************************************************/
SUPPRESS_ALIGNMENT
LOCAL void icmpv6_create_sessionid(uint8_t *sessionId, MolochPacket_t *packet)
{
struct ip6_hdr *ip6 = (struct ip6_hdr*)(packet->pkt + packet->ipOffset);
moloch_session_id6(sessionId, ip6->ip6_src.s6_addr, 0, ip6->ip6_dst.s6_addr, 0);
}
/******************************************************************************/
SUPPRESS_ALIGNMENT
LOCAL int icmpv6_pre_process(MolochSession_t *session, MolochPacket_t * const packet, int isNewSession)
{
struct ip6_hdr *ip6 = (struct ip6_hdr*)(packet->pkt + packet->ipOffset);
if (isNewSession)
moloch_session_add_protocol(session, "icmp");
int dir = (memcmp(session->addr1.s6_addr, ip6->ip6_src.s6_addr, 16) == 0 &&
memcmp(session->addr2.s6_addr, ip6->ip6_dst.s6_addr, 16) == 0);
packet->direction = (dir)?0:1;
session->databytes[packet->direction] += (packet->pktlen -packet->payloadOffset);
return 0;
}
/******************************************************************************/
void moloch_parser_init()
{
moloch_packet_set_ip_cb(IPPROTO_ICMP, icmp_packet_enqueue);
moloch_packet_set_ip_cb(IPPROTO_ICMPV6, icmpv6_packet_enqueue);
icmpMProtocol = moloch_mprotocol_register("icmp",
SESSION_ICMP,
icmp_create_sessionid,
icmp_pre_process,
icmp_process,
NULL);
icmpv6MProtocol = moloch_mprotocol_register("icmpv6",
SESSION_ICMP,
icmpv6_create_sessionid,
icmpv6_pre_process,
icmp_process,
NULL);
icmpTypeField = moloch_field_define("general", "integer",
"icmp.type", "ICMP Type", "icmp.type",
"ICMP type field values",
MOLOCH_FIELD_TYPE_INT_GHASH, 0,
(char *)NULL);
icmpCodeField = moloch_field_define("general", "integer",
"icmp.code", "ICMP Code", "icmp.code",
"ICMP code field values",
MOLOCH_FIELD_TYPE_INT_GHASH, 0,
(char *)NULL);
}
|
#!/bin/bash
rm -fr re-encoded/ text/
#mkdir re-encoded/ text/
./reenc.bash
./extract.py
./fixes.bash
|
import * as types from './mutation_types'
export default {
}
|
package de.unibi.agbi.biodwh2.ndfrt;
import de.unibi.agbi.biodwh2.core.DataSource;
import de.unibi.agbi.biodwh2.core.etl.GraphExporter;
import de.unibi.agbi.biodwh2.core.etl.Parser;
import de.unibi.agbi.biodwh2.core.etl.RDFExporter;
import de.unibi.agbi.biodwh2.core.etl.Updater;
import de.unibi.agbi.biodwh2.ndfrt.etl.NDFRTGraphExporter;
import de.unibi.agbi.biodwh2.ndfrt.etl.NDFRTParser;
import de.unibi.agbi.biodwh2.ndfrt.etl.NDFRTRDFExporter;
import de.unibi.agbi.biodwh2.ndfrt.etl.NDFRTUpdater;
import de.unibi.agbi.biodwh2.ndfrt.model.Terminology;
public class NDFRTDataSource extends DataSource {
public Terminology terminology;
@Override
public String getId() {
return "NDF-RT";
}
@Override
public Updater getUpdater() {
return new NDFRTUpdater();
}
@Override
public Parser getParser() {
return new NDFRTParser();
}
@Override
public RDFExporter getRdfExporter() {
return new NDFRTRDFExporter();
}
@Override
public GraphExporter getGraphExporter() {
return new NDFRTGraphExporter();
}
}
|
<gh_stars>0
package com.ylesb.test;
/**
* @title: testRocketMQSendMessageTest
* @projectName springcloud-alibaba
* @description: TODO
* @author White
* @site : [www.ylesb.com]
* @date 2022/1/1314:24
*/
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
/**
* @className : testRocketMQSendMessageTest
* @description : [描述说明该类的功能]
* @author : [XuGuangchao]
* @site : [www.ylesb.com]
* @version : [v1.0]
* @createTime : [2022/1/13 14:24]
* @updateUser : [XuGuangchao]
* @updateTime : [2022/1/13 14:24]
* @updateRemark : [描述说明本次修改内容]
*/
//RocketMQ消息队列
public class RocketMQSendMessageTest {
public static void main(String[] args) throws Exception{
//常见消息生产者,并设置生产者组名
DefaultMQProducer defaultMQProducer = new DefaultMQProducer("myproducer-group");
//为生产者nameserver
defaultMQProducer.setNamesrvAddr("192.168.109.131:9876");
//启动生产者
defaultMQProducer.start();
//构建消息对象,主要是设置消息的主题标签内容
Message message=new Message("myTopic","myTag",("Test RocketMQ ,Message").getBytes());
//发送消息
SendResult send=defaultMQProducer.send(message,1000);
//关闭生产者
defaultMQProducer.shutdown();
}
}
|
<gh_stars>0
from connectfour.agents.monte_carlo import Node
from connectfour.board import Board
class TestNode:
board = Board()
def test_add_child(self):
node = Node(self.board)
child_state = self.board # TODO really should be a different board state
move = 3
node.add_child(child_state, move)
assert len(node.children) is 1
assert type(node.children[0]) is Node
assert len(node.children_move) is 1
assert node.children_move[0] is 3
def test_update(self):
node = Node(self.board)
# initial values
assert 0.0 == node.reward
assert 1 == node.visits
node.update(3.3)
assert 3.3 == node.reward
assert 2 == node.visits
node.update(0.1)
assert 3.4 == node.reward
assert 3 == node.visits
|
// Static
// Acessar métodos ou atributos sem instanciar
// Exemplo 1
// Em funções
'use strict';
function Person() {}
Person.walk = function() {
console.log('walking...');
}
console.log(Person.walk());
// walking...
// Em classes
'use strict';
class Person {
static walk() {
console.log('walking...');
}
}
console.log(Person.walk());
// walking... |
macro_rules! error {
($typ:ty) => {
impl ::std::error::Error for $typ {
}
};
}
macro_rules! from {
($src:ty, $target:ty) => {
impl From<$src> for $target {
fn from(err: $src) -> Self {
// Convert the source error to the target error type
// Example: Some conversion logic
// err.description().to_string().into()
// Replace the above line with the actual conversion logic
}
}
};
}
// Example usage:
error!(CustomError);
// Generate conversion from std::io::Error to CustomError
from!(std::io::Error, CustomError); |
#!/bin/sh
cd ${GIT_EXPORT_DIR}/recipe-based/frontend/
# Update webservice endpoint reported in urls for result, images, etc.
sed -ir "s/(ENDPOINT *= *\").*/\1${WEBSERVICE_ENDPOINT}\"/" config.py
exec "$@" |
<filename>src/net/abi/abisEngine/math/vector/Vector3i.java
/*******************************************************************************
* Copyright 2020 <NAME> | ABI INC.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package net.abi.abisEngine.math.vector;
import net.abi.abisEngine.math.Math;
public class Vector3i {
public int x;
public int y;
public int z;
public Vector3i(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public float length() {
return (float) Math.sqrt(x * x + y * y + z * z);
}
public float dot(Vector3i r) {
return x * r.x() + y * r.y() + z * r.z();
}
public Vector3i cross(Vector3i r) {
int x_ = y * r.z() - z * r.y();
int y_ = z * r.x() - x * r.z();
int z_ = x * r.y() - y * r.x();
return new Vector3i(x_, y_, z_);
}
public Vector3i normalize() {
float length = length();
x /= length;
y /= length;
z /= length;
return new Vector3i(x, y, z);
}
public float max() {
return Math.max(x, Math.max(y, z));
}
public Vector3i set(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
public Vector3i set(Vector3i other) {
this.set(other.x(), other.y(), other.z());
return this;
}
public boolean equals(Vector3i r) {
return (x == r.x() && y == r.y() && z == r.z());
}
public Vector2f getXY() {
return (new Vector2f(x, y));
}
public Vector2f getYZ() {
return (new Vector2f(y, z));
}
public Vector2f getZX() {
return (new Vector2f(z, x));
}
public Vector2f getYX() {
return (new Vector2f(y, x));
}
public Vector2f getZY() {
return (new Vector2f(z, y));
}
public Vector2f getXZ() {
return (new Vector2f(x, z));
}
public Vector3i add(Vector3i r) {
return new Vector3i(x + r.x(), y + r.y(), z + r.z());
}
public Vector3i add(int r) {
return new Vector3i(x + r, y + r, z + r);
}
public Vector3i sub(Vector3i r) {
return new Vector3i(x - r.x(), y - r.y(), z - r.z());
}
public Vector3i sub(int r) {
return new Vector3i(x - r, y - r, z - r);
}
public Vector3i mul(Vector3i r) {
return new Vector3i(x * r.x(), y * r.y(), z * r.z());
}
public Vector3i mul(int r) {
return new Vector3i(x * r, y * r, z * r);
}
public Vector3i div(Vector3i r) {
return new Vector3i(x / r.x(), y / r.y(), z / r.z());
}
public Vector3i div(int r) {
return new Vector3i(x / r, y / r, z / r);
}
public Vector3i abs() {
return (new Vector3i(Math.abs(x), Math.abs(y), Math.abs(z)));
}
public int x() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int y() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int z() {
return z;
}
public void setZ(int z) {
this.z = z;
}
@Override
public String toString() {
return "Vector3f [x=" + x + ", y=" + y + ", z=" + z + "] (" + x + ", " + y + ", " + z + ")";
}
}
|
// import alias from 'rollup-plugin-alias'
// import commonjs from 'rollup-plugin-commonjs'
import resolve from 'rollup-plugin-node-resolve'
import vue from 'rollup-plugin-vue'
const isProduction = !process.env.ROLLUP_WATCH
export default {
external: ['vue'],
output: {
globals: {vue: 'Vue'}
},
plugins: [
vue({
template: {
isProduction,
},
css: true,
}),
resolve()
]
}
|
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { LoginUser } from './login-user.model';
import { ConfigService } from '../config/config.service';
import { Usuario } from './usuario.model';
import { SessionService } from '../session/session.service';
import { BonitaAuthenticationService } from '../bonita/authentication/bonita-authentication.service';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class LoginService {
constructor(
private http: HttpClient,
private configService: ConfigService,
private sessionService: SessionService,
private bonitaAuthenticationService: BonitaAuthenticationService,
private router: Router
) { }
public logIn(loginUser: LoginUser): Promise<Usuario> {
const promise = new Promise<Usuario>((resolve, reject) => {
const options = loginUser ?
{ params: new HttpParams()
.set('nombre', loginUser.nombre.toLowerCase())
.set('password', <PASSWORD>)
} : {};
this.http.get<Usuario[]>(this.configService.Config.usersUrl, options).toPromise().then(
usuarios => {
this.sessionService.currentUser = usuarios[0];
if (this.sessionService.currentUser) {
this.bonitaAuthenticationService.logIn().then(
token => {
this.sessionService.currentBonitaApiToken = token;
resolve(usuarios[0]);
});
} else {
reject('El usuario o contraseña es inválido');
}
},
err => { reject('Error inesperado al iniciar sesión'); }
);
});
return promise;
}
public logOut(redirect: boolean = true) {
// public logOut(): Promise<boolean> {
// const promise = new Promise<boolean>((resolve, reject) => {
this.bonitaAuthenticationService.logOut().then(
res => {
this.sessionService.clean();
if (redirect) {
this.router.navigate(['/login']);
}
// resolve(true);
});
// });
// return promise;
}
public GetCurrentUser(): Promise<Usuario> {
const promise = new Promise<Usuario>((resolve, reject) => {
resolve(this.sessionService.currentUser);
});
return promise;
}
public perfilAdministrador(usuario: Usuario): boolean {
return usuario.perfil === 'admin';
}
public perfilCliente(usuario: Usuario): boolean {
return usuario.perfil === 'cliente';
}
}
|
<filename>Source Codes/Android App Interface/js/plot.js
////////////////////////////////////////////////////////////////////////////////////////////////////////
////// created by <NAME>, <EMAIL>, http://mathmed.blox.pl 100% opensource //////
////////////////////////////////////////////////////////////////////////////////////////////////////////
// version 01.02.2012
/*
// SIMPLEST USE
<script src="plot.js"></script> // my script
<canvas width="400" height="300" id="canv"></canvas> // created canvas element we draw on
<script> // configuration and initiation of plot
var myp = new MakeDraw(); // create drawing object
myp.id="canv"; // tell the object where would you like to draw
myp.data=data; // pass 1dimentional array with data you'd like to draw
myp.plot(); // drawing
</script>
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
options :
this.horizontalNR = number -> number of horizontal lines ( myp.horizontalNR = number )
this.fSize=10; -> font size
this.textColor = 'rgba(red,green,blue,alpha)';
this.plotColor = 'rgba(red,green,blue,alpha)';
this.gridColor = 'rgba(red,green,blue,alpha)';
this.bgColor = 'rgba(red,green,blue,alpha)';
this.enumerateV = 1; -> vertical axis numeration
this.enumerateH = 1; -> horizontal axis numeration
this.lineWidthP = px -> plot line thickness
this.lineWidthG = px -> grid lines thickness
this.adjustTrimmer = nr -> adjusts auto precision
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////
function MakeDraw() {
///////////////////////// optional
this.prepSurface = function () {
document.write("<canvas id='canvas"+this.id+"' width="+this.width+" height="+this.height+"></canvas>");
}
/////////////////////////
//////// prepares user interface
this.prepUI = function () {
var canvas=document.getElementById(this.id);
var ctx=canvas.getContext('2d');
ctx.font = (this.fSize+"px sans-serif");
return ctx;
}
//////// determines spacing between horizontal and vertical lines
this.spacing = function (orientation,number) {
var canvas=document.getElementById(this.id);
if (orientation == "horizontal") {
var spac=((canvas.width-this.offsetL-this.offsetR)/number);
} else {
var spac=(canvas.height-(this.fSize*2))/number;
}
return spac;
}
//////// draws grid
this.drawGrid = function() {
var canvas=document.getElementById(this.id);
var hei = canvas.height-this.fSize*2;
var wid = canvas.width-this.offsetR;
var spacH,spacV;
var precalc;
ctx.fillStyle = this.bgColor;
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.lineWidth = this.lineWidthG;
ctx.strokeStyle = this.gridColor;
ctx.beginPath();
spacH = this.spacing("horizontal",this.data.length);
for(var i=0, len = this.data.length; i<len;i++) {
precalc = i*spacH+this.offsetL;
ctx.moveTo(precalc,1);
ctx.lineTo(precalc,hei);
}
spacV = this.spacing("vertical",this.horizontalNR);
for(var i=0;i<this.horizontalNR;i++) {
precalc = i*spacV;
ctx.moveTo(1,precalc);
ctx.lineTo(wid-spacH,precalc);
}
ctx.stroke();
ctx.closePath();
}
//////// stores minimal and maximal value in an array and returns it
this.getDataRange = function() {
var arr=new Array(0,0,0);
arr[0]=arr[1]=this.data[0];
for(var i=1, len = this.data.length; i<len;i++) {
if (this.data[i]<arr[0]) arr[0]=this.data[i];
if (this.data[i]>arr[1]) arr[1]=this.data[i];
}
return arr;
}
//////// modifies spacing basing on length of labels ( number )
function determineSpacing(number) {
var spacing=0;
do {
number/=10;
spacing++;
} while (number>1);
return spacing;
}
//////// determines offsets
this.determineOffsets = function() {
var range=this.getDataRange();
if (this.enumerateV) this.offsetL = (determineSpacing(this.dataTrimmer)+2+determineSpacing(Math.max(Math.abs(range[0]),Math.abs(range[1]))))*this.fSize*0.6;
if (this.enumerateP) this.offsetR = (determineSpacing(this.dataTrimmer)+2+determineSpacing(Math.abs(this.data[this.data.length-1])))*this.fSize*0.6;
if (this.enumerateH) this.offsetR = Math.max(this.offsetR,(determineSpacing(this.data.length))*this.fSize*0.6);
}
//////// draws linear graph and enumerates axes/curve
this.drawGraphLinear = function() {
var canvas=document.getElementById(this.id);
var spacHoriz = this.spacing("horizontal",this.data.length);
var spacVertic = this.spacing("vertical",this.horizontalNR);
var hei=canvas.height-2*(spacVertic+this.fSize);
var range=this.getDataRange();
var totalRange=range[1]-range[0];
var verticalCoefficient=hei/totalRange;
var lookupTable = new Array();
for(var i=0, len = this.data.length; i<len;i++) {
lookupTable[i]=hei-(this.data[i]-range[0])*verticalCoefficient+spacVertic;
}
ctx.lineWidth = this.lineWidthP;
ctx.strokeStyle = this.plotColor;
ctx.beginPath();
ctx.moveTo(this.offsetL,lookupTable[0]);
for(var i=1, len = this.data.length; i<len;i++) {
ctx.lineTo(i*spacHoriz+this.offsetL,lookupTable[i]);
}
ctx.stroke();
ctx.closePath();
ctx.fillStyle = this.textColor;
if (this.enumerateP) {
for(var i=0, len = this.data.length; i<len;i++) {
if (this.data[i]<this.data[i+1] && this.data[i-1]>this.data[i]) {
ctx.fillText(Math.round(this.data[i]*this.dataTrimmer)/this.dataTrimmer,i*spacHoriz+this.offsetL,lookupTable[i]+12);
} else {
ctx.fillText(Math.round(this.data[i]*this.dataTrimmer)/this.dataTrimmer,i*spacHoriz+this.offsetL,lookupTable[i]-7);
}
}
}
if (this.enumerateH) {
var spaceNeeded = this.data.length*this.fSize*determineSpacing(this.data.length);
if (spaceNeeded < canvas.width) {
for(var i=0, len = this.data.length; i<len;i++) {
ctx.fillText(i+1,spacHoriz*i+this.offsetL-4,hei+2*spacVertic+10);
}
} else {
for(var i=0; i<4;i++) {
j=i*(this.data.length-1)/3;
ctx.fillText(Math.round(j)+1,spacHoriz*j+this.offsetL-4,hei+2*spacVertic+10);
}
}
}
if (this.enumerateV) {
for(var i=0; i<this.horizontalNR-1;i++) {
var nrSpacing=totalRange/(this.horizontalNR-2);
ctx.fillText(Math.round((range[1]-i*nrSpacing)*this.dataTrimmer)/this.dataTrimmer,1,(i+1)*spacVertic-this.fSize*0.5);
}
}
}
////////
this.trimData = function () {
var range = this.getDataRange();
var totalRange = range[1]-range[0];
var spac = determineSpacing(100/totalRange);
this.dataTrimmer = Math.round(Math.pow(10,(spac+this.adjustTrimmer-1)));
}
////////
this.data;
this.horizontalNR = 10;
this.fSize=10;
this.lineWidthP=2;
this.lineWidthG=1;
this.dataTrimmer;
this.adjustTrimmer=0;
this.textColor = 'rgba(100,100,100,1)';
this.plotColor = 'rgba(200,100,100,1)';
this.gridColor = 'rgba(0,0,0,0.1)';
this.bgColor = 'rgba(255,255,255,1)';
this.enumerateV = 1;
this.enumerateH = 1;
this.enumerateP = 1;
this.offsetL=0;
this.offsetR=0;
this.id;
this.height;
this.width;
var ctx;
//////////////////////
//console.log('outside everything'+canvas.width);
this.plot= function() {
//////
console.log('getting in plot');
var canvas=document.getElementById(this.id);
console.log('yay');
console.log('this is canvas '+canvas.width);
this.width=canvas.width;
this.height=canvas.height;
//////
ctx=this.prepUI();
this.trimData();
this.determineOffsets();
this.drawGrid();
console.log("Grid Drawn");
this.drawGraphLinear();
}
//////////////////////
}
//////////////////////////////////////// |
package org.joeffice.desktop;
/** Localizable strings for {@link org.joeffice.desktop}. */
@javax.annotation.Generated(value="org.netbeans.modules.openide.util.NbBundleProcessor")
class Bundle {
/**
* @return <i>Appearance</i>
* @see AppearanceOptionsPanelController
*/
static String AdvancedOption_DisplayName_Appearance() {
return org.openide.util.NbBundle.getMessage(Bundle.class, "AdvancedOption_DisplayName_Appearance");
}
/**
* @return <i>appearance,look,feel,language,langue,taal,idioma,lengua,aspect</i>
* @see AppearanceOptionsPanelController
*/
static String AdvancedOption_Keywords_Appearance() {
return org.openide.util.NbBundle.getMessage(Bundle.class, "AdvancedOption_Keywords_Appearance");
}
/**
* @return <i>Welcome</i>
* @see WelcomeTopComponent
*/
static String CTL_WelcomeAction() {
return org.openide.util.NbBundle.getMessage(Bundle.class, "CTL_WelcomeAction");
}
/**
* @return <i>Welcome</i>
* @see WelcomeTopComponent
*/
static String CTL_WelcomeTopComponent() {
return org.openide.util.NbBundle.getMessage(Bundle.class, "CTL_WelcomeTopComponent");
}
/**
* @return <i>This is a Welcome window</i>
* @see WelcomeTopComponent
*/
static String HINT_WelcomeTopComponent() {
return org.openide.util.NbBundle.getMessage(Bundle.class, "HINT_WelcomeTopComponent");
}
private void Bundle() {}
}
|
<gh_stars>100-1000
//
// CBZVectorSplashView.h
// Telly
//
// Created by <NAME> on 8/7/14.
// Copyright (c) 2014 Telly, Inc. All rights reserved.
//
#import "CBZSplashView.h"
/**
* VectorSplash uses a UIBezierPath to carve a mask in the middle that expands while revealing the content behind it.
*/
@interface CBZVectorSplashView : CBZSplashView
- (instancetype)initWithBezierPath:(UIBezierPath *)bezier backgroundColor:(UIColor *)backgroundColor;
@end
|
<gh_stars>0
const TextModel = require('../model/Text');
const conection = require('../helper/conection');
class CreateTextService{
async execute(texto){
const textModel = new TextModel(texto);
await conection('texto').insert(textModel);
return textModel;
}
}
module.exports = CreateTextService; |
<filename>tests/cmd_app_touch/touch/src/ux/parse/Reader.js
Ext.define('Ext.ux.parse.Reader', {
extend: 'Ext.data.reader.Json',
alias: 'reader.parse',
getResponseData: function(response) {
if(response instanceof Parse.Relation) {
return null;
} if (response instanceof Parse.Collection || Ext.isArray(response)) {
var results = [];
if (Ext.isArray(response)) {
response = {
models: response
}
}
Ext.Array.forEach(response.models, function(item) {
item.attributes.id = item.id;
results.push(item.attributes);
});
return results;
}
return response;
},
buildRecordDataExtractor: function() {
var me = this,
code = [
'return function(source) {',
'return source;',
'}'
];
return Ext.functionFactory(code.join('')).call(me);
}
})
; |
<gh_stars>0
#include "ObjectPrueba.h"
#ifndef STACK_H
#define STACK_H
#define stack(T) \
typedef struct Stack_##T##Private Stack_##T##Private; \
\
typedef struct stack_##T \
{ \
Object object; \
private(Stack_##T); \
void (*Push)(T *); \
T *(*Pop)(void); \
T *(*PeekStackPointer)(void); \
} Stack_##T; \
#define Stack(T) Stack_##T
#define StackCollection(T) StackExpand(N, T)
#define StackExpand(N, T) N##T()
stack(Int16);
stack(Int32);
stack(Int64);
stack(UInt16);
stack(UInt32);
stack(UInt64);
stack(String);
/* Constructors */
extern void *NStack_Int16(void);
extern void *NStack_Int32(void);
extern void *NStack_Int64(void);
extern void *NStack_UInt16(void);
extern void *NStack_UInt32(void);
extern void *NStack_UInt64(void);
extern void *NStack_String(void);
/* Int16 */
extern void Stack_Int16_Push(Int16 *, Stack_Int16 * const);
extern Int16 *Stack_Int16_Pop(Stack_Int16 * const);
extern Int16 *Stack_Int16_PeekStackPointer(Stack_Int16 * const);
/* Int32 */
extern void Stack_Int32_Push(Int32 *, Stack_Int32 * const);
extern Int32 *Stack_Int32_Pop(Stack_Int32 * const);
extern Int32 *Stack_Int32_PeekStackPointer(Stack_Int32 * const);
/* Int64 */
extern void Stack_Int64_Push(Int64 *, Stack_Int64 * const);
extern Int64 *Stack_Int64_Pop(Stack_Int64 * const);
extern Int64 *Stack_Int64_PeekStackPointer(Stack_Int64 * const);
/* UInt16 */
extern void Stack_UInt16_Push(UInt16 *, Stack_UInt16 * const);
extern UInt16 *Stack_UInt16_Pop(Stack_UInt16 * const);
extern UInt16 *Stack_UInt16_PeekStackPointer(Stack_UInt16 * const);
/* UInt32 */
extern void Stack_UInt32_Push(UInt32 *, Stack_UInt32 * const);
extern UInt32 *Stack_UInt32_Pop(Stack_UInt32 * const);
extern UInt32 *Stack_UInt32_PeekStackPointer(Stack_UInt32 * const);
/* UInt64 */
extern void Stack_UInt64_Push(UInt64 *, Stack_UInt64 * const);
extern UInt64 *Stack_UInt64_Pop(Stack_UInt64 * const);
extern UInt64 *Stack_UInt64_PeekStackPointer(Stack_UInt64 * const);
/* String */
extern void Stack_String_Push(String *, Stack_String * const);
extern String *Stack_String_Pop(Stack_String * const);
extern String *Stack_String_PeekStackPointer(Stack_String * const);
#endif /* STACK_H */ |
package com.uber.nullaway;
import org.junit.Test;
public class NullAwayBytecodeInteractionsTests extends NullAwayTestsBase {
@Test
public void typeUseJarReturn() {
defaultCompilationHelper
.addSourceLines(
"Test.java",
"package com.uber;",
"import com.uber.lib.*;",
"class Test {",
" void foo(CFNullableStuff.NullableReturn r) {",
" // BUG: Diagnostic contains: dereferenced expression",
" r.get().toString();",
" }",
"}")
.doTest();
}
@Test
public void typeUseJarParam() {
defaultCompilationHelper
.addSourceLines(
"Test.java",
"package com.uber;",
"import com.uber.lib.*;",
"class Test {",
" void foo(CFNullableStuff.NullableParam p) {",
" p.doSomething(null);",
" // BUG: Diagnostic contains: passing @Nullable parameter",
" p.doSomething2(null, new Object());",
" p.doSomething2(new Object(), null);",
" }",
"}")
.doTest();
}
@Test
public void typeUseJarField() {
defaultCompilationHelper
.addSourceLines(
"Test.java",
"package com.uber;",
"import com.uber.lib.*;",
"class Test {",
" void foo(CFNullableStuff c) {",
" // BUG: Diagnostic contains: dereferenced expression c.f",
" c.f.toString();",
" }",
"}")
.doTest();
}
@Test
public void typeUseJarOverride() {
defaultCompilationHelper
.addSourceLines(
"Test.java",
"package com.uber;",
"import com.uber.lib.*;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"class Test {",
" class Test1 implements CFNullableStuff.NullableReturn {",
" public @Nullable Object get() { return null; }",
" }",
" class Test2 implements CFNullableStuff.NullableParam {",
" // BUG: Diagnostic contains: parameter o is @NonNull",
" public void doSomething(Object o) {}",
" // BUG: Diagnostic contains: parameter p is @NonNull",
" public void doSomething2(Object o, Object p) {}",
" }",
" class Test3 implements CFNullableStuff.NullableParam {",
" public void doSomething(@Nullable Object o) {}",
" public void doSomething2(Object o, @Nullable Object p) {}",
" }",
"}")
.doTest();
}
}
|
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+0+512-rare/13-model --tokenizer_name model-configs/1024-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+0+512-rare/13-512+0+512-N-VB-IP-first-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function replace_all_but_nouns_and_verbs_first_half_quarter --eval_function penultimate_quarter_eval |
#!/usr/bin/env bash
set -xe
ENV_FILE="${1}"; shift # path to environment yaml or lock file
NEW_ENV="${1}"; shift # true or false indicating whether env update should occur
# Capture last optional arg or set a ENV_NAME. This can be changed but be
# careful... setting the path for both the dockerfile and runtime container
# can be tricky
if [[ -z "${1+x}" ]] || [[ "${1}" == "" ]]; then
ENV_NAME=default
else
ENV_NAME="${1}"; shift
fi
# Set a default value for skipping the conda solve (using a lock file).
: ${SKIP_CONDA_SOLVE:=no}
# ==== install conda dependencies ====
if ! ${NEW_ENV};then
if [[ $(basename "${ENV_FILE}") =~ "*lock*" ]];then
echo "${ENV_FILE} should not be a lock file as this is not supported when \
only updating the conda environment. Consider setting NEW_ENV to yes."
exit 1
fi
echo Installing into current conda environment
conda env update -f "${ENV_FILE}"
# Env not being updated... create one now:
elif [[ "${SKIP_CONDA_SOLVE}" == "no" ]];then
conda env create --prefix=/opt/conda/envs/${ENV_NAME} -f "${ENV_FILE}"
elif [[ "${SKIP_CONDA_SOLVE}" == "yes" ]];then
conda create --prefix=/opt/conda/envs/${ENV_NAME} --file "${ENV_FILE}"
# This needs to be set using the ENV directive in the docker file
PATH="/opt/conda/envs/${ENV_NAME}/bin:${PATH}"
# For now install pip section manually. We could consider using pip-tools...
# See https://github.com/conda-incubator/conda-lock/issues/4
pip install https://github.com/dirkcgrunwald/jupyter_codeserver_proxy-/archive/5596bc9c2fbd566180545fa242c659663755a427.tar.gz
else
echo "SKIP_CONDA_SOLVE should be yes or no instead got: '${SKIP_CONDA_SOLVE}'"
exit 1
fi
# ========= list dependencies ========
/opt/conda/bin/conda list
# ========== cleanup conda ===========
/opt/conda/bin/conda clean -afy
# remove unnecissary files (statis, js.maps)
find /opt/conda/ -follow -type f -name '*.a' -delete
find /opt/conda/ -follow -type f -name '*.js.map' -delete
# Fix permissions
fix-permissions "/opt/conda/envs/${ENV_NAME}" || fix-permissions /opt/conda/bin
|
#!/bin/sh
wget http://www.saxonica.com/download/SaxonPE9-4-0-4J.zip
unzip SaxonPE9-4-0-4J.zip
mv saxon9pe.jar lib/
rm saxon*.jar
rm SaxonPE9-4-0-4J.zip
wget http://jdbc.postgresql.org/download/postgresql-9.1-902.jdbc4.jar
mv postgresql-9.1-902.jdbc4.jar lib/postgresql-9.1-902.jdbc4.jar |
import numpy as np
def add(x, y):
# adds two matrices x and y
return np.add(x, y)
def subtract(x, y):
# subtracts two matrices x and y
return np.subtract(x, y)
def multiply(x, y):
# multiplies two matrices x and y
return np.matmul(x, y)
def transpose(x):
# transpose a matrix x
return np.transpose(x)
def determinant(x):
# finds the determinant of a matrix x
return np.linalg.det(x)
def inverse(x):
# finds the inverse of a matrix x
return np.linalg.inv(x) |
/* global chrome */
chrome.runtime.onInstalled.addListener((details) => {
if (details.reason === 'install') {
chrome.runtime.openOptionsPage()
}
})
|
<gh_stars>100-1000
import checkThreshold, { checkPercentage, checkValue, isPercentage, percentToNumber } from './threshold';
describe('@modus/gimbal-core/utils/threshold', (): void => {
describe('checkPercentage', (): void => {
describe('lower mode', (): void => {
it('should succeed', (): void => {
const ret = checkPercentage('4%', '2%', 'lower');
expect(ret).toBe(true);
});
it('should succeed when same value', (): void => {
const ret = checkPercentage('4%', '4%', 'lower');
expect(ret).toBe(true);
});
it('should fail', (): void => {
const ret = checkPercentage('4%', '5%', 'lower');
expect(ret).toBe(false);
});
});
describe('upper mode', (): void => {
it('should succeed', (): void => {
const ret = checkPercentage('4%', '5%', 'upper');
expect(ret).toBe(true);
});
it('should succeed when same value', (): void => {
const ret = checkPercentage('4%', '4%', 'upper');
expect(ret).toBe(true);
});
it('should fail', (): void => {
const ret = checkPercentage('4%', '3%', 'upper');
expect(ret).toBe(false);
});
});
});
describe('checkValue', (): void => {
describe('lower mode', (): void => {
it('should succeed', (): void => {
const ret = checkValue(4, 2, 'lower');
expect(ret).toBe(true);
});
it('should succeed when same value', (): void => {
const ret = checkValue(4, 4, 'lower');
expect(ret).toBe(true);
});
it('should fail', (): void => {
const ret = checkValue(4, 5, 'lower');
expect(ret).toBe(false);
});
});
describe('upper mode', (): void => {
it('should succeed', (): void => {
const ret = checkValue(4, 5, 'upper');
expect(ret).toBe(true);
});
it('should succeed when same value', (): void => {
const ret = checkValue(4, 4, 'upper');
expect(ret).toBe(true);
});
it('should fail', (): void => {
const ret = checkValue(4, 3, 'upper');
expect(ret).toBe(false);
});
});
});
describe('isPercentage', (): void => {
it('should be a percentage', (): void => {
const ret = isPercentage('1%');
expect(ret).toBe(true);
});
it('should not be a percentage', (): void => {
const ret = isPercentage(1458917245);
expect(ret).toBe(false);
});
});
describe('percentToNumber', (): void => {
it('should return a number', (): void => {
const ret = percentToNumber('58%');
expect(ret).toBe(58);
});
});
describe('checkThreshold', (): void => {
describe('lower mode', (): void => {
it('should succeed with a percentage', (): void => {
const ret = checkThreshold('4%', '2%', 'lower');
expect(ret).toBe(true);
});
it('should succeed with a percentage when same value', (): void => {
const ret = checkThreshold('4%', '4%', 'lower');
expect(ret).toBe(true);
});
it('should fail with a percentage', (): void => {
const ret = checkThreshold('4%', '5%', 'lower');
expect(ret).toBe(false);
});
it('should succeed with a value', (): void => {
const ret = checkThreshold(4, 2, 'lower');
expect(ret).toBe(true);
});
it('should succeed with a value when same value', (): void => {
const ret = checkThreshold(4, 4, 'lower');
expect(ret).toBe(true);
});
it('should fail with a value', (): void => {
const ret = checkThreshold(4, 5, 'lower');
expect(ret).toBe(false);
});
});
describe('upper mode', (): void => {
it('should succeed with a percentage', (): void => {
const ret = checkThreshold('4%', '5%');
expect(ret).toBe(true);
});
it('should succeed with a percentage when same value', (): void => {
const ret = checkThreshold('4%', '4%');
expect(ret).toBe(true);
});
it('should fail with a percentage', (): void => {
const ret = checkThreshold('4%', '3%');
expect(ret).toBe(false);
});
it('should succeed with a value', (): void => {
const ret = checkThreshold(4, 5);
expect(ret).toBe(true);
});
it('should succeed with a value when same value', (): void => {
const ret = checkThreshold(4, 4);
expect(ret).toBe(true);
});
it('should fail with a value', (): void => {
const ret = checkThreshold(4, 3);
expect(ret).toBe(false);
});
});
});
});
|
#!/bin/bash
# v1.0.0
#------------------------------------------------------------------------------
# print the specs for the create-full-7z-package functionality
#------------------------------------------------------------------------------
doSpecCreateFull7zPackage(){
doLog "INFO ::: START ::: create-full-7z-package" ;
cat doc/txt/pgsql-runner/specs/pckg/create-full-7z-package.spec.txt
sleep $sleep_interval
printf "\033[2J";printf "\033[0;0H"
doLog "INFO ::: STOP ::: create-full-7z-package" ;
}
#eof spec doCreateFullPackage
|
package nsq
import (
"context"
"log"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/nsqio/go-nsq"
)
// Consumer instance
type Consumer struct {
listenAddress []string
prefix string
handlers []ConsumerHandler
nsqConsumers []*nsq.Consumer
stopTimeout time.Duration
}
// ConsumerConfig config for the consumer instance
type ConsumerConfig struct {
ListenAddress []string
Prefix string
StopTimeout time.Duration
}
// ConsumerHandler handler for consumer
type ConsumerHandler struct {
Topic string
Channel string
Concurrent int
MaxAttempts uint16
MaxInFlight int
Enable bool
Handler func(message IMessage) error
}
// NewConsumer will instantiate the nsq consumer
func NewConsumer(cfg ConsumerConfig) *Consumer {
return &Consumer{
listenAddress: cfg.ListenAddress,
prefix: cfg.Prefix,
}
}
// RegisterHandler will register the consumer handlers
func (c *Consumer) RegisterHandler(handler ConsumerHandler) {
if handler.Enable {
c.handlers = append(c.handlers, handler)
}
}
// Run will connecting all registered consumer handlers to the nsqlookupd address
func (c *Consumer) Run() error {
for _, h := range c.handlers {
cfg := nsq.NewConfig()
cfg.MaxAttempts = h.MaxAttempts
cfg.MaxInFlight = h.MaxInFlight
q, err := nsq.NewConsumer(h.Topic, h.Channel, cfg)
if err != nil {
return err
}
if h.Concurrent != 0 {
q.AddConcurrentHandlers(c.handle(h.Handler), h.Concurrent)
} else {
q.AddHandler(c.handle(h.Handler))
}
err = q.ConnectToNSQLookupds(c.listenAddress)
if err != nil {
err = q.ConnectToNSQDs(c.listenAddress)
}
if err != nil {
return err
}
c.nsqConsumers = append(c.nsqConsumers, q)
}
return nil
}
// RunDirect will connecting all registered consumer handlers directly to the nsqd address
func (c *Consumer) RunDirect() error {
for _, h := range c.handlers {
cfg := nsq.NewConfig()
cfg.MaxAttempts = h.MaxAttempts
cfg.MaxInFlight = h.MaxInFlight
q, err := nsq.NewConsumer(h.Topic, h.Channel, cfg)
if err != nil {
return err
}
if h.Concurrent != 0 {
q.AddConcurrentHandlers(c.handle(h.Handler), h.Concurrent)
} else {
q.AddHandler(c.handle(h.Handler))
}
err = q.ConnectToNSQDs(c.listenAddress)
if err != nil {
return err
}
c.nsqConsumers = append(c.nsqConsumers, q)
}
return nil
}
// handle will convert the func(msg Message) error into nsq.HandlerFunc
func (c *Consumer) handle(fn func(IMessage) error) nsq.HandlerFunc {
return func(message *nsq.Message) error {
msg := &Message{
message,
}
return fn(msg)
}
}
// Wait waits for the stop/restart signal and shutdown the NSQ consumers
// gracefully
func (c *Consumer) Wait() {
<-WaitTermSig(c.stop)
}
// stop the nsq consumers gracefully
func (c *Consumer) stop(ctx context.Context) error {
var wg sync.WaitGroup
for _, con := range c.nsqConsumers {
wg.Add(1)
con := con
go func() { // use goroutines to stop all of them ASAP
defer wg.Done()
con.Stop()
select {
case <-con.StopChan:
case <-ctx.Done():
case <-time.After(c.stopTimeout):
}
}()
}
wg.Wait()
return nil
}
// WaitTermSig wait for termination signal
func WaitTermSig(handler func(context.Context) error) <-chan struct{} {
stoppedCh := make(chan struct{})
go func() {
signals := make(chan os.Signal, 1)
// wait for the sigterm
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
<-signals
// We received an os signal, shut down.
if err := handler(context.Background()); err != nil {
log.Printf("graceful shutdown fail: %v", err)
} else {
log.Println("gracefull shutdown success")
}
close(stoppedCh)
}()
return stoppedCh
}
|
#!/bin/bash
#
# test case 6.1
#
# xfer funds between lite accounts
# ids, amount and server IP:Port needed
#
# set cli command and see if it exists
#
export cli=../cmd/cli/cli
if [ ! -f $cli ]; then
echo "cli command not found in ../cmd/cli, attempting to build"
./build_cli.sh
if [ ! -f $cli ]; then
echo "cli command failed to build"
exit 0
fi
fi
# check for command line parameters
#
# if IDs not entered on the command line, prompt for one and exit
if [ -z $1 ]; then
echo "Usage: test_case_6.1.sh fromID toID numTokens IPAddress:Port"
exit 0
fi
# see if $1 is really an ID
id1=$1
size=${#id1}
if [ $size -lt 59 ]; then
echo "Expected acc://<48 byte string>/ACME"
exit 0
fi
if [ -z $2 ]; then
echo "Usage: test_case_6.1.sh fromID toID numTokens IPAddress:Port"
exit 0
fi
# see if $2 is really an ID
id2=$2
size=${#id2}
if [ $size -lt 59 ]; then
echo "Expected acc://<48 byte string>/ACME"
exit 0
fi
if [ -z $3 ]; then
echo "Usage: test_case_6.1.sh fromID toID numTokens IPAddress:Port"
exit 0
fi
# call our xfer script
./cli_xfer_tokens.sh $id1 $id2 $3 $4
|
#!/bin/sh
# G O U R C E . S H
# BRL-CAD
#
# Published in 2021 by the United States Government.
# This work is in the public domain.
#
#
###
# Note - for current gource git log formatting, see:
#
# gource --log-command git
STARTDATE=2019-11-01
STARTSHA1=$(git rev-list -n1 --before="$STARTDATE" main)
STARTAUTH=$(git log -n 1 --format='%an' $STARTSHA1)
STARTTIME=$(git log -n 1 --format='%at' $STARTSHA1)
echo "user:$STARTAUTH" > input.log
echo "$STARTTIME" >> input.log
git ls-tree -r $STARTSHA1| awk '{printf ":000000 %s 0000000000 %s A\t%s\n", $1, substr($3, 1, 10), $4}' >> input.log
echo "" >> input.log
git log --pretty=format:user:%aN%n%ct --reverse --raw --encoding=UTF-8 --no-renames --no-show-signature --after=$STARTDATE >> input.log
g++ -o git2gource git2gource.cpp
./git2gource input.log > gource.log
#gource --date-format "%F" --key --1920x1080 --hide filenames,mouse,progress --file-idle-time 0 --max-files 0 --highlight-users --multi-sampling --auto-skip-seconds .1 -s 0.6 gource.log
# Local Variables:
# tab-width: 8
# mode: sh
# sh-indentation: 4
# sh-basic-offset: 4
# indent-tabs-mode: t
# End:
# ex: shiftwidth=4 tabstop=8
|
window.onload = () => {
// Creating helper function to set multiple attributes
function setAttribute(elmName,attribute){
for(let key in attribute){
elmName.setAttribute('elmName','attribute[key]');
}
}
var html = document.getElementsByTagName('html');
html.style.innerText = `font-size: 12px;font-weight: 300;`;
var body = document.getElementsByTagName('body');
body.style.width = '90vw';
var main = document.createElement('main');
var startScreen = document.createElement('div'); // create a div
startScreen.setAttribute('id','startScreen'); // setting id to div
var note1 = document.createElement('h1');
note1.innerText = "Guess the Random number between 1-100";
startScreen.appendChild(note1); // added a heading to start screen
main.appendChild(startScreen); // added a div to main
document.body.appendChild(main); // added a main in body
}
|
#!/bin/bash
# Project: Game Server Managers - LinuxGSM
# Author: Daniel Gibbs
# License: MIT License, Copyright (c) 2020 Daniel Gibbs
# Purpose: Travis CI Tests: Minecraft | Linux Game Server Management Script
# Contributors: https://linuxgsm.com/contrib
# Documentation: https://docs.linuxgsm.com
# Website: https://linuxgsm.com
# DO NOT EDIT THIS FILE
# LinuxGSM configuration is no longer edited here
# To update your LinuxGSM config go to:
# lgsm/config-lgsm
# https://docs.linuxgsm.com/configuration/linuxgsm-config
# Debugging
if [ -f ".dev-debug" ]; then
exec 5>dev-debug.log
BASH_XTRACEFD="5"
set -x
fi
version="v20.2.0"
shortname="mc"
gameservername="mcserver"
rootdir=$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")
selfname=$(basename "$(readlink -f "${BASH_SOURCE[0]}")")
lgsmdir="${rootdir}/lgsm"
logdir="${rootdir}/log"
lgsmlogdir="${logdir}/lgsm"
steamcmddir="${HOME}/.steam/steamcmd"
serverfiles="${rootdir}/serverfiles"
functionsdir="${lgsmdir}/functions"
tmpdir="${lgsmdir}/tmp"
datadir="${lgsmdir}/data"
lockdir="${lgsmdir}/lock"
serverlist="${datadir}/serverlist.csv"
serverlistmenu="${datadir}/serverlistmenu.csv"
configdir="${lgsmdir}/config-lgsm"
configdirserver="${configdir}/${gameservername}"
configdirdefault="${lgsmdir}/config-default"
userinput="${1}"
# Allows for testing not on Travis CI.
# if using travis for tests
if [ -n "${TRAVIS}" ]; then
selfname="travis"
# if not using travis for tests
else
TRAVIS_BRANCH="develop"
TRAVIS_BUILD_DIR="${rootdir}"
fi
travistest="1"
## GitHub Branch Select
# Allows for the use of different function files
# from a different repo and/or branch.
githubuser="GameServerManagers"
githubrepo="LinuxGSM"
githubbranch="${TRAVIS_BRANCH}"
# Core function that is required first.
core_functions.sh(){
functionfile="${FUNCNAME[0]}"
fn_bootstrap_fetch_file_github "lgsm/functions" "core_functions.sh" "${functionsdir}" "chmodx" "run" "noforcedl" "nomd5"
}
# Bootstrap
# Fetches the core functions required before passed off to core_dl.sh.
fn_bootstrap_fetch_file(){
remote_fileurl="${1}"
local_filedir="${2}"
local_filename="${3}"
chmodx="${4:-0}"
run="${5:-0}"
forcedl="${6:-0}"
md5="${7:-0}"
# Download file if missing or download forced.
if [ ! -f "${local_filedir}/${local_filename}" ]||[ "${forcedl}" == "forcedl" ]; then
if [ ! -d "${local_filedir}" ]; then
mkdir -p "${local_filedir}"
fi
# If curl exists download file.
if [ "$(command -v curl 2>/dev/null)" ]; then
# Trap to remove part downloaded files.
echo -en " fetching ${local_filename}...\c"
curlcmd=$(curl -s --fail -L -o "${local_filedir}/${local_filename}" "${remote_fileurl}" 2>&1)
local exitcode=$?
if [ ${exitcode} -ne 0 ]; then
echo -e "FAIL"
if [ -f "${lgsmlog}" ]; then
echo -e "${remote_fileurl}" | tee -a "${lgsmlog}"
echo -e "${curlcmd}" | tee -a "${lgsmlog}"
fi
exit 1
else
echo -e "OK"
fi
else
echo -e "[ FAIL ] Curl is not installed"
exit 1
fi
# Make file chmodx if chmodx is set.
if [ "${chmodx}" == "chmodx" ]; then
chmod +x "${local_filedir}/${local_filename}"
fi
fi
if [ -f "${local_filedir}/${local_filename}" ]; then
# Run file if run is set.
if [ "${run}" == "run" ]; then
# shellcheck source=/dev/null
source "${local_filedir}/${local_filename}"
fi
fi
}
fn_bootstrap_fetch_file_github(){
github_file_url_dir="${1}"
github_file_url_name="${2}"
githuburl="https://raw.githubusercontent.com/${githubuser}/${githubrepo}/${githubbranch}/${github_file_url_dir}/${github_file_url_name}"
remote_fileurl="${githuburl}"
local_filedir="${3}"
local_filename="${github_file_url_name}"
chmodx="${4:-0}"
run="${5:-0}"
forcedl="${6:-0}"
md5="${7:-0}"
# Passes vars to the file download function.
fn_bootstrap_fetch_file "${remote_fileurl}" "${local_filedir}" "${local_filename}" "${chmodx}" "${run}" "${forcedl}" "${md5}"
}
# Installer menu.
fn_print_center() {
columns=$(tput cols)
line="$*"
printf "%*s\n" $(( (${#line} + columns) / 2)) "${line}"
}
fn_print_horizontal(){
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' "="
}
# Bash menu.
fn_install_menu_bash() {
local resultvar=$1
title=$2
caption=$3
options=$4
fn_print_horizontal
fn_print_center "${title}"
fn_print_center "${caption}"
fn_print_horizontal
menu_options=()
while read -r line || [[ -n "${line}" ]]; do
var=$(echo -e "${line}" | awk -F "," '{print $2 " - " $3}')
menu_options+=( "${var}" )
done < "${options}"
menu_options+=( "Cancel" )
select option in "${menu_options[@]}"; do
if [ "${option}" ]&&[ "${option}" != "Cancel" ]; then
eval "$resultvar=\"${option/%\ */}\""
fi
break
done
}
# Whiptail/Dialog menu.
fn_install_menu_whiptail() {
local menucmd=$1
local resultvar=$2
title=$3
caption=$4
options=$5
height=${6:-40}
width=${7:-80}
menuheight=${8:-30}
IFS=","
menu_options=()
while read -r line; do
key=$(echo -e "${line}" | awk -F "," '{print $3}')
val=$(echo -e "${line}" | awk -F "," '{print $2}')
menu_options+=( "${val//\"}" "${key//\"}" )
done < "${options}"
OPTION=$(${menucmd} --title "${title}" --menu "${caption}" "${height}" "${width}" "${menuheight}" "${menu_options[@]}" 3>&1 1>&2 2>&3)
if [ $? == 0 ]; then
eval "$resultvar=\"${OPTION}\""
else
eval "$resultvar="
fi
}
# Menu selector.
fn_install_menu() {
local resultvar=$1
local selection=""
title=$2
caption=$3
options=$4
# Get menu command.
for menucmd in whiptail dialog bash; do
if [ "$(command -v "${menucmd}")" ]; then
menucmd=$(command -v "${menucmd}")
break
fi
done
case "$(basename "${menucmd}")" in
whiptail|dialog)
fn_install_menu_whiptail "${menucmd}" selection "${title}" "${caption}" "${options}" 40 80 30;;
*)
fn_install_menu_bash selection "${title}" "${caption}" "${options}";;
esac
eval "$resultvar=\"${selection}\""
}
# Gets server info from serverlist.csv and puts in to array.
fn_server_info(){
IFS=","
server_info_array=($(grep -aw "${userinput}" "${serverlist}"))
shortname="${server_info_array[0]}" # csgo
gameservername="${server_info_array[1]}" # csgoserver
gamename="${server_info_array[2]}" # Counter Strike: Global Offensive
}
fn_install_getopt(){
userinput="empty"
echo -e "Usage: $0 [option]"
echo -e ""
echo -e "Installer - Linux Game Server Managers - Version ${version}"
echo -e "https://linuxgsm.com"
echo -e ""
echo -e "Commands"
echo -e "install\t\t| Select server to install."
echo -e "servername\t| Enter name of game server to install. e.g $0 csgoserver."
echo -e "list\t\t| List all servers available for install."
exit
}
fn_install_file(){
local_filename="${gameservername}"
if [ -e "${local_filename}" ]; then
i=2
while [ -e "${local_filename}-${i}" ] ; do
(( i++ ))
done
local_filename="${local_filename}-${i}"
fi
cp -R "${selfname}" "${local_filename}"
sed -i -e "s/shortname=\"core\"/shortname=\"${shortname}\"/g" "${local_filename}"
sed -i -e "s/gameservername=\"core\"/gameservername=\"${gameservername}\"/g" "${local_filename}"
echo -e "Installed ${gamename} server as ${local_filename}"
echo -e ""
if [ ! -d "${serverfiles}" ]; then
echo -e "./${local_filename} install"
else
echo -e "Remember to check server ports"
echo -e "./${local_filename} details"
fi
echo -e ""
exit
}
# Prevent LinuxGSM from running as root. Except if doing a dependency install.
if [ "$(whoami)" == "root" ]; then
if [ "${userinput}" == "install" ]||[ "${userinput}" == "auto-install" ]||[ "${userinput}" == "i" ]||[ "${userinput}" == "ai" ]; then
if [ "${shortname}" == "core" ]; then
echo -e "[ FAIL ] Do NOT run this script as root!"
exit 1
fi
elif [ ! -f "${functionsdir}/core_functions.sh" ]||[ ! -f "${functionsdir}/check_root.sh" ]||[ ! -f "${functionsdir}/core_messages.sh" ]; then
echo -e "[ FAIL ] Do NOT run this script as root!"
exit 1
else
core_functions.sh
check_root.sh
fi
fi
# LinuxGSM installer mode.
if [ "${shortname}" == "core" ]; then
# Download the latest serverlist. This is the complete list of all supported servers.
fn_bootstrap_fetch_file_github "lgsm/data" "serverlist.csv" "${datadir}" "nochmodx" "norun" "forcedl" "nomd5"
if [ ! -f "${serverlist}" ]; then
echo -e "[ FAIL ] serverlist.csv could not be loaded."
exit 1
fi
if [ "${userinput}" == "list" ]||[ "${userinput}" == "l" ]; then
{
tail -n +2 "${serverlist}" | awk -F "," '{print $2 "\t" $3}'
} | column -s $'\t' -t | more
exit
elif [ "${userinput}" == "install" ]||[ "${userinput}" == "i" ]; then
tail -n +2 "${serverlist}" | awk -F "," '{print $1 "," $2 "," $3}' > "${serverlistmenu}"
fn_install_menu result "LinuxGSM" "Select game server to install." "${serverlistmenu}"
userinput="${result}"
fn_server_info
if [ "${result}" == "${gameservername}" ]; then
fn_install_file
elif [ "${result}" == "" ]; then
echo -e "Install canceled"
else
echo -e "[ FAIL ] menu result does not match gameservername"
echo -e "result: ${result}"
echo -e "gameservername: ${gameservername}"
fi
elif [ "${userinput}" ]; then
fn_server_info
if [ "${userinput}" == "${gameservername}" ]||[ "${userinput}" == "${gamename}" ]||[ "${userinput}" == "${shortname}" ]; then
fn_install_file
else
echo -e "[ FAIL ] unknown game server"
fi
else
fn_install_getopt
fi
# LinuxGSM server mode.
else
core_functions.sh
if [ "${shortname}" != "core-dep" ]; then
# Load LinuxGSM configs.
# These are required to get all the default variables for the specific server.
# Load the default config. If missing download it. If changed reload it.
if [ ! -f "${configdirdefault}/config-lgsm/${gameservername}/_default.cfg" ]; then
mkdir -p "${configdirdefault}/config-lgsm/${gameservername}"
fn_fetch_config "lgsm/config-default/config-lgsm/${gameservername}" "_default.cfg" "${configdirdefault}/config-lgsm/${gameservername}" "_default.cfg" "nochmodx" "norun" "noforcedl" "nomd5"
fi
if [ ! -f "${configdirserver}/_default.cfg" ]; then
mkdir -p "${configdirserver}"
echo -en " copying _default.cfg...\c"
cp -R "${configdirdefault}/config-lgsm/${gameservername}/_default.cfg" "${configdirserver}/_default.cfg"
exitcode=$?
if [ ${exitcode} -ne 0 ]; then
echo -e "FAIL"
exit 1
else
echo -e "OK"
fi
else
function_file_diff=$(diff -q "${configdirdefault}/config-lgsm/${gameservername}/_default.cfg" "${configdirserver}/_default.cfg")
if [ "${function_file_diff}" != "" ]; then
fn_print_warn_nl "_default.cfg has been altered. reloading config."
echo -en " copying _default.cfg...\c"
cp -R "${configdirdefault}/config-lgsm/${gameservername}/_default.cfg" "${configdirserver}/_default.cfg"
exitcode=$?
if [ ${exitcode} -ne 0 ]; then
echo -e "FAIL"
exit 1
else
echo -e "OK"
fi
fi
fi
# shellcheck source=/dev/null
source "${configdirserver}/_default.cfg"
# Load the common.cfg config. If missing download it.
if [ ! -f "${configdirserver}/common.cfg" ]; then
fn_fetch_config "lgsm/config-default/config-lgsm" "common-template.cfg" "${configdirserver}" "common.cfg" "${chmodx}" "nochmodx" "norun" "noforcedl" "nomd5"
# shellcheck source=/dev/null
source "${configdirserver}/common.cfg"
else
# shellcheck source=/dev/null
source "${configdirserver}/common.cfg"
fi
# Load the instance.cfg config. If missing download it.
if [ ! -f "${configdirserver}/${selfname}.cfg" ]; then
fn_fetch_config "lgsm/config-default/config-lgsm" "instance-template.cfg" "${configdirserver}" "${selfname}.cfg" "nochmodx" "norun" "noforcedl" "nomd5"
# shellcheck source=/dev/null
source "${configdirserver}/${selfname}.cfg"
else
# shellcheck source=/dev/null
source "${configdirserver}/${selfname}.cfg"
fi
# Load the linuxgsm.sh in to tmpdir. If missing download it.
if [ ! -f "${tmpdir}/linuxgsm.sh" ]; then
fn_fetch_file_github "" "linuxgsm.sh" "${tmpdir}" "chmodx" "norun" "noforcedl" "nomd5"
fi
fi
# Enables ANSI colours from core_messages.sh. Can be disabled with ansi=off.
fn_ansi_loader
# Prevents running of core_exit.sh for Travis-CI.
if [ "${travistest}" != "1" ]; then
getopt=$1
core_getopt.sh
fi
fi
fn_currentstatus_tmux(){
check_status.sh
if [ "${status}" != "0" ]; then
currentstatus="ONLINE"
else
currentstatus="OFFLINE"
fi
}
fn_setstatus(){
fn_currentstatus_tmux
echo""
echo -e "Required status: ${requiredstatus}"
counter=0
echo -e "Current status: ${currentstatus}"
while [ "${requiredstatus}" != "${currentstatus}" ]; do
counter=$((counter+1))
fn_currentstatus_tmux
echo -en "New status: ${currentstatus}\\r"
if [ "${requiredstatus}" == "ONLINE" ]; then
(command_start.sh > /dev/null 2>&1)
else
(command_stop.sh > /dev/null 2>&1)
fi
if [ "${counter}" -gt "5" ]; then
currentstatus="FAIL"
echo -e "Current status: ${currentstatus}"
echo -e ""
echo -e "Unable to start or stop server."
exit 1
fi
done
echo -en "New status: ${currentstatus}\\r"
echo -e "\n"
echo -e "Test starting:"
echo -e ""
}
# End of every test will expect the result to either pass or fail
# If the script does not do as intended the whole test will fail
# if expecting a pass
fn_test_result_pass(){
if [ $? != 0 ]; then
echo -e "================================="
echo -e "Expected result: PASS"
echo -e "Actual result: FAIL"
fn_print_fail_nl "TEST FAILED"
exitcode=1
core_exit.sh
else
echo -e "================================="
echo -e "Expected result: PASS"
echo -e "Actual result: PASS"
fn_print_ok_nl "TEST PASSED"
echo -e ""
fi
}
# if expecting a fail
fn_test_result_fail(){
if [ $? == 0 ]; then
echo -e "================================="
echo -e "Expected result: FAIL"
echo -e "Actual result: PASS"
fn_print_fail_nl "TEST FAILED"
exitcode=1
core_exit.sh
else
echo -e "================================="
echo -e "Expected result: FAIL"
echo -e "Actual result: FAIL"
fn_print_ok_nl "TEST PASSED"
echo -e ""
fi
}
# test result n/a
fn_test_result_na(){
echo -e "================================="
echo -e "Expected result: N/A"
echo -e "Actual result: N/A"
fn_print_fail_nl "TEST N/A"
}
sleeptime="0"
echo -e "================================="
echo -e "Travis CI Tests"
echo -e "Linux Game Server Manager"
echo -e "by Daniel Gibbs"
echo -e "Contributors: http://goo.gl/qLmitD"
echo -e "https://linuxgsm.com"
echo -e "================================="
echo -e ""
echo -e "================================="
echo -e "Server Tests"
echo -e "Using: ${gamename}"
echo -e "Testing Branch: ${TRAVIS_BRANCH}"
echo -e "================================="
echo -e ""
echo -e "Tests Summary"
echo -e "================================="
echo -e "0.0 - Pre-test Tasks"
echo -e "0.1 - Create log dir's"
echo -e "0.2 - Enable dev-debug"
echo -e ""
echo -e "1.0 - Pre-install tests"
echo -e "1.1 - start - no files"
echo -e "1.2 - getopt"
echo -e "1.3 - getopt with incorrect args"
echo -e ""
echo -e "2.0 - Installation"
echo -e "2.1 - install"
echo -e ""
echo -e "3.0 - Start/Stop/Restart Tests"
echo -e "3.1 - start"
echo -e "3.2 - start - online"
echo -e "3.3 - start - updateonstart"
echo -e "3.4 - stop"
echo -e "3.5 - stop - offline"
echo -e "3.6 - restart"
echo -e "3.7 - restart - offline"
echo -e ""
echo -e "4.0 - Update Tests"
echo -e "4.1 - update"
echo -e "4.2 - update-lgsm"
echo -e ""
echo -e "5.0 - Monitor Tests"
echo -e "5.1 - monitor - online"
echo -e "5.2 - monitor - offline - with lockfile"
echo -e "5.3 - monitor - offline - no lockfile"
echo -e "5.4 - test-alert"
echo -e ""
echo -e "6.0 - Details Tests"
echo -e "6.1 - details"
echo -e "6.2 - postdetails"
echo -e ""
echo -e "7.0 - Backup Tests"
echo -e "7.1 - backup"
echo -e ""
echo -e "8.0 - Development Tools Tests"
echo -e "8.1 - dev - detect glibc"
echo -e "8.2 - dev - detect ldd"
echo -e "8.3 - dev - detect deps"
echo -e "8.4 - dev - query-raw"
echo -e ""
echo -e "9.0 - Donate"
echo -e "9.1 - donate"
echo -e ""
echo -e "0.0 - Pre-test Tasks"
echo -e "=================================================================="
echo -e "Description:"
echo -e "Create log dir's"
echo -e ""
echo -e ""
echo -e "0.1 - Create log dir's"
echo -e "================================="
echo -e ""
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
install_logs.sh
)
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "0.2 - Enable dev-debug"
echo -e "================================="
echo -e "Description:"
echo -e "Enable dev-debug"
echo -e ""
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_dev_debug.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "1.0 - Pre-install tests"
echo -e "=================================================================="
echo -e ""
echo -e "1.1 - start - no files"
echo -e "================================="
echo -e "Description:"
echo -e "test script reaction to missing server files."
echo -e "Command: ./${gameservername} start"
echo -e ""
# Allows for testing not on Travis CI
if [ -z "${TRAVIS}" ]; then
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_start.sh
)
fn_test_result_fail
else
echo -e "Test bypassed"
fi
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "1.2 - getopt"
echo -e "================================="
echo -e "Description:"
echo -e "displaying options messages."
echo -e "Command: ./${gameservername}"
echo -e ""
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
core_getopt.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "1.3 - getopt with incorrect args"
echo -e "================================="
echo -e "Description:"
echo -e "displaying options messages."
echo -e "Command: ./${gameservername} abc123"
echo -e ""
getopt="abc123"
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
core_getopt.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "2.0 - Installation"
echo -e "=================================================================="
echo -e ""
echo -e "2.1 - install"
echo -e "================================="
echo -e "Description:"
echo -e "install ${gamename} server."
echo -e "Command: ./${gameservername} auto-install"
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
fn_autoinstall
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "3.0 - Start/Stop/Restart Tests"
echo -e "=================================================================="
echo -e ""
echo -e "3.1 - start"
echo -e "================================="
echo -e "Description:"
echo -e "start ${gamename} server."
echo -e "Command: ./${gameservername} start"
requiredstatus="OFFLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_start.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "3.2 - start - online"
echo -e "================================="
echo -e "Description:"
echo -e "start ${gamename} server while already running."
echo -e "Command: ./${gameservername} start"
requiredstatus="ONLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_start.sh
)
fn_test_result_fail
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "3.3 - start - updateonstart"
echo -e "================================="
echo -e "Description:"
echo -e "will update server on start."
echo -e "Command: ./${gameservername} start"
requiredstatus="OFFLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
updateonstart="on";command_start.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "30s Pause"
echo -e "================================="
echo -e "Description:"
echo -e "give time for server to fully start."
echo -e "Command: sleep 30"
requiredstatus="ONLINE"
fn_setstatus
sleep 30
echo -e ""
echo -e "3.4 - stop"
echo -e "================================="
echo -e "Description:"
echo -e "stop ${gamename} server."
echo -e "Command: ./${gameservername} stop"
requiredstatus="ONLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_stop.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "3.5 - stop - offline"
echo -e "================================="
echo -e "Description:"
echo -e "stop ${gamename} server while already stopped."
echo -e "Command: ./${gameservername} stop"
requiredstatus="OFFLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_stop.sh
)
fn_test_result_fail
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "3.6 - restart"
echo -e "================================="
echo -e "Description:"
echo -e "restart ${gamename}."
echo -e "Command: ./${gameservername} restart"
requiredstatus="ONLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_restart.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "3.7 - restart - offline"
echo -e "================================="
echo -e "Description:"
echo -e "restart ${gamename} while already stopped."
echo -e "Command: ./${gameservername} restart"
requiredstatus="OFFLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_restart.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "4.0 - Update Tests"
echo -e "=================================================================="
echo -e ""
echo -e "4.1 - update"
echo -e "================================="
echo -e "Description:"
echo -e "check for updates."
echo -e "Command: ./${gameservername} update"
requiredstatus="OFFLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_update.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "4.2 - update-lgsm"
echo -e "================================="
echo -e "Description:"
echo -e "update LinuxGSM."
echo -e ""
echo -e "Command: ./jc2server update-lgam"
requiredstatus="ONLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_update_linuxgsm.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "Inserting IP address"
echo -e "================================="
echo -e "Description:"
echo -e "Inserting Travis IP in to config."
echo -e "Allows monitor to work"
if [ "$(ip -o -4 addr|grep eth0)" ]; then
travisip=$(ip -o -4 addr | grep eth0 | awk '{print $4}' | grep -oe '\([0-9]\{1,3\}\.\?\)\{4\}' | grep -v 127.0.0)
else
travisip=$(ip -o -4 addr | grep ens | awk '{print $4}' | grep -oe '\([0-9]\{1,3\}\.\?\)\{4\}' | sort -u | grep -v 127.0.0)
fi
sed -i "/server-ip=/c\server-ip=${travisip}" "${serverfiles}/server.properties"
echo -e "IP: ${travisip}"
echo -e ""
echo -e "5.0 - Monitor Tests"
echo -e "=================================================================="
echo -e ""
info_config.sh
echo -e "Server IP - Port: ${ip}:${port}"
echo -e "Server IP - Query Port: ${ip}:${queryport}"
echo -e ""
echo -e "30s Pause"
echo -e "================================="
echo -e "Description:"
echo -e "give time for server to fully start."
echo -e "Command: sleep 30"
requiredstatus="ONLINE"
fn_setstatus
sleep 30
echo -e ""
echo -e "5.1 - monitor - online"
echo -e "================================="
echo -e "Description:"
echo -e "run monitor server while already running."
echo -e "Command: ./${gameservername} monitor"
requiredstatus="ONLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_monitor.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "5.2 - monitor - offline - with lockfile"
echo -e "================================="
echo -e "Description:"
echo -e "run monitor while server is offline with lockfile."
echo -e "Command: ./${gameservername} monitor"
requiredstatus="OFFLINE"
fn_setstatus
fn_print_info_nl "creating lockfile."
date '+%s' > "${lockdir}/${selfname}.lock"
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_monitor.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "5.3 - monitor - offline - no lockfile"
echo -e "================================="
echo -e "Description:"
echo -e "run monitor while server is offline with no lockfile."
echo -e "Command: ./${gameservername} monitor"
requiredstatus="OFFLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_monitor.sh
)
fn_test_result_fail
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "5.4 - test-alert"
echo -e "================================="
echo -e "Description:"
echo -e "run monitor while server is offline with no lockfile."
echo -e "Command: ./${gameservername} test-alert"
requiredstatus="OFFLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_test_alert.sh
)
fn_test_result_fail
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "6.0 - Details Tests"
echo -e "=================================================================="
echo -e ""
echo -e "6.1 - details"
echo -e "================================="
echo -e "Description:"
echo -e "display details."
echo -e "Command: ./${gameservername} details"
requiredstatus="ONLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_details.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "6.2 - postdetails"
echo -e "================================="
echo -e "Description:"
echo -e "post details."
echo -e "Command: ./${gameservername} postdetails"
requiredstatus="ONLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_postdetails.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "7.0 - Backup Tests"
echo -e "=================================================================="
echo -e ""
echo -e "7.1 - backup"
echo -e "================================="
echo -e "Description:"
echo -e "run a backup."
echo -e "Command: ./${gameservername} backup"
requiredstatus="ONLINE"
fn_setstatus
echo -e "test de-activated until issue #1839 fixed"
#(command_backup.sh)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "8.0 - Development Tools Tests"
echo -e "=================================================================="
echo -e ""
echo -e "8.1 - dev - detect glibc"
echo -e "================================="
echo -e "Description:"
echo -e "detect glibc."
echo -e "Command: ./${gameservername} detect-glibc"
requiredstatus="ONLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_dev_detect_glibc.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "8.2 - dev - detect ldd"
echo -e "================================="
echo -e "Description:"
echo -e "detect ldd."
echo -e "Command: ./${gameservername} detect-ldd"
requiredstatus="ONLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_dev_detect_ldd.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "8.3 - dev - detect deps"
echo -e "================================="
echo -e "Description:"
echo -e "detect dependencies."
echo -e "Command: ./${gameservername} detect-deps"
requiredstatus="ONLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_dev_detect_deps.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "Inserting IP address"
echo -e "================================="
echo -e "Description:"
echo -e "Inserting Travis IP in to config."
echo -e "Allows monitor to work"
if [ "$(ip -o -4 addr|grep eth0)" ]; then
travisip=$(ip -o -4 addr | grep eth0 | awk '{print $4}' | grep -oe '\([0-9]\{1,3\}\.\?\)\{4\}' | grep -v 127.0.0)
else
travisip=$(ip -o -4 addr | grep ens | awk '{print $4}' | grep -oe '\([0-9]\{1,3\}\.\?\)\{4\}' | sort -u | grep -v 127.0.0)
fi
sed -i "/server-ip=/c\server-ip=${travisip}" "${serverfiles}/server.properties"
echo -e "IP: ${travisip}"
echo -e ""
echo -e "8.4 - dev - query-raw"
echo -e "================================="
echo -e "Description:"
echo -e "raw query output."
echo -e "Command: ./${gameservername} query-raw"
requiredstatus="ONLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_dev_query_raw.sh
)
fn_test_result_na
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "9.0 - Donate"
echo -e "=================================================================="
echo -e ""
echo -e "9.1 - donate"
echo -e "================================="
echo -e "Description:"
echo -e "donate."
echo -e "Command: ./${gameservername} donate"
requiredstatus="ONLINE"
fn_setstatus
(
exec 5>"${TRAVIS_BUILD_DIR}/dev-debug.log"
BASH_XTRACEFD="5"
set -x
command_donate.sh
)
fn_test_result_pass
echo -e "run order"
echo -e "================="
grep functionfile= "${TRAVIS_BUILD_DIR}/dev-debug.log" | sed 's/functionfile=//g'
echo -e ""
echo -e "================================="
echo -e "Server Tests - Complete!"
echo -e "Using: ${gamename}"
echo -e "================================="
requiredstatus="OFFLINE"
fn_setstatus
core_exit.sh
|
#!/bin/sh
#
# Copyright (c) 2007, Cameron Rich
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the axTLS project nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
# Generate the certificates and keys for testing.
#
PROJECT_NAME="axTLS Project"
# Generate the openssl configuration files.
cat > ca_cert.conf << EOF
[ req ]
distinguished_name = req_distinguished_name
prompt = no
[ req_distinguished_name ]
O = $PROJECT_NAME Dodgy Certificate Authority
EOF
cat > certs.conf << EOF
[ req ]
distinguished_name = req_distinguished_name
prompt = no
[ req_distinguished_name ]
O = $PROJECT_NAME
CN = 127.0.0.1
EOF
cat > device_cert.conf << EOF
[ req ]
distinguished_name = req_distinguished_name
prompt = no
[ req_distinguished_name ]
O = $PROJECT_NAME Device Certificate
EOF
# private key generation
openssl genrsa -out axTLS.ca_key.pem 1024
openssl genrsa -out axTLS.key_512.pem 512
openssl genrsa -out axTLS.key_1024.pem 1024
openssl genrsa -out axTLS.key_1042.pem 1042
openssl genrsa -out axTLS.key_2048.pem 2048
openssl genrsa -out axTLS.key_4096.pem 4096
openssl genrsa -out axTLS.device_key.pem 1024
openssl genrsa -aes128 -passout pass:abcd -out axTLS.key_aes128.pem 512
openssl genrsa -aes256 -passout pass:abcd -out axTLS.key_aes256.pem 512
# convert private keys into DER format
openssl rsa -in axTLS.key_512.pem -out axTLS.key_512 -outform DER
openssl rsa -in axTLS.key_1024.pem -out axTLS.key_1024 -outform DER
openssl rsa -in axTLS.key_1042.pem -out axTLS.key_1042 -outform DER
openssl rsa -in axTLS.key_2048.pem -out axTLS.key_2048 -outform DER
openssl rsa -in axTLS.key_4096.pem -out axTLS.key_4096 -outform DER
openssl rsa -in axTLS.device_key.pem -out axTLS.device_key -outform DER
# cert requests
openssl req -out axTLS.ca_x509.req -key axTLS.ca_key.pem -new \
-config ./ca_cert.conf
openssl req -out axTLS.x509_512.req -key axTLS.key_512.pem -new \
-config ./certs.conf
openssl req -out axTLS.x509_1024.req -key axTLS.key_1024.pem -new \
-config ./certs.conf
openssl req -out axTLS.x509_1042.req -key axTLS.key_1042.pem -new \
-config ./certs.conf
openssl req -out axTLS.x509_2048.req -key axTLS.key_2048.pem -new \
-config ./certs.conf
openssl req -out axTLS.x509_4096.req -key axTLS.key_4096.pem -new \
-config ./certs.conf
openssl req -out axTLS.x509_device.req -key axTLS.device_key.pem -new \
-config ./device_cert.conf
openssl req -out axTLS.x509_aes128.req -key axTLS.key_aes128.pem \
-new -config ./certs.conf -passin pass:abcd
openssl req -out axTLS.x509_aes256.req -key axTLS.key_aes256.pem \
-new -config ./certs.conf -passin pass:abcd
# generate the actual certs.
openssl x509 -req -in axTLS.ca_x509.req -out axTLS.ca_x509.pem \
-sha1 -days 5000 -signkey axTLS.ca_key.pem
openssl x509 -req -in axTLS.x509_512.req -out axTLS.x509_512.pem \
-sha1 -CAcreateserial -days 5000 \
-CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem
openssl x509 -req -in axTLS.x509_1024.req -out axTLS.x509_1024.pem \
-sha1 -CAcreateserial -days 5000 \
-CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem
openssl x509 -req -in axTLS.x509_1042.req -out axTLS.x509_1042.pem \
-sha1 -CAcreateserial -days 5000 \
-CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem
openssl x509 -req -in axTLS.x509_2048.req -out axTLS.x509_2048.pem \
-md5 -CAcreateserial -days 5000 \
-CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem
openssl x509 -req -in axTLS.x509_4096.req -out axTLS.x509_4096.pem \
-md5 -CAcreateserial -days 5000 \
-CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem
openssl x509 -req -in axTLS.x509_device.req -out axTLS.x509_device.pem \
-sha1 -CAcreateserial -days 5000 \
-CA axTLS.x509_512.pem -CAkey axTLS.key_512.pem
openssl x509 -req -in axTLS.x509_aes128.req \
-out axTLS.x509_aes128.pem \
-sha1 -CAcreateserial -days 5000 \
-CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem
openssl x509 -req -in axTLS.x509_aes256.req \
-out axTLS.x509_aes256.pem \
-sha1 -CAcreateserial -days 5000 \
-CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem
# note: must be root to do this
DATE_NOW=`date`
if date -s "Jan 1 2025"; then
openssl x509 -req -in axTLS.x509_512.req -out axTLS.x509_bad_before.pem \
-sha1 -CAcreateserial -days 365 \
-CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem
date -s "$DATE_NOW"
touch axTLS.x509_bad_before.pem
fi
openssl x509 -req -in axTLS.x509_512.req -out axTLS.x509_bad_after.pem \
-sha1 -CAcreateserial -days -365 \
-CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem
# some cleanup
rm axTLS*.req
rm axTLS.srl
rm *.conf
# need this for the client tests
openssl x509 -in axTLS.ca_x509.pem -outform DER -out axTLS.ca_x509.cer
openssl x509 -in axTLS.x509_512.pem -outform DER -out axTLS.x509_512.cer
openssl x509 -in axTLS.x509_1024.pem -outform DER -out axTLS.x509_1024.cer
openssl x509 -in axTLS.x509_1042.pem -outform DER -out axTLS.x509_1042.cer
openssl x509 -in axTLS.x509_2048.pem -outform DER -out axTLS.x509_2048.cer
openssl x509 -in axTLS.x509_4096.pem -outform DER -out axTLS.x509_4096.cer
openssl x509 -in axTLS.x509_device.pem -outform DER -out axTLS.x509_device.cer
# generate pkcs8 files (use RC4-128 for encryption)
openssl pkcs8 -in axTLS.key_512.pem -passout pass:abcd -topk8 -v1 PBE-SHA1-RC4-128 -out axTLS.encrypted_pem.p8
openssl pkcs8 -in axTLS.key_512.pem -passout pass:abcd -topk8 -outform DER -v1 PBE-SHA1-RC4-128 -out axTLS.encrypted.p8
openssl pkcs8 -in axTLS.key_512.pem -nocrypt -topk8 -out axTLS.unencrypted_pem.p8
openssl pkcs8 -in axTLS.key_512.pem -nocrypt -topk8 -outform DER -out axTLS.unencrypted.p8
# generate pkcs12 files (use RC4-128 for encryption)
openssl pkcs12 -export -in axTLS.x509_1024.pem -inkey axTLS.key_1024.pem -certfile axTLS.ca_x509.pem -keypbe PBE-SHA1-RC4-128 -certpbe PBE-SHA1-RC4-128 -name "p12_with_CA" -out axTLS.withCA.p12 -password pass:abcd
openssl pkcs12 -export -in axTLS.x509_1024.pem -inkey axTLS.key_1024.pem -keypbe PBE-SHA1-RC4-128 -certpbe PBE-SHA1-RC4-128 -name "p12_without_CA" -out axTLS.withoutCA.p12 -password pass:abcd
openssl pkcs12 -export -in axTLS.x509_1024.pem -inkey axTLS.key_1024.pem -keypbe PBE-SHA1-RC4-128 -certpbe PBE-SHA1-RC4-128 -out axTLS.noname.p12 -password pass:abcd
# PEM certificate chain
cat axTLS.ca_x509.pem >> axTLS.x509_device.pem
# set default key/cert for use in the server
xxd -i axTLS.x509_1024.cer | sed -e \
"s/axTLS_x509_1024_cer/default_certificate/" > ../../ssl/cert.h
xxd -i axTLS.key_1024 | sed -e \
"s/axTLS_key_1024/default_private_key/" > ../../ssl/private_key.h
|
package com.pickth.comepennyrenewal.net.service;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.DELETE;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
/**
* Created by Kim on 2017-02-08.
*/
public class CommentService extends BaseService {
public CommentService() {
super(CommentAPI.class);
}
/**
* 댓글 목록 가져오기
* @param ideaId 아이디어 아이디
* @param offset 시작점
* @return
*/
public Call<ResponseBody> getCommentList(int ideaId, int offset) {
return getAPI().getCommentList(ideaId, offset);
}
/**
* 댓글을 작성합니다
* @param ideaId 아이디어 아이디
* @param userId 유저 아이디
* @param comment 댓글 내용
* @return
*/
public Call<ResponseBody> postComment(int ideaId, String userId, String comment) {
return getAPI().postComment(ideaId, userId, comment);
}
/**
* 댓글을 수정합니다
* @param commentId 댓글 아이디
* @param comment 수정할 댓글 내용
* @return
*/
public Call<ResponseBody> putComment(int commentId, String comment) {
return getAPI().putComment(commentId, comment);
}
/**
* 댓글을 삭제합니다
* @param commentId 댓글 아이디
* @return
*/
public Call<ResponseBody> deleteComment(int commentId) {
return getAPI().deleteCommnet(commentId);
}
@Override
public CommentAPI getAPI() {
return (CommentAPI)super.getAPI();
}
public interface CommentAPI {
@GET("/comment/{idea_id}")
public Call<ResponseBody> getCommentList(@Path("idea_id") int ideaId, @Query("offset") int offset);
@FormUrlEncoded
@POST("/comment")
public Call<ResponseBody> postComment(@Field("idea_id") int ideaId, @Field("user_id") String userId, @Field("comment") String comment);
@PUT("/comment/{comment_id}")
public Call<ResponseBody> putComment(@Path("comment_id") int commentId, @Query("comment") String comment);
@DELETE("/comment/{comment_id}")
public Call<ResponseBody> deleteCommnet(@Path("comment_id") int CommentId);
}
}
|
# |source| this file to enable metrics in the current shell
echoSafecoinMetricsConfig() {
declare metrics_config_sh
metrics_config_sh="$(dirname "${BASH_SOURCE[0]}")"/lib/config.sh
if [[ ! -f "$metrics_config_sh" ]]; then
echo "Run start.sh first" >&2
return 1
fi
(
# shellcheck source=/dev/null
source "$metrics_config_sh"
echo "host=http://localhost:10016,db=testnet,u=$INFLUXDB_WRITE_USER,p=$INFLUXDB_WRITE_PASSWORD"
)
}
SAFEANA_METRICS_CONFIG=$(echoSafecoinMetricsConfig)
export SAFEANA_METRICS_CONFIG
unset -f echoSafecoinMetricsConfig
__configure_metrics_sh="$(cd "$(dirname "${BASH_SOURCE[0]}")"/../.. || true; pwd)"/scripts/configure-metrics.sh
if [[ -f $__configure_metrics_sh ]]; then
# shellcheck source=scripts/configure-metrics.sh
source "$__configure_metrics_sh"
fi
__configure_metrics_sh=
|
// app.js
const express = require('express');
const path = require('path');
const cors = require('cors');
const helmet = require('helmet');
const bodyParser = require('body-parser');
const logger = require('morgan');
function normalizePort(val) {
const port = parseInt(val, 10);
if (Number.isNaN(port)) { return val; }
if (port >= 0) { return port; }
return false;
}
const app = express();
app.use(cors({ credentials: true }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(helmet());
app.use(logger('dev'));
// Serve the React application
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
const port = normalizePort(process.env.PORT || 3000);
app.listen(port, () => {
console.log(`API listening on port: ${port}`);
});
|
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UserPermissionManager:
class Scope:
READ = 'read'
WRITE = 'write'
def __init__(self):
self.permissions = set()
def add_scope(self, scope):
self.permissions.add(scope)
def remove_scope(self, scope):
self.permissions.discard(scope)
def has_scope(self, scope):
return scope in self.permissions
# Example usage
user_permissions = UserPermissionManager()
user_permissions.add_scope(UserPermissionManager.Scope.READ)
user_permissions.add_scope(UserPermissionManager.Scope.WRITE)
print(user_permissions.has_scope(UserPermissionManager.Scope.READ)) # Output: True
print(user_permissions.has_scope(UserPermissionManager.Scope.WRITE)) # Output: True
print(user_permissions.has_scope('admin')) # Output: False |
<reponame>vicsmr/customers-and-orders<filename>product-backend/src/main/java/io/eventuate/examples/tram/sagas/ordersandcustomers/products/domain/Product.java
package io.eventuate.examples.tram.sagas.ordersandcustomers.products.domain;
import javax.persistence.*;
import java.util.Collections;
import java.util.Map;
@Entity
@Table(name="Product")
@Access(AccessType.FIELD)
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int stock;
@ElementCollection
private Map<Long, Integer> stockReservations;
int availableStock() {
return this.stock - stockReservations.values().stream().reduce(0, Integer::sum);
}
public Product() {
}
public Product(String name, int stock) {
this.name = name;
this.stock = stock;
this.stockReservations = Collections.emptyMap();
}
public Long getId() {
return id;
}
public int getStock() {
return availableStock();
}
public void reserveStock(Long orderId, int productAmount) {
if (availableStock() >= productAmount) {
stockReservations.put(orderId, productAmount);
} else
throw new ProductStockLimitExceededException();
}
}
|
//#####################################################################
// Copyright 2009, <NAME>, <NAME>
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
// Class READ_WRITE_ARRAY_COLLECTION
//#####################################################################
#ifndef COMPILE_WITHOUT_READ_WRITE_SUPPORT
#include <PhysBAM_Tools/Read_Write/Arrays/READ_WRITE_ARRAY_COLLECTION.h>
#include <PhysBAM_Tools/Read_Write/Data_Structures/READ_WRITE_ELEMENT_ID.h>
#include <PhysBAM_Tools/Read_Write/Data_Structures/READ_WRITE_HASHTABLE.h>
#include <PhysBAM_Tools/Vectors/VECTOR_1D.h>
#include <PhysBAM_Tools/Vectors/VECTOR_2D.h>
#include <PhysBAM_Tools/Vectors/VECTOR_3D.h>
namespace PhysBAM{
//#####################################################################
// Function Read_Write_Array_Collection_Registry
//#####################################################################
template<class RW> HASHTABLE<ATTRIBUTE_ID,READ_WRITE_ARRAY_COLLECTION_FUNCTIONS>& Read_Write<ARRAY_COLLECTION,RW>::
Read_Write_Array_Collection_Registry()
{
static HASHTABLE<ATTRIBUTE_ID,READ_WRITE_ARRAY_COLLECTION_FUNCTIONS> read_write_array_collection_registry;
return read_write_array_collection_registry;
}
//#####################################################################
// Function Attribute_Names_Registry
//#####################################################################
static HASHTABLE<ATTRIBUTE_ID,const char*>& Attribute_Names_Registry()
{
static HASHTABLE<ATTRIBUTE_ID,const char*> names_registry;
return names_registry;
}
//#####################################################################
// Function Register_Attribute_Name
//#####################################################################
void Register_Attribute_Name(const ATTRIBUTE_ID id,const char* name)
{
PHYSBAM_ASSERT(Attribute_Names_Registry().Set(id,name));
}
//#####################################################################
// Function Register_Attribute_Name
//#####################################################################
const char* Get_Attribute_Name(const ATTRIBUTE_ID id)
{
if(const char** name=Attribute_Names_Registry().Get_Pointer(id)) return *name;
return 0;
}
#include <PhysBAM_Tools/Log/DEBUG_UTILITIES.h>
//#####################################################################
// Function Read_Arrays
//#####################################################################
template<class RW> void Read_Write<ARRAY_COLLECTION,RW>::
Read_Arrays(std::istream& input,ARRAY_COLLECTION& object)
{
int size;
ATTRIBUTE_INDEX num_attributes;
Read_Binary<RW>(input,size,num_attributes);
object.Resize(size);
for(ATTRIBUTE_INDEX i(1);i<=num_attributes;i++){
ATTRIBUTE_ID hashed_id;int read_size;
Read_Binary<RW>(input,hashed_id,read_size);
READ_WRITE_ARRAY_COLLECTION_FUNCTIONS* read_write_functions=Read_Write_Array_Collection_Registry().Get_Pointer(Type_Only(hashed_id));
if(!read_write_functions){input.ignore(read_size);continue;}
if(!read_write_functions->Read && read_write_functions->sample_attribute)
PHYSBAM_FATAL_ERROR(STRING_UTILITIES::string_sprintf("No read registered for id %i\n",Value(hashed_id)));
ATTRIBUTE_INDEX index=object.Get_Attribute_Index(Id_Only(hashed_id));
if(!index) index=object.Add_Array(Id_Only(hashed_id),read_write_functions->sample_attribute->Clone_Default());
// TODO: this really ought to know whether we're running in float or double
else read_write_functions=Read_Write_Array_Collection_Registry().Get_Pointer(Type_Only(object.arrays(index)->Hashed_Id()));
read_write_functions->Read(input,*object.arrays(index));
object.arrays(index)->id=Id_Only(hashed_id);}
}
//#####################################################################
// Function Write_Arrays
//#####################################################################
template<class RW> void Read_Write<ARRAY_COLLECTION,RW>::
Write_Arrays(std::ostream& output,const ARRAY_COLLECTION& object)
{
Write_Binary<RW>(output,object.number,object.arrays.m);
for(ATTRIBUTE_INDEX i(1);i<=object.arrays.m;i++){
const ARRAY_COLLECTION_ELEMENT_BASE* entry=object.arrays(i);
const READ_WRITE_ARRAY_COLLECTION_FUNCTIONS* read_write_functions=Read_Write_Array_Collection_Registry().Get_Pointer(Type_Only(entry->Hashed_Id()));
if(!read_write_functions || !read_write_functions->Write || !read_write_functions->Write_Size)
PHYSBAM_FATAL_ERROR(STRING_UTILITIES::string_sprintf("No write registered for id %i (type %s)\n",Value(entry->id),typeid(*entry).name()));
int calculated_write_size=read_write_functions->Write_Size(*entry);
Write_Binary<RW>(output,entry->Typed_Hashed_Id(RW()),calculated_write_size);
if(calculated_write_size) read_write_functions->Write(output,*entry);}
}
//#####################################################################
// Function Print
//#####################################################################
template<class RW> void Read_Write<ARRAY_COLLECTION,RW>::
Print(std::ostream& output,const ARRAY_COLLECTION& object,const int p)
{
if(p<1 || p>object.number) throw INDEX_ERROR("Index out of range");
for(ATTRIBUTE_INDEX i(1);i<=object.arrays.m;i++){
const ARRAY_COLLECTION_ELEMENT_BASE* entry=object.arrays(i);
const READ_WRITE_ARRAY_COLLECTION_FUNCTIONS* read_write_functions=Read_Write_Array_Collection_Registry().Get_Pointer(Type_Only(entry->Hashed_Id()));
if(!read_write_functions || !read_write_functions->Print)
PHYSBAM_FATAL_ERROR(STRING_UTILITIES::string_sprintf("No print registered for id %i (type %s)\n",Value(entry->id),typeid(*entry).name()));
read_write_functions->Print(output,*entry,p);}
}
//#####################################################################
template class Read_Write<ARRAY_COLLECTION,float>;
template class Read_Write<ARRAY_COLLECTION,double>;
}
#endif
|
import numpy as np
from math import comb
import pickle as pkl
from tqdm import tqdm
def give_possible_options(combs, num_arrivals, num_services, arrivals, services, combnum, curr_comb, pkl_name_inter_depart):
if services == 1:
curr_comb = np.append(curr_comb, arrivals)
with open(pkl_name_inter_depart, 'rb') as f:
count, combp = pkl.load(f)
combp[count, :] = curr_comb
count += 1
with open(pkl_name_inter_depart, 'wb') as f:
pkl.dump((count, combp), f)
combs[combnum, num_services - services] = arrivals
combnum += 1
else:
for ind in range(arrivals, -1, -1):
if services == num_services:
curr_comb = np.array([])
give_possible_options(combs, num_arrivals, num_services, arrivals - ind,
services-1, combnum, np.append(curr_comb, ind), pkl_name_inter_depart)
return combs
def possibilites_after_initial_arrivals(num_arrivals, arrivals, services, curr_comb, combnum, pkl_name_inter_depart):
if services == 1:
## computing the values to add to cuu_comb
with open(pkl_name_inter_depart, 'rb') as f:
count, combp = pkl.load(f)
if arrivals == 1: # if there is only one customer to arrive then it can either during or after service
update_crr_comb = np.array([1, 0])
size_comb = np.append(curr_comb, update_crr_comb).shape[0]
combp = np.append(combp, np.append(curr_comb, update_crr_comb).reshape(1, size_comb), axis=0)
count += 1
# print(np.append(curr_comb, update_crr_comb))
update_crr_comb = np.array([0, 1])
combp = np.append(combp, np.append(curr_comb, update_crr_comb).reshape(1, size_comb), axis=0)
count += 1
# print(np.append(curr_comb, update_crr_comb))
else: # all customers arrived already
update_crr_comb = np.array([0, 0])
size_comb = np.append(curr_comb, update_crr_comb).shape[0]
if combp.shape[0] == 0: # If this is the first time we add to te combination matrix
combp = np.append(curr_comb, update_crr_comb).reshape(1, size_comb) # first combination
else:
combp = np.append(combp, np.append(curr_comb, update_crr_comb).reshape(1, size_comb), axis=0) # adding a further combination
count += 1
# print(np.append(curr_comb, update_crr_comb))
with open(pkl_name_inter_depart, 'wb') as f: # dump to pkl
pkl.dump((count, combp), f)
combnum += 1
else:
# if the
if (services != num_arrivals) & (arrivals >= services):
lb = 0
else:
lb = -1
for ind in range(arrivals, lb, -1):
if services == num_arrivals:
curr_comb = np.array([])
if ind == 0:
in_service = ind
inter_arrive = 1
else:
in_service = ind
inter_arrive = 0
## computing the values to add to cuu_comb
else:
in_service = ind
inter_arrive = 0
update_crr_comb = np.array([in_service, inter_arrive])
possibilites_after_initial_arrivals(num_arrivals, arrivals - (in_service + inter_arrive), services-1,
np.append(curr_comb, update_crr_comb), combnum, pkl_name_inter_depart)
# in case we need to decide whether arrivals occurs at service or not
# if only one customer is left to arrive, it is also possible that she will arrive after service is done
if (num_arrivals > services) & (ind == 1) & (arrivals == services): # cond(1): cannot happen in the first service cond(2): only if one customer should arrive cond(3): only if remianing arrival equals remianing services
in_service = 0
inter_arrive = 1
update_crr_comb = np.array([in_service, inter_arrive])
possibilites_after_initial_arrivals(num_arrivals, arrivals - (in_service + inter_arrive), services - 1,
np.append(curr_comb, update_crr_comb), combnum,
pkl_name_inter_depart)
def main():
for num_arrivals in tqdm(range(2, 6)):
arrivals = num_arrivals
services = num_arrivals
pkl_name_inter_depart = '../pkl/combs'+str(num_arrivals-1)+'.pkl'
combs = np.array([])
count = 0
with open(pkl_name_inter_depart, 'wb') as f:
pkl.dump((count, combs), f)
combnum = 0
curr_comb = np.array([])
possibilites_after_initial_arrivals(num_arrivals, arrivals, services, curr_comb, combnum, pkl_name_inter_depart)
with open(pkl_name_inter_depart, 'rb') as f:
count, combp = pkl.load(f)
print(combp)
print(count)
if False:
num_arrivals = 3
num_services = 4
arrivals = num_arrivals
services = num_services
pkl_name_inter_depart = '../pkl/combs.pkl'
num_possi_coms = comb(num_arrivals + num_services - 1, num_services - 1)
combs = np.zeros((num_possi_coms, num_services))
count = 0
with open(pkl_name_inter_depart, 'wb') as f:
pkl.dump((count,combs), f)
combnum = 0
curr_comb = np.array([])
give_possible_options(combs, num_arrivals, num_services, arrivals, services, combnum,
curr_comb, pkl_name_inter_depart)
with open(pkl_name_inter_depart, 'rb') as f:
count, combp = pkl.load(f)
print(combp)
if __name__ == '__main__':
main() |
#
#-----------------------------------------------------------------------
#
# This file defines a function that creates a model configuration file
# in the specified run directory.
#
#-----------------------------------------------------------------------
#
function create_model_configure_file() {
#
#-----------------------------------------------------------------------
#
# Save current shell options (in a global array). Then set new options
# for this script/function.
#
#-----------------------------------------------------------------------
#
{ save_shell_opts; set -u -x; } > /dev/null 2>&1
#
#-----------------------------------------------------------------------
#
# Get the full path to the file in which this script/function is located
# (scrfunc_fp), the name of that file (scrfunc_fn), and the directory in
# which the file is located (scrfunc_dir).
#
#-----------------------------------------------------------------------
#
local scrfunc_fp=$( readlink -f "${BASH_SOURCE[0]}" )
local scrfunc_fn=$( basename "${scrfunc_fp}" )
local scrfunc_dir=$( dirname "${scrfunc_fp}" )
#
#-----------------------------------------------------------------------
#
# Get the name of this function.
#
#-----------------------------------------------------------------------
#
local func_name="${FUNCNAME[0]}"
#
#-----------------------------------------------------------------------
#
# Specify the set of valid argument names for this script/function. Then
# process the arguments provided to this script/function (which should
# consist of a set of name-value pairs of the form arg1="value1", etc).
#
#-----------------------------------------------------------------------
#
local valid_args=(
cdate \
run_dir \
nthreads \
sub_hourly_post \
dt_subhourly_post_mnts \
dt_atmos \
)
process_args valid_args "$@"
#
#-----------------------------------------------------------------------
#
# For debugging purposes, print out values of arguments passed to this
# script. Note that these will be printed out only if VERBOSE is set to
# TRUE.
#
#-----------------------------------------------------------------------
#
print_input_args valid_args
#
#-----------------------------------------------------------------------
#
# Declare local variables.
#
#-----------------------------------------------------------------------
#
local yyyy \
mm \
dd \
hh \
dot_quilting_dot \
dot_print_esmf_dot \
settings \
model_config_fp
#
#-----------------------------------------------------------------------
#
# Create a model configuration file in the specified run directory.
#
#-----------------------------------------------------------------------
#
print_info_msg "$VERBOSE" "
Creating a model configuration file (\"${MODEL_CONFIG_FN}\") in the specified
run directory (run_dir):
run_dir = \"${run_dir}\""
#
# Extract from cdate the starting year, month, day, and hour of the forecast.
#
yyyy=${cdate:0:4}
mm=${cdate:4:2}
dd=${cdate:6:2}
hh=${cdate:8:2}
#
# Set parameters in the model configure file.
#
dot_quilting_dot="."${QUILTING,,}"."
dot_print_esmf_dot="."${PRINT_ESMF,,}"."
#
#-----------------------------------------------------------------------
#
# Create a multiline variable that consists of a yaml-compliant string
# specifying the values that the jinja variables in the template
# model_configure file should be set to.
#
#-----------------------------------------------------------------------
#
settings="\
'PE_MEMBER01': ${PE_MEMBER01}
'start_year': $yyyy
'start_month': $mm
'start_day': $dd
'start_hour': $hh
'nhours_fcst': ${FCST_LEN_HRS}
'dt_atmos': ${DT_ATMOS}
'atmos_nthreads': ${nthreads:-1}
'ncores_per_node': ${NCORES_PER_NODE}
'restart_interval': ${RESTART_INTERVAL}
'quilting': ${dot_quilting_dot}
'print_esmf': ${dot_print_esmf_dot}
'output_grid': ${WRTCMP_output_grid}"
# 'output_grid': \'${WRTCMP_output_grid}\'"
#
# If the write-component is to be used, then specify a set of computational
# parameters and a set of grid parameters. The latter depends on the type
# (coordinate system) of the grid that the write-component will be using.
#
if [ "$QUILTING" = "TRUE" ]; then
settings="${settings}
'write_groups': ${WRTCMP_write_groups}
'write_tasks_per_group': ${WRTCMP_write_tasks_per_group}
'cen_lon': ${WRTCMP_cen_lon}
'cen_lat': ${WRTCMP_cen_lat}
'lon1': ${WRTCMP_lon_lwr_left}
'lat1': ${WRTCMP_lat_lwr_left}"
if [ "${WRTCMP_output_grid}" = "lambert_conformal" ]; then
settings="${settings}
'stdlat1': ${WRTCMP_stdlat1}
'stdlat2': ${WRTCMP_stdlat2}
'nx': ${WRTCMP_nx}
'ny': ${WRTCMP_ny}
'dx': ${WRTCMP_dx}
'dy': ${WRTCMP_dy}
'lon2': \"\"
'lat2': \"\"
'dlon': \"\"
'dlat': \"\""
elif [ "${WRTCMP_output_grid}" = "regional_latlon" ] || \
[ "${WRTCMP_output_grid}" = "rotated_latlon" ]; then
settings="${settings}
'lon2': ${WRTCMP_lon_upr_rght}
'lat2': ${WRTCMP_lat_upr_rght}
'dlon': ${WRTCMP_dlon}
'dlat': ${WRTCMP_dlat}
'stdlat1': \"\"
'stdlat2': \"\"
'nx': \"\"
'ny': \"\"
'dx': \"\"
'dy': \"\""
fi
fi
#
# If sub_hourly_post is set to "TRUE", then the forecast model must be
# directed to generate output files on a sub-hourly interval. Do this
# by specifying the output interval in the model configuration file
# (MODEL_CONFIG_FN) in units of number of forecat model time steps (nsout).
# nsout is calculated using the user-specified output time interval
# dt_subhourly_post_mnts (in units of minutes) and the forecast model's
# main time step dt_atmos (in units of seconds). Note that nsout is
# guaranteed to be an integer because the experiment generation scripts
# require that dt_subhourly_post_mnts (after conversion to seconds) be
# evenly divisible by dt_atmos. Also, in this case, the variable nfhout
# [which specifies the (low-frequency) output interval in hours after
# forecast hour nfhmax_hf; see the jinja model_config template file] is
# set to 0, although this doesn't matter because any positive of nsout
# will override nfhout.
#
# If sub_hourly_post is set to "FALSE", then the workflow is hard-coded
# (in the jinja model_config template file) to direct the forecast model
# to output files every hour. This is done by setting (1) nfhout_hf to
# 1 in that jinja template file, (2) nfhout to 1 here, and (3) nsout to
# -1 here which turns off output by time step interval.
#
# Note that the approach used here of separating how hourly and subhourly
# output is handled should be changed/generalized/simplified such that
# the user should only need to specify the output time interval (there
# should be no need to specify a flag like sub_hourly_post); the workflow
# should then be able to direct the model to output files with that time
# interval and to direct the post-processor to process those files
# regardless of whether that output time interval is larger than, equal
# to, or smaller than one hour.
#
if [ "${sub_hourly_post}" = "TRUE" ]; then
nsout=$(( dt_subhourly_post_mnts*60 / dt_atmos ))
nfhout=0
else
nfhout=1
nsout=-1
fi
settings="${settings}
'nfhout': ${nfhout}
'nsout': ${nsout}"
print_info_msg $VERBOSE "
The variable \"settings\" specifying values to be used in the \"${MODEL_CONFIG_FN}\"
file has been set as follows:
#-----------------------------------------------------------------------
settings =
$settings"
#
#-----------------------------------------------------------------------
#
# Call a python script to generate the experiment's actual MODEL_CONFIG_FN
# file from the template file.
#
#-----------------------------------------------------------------------
#
model_config_fp="${run_dir}/${MODEL_CONFIG_FN}"
$USHDIR/fill_jinja_template.py -q \
-u "${settings}" \
-t ${MODEL_CONFIG_TMPL_FP} \
-o ${model_config_fp} || \
print_err_msg_exit "\
Call to python script fill_jinja_template.py to create a \"${MODEL_CONFIG_FN}\"
file from a jinja2 template failed. Parameters passed to this script are:
Full path to template rocoto XML file:
MODEL_CONFIG_TMPL_FP = \"${MODEL_CONFIG_TMPL_FP}\"
Full path to output rocoto XML file:
model_config_fp = \"${model_config_fp}\"
Namelist settings specified on command line:
settings =
$settings"
#
#-----------------------------------------------------------------------
#
# Restore the shell options saved at the beginning of this script/function.
#
#-----------------------------------------------------------------------
#
{ restore_shell_opts; } > /dev/null 2>&1
}
|
<reponame>ceumicrodata/respect-trade-similarity
import glob
import pandas as pd
file_list = glob.glob('../temp/index/data/*')
#Select those which contain the import data
file_list = [db for db in file_list if "IMP" in db]
df = pd.concat([pd.read_csv(f).drop('Unnamed: 0',axis=1).rename(columns=lambda x: x.split('_')[0]).assign(FILE=f[10:14]) for f in file_list])
df = df.pivot_table(index=['DECLARANT','PARTNER'],columns='FILE')
print(list(df.columns.values))
df.to_csv('../temp/index/dirty/INDEX_IMP.csv')
"""
declarants = []
partners = []
for filename in file_list:
df = pd.read_csv(filename)
declarants + list(df["DECLARANT_ISO"].unique())
partners + list(df["PARTNER_ISO"].unique())
print("DECLARANCT_ISO",len(df["DECLARANT_ISO"].unique()),"PARTNER",len(df["PARTNER_ISO"].unique()))
from itertools import product
df = pd.DataFrame(list(product(list(set(declarants)), list(set(partners)))), columns=["DECLARANT_ISO","PARTNER_ISO"])
for filename in file_list:
df = pd.merge(df,pd.read_csv(filename), left_on = ["DECLARANT_ISO","PARTNER_ISO"], right_on = ["DECLARANT_ISO","PARTNER_ISO"], how="left")
#df = pd.concat([df,pd.read_csv(filename)], axis = 1, keys=["DECLARANT_ISO","PARTNER_ISO"],join="inner")
df.to_csv("index_IMP.csv")
"""
|
// Swift Package.swift
import PackageDescription
let package = Package(
name: "FluentDarkModeKit",
platforms: [.iOS(.v11)],
products: [
.library(name: "FluentDarkModeKit", targets: ["DarkModeCore", "FluentDarkModeKit"]),
],
targets: [
.target(name: "DarkModeCore", cSettings: [.define("SWIFT_PACKAGE")]),
.target(name: "FluentDarkModeKit", dependencies: ["DarkModeCore"]),
.testTarget(name: "FluentDarkModeKitTests", dependencies: ["FluentDarkModeKit"]),
]
) |
from sklearn.cluster import DBSCAN
import numpy as np
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
# Use the application default credentials
cred = credentials.ApplicationDefault()
firebase_admin.initialize_app(cred, {
'projectId': "covid-cluster",
})
store = firestore.client()
def cluster(data, context):
store = firestore.client()
doc_ref = store.collection(u'Locations')
points = []
docs = doc_ref.get()
for doc in docs:
points.append(np.array(list(doc.to_dict().values())))
points = np.array(points)
db = DBSCAN(eps=3, min_samples=15).fit(points)
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
core_samples_mask[db.core_sample_indices_] = True
labels = db.labels_
# Number of clusters in labels, ignoring noise if present.
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
for i in range(n_clusters_):
points_of_cluster = points[labels==i,:]
c = np.mean(points_of_cluster, axis=0)
store.collection(u'Parties').add({"Longtitude": c[0], "Latitude": c[1]}) |
import dbAPI from '../api/dataBroker.js'
import moment from 'moment'
import { create } from 'apisauce'
import { storeData } from '../redis/waterworks/usage.js'
const timeTables = [
// //Today
// {
// from: moment().startOf('d').format('YYYY-MM-DD').format('YYYY-MM-DD'),
// to: moment().endOf('d').format('YYYY-MM-DD').format('YYYY-MM-DD'),
// },
// //Yesterday
// {
// from: moment().subtract(1, 'd').startOf('d').format('YYYY-MM-DD'),
// to: moment().subtract(1, 'd').endOf('d').format('YYYY-MM-DD')
// },
// //last 3 days
// {
// from: moment().subtract(3, 'd').startOf('d').format('YYYY-MM-DD'),
// to: moment().subtract(1, 'd').endOf('d').format('YYYY-MM-DD')
// },
// //this week
{
from: moment().startOf('week').startOf('day').format('YYYY-MM-DD'),
to: moment().startOf('day').format('YYYY-MM-DD')
},
//last 7 days
{
from: moment().subtract(7, 'd').startOf('day').format('YYYY-MM-DD'),
to: moment().subtract(1, 'd').startOf('day').format('YYYY-MM-DD')
},
//this month
{
from: moment().startOf('month').endOf('d').format('YYYY-MM-DD'),
to: moment().startOf('d').format('YYYY-MM-DD')
},
// //last 30 days
{
from: moment().subtract(30, 'd').startOf('d').format('YYYY-MM-DD'),
to: moment().subtract(1, 'd').endOf('d').format('YYYY-MM-DD')
},
// //last 60 days
// {
// from: moment().subtract(60, 'd').startOf('d').format('YYYY-MM-DD'),
// to: moment().subtract(1, 'd').endOf('d').format('YYYY-MM-DD')
// },
// last 90 days
{
from: moment().subtract(90, 'd').startOf('d').format('YYYY-MM-DD'),
to: moment().subtract(1, 'd').endOf('d').format('YYYY-MM-DD')
},
// last year
{
from: moment().subtract(1, 'y').startOf('y').format('YYYY-MM-DD'),
to: moment().startOf('y').format('YYYY-MM-DD')
}
]
/**
* Get Benchmark of devices
*/
const getBenchmark = async (orgId, uuids, p) => {
let response = await dbAPI.get(`/v2/waterworks/data/benchmark/${orgId}/${p.from}/${p.to}`)
if (response.ok) {
return response.data
}
else {
console.log('Error getting Benchmark', response)
}
}
/**
* Get Min Water Temperature
*/
const getWaterTemperature = async (orgId, uuids, p) => {
if (uuids) {
let response = await dbAPI.post(`/v2/waterworks/data/minWTemp/${p.from}/${p.to}`, uuids)
if (response.ok) {
return response.data
}
else {
return console.log('Error getting minWaterTemp', response.ok)
}
}
else {
let response = await dbAPI.get(`/v2/waterworks/data/minWTemp/${p.from}/${p.to}`)
if (response.ok) {
return response.data
}
else {
return console.log('Error getting minWaterTemp', response.ok)
}
}
}
/**
* Get Min Ambient Temperature
*/
const getAmbientTemperature = async (orgId, uuids, p) => {
if (uuids) {
let response = await dbAPI.post(`/v2/waterworks/data/minATemp/${p.from}/${p.to}`, uuids)
if (response.ok) {
return response.data
}
else {
console.log('Error getting minAmbientTemp', response.ok)
}
}
else {
let response = await dbAPI.get(`/v2/waterworks/data/minATemp/${p.from}/${p.to}`)
if (response.ok) {
return response.data
}
else {
console.log('Error getting minAmbientTemp', response.ok)
}
}
}
/**
* Get Max Flow
*/
const getMaxFlow = async (orgId, uuids, p) => {
if (uuids) {
let response = await dbAPI.post(`/v2/waterworks/data/maxFlow/${p.from}/${p.to}`, uuids)
if (response.ok) {
return response.data
}
else {
console.log('Error getting maxFlow', response.ok)
}
}
else {
let response = await dbAPI.get(`/v2/waterworks/data/maxFlow/${p.from}/${p.to}`)
if (response.ok) {
return response.data
}
else {
console.log('Error getting maxFlow', response.ok)
}
}
}
/**
* Get Min Flow
*/
const getMinFlow = async (orgId, uuids, p) => {
if (uuids) {
let response = await dbAPI.post(`/v2/waterworks/data/minFlow/${p.from}/${p.to}`, uuids)
if (response.ok) {
return response.data
}
else {
console.log('Error getting minFlow', response.ok)
}
}
else {
let response = await dbAPI.get(`/v2/waterworks/data/minFlow/${p.from}/${p.to}`)
if (response.ok) {
return response.data
}
else {
console.log('Error getting minFlow', response.ok)
}
}
}
const getReading = async (orgId, uuids, p) => {
if (uuids) {
let response = await dbAPI.post(`/v2/waterworks/data/volume/${p.from}/${p.to}`, uuids)
if (response.ok) {
return response.data
}
else {
console.log('Error getting Volume', response.ok)
}
}
else {
let response = await dbAPI.get(`/v2/waterworks/data/volume/${p.from}/${p.to}`)
if (response.ok) {
return response.data
}
else {
console.log('Error getting Volume', response.ok)
}
}
}
const getUsageByDay = async (orgId, uuids, p) => {
//https://services.senti.cloud/databroker/v2/waterworks/data/totalusagebyday/2021-12-31/2022-03-01
if (uuids) {
let response = await dbAPI.post(`/v2/waterworks/data/usagebyday/${p.from}/${p.to}`, uuids)//?
if (response.ok) {
return response.data//?
}
else {
response.ok
}
}
else {
let response = await dbAPI.get(`/v2/waterworks/data/totalusagebyday/${orgId}/${p.from}/${p.to}`)
if (response.ok) {
return response.data//?
}
else {
response.ok
}
}
}
/**
* @param uuids List of device UUIDS
* @param {UUIDv4} orgId Org UUID
*/
export const execCronUsage = async (uuids, orgId, period) => {
/**
* Get the data
*/
if (period) {
/**
* Custom request
*/
let usageByDate = await getUsageByDay(orgId, uuids, period)
storeData(uuids, orgId, [{ p: period, data: usageByDate }], 'usage')
}
else {
/**
* Store the data in redis
*/
// let usagesByDate2 = await Promise.all(timeTables.map(async t => ({ p: t, data: await getUsageByDay(orgId, uuids, t) })))
let usageGet = async () => {
let res = []
for (const t in timeTables) {
console.log(timeTables[t], t)
let data = await getUsageByDay(orgId, uuids, timeTables[t])
res.push({ p: timeTables[t], data: data})
}
return res
}
let usagesByDate = await usageGet()
storeData(uuids, orgId, usagesByDate, 'usage')
}
}
export const execCronBenchmark = async (uuids, orgId, period) => {
if (period) {
let benchmark = await getBenchmark(orgId, uuids, period)
storeData(uuids, orgId, [{ p: period, data: benchmark }], 'benchmark')
}
else {
let benchmarkGet = async () => {
let res = []
for (const t in timeTables) {
let data = await getBenchmark(orgId, uuids, timeTables[t])
res.push({ p: timeTables[t], data: data })
}
return res
}
let benchm = await benchmarkGet()
// await Promise.all(timeTables.map(async t => ({ p: t, data: await getBenchmark(orgId, uuids, t) })))
storeData(uuids, orgId, benchm, 'benchmark')
}
}
export const execCronWaterTemperature = async (uuids, orgId, period) => {
if (period) {
let waterTemp = await getWaterTemperature(orgId, uuids, period)
storeData(uuids, orgId, [{ p: period, data: waterTemp }], 'minWTemp')
}
else {
let minWTempGet = async () => {
let res = []
for (const t in timeTables) {
let data = await getWaterTemperature(orgId, uuids, timeTables[t])
res.push({ p: timeTables[t], data: data })
}
return res
}
let waterTemp = await minWTempGet()
// await Promise.all(timeTables.map(async t => ({ p: t, data: await getWaterTemperature(orgId, uuids, t) })))
storeData(uuids, orgId, waterTemp, 'minWTemp')
}
}
export const execCronAmbientTemperature = async (uuids, orgId, period) => {
if (period) {
let ambientTemp = await getAmbientTemperature(orgId, uuids, period)
storeData(uuids, orgId, [{ p: period, data: ambientTemp }], 'minATemp')
}
else {
let minATempGet = async () => {
let res = []
for (const t in timeTables) {
let data = await getAmbientTemperature(orgId, uuids, timeTables[t])
res.push({ p: timeTables[t], data: data })
}
return res
}
let ambientTemp = await minATempGet()
// await Promise.all(timeTables.map(async t => ({ p: t, data: await getAmbientTemperature(orgId, uuids, t) })))
storeData(uuids, orgId, ambientTemp, 'minATemp')
}
}
export const execCronMaxFlow = async (uuids, orgId, period) => {
if (period) {
let maxFlow = await getMaxFlow(orgId, uuids, period)
storeData(uuids, orgId, [{ p: period, data: maxFlow }], 'maxFlow')
}
else {
let maxFlowGet = async () => {
let res = []
for (const t in timeTables) {
let data = await getMaxFlow(orgId, uuids, timeTables[t])
res.push({ p: timeTables[t], data: data })
}
return res
}
let maxFlow = await maxFlowGet()
// await Promise.all(timeTables.map(async t => ({ p: t, data: await getMaxFlow(orgId, uuids, t) })))
storeData(uuids, orgId, maxFlow, 'maxFlow')
}
}
export const execCronMinFlow = async (uuids, orgId, period) => {
if (period) {
let minFlow = await getMinFlow(orgId, uuids, period)
storeData(uuids, orgId, [{ p: period, data: minFlow }], 'minFlow')
}
else {
let minFlowGet = async () => {
let res = []
for (const t in timeTables) {
let data = await getMinFlow(orgId, uuids, timeTables[t])
res.push({ p: timeTables[t], data: data })
}
return res
}
let minFlow = await minFlowGet()
// await Promise.all(timeTables.map(async t => ({ p: t, data: await getMinFlow(orgId, uuids, t) })))
storeData(uuids, orgId, minFlow, 'minFlow')
}
}
export const execCronReading = async (uuids, orgId, period) => {
if (period) {
let reading = await getReading(orgId, uuids, period)
storeData(uuids, orgId, [{ p: period, data: reading }], 'volume')
}
else {
let volumeGet = async () => {
let res = []
for (const t in timeTables) {
let data = await getReading(orgId, uuids, timeTables[t])
res.push({ p: timeTables[t], data: data })
}
return res
}
let reading = await volumeGet()
// await Promise.all(timeTables.map(async t => ({ p: t, data: await getReading(orgId, uuids, t) })))
storeData(uuids, orgId, reading, 'volume')
}
} |
<gh_stars>10-100
/**
* @file : sysparam.h
* @brief : Physical parameters of the system header file, in C++11/14,
* @details : as a struct, have total energy E, total magnetization M, temperature of entire system T (in energy units)
*
* @author : <NAME> <<EMAIL>>
* @date : 20171229
* @ref : <NAME>, Computational Physics, University of Oslo (2015)
*
* https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=ernestsaveschristmas%2bpaypal%40gmail%2ecom&lc=US&item_name=ernestyalumni¤cy_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted
*
* which won't go through a 3rd. party such as indiegogo, kickstarter, patreon.
* Otherwise, I receive emails and messages on how all my (free) material on
* physics, math, and engineering have helped students with their studies,
* and I know what it's like to not have money as a student, but love physics
* (or math, sciences, etc.), so I am committed to keeping all my material
* open-source and free, whether or not
* sufficiently crowdfunded, under the open-source MIT license:
* feel free to copy, edit, paste, make your own versions, share, use as you wish.
* Just don't be an asshole and not give credit where credit is due.
* Peace out, never give up! -EY
*
* */
/*
* COMPILATION TIP
* g++ main.cpp ./structs/structs.cpp -o main
*
* */
#ifndef __SYSPARAM_H__
#define __SYSPARAM_H__
#include <memory>
#include <cmath> // std::exp
struct Sysparam {
double E; // total energy E
double M; // total magnetization M
double T; // temperature T of the system
// constructors
Sysparam(); // default constructor
Sysparam(double, double, double) ;
Sysparam(double) ; // only given the temperature T of the system
};
struct Avg {
// (data) members
// average values of physical parameters
double Eavg;
double Mavg;
double Esq_avg; // Esq = E*E
double Msq_avg; // Msq = M*M
double absM_avg; // absM = |M|
// constructors
Avg(); // default constructor
Avg(double,double,double,double,double);
};
/** @struct TransProb
* @brief transition probabilities to new spin configuration for 2-dim. Ising model
* */
struct TransProb {
// (data) members
// transition probabilities data
std::unique_ptr<double[]> transprob;
double J; // spin constant
// constructors
TransProb(); // default constructor
TransProb(double, Sysparam& );
// getting functions
/** @fn get_by_DeltaE
* @details given DeltaE (\Delta E), DeltaE = -8J, -4J,...8J, we want to get the
* transition probability from std::unique_ptr transprob (but transprob indexed by
* 0,1,...(17-1)
* */
double get_by_DeltaE(int);
};
#endif // __SYSPARAM_H__
|
<reponame>seratch/junithelper
package org.junithelper.core.util;
import org.junithelper.core.exception.JUnitHelperCoreException;
public final class Assertion {
private String name;
private Assertion(String name) {
if (name == null || name.length() == 0) {
throw new JUnitHelperCoreException("assertion target name must not be empty.");
}
this.name = name;
}
public static Assertion on(String name) {
return new Assertion(name);
}
public <T> void mustNotBeNull(T arg) {
if (arg == null) {
throw new JUnitHelperCoreException(name + " must not be null.");
}
}
public void mustNotBeEmpty(String arg) {
if (arg == null || arg.length() == 0) {
throw new JUnitHelperCoreException(name + " must not be empty.");
}
}
public void mustBeGreaterThan(int arg, int lowerLimit) {
if (arg <= lowerLimit) {
throw new JUnitHelperCoreException(name + " must not be greater than " + lowerLimit + ".");
}
}
public void mustBeGreaterThanOrEqual(int arg, int lowerLimit) {
if (arg < lowerLimit) {
throw new JUnitHelperCoreException(name + " must not be greater than or equal " + lowerLimit + ".");
}
}
public void mustBeLessThan(int arg, int upperLimit) {
if (arg >= upperLimit) {
throw new JUnitHelperCoreException(name + " must not be less than " + upperLimit + ".");
}
}
public void mustBeLessThanOrEqual(int arg, int upperLimit) {
if (arg > upperLimit) {
throw new JUnitHelperCoreException(name + " must not be less than or equal " + upperLimit + ".");
}
}
public void mustBeGreaterThan(long arg, long lowerLimit) {
if (arg <= lowerLimit) {
throw new JUnitHelperCoreException(name + " must not be greater than " + lowerLimit + ".");
}
}
public void mustBeGreaterThanOrEqual(long arg, long lowerLimit) {
if (arg < lowerLimit) {
throw new JUnitHelperCoreException(name + " must not be greater than or equal " + lowerLimit + ".");
}
}
public void mustBeLessThan(long arg, long upperLimit) {
if (arg >= upperLimit) {
throw new JUnitHelperCoreException(name + " must not be less than " + upperLimit + ".");
}
}
public void mustBeLessThanOrEqual(long arg, long upperLimit) {
if (arg > upperLimit) {
throw new JUnitHelperCoreException(name + " must not be less than or equal " + upperLimit + ".");
}
}
public void mustBeGreaterThan(double arg, double lowerLimit) {
if (arg <= lowerLimit) {
throw new JUnitHelperCoreException(name + " must not be greater than " + lowerLimit + ".");
}
}
public void mustBeGreaterThanOrEqual(double arg, double lowerLimit) {
if (arg < lowerLimit) {
throw new JUnitHelperCoreException(name + " must not be greater than or equal " + lowerLimit + ".");
}
}
public void mustBeLessThan(double arg, double upperLimit) {
if (arg >= upperLimit) {
throw new JUnitHelperCoreException(name + " must not be less than " + upperLimit + ".");
}
}
public void mustBeLessThanOrEqual(double arg, double upperLimit) {
if (arg > upperLimit) {
throw new JUnitHelperCoreException(name + " must not be less than or equal " + upperLimit + ".");
}
}
}
|
/*\
title: $:/plugins/sq/streams/filters/get-stream-nodes.js
type: application/javascript
module-type: filteroperator
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports["get-stream-nodes"] = function(source,operator,options) {
var results = [],
suffixes = (operator.suffixes || []),
matchTitles = (suffixes[0] || []).indexOf("matchtitles") !== -1;
source(function(tiddler,title) {
var processNode = function(node,nodeTitle) {
if(node && node.fields["stream-list"] && node.fields["stream-type"]) {
results.push(nodeTitle);
var streamList = $tw.utils.parseStringArray(node.fields["stream-list"]);
$tw.utils.each(streamList,function(streamListNodeTitle) {
var streamListNode = options.wiki.getTiddler(streamListNodeTitle);
if(streamListNode) {
processNode(streamListNode,streamListNodeTitle);
}
});
} else {
results.push(nodeTitle);
}
}
if(tiddler) {
processNode(tiddler,title);
}
});
return results;
};
})();
|
<reponame>smagill/opensphere-desktop
package io.opensphere.core.util.fx.tabpane;
import javafx.beans.InvalidationListener;
import javafx.beans.WeakInvalidationListener;
import javafx.scene.Node;
import javafx.scene.control.Tab;
import javafx.scene.layout.StackPane;
/** A region for each tab to contain the tab's content node */
public class OSTabContentRegion extends StackPane
{
/** The tab for which the content region is defined. */
private Tab myTab;
/** The listener for invalidation of the tab content. */
private InvalidationListener tabContentListener = v -> updateContent();
/** The listener for invalidation of the selection of the tab. */
private InvalidationListener tabSelectedListener = v -> setVisible(myTab.isSelected());
/** Weak reference for the content listener. */
private WeakInvalidationListener weakTabContentListener = new WeakInvalidationListener(tabContentListener);
/** Weak reference for the selection listener. */
private WeakInvalidationListener weakTabSelectedListener = new WeakInvalidationListener(tabSelectedListener);
/**
* Creates a new tab content region for the supplied tab.
*
* @param tab The tab for which the content region is defined.
*/
public OSTabContentRegion(Tab tab)
{
getStyleClass().setAll("tab-content-area");
setManaged(false);
this.myTab = tab;
updateContent();
setVisible(tab.isSelected());
tab.selectedProperty().addListener(weakTabSelectedListener);
tab.contentProperty().addListener(weakTabContentListener);
}
/**
* Gets the value of the {@link #myTab} field.
*
* @return the value stored in the {@link #myTab} field.
*/
public Tab getTab()
{
return myTab;
}
/** Updates the content for the tab's region. */
private void updateContent()
{
Node newContent = getTab().getContent();
if (newContent == null)
{
getChildren().clear();
}
else
{
getChildren().setAll(newContent);
}
}
/**
* Invalidates all listeners for the supplied tab.
*
* @param tab the tab for which to invalidate the listeners.
*/
public void removeListeners(Tab tab)
{
tab.selectedProperty().removeListener(weakTabSelectedListener);
tab.contentProperty().removeListener(weakTabContentListener);
}
}
|
<filename>mybatis-plus-generator/src/test/java/com/baomidou/mybatisplus/test/generator/GeneratorTest.java
package com.baomidou.mybatisplus.test.generator;
import java.util.Scanner;
/**
* <p>
* Generator test
* </p>
*
* @author hubin
* @since 2018-01-11
*/
public class GeneratorTest {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static int scanner() {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append(" !!代码生成, 输入 0 表示使用 Velocity 引擎 !!");
help.append("\n对照表:");
help.append("\n0 = Velocity 引擎");
help.append("\n1 = Freemarker 引擎");
help.append("\n请输入:");
System.out.println(help.toString());
int slt = 0;
// 现在有输入数据
if (scanner.hasNext()) {
String ipt = scanner.next();
if ("1".equals(ipt)) {
slt = 1;
}
}
return slt;
}
}
|
def drop_duplicates(lst):
new_list = []
for i in lst:
if i not in new_list:
new_list.append(i)
return new_list |
<reponame>onearmbandit/MTAV
require('../../scss/website/whathavewedone-page.scss');
(function ($) {
})(jQuery);
|
#!/bin/bash
cd sfja
yarn && yarn start
|
//============================================================================
// Copyright 2009-2020 ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
//============================================================================
#ifndef VARIABLEITEMWIDGET_HPP_
#define VARIABLEITEMWIDGET_HPP_
#include "ui_VariablePropDialog.h"
#include "ui_VariableAddDialog.h"
#include "ui_VariableItemWidget.h"
#include "InfoPanelItem.hpp"
#include "VariableModelDataObserver.hpp"
#include "VInfo.hpp"
class LineEdit;
class ModelColumn;
class VariableModel;
class VariableModelData;
class VariableModelDataHandler;
class VariableSortModel;
class VariableSearchLine;
class VProperty;
class VariablePropDialog : public QDialog, public VariableModelDataObserver, private Ui::VariablePropDialog
{
Q_OBJECT
public:
VariablePropDialog(VariableModelDataHandler* data,int defineIndex,QString name,QString value,bool frozen,QWidget* parent=nullptr);
~VariablePropDialog() override;
QString name() const;
QString value() const;
void notifyCleared(VariableModelDataHandler*) override;
void notifyUpdated(VariableModelDataHandler*) override;
public Q_SLOTS:
void accept() override;
void slotSuspendedChanged(bool s);
protected Q_SLOTS:
void on_nameEdit__textEdited(QString);
void on_valueEdit__textChanged();
protected:
void suspendEdit(bool);
void readSettings();
void writeSettings();
bool genVar_;
VariableModelDataHandler* data_;
int defineIndex_;
QString oriName_;
QString nodeName_;
QString nodeType_;
QString nodeTypeCapital_;
QString defineNodeName_;
QString defineNodeType_;
bool cleared_;
bool suspended_;
};
class VariableAddDialog : public QDialog, public VariableModelDataObserver, private Ui::VariableAddDialog
{
Q_OBJECT
public:
VariableAddDialog(VariableModelDataHandler* data,QWidget* parent=nullptr);
VariableAddDialog(VariableModelDataHandler* data,QString name,QString value,QWidget* parent=nullptr);
~VariableAddDialog() override;
QString name() const;
QString value() const;
void notifyCleared(VariableModelDataHandler*) override;
void notifyUpdated(VariableModelDataHandler*) override {}
public Q_SLOTS:
void accept() override;
void slotSuspendedChanged(bool s);
protected:
void init();
void suspendEdit(bool);
void readSettings();
void writeSettings();
VariableModelDataHandler* data_;
QString nodeName_;
QString nodeType_;
QString nodeTypeCapital_;
bool cleared_;
bool suspended_;
};
class VariableItemWidget : public QWidget, public InfoPanelItem, protected Ui::VariableItemWidget
{
Q_OBJECT
public:
explicit VariableItemWidget(QWidget *parent=nullptr);
~VariableItemWidget() override;
void reload(VInfo_ptr) override;
QWidget* realWidget() override;
void clearContents() override;
public Q_SLOTS:
void slotFilterTextChanged(QString text);
void slotItemSelected(const QModelIndex& idx,const QModelIndex& prevIdx);
protected Q_SLOTS:
void on_actionProp_triggered();
void on_actionAdd_triggered();
void on_actionDelete_triggered();
void on_varView_doubleClicked(const QModelIndex& index);
void on_actionFilter_triggered();
void on_actionSearch_triggered();
void on_actionCopy_triggered();
void on_actionCopyFull_triggered();
void on_actionAddToTableView_triggered();
void on_shadowTb_clicked(bool showShadowed);
void slotVariableEdited();
void slotVariableAdded();
Q_SIGNALS:
void suspendedChanged(bool);
protected:
void checkActionState();
void editItem(const QModelIndex& index);
void duplicateItem(const QModelIndex& index);
void addItem(const QModelIndex& index);
void removeItem(const QModelIndex& index);
void updateState(const ChangeFlags&) override;
void toClipboard(QString txt) const;
void regainSelection();
void saveExpandState();
void restoreExpandState();
void nodeChanged(const VNode*, const std::vector<ecf::Aspect::Type>&) override;
void defsChanged(const std::vector<ecf::Aspect::Type>&) override;
VariableModelDataHandler* data_;
VariableModel* model_;
VariableSortModel* sortModel_;
LineEdit* filterLine_;
VariableSearchLine *searchLine_;
VProperty* shadowProp_{nullptr};
VInfo_ptr lastSelection_;
bool canSaveLastSelection_{true};
QList<bool> expanded_;
ModelColumn *tableViewColumns_;
};
#endif
|
<gh_stars>0
package io.github.cottonmc.component.energy.impl;
import io.github.cottonmc.component.UniversalComponents;
import io.github.cottonmc.component.energy.CapacitorComponent;
import io.github.cottonmc.component.energy.type.EnergyType;
import nerdhub.cardinal.components.api.ComponentType;
import nerdhub.cardinal.components.api.util.sync.ChunkSyncedComponent;
import net.minecraft.world.chunk.Chunk;
public class ChunkSyncedCapacitorComponent extends SimpleCapacitorComponent implements ChunkSyncedComponent<CapacitorComponent> {
private ComponentType<CapacitorComponent> componentType;
private Chunk chunk;
public ChunkSyncedCapacitorComponent(int maxEnergy, EnergyType type, Chunk chunk) {
this(maxEnergy, type, UniversalComponents.CAPACITOR_COMPONENT, chunk);
}
public ChunkSyncedCapacitorComponent(int maxEnergy, EnergyType type, ComponentType<CapacitorComponent> componentType, Chunk chunk) {
super(maxEnergy, type);
this.componentType = componentType;
this.chunk = chunk;
listen(this::sync);
}
@Override
public Chunk getChunk() {
return chunk;
}
@Override
public ComponentType<CapacitorComponent> getComponentType() {
return componentType;
}
}
|
#/bin/bash
cp -r build/html/* ../../ECPy-doc/
|
#!/bin/bash
set -e
set -o pipefail
# Uncomment for testing purposes:
#GITHUB_TOKEN=YOUR_TOKEN_HERE
#GITHUB_REPOSITORY=invertase/extensions-release-testing
# -------------------
# Functions
# -------------------
json_escape () {
printf '%s' "$1" | python -c 'import json,sys; print(json.dumps(sys.stdin.read()))'
}
# Creates a new GitHub release
# ARGS:
# 1: Name of the release (becomes the release title on GitHub)
# 2: Markdown body of the release
# 3: Release Git tag
create_github_release(){
local response=''
local release_name=$1
local release_body=$2
local release_tag=$3
local body='{
"tag_name": "%s",
"target_commitish": "master",
"name": "%s",
"body": %s,
"draft": false,
"prerelease": false
}'
# shellcheck disable=SC2059
body=$(printf "$body" "$release_tag" "$release_name" "$release_body")
response=$(curl --request POST \
--url https://api.github.com/repos/${GITHUB_REPOSITORY}/releases \
--header "Authorization: Bearer $GITHUB_TOKEN" \
--header 'Content-Type: application/json' \
--data "$body" \
-s)
created=$(echo "$response" | python -c "import sys, json; data = json.load(sys.stdin); print(data.get('id', sys.stdin))")
if [ "$created" != "$response" ]; then
printf "release created successfully!\n"
else
printf "release failed to create; "
printf "\n%s\n" "$body"
printf "\n%s\n" "$response"
exit 1;
fi
}
# Updates an existing GitHub release
# ARGS:
# 1: Name of the release (becomes the release title on GitHub)
# 2: Markdown body of the release
# 3: Release Git tag
# 4: ID of the existing release
update_github_release(){
local response=''
local release_name=$1
local release_body=$2
local release_tag=$3
local release_id=$4
local body='{
"tag_name": "%s",
"target_commitish": "master",
"name": "%s",
"body": %s,
"draft": false,
"prerelease": false
}'
# shellcheck disable=SC2059
body=$(printf "$body" "$release_tag" "$release_name" "$release_body")
response=$(curl --request PATCH \
--url "https://api.github.com/repos/$GITHUB_REPOSITORY/releases/$release_id" \
--header "Authorization: Bearer $GITHUB_TOKEN" \
--header 'Content-Type: application/json' \
--data "$body" \
-s)
updated=$(echo "$response" | python -c "import sys, json; data = json.load(sys.stdin); print(data.get('id', sys.stdin))")
if [ "$updated" != "$response" ]; then
printf "release updated successfully!\n"
else
printf "release failed to update; "
printf "\n%s\n" "$body"
printf "\n%s\n" "$response"
exit 1;
fi
}
# Creates or updates a GitHub release
# ARGS:
# 1: Extension name
# 2: Extension version
# 3: Markdown body to use for the release
create_or_update_github_release() {
local response=''
local release_id=''
local extension_name=$1
local extension_version=$2
local release_body=$3
local release_tag="$extension_name-$extension_version"
local release_name="$extension_name $extension_version"
response=$(curl --request GET \
--url "https://api.github.com/repos/${GITHUB_REPOSITORY}/releases/tags/${release_tag}" \
--header "Authorization: Bearer $GITHUB_TOKEN" \
--header 'Content-Type: application/json' \
--data "$body" \
-s)
release_id=$(echo "$response" | python -c "import sys, json; data = json.load(sys.stdin); print(data.get('id', 'Not Found'))")
if [ "$release_id" != "Not Found" ]; then
existing_release_body=$(echo "$response" | python -c "import sys, json; data = json.load(sys.stdin); print(data.get('body', ''))")
existing_release_body=$(json_escape "$existing_release_body")
# Only update it if the release body is different (this can happen if a change log is manually updated)
printf "Existing release (%s) found for %s - " "$release_id" "$release_tag"
if [ "$existing_release_body" != "$release_body" ]; then
printf "updating it with updated release body ... "
update_github_release "$release_name" "$release_body" "$release_tag" "$release_id"
else
printf "skipping it as release body is already up to date.\n"
fi
else
response_message=$(echo "$response" | python -c "import sys, json; data = json.load(sys.stdin); print(data.get('message'))")
if [ "$response_message" != "Not Found" ]; then
echo "Failed to query release '$release_name' -> GitHub API request failed with response: $response_message"
echo "$response"
exit 1;
else
printf "Creating new release '%s' ... " "$release_tag"
create_github_release "$release_name" "$release_body" "$release_tag"
fi
fi
}
# -------------------
# Main Script
# -------------------
# Ensure that the GITHUB_TOKEN env variable is defined
if [[ -z "$GITHUB_TOKEN" ]]; then
echo "Missing required GITHUB_TOKEN env variable. Set this on the workflow action or on your local environment."
exit 1
fi
# Ensure that the GITHUB_REPOSITORY env variable is defined
if [[ -z "$GITHUB_REPOSITORY" ]]; then
echo "Missing required GITHUB_REPOSITORY env variable. Set this on the workflow action or on your local environment."
exit 1
fi
if [[ $(git branch | grep "^*" | awk '{print $2}') != "master" ]]; then
# Find all extensions based on whether a extension.yaml file exists in the directory
for i in $(find . -type f -name 'extension.yaml' -exec dirname {} \; | sort -u); do
# Pluck extension name from directory name
extension_name=$(echo "$i" | sed "s/\.\///")
# Pluck extension latest version from yaml file
extension_version=$(awk '/^version: /' "$i/extension.yaml" | sed "s/version: //")
# Pluck out change log contents for the latest extension version
changelog_contents=$(awk -v ver="$extension_version" '/^## Version / { if (p) { exit }; if ($3 == ver) { p=1; next} } p && NF' "$i/CHANGELOG.md")
# JSON escape the markdown content for the release body
changelog_contents=$(json_escape "$changelog_contents")
# Creates a new release if it does not exist
# OR
# Updates an existing release with updated content (allows updating CHANGELOG.md which will update relevant release body)
create_or_update_github_release "$extension_name" "$extension_version" "$changelog_contents"
done
else
echo "This action can only run on 'master' branch."
exit 0
fi
|
#!/bin/bash
#
# vi: expandtab tabstop=4 shiftwidth=0
set -o errexit
set -o pipefail
if [ "$DEBUG" == "true" ]; then
set -ex ;export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
fi
readlink_mac() {
cd `dirname $1`
TARGET_FILE=`basename $1`
# Iterate down a (possible) chain of symlinks
while [ -L "$TARGET_FILE" ]
do
TARGET_FILE=`readlink $TARGET_FILE`
cd `dirname $TARGET_FILE`
TARGET_FILE=`basename $TARGET_FILE`
done
# Compute the canonicalized name by finding the physical path
# for the directory we're in and appending the target file.
PHYS_DIR=`pwd -P`
REAL_PATH=$PHYS_DIR/$TARGET_FILE
}
get_current_arch() {
local current_arch
case $(uname -m) in
x86_64)
current_arch=amd64
;;
aarch64)
current_arch=arm64
;;
esac
echo $current_arch
}
pushd $(cd "$(dirname "$0")"; pwd) > /dev/null
readlink_mac $(basename "$0")
cd "$(dirname "$REAL_PATH")"
CUR_DIR=$(pwd)
SRC_DIR=$(cd .. && pwd)
popd > /dev/null
DOCKER_DIR="$SRC_DIR/build/docker"
# https://docs.docker.com/develop/develop-images/build_enhancements/
export DOCKER_BUILDKIT=1
# https://github.com/docker/buildx#with-buildx-or-docker-1903
export DOCKER_CLI_EXPERIMENTAL=enabled
REGISTRY=${REGISTRY:-docker.io/yunion}
TAG=${TAG:-latest}
CURRENT_ARCH=$(get_current_arch)
ARCH=${ARCH:-$CURRENT_ARCH}
build_bin() {
local BUILD_ARCH=$2
local BUILD_CGO=$3
case "$1" in
baremetal-agent)
rm -vf _output/bin/$1
rm -rvf _output/bin/bundles/$1
GOOS=linux make cmd/$1
;;
climc)
if [[ "$BUILD_ARCH" == *arm64 ]]; then
# exclude rbdcli for arm64
env $BUILD_ARCH $BUILD_CGO make -C "$SRC_DIR" docker-alpine-build F="cmd/$1 $(ls -d cmd/*cli|grep -v rbdcli|xargs)"
else
env $BUILD_ARCH $BUILD_CGO make -C "$SRC_DIR" docker-alpine-build F="cmd/$1 cmd/*cli"
fi
;;
host-deployer | telegraf-raid-plugin)
env $BUILD_ARCH $BUILD_CGO make -C "$SRC_DIR" docker-centos-build F="cmd/$1"
;;
*)
env $BUILD_ARCH $BUILD_CGO make -C "$SRC_DIR" docker-alpine-build F="cmd/$1"
;;
esac
}
build_bundle_libraries() {
for bundle_component in 'baremetal-agent'; do
if [ $1 == $bundle_component ]; then
$CUR_DIR/bundle_libraries.sh _output/bin/bundles/$1 _output/bin/$1
break
fi
done
}
build_image() {
local tag=$1
local file=$2
local path=$3
docker buildx build -t "$tag" -f "$2" "$3" --push
docker pull "$tag"
}
buildx_and_push() {
local tag=$1
local file=$2
local path=$3
local arch=$4
docker buildx build -t "$tag" --platform "linux/$arch" -f "$2" "$3" --push
docker pull "$tag"
}
get_image_name() {
local component=$1
local arch=$2
local is_all_arch=$3
local img_name="$REGISTRY/$component:$TAG"
if [[ "$is_all_arch" == "true" || "$arch" == arm64 ]]; then
img_name="${img_name}-$arch"
fi
echo $img_name
}
build_process() {
local component=$1
local arch=$2
local is_all_arch=$3
local img_name=$(get_image_name $component $arch $is_all_arch)
build_bin $component
build_bundle_libraries $component
build_image $img_name $DOCKER_DIR/Dockerfile.$component $SRC_DIR
}
build_process_with_buildx() {
local component=$1
local arch=$2
local is_all_arch=$3
local img_name=$(get_image_name $component $arch $is_all_arch)
build_env="GOARCH=$arch"
if [[ "$arch" == arm64 ]]; then
build_env="$build_env"
if [[ $component == host ]]; then
build_env="$build_env CGO_ENABLED=1"
fi
fi
case "$component" in
host | torrent)
buildx_and_push $img_name $DOCKER_DIR/multi-arch/Dockerfile.$component $SRC_DIR $arch
;;
*)
build_bin $component $build_env
buildx_and_push $img_name $DOCKER_DIR/Dockerfile.$component $SRC_DIR $arch
;;
esac
}
general_build() {
local component=$1
# 如果未指定,则默认使用当前架构
local arch=${2:-$CURRENT_ARCH}
local is_all_arch=$3
if [[ "$CURRENT_ARCH" == "$arch" ]]; then
build_process $component $arch $is_all_arch
else
build_process_with_buildx $component $arch $is_all_arch
fi
}
make_manifest_image() {
local component=$1
local img_name=$(get_image_name $component "" "false")
docker manifest create --amend $img_name \
$img_name-amd64 \
$img_name-arm64
docker manifest annotate $img_name $img_name-arm64 --arch arm64
docker manifest push $img_name
}
ALL_COMPONENTS=$(ls cmd | grep -v '.*cli$' | xargs)
if [ "$#" -lt 1 ]; then
echo "No component is specified~"
echo "You can specify a component in [$ALL_COMPONENTS]"
echo "If you want to build all components, specify the component to: all."
exit
elif [ "$#" -eq 1 ] && [ "$1" == "all" ]; then
echo "Build all onecloud docker images"
COMPONENTS=$ALL_COMPONENTS
else
COMPONENTS=$@
fi
cd $SRC_DIR
mkdir -p $SRC_DIR/_output
for component in $COMPONENTS; do
if [[ $component == *cli ]]; then
echo "Please build image for climc"
continue
fi
echo "Start to build component: $component"
if [[ $component == baremetal-agent ]]; then
if [[ "$ARCH" == "arm64" ]]; then
continue
fi
build_process $component
continue
fi
case "$ARCH" in
all)
for arch in "arm64" "amd64"; do
general_build $component $arch "true"
done
make_manifest_image $component
;;
*)
if [ -e "$DOCKER_DIR/Dockerfile.$component" ]; then
general_build $component $ARCH "false"
fi
;;
esac
done
|
# https://developer.zendesk.com/rest_api/docs/voice-api/phone_numbers#show-phone-number
zdesk_channels_voice_phone_number_show () {
method=GET
url="$(echo "/api/v2/channels/voice/phone_numbers/{id}.json" | sed \
-e "s/{id}"/"$1"/ \
)"
shift
} |
// (C) 2019-2020 GoodData Corporation
import { AttributeGranularityResourceAttribute } from "@gooddata/api-client-tiger";
import { DateAttributeGranularity } from "@gooddata/sdk-model";
import { NotSupported } from "@gooddata/sdk-backend-spi";
type TigerToSdk = {
[key in AttributeGranularityResourceAttribute]: DateAttributeGranularity;
};
type SdkToTiger = {
[key in DateAttributeGranularity]: AttributeGranularityResourceAttribute | undefined;
};
/*
Year = "year",
Day = "day",
Hour = "hour",
Minute = "minute",
Day = "day",
Quarter = "quarter",
Month = "month",
Week = "week",
QuarterOfYear = "quarterOfYear",
MonthOfYear = "monthOfYear",
DayOfYear = "dayOfYear",
DayOfWeek = "dayOfWeek",
DayOfMonth = "dayOfMonth",
HourOfDay = "hourOfDay",
MinuteOfHour = "minuteOfHour",
WeekOfYear = "weekOfYear",
*/
const TigerToSdkGranularityMap: TigerToSdk = {
[AttributeGranularityResourceAttribute.Year]: "GDC.time.year",
[AttributeGranularityResourceAttribute.Day]: "GDC.time.date",
[AttributeGranularityResourceAttribute.Hour]: "GDC.time.hour",
[AttributeGranularityResourceAttribute.Minute]: "GDC.time.minute",
[AttributeGranularityResourceAttribute.Day]: "GDC.time.date",
[AttributeGranularityResourceAttribute.Quarter]: "GDC.time.quarter",
[AttributeGranularityResourceAttribute.Month]: "GDC.time.month",
[AttributeGranularityResourceAttribute.Week]: "GDC.time.week_us",
[AttributeGranularityResourceAttribute.QuarterOfYear]: "GDC.time.quarter_in_year",
[AttributeGranularityResourceAttribute.MonthOfYear]: "GDC.time.month_in_year",
[AttributeGranularityResourceAttribute.DayOfYear]: "GDC.time.day_in_year",
[AttributeGranularityResourceAttribute.DayOfWeek]: "GDC.time.day_in_week",
[AttributeGranularityResourceAttribute.DayOfMonth]: "GDC.time.day_in_month",
[AttributeGranularityResourceAttribute.HourOfDay]: "GDC.time.hour_in_day",
[AttributeGranularityResourceAttribute.MinuteOfHour]: "GDC.time.minute_in_hour",
[AttributeGranularityResourceAttribute.WeekOfYear]: "GDC.time.week_in_year",
};
/**
* Converts supported tiger backend granularities to values recognized by the SDK.
*
* @param granularity - tiger granularity
*/
export function toSdkGranularity(
granularity: AttributeGranularityResourceAttribute,
): DateAttributeGranularity {
return TigerToSdkGranularityMap[granularity];
}
const SdkToTigerGranularityMap: SdkToTiger = {
"GDC.time.year": AttributeGranularityResourceAttribute.Year,
"GDC.time.date": AttributeGranularityResourceAttribute.Day,
"GDC.time.hour": AttributeGranularityResourceAttribute.Hour,
"GDC.time.minute": AttributeGranularityResourceAttribute.Minute,
"GDC.time.quarter": AttributeGranularityResourceAttribute.Quarter,
"GDC.time.month": AttributeGranularityResourceAttribute.Month,
"GDC.time.week_us": AttributeGranularityResourceAttribute.Week,
"GDC.time.week": AttributeGranularityResourceAttribute.Week,
"GDC.time.quarter_in_year": AttributeGranularityResourceAttribute.QuarterOfYear,
"GDC.time.month_in_year": AttributeGranularityResourceAttribute.MonthOfYear,
"GDC.time.day_in_year": AttributeGranularityResourceAttribute.DayOfYear,
"GDC.time.day_in_week": AttributeGranularityResourceAttribute.DayOfWeek,
"GDC.time.day_in_month": AttributeGranularityResourceAttribute.DayOfMonth,
"GDC.time.week_in_year": AttributeGranularityResourceAttribute.WeekOfYear,
"GDC.time.hour_in_day": AttributeGranularityResourceAttribute.HourOfDay,
"GDC.time.minute_in_hour": AttributeGranularityResourceAttribute.MinuteOfHour,
"GDC.time.day_in_euweek": undefined,
"GDC.time.day_in_quarter": undefined,
"GDC.time.euweek_in_quarter": undefined,
"GDC.time.euweek_in_year": undefined,
"GDC.time.month_in_quarter": undefined,
"GDC.time.week_in_quarter": undefined,
};
/**
* Converts granularity values recognized by the SDK into granularities known by tiger. Note that
* SDK granularities are superset of those supported by tiger.
*
* @throws NotSupport if the input granularity is not supported by tiger
*/
export function toTigerGranularity(
granularity: DateAttributeGranularity,
): AttributeGranularityResourceAttribute {
const tigerGranularity = SdkToTigerGranularityMap[granularity];
if (!tigerGranularity) {
throw new NotSupported(`The ${granularity} is not supported on tiger backend.`);
}
return tigerGranularity;
}
|
var structCatch_1_1Matchers_1_1Vector_1_1UnorderedEqualsMatcher =
[
[ "UnorderedEqualsMatcher", "structCatch_1_1Matchers_1_1Vector_1_1UnorderedEqualsMatcher.html#ab78e6bbbad05472815a695650edc062c", null ],
[ "describe", "structCatch_1_1Matchers_1_1Vector_1_1UnorderedEqualsMatcher.html#a33b685a1505a0afe06ded7e0d207bc14", null ],
[ "match", "structCatch_1_1Matchers_1_1Vector_1_1UnorderedEqualsMatcher.html#abd5547585ba722cf3bb7aa3f9a8ffc0e", null ]
]; |
aws appmesh create-virtual-node --cli-input-json file://v2/customer-v2-vn.json |
package com.jinjunhang.contract.controller;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import com.jinjunhang.contract.R;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* A simple {@link Fragment} subclass.
*/
public class DatePickerFragment extends DialogFragment {
public static final String TAG = "DatePickerFragment";
public static final String EXTRA_DATE = "com.jinjunhang.contract.date";
private Date mDate;
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_DATE, date);
DatePickerFragment datePickerFragment = new DatePickerFragment();
datePickerFragment.setArguments(args);
return datePickerFragment;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mDate = (Date)getArguments().getSerializable(EXTRA_DATE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(mDate);
final int year = calendar.get(Calendar.YEAR);
final int month = calendar.get(Calendar.MONTH);
final int day = calendar.get(Calendar.DAY_OF_MONTH);
View v = getActivity().getLayoutInflater().inflate(R.layout.dialog_date, null);
DatePicker datePicker = (DatePicker)v.findViewById(R.id.dialog_date_picker);
datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mDate = new GregorianCalendar(year, monthOfYear, dayOfMonth).getTime();
getArguments().putSerializable(EXTRA_DATE, mDate);
}
});
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "DialogInterface.onClick called");
sendResult(SearchOrderActivity.RESULT_OK);
}
})
.create();
}
private void sendResult(int resultCode) {
Log.d(TAG, "sendResult begin");
if (getTargetFragment() == null)
return;
Intent i = new Intent();
i.putExtra(EXTRA_DATE, mDate);
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, i);
Log.d(TAG, "sendResult end");
}
}
|
<filename>priest-satellite-manager/src/main/java/com/kinstalk/satellite/service/impl/ReportLastHoursApiServiceImpl.java
package com.kinstalk.satellite.service.impl;
import com.google.common.collect.Iterables;
import com.kinstalk.satellite.dao.ReportLastHoursApiDao;
import com.kinstalk.satellite.domain.ReportLastHoursApi;
import com.kinstalk.satellite.service.api.ReportLastHoursApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* User: liuling
* Date: 16/4/12
* Time: 下午6:42
*/
@Service
public class ReportLastHoursApiServiceImpl implements ReportLastHoursApiService {
private static Logger LOGGER = LoggerFactory.getLogger(ReportLastHoursApiServiceImpl.class);
@Resource
private ReportLastHoursApiDao reportLastHoursApiDao;
@Value("${batch.insert.size}")
private int batchSize;
@Override
public boolean insert(ReportLastHoursApi reportLastHoursApi) {
int row = reportLastHoursApiDao.insert(reportLastHoursApi);
//LOGGER.info("insert reportLastHoursApi,reportLastHoursApi:{},row:{}", reportLastHoursApi.toString(), row);
return true;
}
@Override
public List<ReportLastHoursApi> findByApiId(Long apiId) {
return reportLastHoursApiDao.getByApiId(apiId);
}
@Override
public boolean batchInsertReportLastHour(List<ReportLastHoursApi> reportLastHoursApis) {
Iterable<List<ReportLastHoursApi>> sets = Iterables.partition(reportLastHoursApis, batchSize);
for (List<ReportLastHoursApi> list : sets) {
if (list == null || list.size() == 0) {
continue;
}
int row = reportLastHoursApiDao.batchInsertReportLastHour(list);
if (row == 0) {
return false;
}
}
return true;
}
@Override
public boolean batchDeleteLastHours(Long time) {
int row = reportLastHoursApiDao.batchDeleteLastHours(time);
LOGGER.info("batch delete last hours,time:{},row:{}", time, row);
return true;
}
}
|
import {
IncludeStyles,
getRegisteredTypes,
getStyleModulesFor,
resetIncludeStyles
} from './include-styles';
describe('styles', () => {
describe('modules', () => {
describe('IncludeStyles', () => {
afterEach(() => {
resetIncludeStyles();
});
describe('.getRegisteredTypes()', () => {
it('should return all types that were decorated', () => {
@IncludeStyles('style-module')
class Comp1 {}
@IncludeStyles('style-module', 'other-style-module')
class Comp2 {}
expect(getRegisteredTypes()).toEqual([Comp1, Comp2]);
});
});
describe('.getStyleModulesFor()', () => {
it('should register one or more styles for a type', () => {
@IncludeStyles('style-module')
class Comp1 {}
@IncludeStyles('style-module', 'other-style-module')
class Comp2 {}
expect(getStyleModulesFor(Comp1)).toEqual(['style-module']);
expect(getStyleModulesFor(Comp2)).toEqual([
'style-module',
'other-style-module'
]);
});
it('should return an empty array if the type was not decorated', () => {
expect(getStyleModulesFor(class Unregistered {})).toEqual([]);
});
});
});
});
});
|
#!/bin/bash
# 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.
set -e
# first arg is `-something` or `+something`
if [ "${1#-}" != "$1" ] || [ "${1#+}" != "$1" ]; then
set -- /opt/couchdb/bin/couchdb "$@"
fi
# first arg is the bare word `couchdb`
if [ "$1" = 'couchdb' ]; then
shift
set -- /opt/couchdb/bin/couchdb "$@"
fi
if [ "$1" = '/opt/couchdb/bin/couchdb' ]; then
# this is where runtime configuration changes will be written.
# we need to explicitly touch it here in case /opt/couchdb/etc has
# been mounted as an external volume, in which case it won't exist.
# If running as the couchdb user (i.e. container starts as root),
# write permissions will be granted below.
touch /opt/couchdb/etc/local.d/docker.ini
# if user is root, assume running under the couchdb user (default)
# and ensure it is able to access files and directories that may be mounted externally
if [ "$(id -u)" = '0' ]; then
# Check that we own everything in /opt/couchdb and fix if necessary. We also
# add the `-f` flag in all the following invocations because there may be
# cases where some of these ownership and permissions issues are non-fatal
# (e.g. a config file owned by root with o+r is actually fine), and we don't
# to be too aggressive about crashing here ...
find /opt/couchdb \! \( -user couchdb -group couchdb \) -exec chown -f couchdb:couchdb '{}' +
# Ensure that data files have the correct permissions. We were previously
# preventing any access to these files outside of couchdb:couchdb, but it
# turns out that CouchDB itself does not set such restrictive permissions
# when it creates the files. The approach taken here ensures that the
# contents of the datadir have the same permissions as they had when they
# were initially created. This should minimize any startup delay.
find /opt/couchdb/data -type d ! -perm 0755 -exec chmod -f 0755 '{}' +
find /opt/couchdb/data -type f ! -perm 0644 -exec chmod -f 0644 '{}' +
# Do the same thing for configuration files and directories. Technically
# CouchDB only needs read access to the configuration files as all online
# changes will be applied to the "docker.ini" file below, but we set 644
# for the sake of consistency.
find /opt/couchdb/etc -type d ! -perm 0755 -exec chmod -f 0755 '{}' +
find /opt/couchdb/etc -type f ! -perm 0644 -exec chmod -f 0644 '{}' +
fi
if [ ! -z "$NODENAME" ] && ! grep "couchdb@" /opt/couchdb/etc/vm.args; then
echo "-name couchdb@$NODENAME" >> /opt/couchdb/etc/vm.args
fi
if [ "$COUCHDB_USER" ] && [ "$COUCHDB_PASSWORD" ]; then
# Create admin only if not already present
if ! grep -Pzoqr "\[admins\]\n$COUCHDB_USER =" /opt/couchdb/etc/local.d/*.ini /opt/couchdb/etc/local.ini; then
printf "\n[admins]\n%s = %s\n" "$COUCHDB_USER" "$COUCHDB_PASSWORD" >> /opt/couchdb/etc/local.d/docker.ini
fi
fi
if [ "$COUCHDB_SECRET" ]; then
# Set secret only if not already present
if ! grep -Pzoqr "\[couch_httpd_auth\]\nsecret =" /opt/couchdb/etc/local.d/*.ini /opt/couchdb/etc/local.ini; then
printf "\n[couch_httpd_auth]\nsecret = %s\n" "$COUCHDB_SECRET" >> /opt/couchdb/etc/local.d/docker.ini
fi
fi
if [ "$(id -u)" = '0' ]; then
chown -f couchdb:couchdb /opt/couchdb/etc/local.d/docker.ini || true
fi
# if we don't find an [admins] section followed by a non-comment, display a warning
if ! grep -Pzoqr '\[admins\]\n[^;]\w+' /opt/couchdb/etc/default.d/*.ini /opt/couchdb/etc/local.d/*.ini /opt/couchdb/etc/local.ini; then
# The - option suppresses leading tabs but *not* spaces. :)
cat >&2 <<-'EOWARN'
*************************************************************
ERROR: CouchDB 3.0+ will no longer run in "Admin Party"
mode. You *MUST* specify an admin user and
password, either via your own .ini file mapped
into the container at /opt/couchdb/etc/local.ini
or inside /opt/couchdb/etc/local.d, or with
"-e COUCHDB_USER=admin -e COUCHDB_PASSWORD=password"
to set it via "docker run".
*************************************************************
EOWARN
exit 1
fi
if [ "$(id -u)" = '0' ]; then
exec gosu couchdb "$@"
fi
fi
exec "$@"
|
fn vertical_lifting_base(
left: &mut [&mut [i16]],
middle: &mut [&mut [i16]],
right: &mut [&mut [i16]],
step: usize,
) {
for i in 0..middle.len() {
let middle_len = middle[i].len();
for j in 0..middle_len {
let avg = (left[i][j] + right[i][j]) / 2;
middle[i][j] += avg - middle[i][j];
}
}
} |
@interface VolumeControl : NSObject
- (void)increaseVolume;
- (void)decreaseVolume;
@end
|
package org.hammerlab.bam.check.eager
import caseapp._
import hammerlab.cli._
import org.hammerlab.args.{ FindReadArgs, LogArgs, PostPartitionArgs }
import org.hammerlab.bam.check.indexed.IndexedRecordPositions
import org.hammerlab.bam.check.{ Blocks, CallPartition, CheckerApp, eager, seqdoop }
object CheckBam
extends Cmd {
/**
* Check every (bgzf-decompressed) byte-position in a BAM file for a record-start with and compare the results to the
* true read-start positions.
*
* - Takes one argument: the path to a BAM file.
* - Requires that BAM to have been indexed prior to running by [[org.hammerlab.bgzf.index.IndexBlocks]] and
* [[org.hammerlab.bam.index.IndexRecords]].
*
* @param sparkBam if set, run the [[org.hammerlab.bam.check.eager.Checker]] on the input BAM file. If both [[sparkBam]] and
* [[hadoopBam]] are set, they are compared to each other; if only one is set, then an
* [[IndexedRecordPositions.Args.recordsPath indexed-records]] file is assumed to exist for the BAM, and is
* used as the source of truth against which to compare.
* @param hadoopBam if set, run the [[org.hammerlab.bam.check.seqdoop.Checker]] on the input BAM file. If both [[sparkBam]]
* and [[hadoopBam]] are set, they are compared to each other; if only one is set, then an
* [[IndexedRecordPositions.Args.recordsPath indexed-records]] file is assumed to exist for the BAM, and is
* used as the source of truth against which to compare.
*/
@AppName("Check all uncompressed positions in a BAM file for record-boundary-identification errors")
@ProgName("… org.hammerlab.bam.check.Main")
case class Opts(
@R blocks: Blocks.Args,
@R records: IndexedRecordPositions.Args,
@R logging: LogArgs,
@R printLimit: PrintLimitArgs,
@R partitioning: PostPartitionArgs,
@R findReadArgs: FindReadArgs,
@O("s")
@M("Run the spark-bam checker; if both or neither of -s and -u are set, then they are both run, and the results compared. If only one is set, its results are compared against a \"ground truth\" file generated by the index-records command")
sparkBam: Boolean = false,
@O("upstream") @O("u")
@M("Run the hadoop-bam checker; if both or neither of -s and -u are set, then they are both run, and the results compared. If only one is set, its results are compared against a \"ground truth\" file generated by the index-records command")
hadoopBam: Boolean = false
)
val main = Main(makeApp)
def makeApp(args: Args) =
new CheckerApp(args, Registrar)
with CallPartition {
val calls =
(args.sparkBam, args.hadoopBam) match {
case (true, false) ⇒
vsIndexed[Boolean, eager.Checker]
case (false, true) ⇒
vsIndexed[Boolean, seqdoop.Checker]
case _ ⇒
Blocks()
.mapPartitions {
callPartition[
eager.Checker,
Boolean,
seqdoop.Checker
]
}
}
apply(
calls,
args.partitioning.resultsPerPartition
)
}
import org.hammerlab.kryo
case class Registrar() extends kryo.spark.Registrar(
CallPartition,
CheckerApp
)
}
|
using System;
using System.Windows;
using System.Windows.Interop;
public interface IWindowInteropHelper
{
IntPtr Handle { get; }
bool EnsureHandle();
}
public class WindowInteropHelperWrapper : IWindowInteropHelper
{
private readonly WindowInteropHelper _windowInteropHelper;
public WindowInteropHelperWrapper(WindowInteropHelper windowInteropHelper)
{
_windowInteropHelper = windowInteropHelper;
}
public IntPtr Handle => _windowInteropHelper.Handle;
public bool EnsureHandle()
{
return _windowInteropHelper.EnsureHandle();
}
} |
#!/bin/bash
dashing build Axis
|
//
// EFLaceView.h
// EFLaceView
//
// Created by MacBook Pro ef on 01/08/06.
// Copyright 2006 <NAME>. All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// - Neither the name of Edouard FISCHER nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#import <Cocoa/Cocoa.h>
#import "EFView.h"
@interface EFLaceView : NSView
{
NSObject* _dataObjectsContainer;
NSString* _dataObjectsKeyPath;
NSObject* _selectionIndexesContainer;
NSString* _selectionIndexesKeyPath;
NSArray* _oldDataObjects;
BOOL _isMaking;
NSPoint _startPoint;
NSPoint _endPoint;
NSPoint _rubberStart;
NSPoint _rubberEnd;
BOOL _isRubbing;
id _startHole;
id _endHole;
EFView* _startSubView;
EFView* _endSubView;
id _delegate;
}
#pragma mark -
#pragma mark *** bindings ***
- (void)startObservingDataObjects:(NSArray *)dataObjects;
- (void)stopObservingDataObjects:(NSArray *)dataObjects;
#pragma mark -
#pragma mark *** setters and accessors
- (id)delegate;
- (void)setDelegate:(id)newDelegate;
- (NSMutableArray *)laces;
- (NSArray *)dataObjects;
- (NSIndexSet *)selectionIndexes;
- (NSArray *)oldDataObjects;
- (void)setOldDataObjects:(NSArray *)anOldDataObjects;
#pragma mark -
#pragma mark *** geometry ***
- (BOOL)isStartHole:(NSPoint)aPoint;
- (BOOL)isEndHole:(NSPoint)aPoint;
- (void)drawLinkFrom:(NSPoint)startPoint to:(NSPoint)endPoint color:(NSColor *)insideColor;
- (void)deselectViews;
- (void)selectView:(EFView *)aView;
- (void)selectView:(EFView *)aView state:(BOOL)aBool;
- (NSArray*)selectedSubViews;
- (void) connectHole:(id)startHole toHole:(id)endHole;
@end
@interface NSObject (EFLaceViewDataObject)
+ (NSArray *)keysForNonBoundsProperties;
@end
@interface NSObject (EFLaceViewDelegateMethod)
- (BOOL)EFLaceView:(EFLaceView*)aView shouldSelectView:(EFView *)aView state:(BOOL)aBool;
- (BOOL)EFLaceView:(EFLaceView*)aView shouldSelectLace:(NSDictionary*)aLace;
- (BOOL)EFLaceView:(EFLaceView*)aView shouldConnectHole:(id)startHole toHole:(id)endHole;
- (BOOL)EFLaceView:(EFLaceView*)aView shouldDrawView:(EFView *)aView;
@end |
#!/bin/bash
#
# Copyright (C) 2016 The CyanogenMod Project
# Copyright (C) 2017 The LineageOS Project
#
# 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.
#
set -e
DEVICE_COMMON=msm8937-common
VENDOR=xiaomi
INITIAL_COPYRIGHT_YEAR=2018
# Load extract_utils and do some sanity checks
MY_DIR="${BASH_SOURCE%/*}"
if [[ ! -d "$MY_DIR" ]]; then MY_DIR="$PWD"; fi
CM_ROOT="$MY_DIR"/../../..
HELPER="$CM_ROOT"/vendor/cm/build/tools/extract_utils.sh
if [ ! -f "$HELPER" ]; then
echo "Unable to find helper script at $HELPER"
exit 1
fi
. "$HELPER"
# Initialize the helper for common
setup_vendor "$DEVICE_COMMON" "$VENDOR" "$CM_ROOT" true
# Copyright headers and guards
write_headers "land santoni"
# The standard common blobs
write_makefiles "$MY_DIR"/proprietary-files-qc.txt
# We are done!
write_footers
if [ -s "$MY_DIR"/../$DEVICE/proprietary-files.txt ]; then
# Reinitialize the helper for device
INITIAL_COPYRIGHT_YEAR="$DEVICE_BRINGUP_YEAR"
setup_vendor "$DEVICE" "$VENDOR" "$CM_ROOT" false
# Copyright headers and guards
write_headers
# The standard device blobs
write_makefiles "$MY_DIR"/../$DEVICE/proprietary-files.txt
# We are done!
write_footers
fi
|
AUTHOR='@xer0dayz'
VULN_NAME='Telerik File Upload Web UI'
URI='/Telerik.Web.UI.WebResource.axd?type=rau'
METHOD='GET'
MATCH="RadAsyncUpload\ handler\ is\ registered\ succesfully"
SEVERITY='P2 - HIGH'
CURL_OPTS="--user-agent '' -s -L --insecure"
SECONDARY_COMMANDS=''
GREP_OPTIONS='-i' |
/*
* Copyright (c) 2018 https://www.reactivedesignpatterns.com/
*
* Copyright (c) 2018 https://rdp.reactiveplatform.xyz/
*
*/
package chapter03;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
// 代码清单3-8
public class UsingMapFunction {
public static void main(String[] args) {
// #snip
final List<Integer> numbers = Arrays.asList(1, 2, 3);
final List<Integer> numbersPlusOne =
numbers.stream().map(number -> number + 1).collect(Collectors.toList());
// #snip
System.out.println(numbersPlusOne.toString());
}
}
|
#!/bin/bash
set -e
./build.sh
bin_file=twemproxy
if [[ ! -z "$1" && "$1" == "abtest" ]]; then
bin_file=twemproxy-abtest
fi
output_dir=../twemproxy_bin/bin
if [[ -d $output_dir && -w $output_dir ]]; then
cp -rvp ./src/nutcracker $output_dir/$bin_file
echo "cp bin finished"
else
echo "$output_dir not exists or access denied"
fi
|
import React from 'react';
class WebcamCaptureButton extends React.Component {
constructor() {
super();
this.onClick = this.onClick.bind(this);
}
onClick(e) {
if (this.props.onClick) {
this.props.onClick(e);
}
}
render() {
return (
<React.Fragment>
<style jsx>
{`
button {
position: absolute;
bottom: 30px;
left: 50%;
transform: translate(-50%, 0px);
background-color: rgba(255, 255, 255, 0.25);
border-radius: 4px;
border: none;
color: rgba(0, 0, 0, 0.5);
font-size: 32px;
font-weight: bold;
outline: none;
padding: 30px 35px;
box-shadow: 0px 10px 20px 0px rgba(0,0,0,0.5);
cursor: pointer;
transition:
box-shadow 200ms cubic-bezier(0.68, -0.55, 0.27, 1.55),
transform 200ms cubic-bezier(0.68, -0.55, 0.27, 1.55);
}
button:active {
box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.5);
transform: translate(-50%, 10px);
}
`}
</style>
<button
className='capture-button'
onClick={this.onClick}
>
{this.props.children}
</button>
</React.Fragment>
);
}
}
export default WebcamCaptureButton;
|
<reponame>Changliu52/UnicornTeensyDrone
#ifndef LPS331_h
#define LPS331_h
#include <Arduino.h> // for byte data type
// SA0 states
#define LPS331_SA0_LOW 0
#define LPS331_SA0_HIGH 1
#define LPS331_SA0_AUTO 2
// register addresses
// Note: Some of the register names in the datasheet are inconsistent
// between Table 14 in section 6 and the register descriptions in
// section 7. Where they differ, the names from section 7 have been
// used here.
#define LPS331_REF_P_XL 0x08
#define LPS331_REF_P_L 0x09
#define LPS331_REF_P_H 0x0A
#define LPS331_WHO_AM_I 0x0F
#define LPS331_RES_CONF 0x10
#define LPS331_CTRL_REG1 0x20
#define LPS331_CTRL_REG2 0x21
#define LPS331_CTRL_REG3 0x22
#define LPS331_INTERRUPT_CFG 0x23
#define LPS331_INT_SOURCE 0x24
#define LPS331_THS_P_L 0x25
#define LPS331_THS_P_H 0x26
#define LPS331_STATUS_REG 0x27
#define LPS331_PRESS_OUT_XL 0x28
#define LPS331_PRESS_OUT_L 0x29
#define LPS331_PRESS_OUT_H 0x2A
#define LPS331_TEMP_OUT_L 0x2B
#define LPS331_TEMP_OUT_H 0x2C
#define LPS331_AMP_CTRL 0x30
#define LPS331_DELTA_PRESS_XL 0x3C
#define LPS331_DELTA_PRESS_L 0x3D
#define LPS331_DELTA_PRESS_H 0x3E
class LPS331
{
public:
LPS331(void);
bool init(byte sa0 = LPS331_SA0_AUTO);
void enableDefault(void);
void writeReg(byte reg, byte value);
byte readReg(byte reg);
float readPressureMillibars(void);
float readPressureInchesHg(void);
long readPressureRaw(void);
float readTemperatureC(void);
float readTemperatureF(void);
int readTemperatureRaw(void);
static float pressureToAltitudeMeters(float pressure_mbar, float altimeter_setting_mbar = 1013.25);
static float pressureToAltitudeFeet(float pressure_inHg, float altimeter_setting_inHg = 29.9213);
private:
byte address;
bool autoDetectAddress(void);
bool testWhoAmI(void);
};
#endif |
def print_dict_keys_alphabetically(mydict):
sorted_keys = sorted(mydict.keys())
for k in sorted_keys:
print(k) |
import numpy as np
from sklearn.linear_model import LinearRegression
# Prepare the data
x = np.arange(1, 100)
y = x * x * x * x * x
# Fit the regression model
model = LinearRegression()
model.fit(x.reshape(-1,1), y)
# Predict the function's value
x_new = np.array([[105]])
prediction = model.predict(x_new)[0]
print("The predicted value of f(105) is:", prediction) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.