text
stringlengths 27
775k
|
|---|
package zio.telemetry.opentracing.example.http
import io.opentracing.propagation.Format.Builtin.{ HTTP_HEADERS => HttpHeadersFormat }
import io.opentracing.propagation.TextMapAdapter
import zio.clock.Clock
import zio.magic._
import zio.telemetry.opentracing.example.http.{ Status => ServiceStatus }
import zio.telemetry.opentracing._
import zio.{ ZIO, ZLayer }
import zhttp.http.{ ->, /, Http, HttpApp, Method, Response, Root }
import zio.json.EncoderOps
import scala.jdk.CollectionConverters._
object BackendApp {
def status(service: ZLayer[Clock, Throwable, OpenTracing]): HttpApp[Clock, Throwable] =
Http.collectM { case request @ Method.GET -> Root / "status" =>
val headers = request.headers.map(h => h.name.toString -> h.value.toString).toMap
ZIO.unit
.spanFrom(HttpHeadersFormat, new TextMapAdapter(headers.asJava), "/status")
.as(Response.jsonString(ServiceStatus.up("backend").toJson))
.inject(service, Clock.live)
}
}
|
# Ruboty::TwitterTrack
Ruboty handler to track the twitter stream with the given words.
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'ruboty-twitter_track'
```
And then execute:
$ bundle
## Usage
```
> @ruboty twitter track by rubygems
@ruboty> Tracked 'rubygems'.
@ruboty> https://twitter.com/haccht/status/123456789
@ruboty> https://twitter.com/haccht/status/123456790
@ruboty> https://twitter.com/haccht/status/123456791
> @ruboty twitter tracking
@ruboty> '100: rubygems'
> @ruboty twitter untrack 100
@ruboty> Untracked '100: rubygems'.
```
## Env
Requires twitter access tokens.
https://apps.twitter.com
```
export CONSUMER_KEY=
export CONSUMER_SECRET=
export ACCESS_TOKEN=
export ACCESS_TOKEN_SECRET=
```
|
# [minshi]
minshi is a simple program, in the spirit of [srandrd](https://github.com/jceb/srandrd),
which listens for monitor connect/disconnect events and prints the event info to
standard output. For a more full-fledged output layout profile manager, see
[kanshi], of which minshi is a minimal, stripped-down version (hence the name).
When an output is connected, minshi will print a single line,
connect <TAB> <output name>
and when an output is disconnected, minshi will print
disconnect <TAB> <output name>
minshi can be used on any Wayland compositor which implements the wlr-output-management protocol.
## Building
Dependencies:
* wayland-client
* scdoc (optional, for man pages)
```sh
meson build
ninja -C build
```
## Usage
```sh
minshi | handler-program
```
where `handler-program` is any executable program or script that will handle
monitor events. If you would like multiple things to happen on connect or
disconnect, you can bundle that functionality into a single handler, or
you can also run multiple instances of minshi.
## License
MIT
[kanshi]: https://wayland.emersion.fr/kanshi/
[srandrd]: https://github.com/jceb/srandrd/
|
# TileEntity
Tile 这个单词的本意是“瓷砖”或“瓦砖”。实际上这里它和 Block 是一个意思。所以它是一个给方块用的概念。
实际上 Mojang 很早(大约 1.8 的时候)就给它改名“Block Entity”了。
出于统一术语的考虑,本教程仍然主要使用“TileEntity”这个称呼,但仍会在特定情况下使用“BlockEntity”或它的中文译名“方块实体”。三种称呼在本教程中指代的是同一概念。
## 为什么要有 TileEntity?
TileEntity 是一种和[实体](../chapter-08/index.md)类似,可以存储一个 NBT 标签的特殊对象。
这意味着,借助 TileEntity,你可以在一个方块中存储超过 4 bits 的数据。
TileEntity 可以通过[实现 `ITickable` 接口](ticking.md)来获得每秒刷新 20 次的能力。
可以说,绝大部分看上去功能异常强大的方块都是基于 TileEntity 的。
## 起点:声明该 Block 持有 TileEntity
```java
public final class MyLavaFurnace extends Block {
public MyLavaFurnace() {
super(Material.ROCK, MapColor.LIGHT_BLUE);
}
@Override
public boolean hasTileEntity(IBlockState state) {
return true;
}
@Override
public TileEntity createTileEntity(World world, IBlockState state) {
return new MyLavaFurnaceEntity();
}
}
public final class MyLavaFurnaceEntity extends TileEntity {
// 暂时什么都没有
}
```
## TileEntity 的注册
TileEntity 虽然需要注册,但它并不走 Forge 的注册表系统,反映在下面两点上:
- `TileEntity` 本身并不是享元对象,也因此不实现 `IForgeRegistryEntry<TileEntity>`。
- `TileEntity` 的注册通过 `GameRegistry.registerTileEntity` 方法完成。
一个比较常见的做法是在注册方块的时候一并注册 TileEntity。
```java
@SubscribeEvent
public static void onBlockRegistration(RegistryEvent.Register<Block> event) {
event.getRegistry().register(new MyLavaFurnace().setRegistryName("my_mod", "lava_furnace"));
// 第一个参数是你要注册的 TileEntity 对应的 class 对象。必须 extends TileEntity。
// 第二个参数的要求和方块的注册名一致。
GameRegistry.registerTileEntity(MyLavaFurnaceEntity.class, new ResourceLocation("my_mod", "lava_furnace"));
}
```
## 持有数据
`TileEntity` 最大的用途在于持有超过 4 bit 的数据,它的数据由一个专门的 `NBTTagCompound` 保存。
```java
public final class MyLavaFurnaceEntity extends TileEntity {
private int progress;
private int fuel;
// 注意,虽然 TileEntity 本身是抽象类,但它并没有任何抽象方法。
// 有鉴于 Minecraft 反序列化 TileEntity 的方式,TileEntity 必须要有 public 的
// 零参构造器。这里我们省略构造器不写,即使用隐式声明的默认构造器。
@Override
public void readFromNBT(NBTTagCompound tag) {
// 从 NBT 标签中读数据,以反序列化 TileEntity
// 一定要调用 super.readFromNBT
super.readFromNBT(tag);
this.progress = tag.getInteger("Progress");
this.fuel = tag.getInteger("Fuel");
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound tag) {
// 向 NBT 标签中写数据,以序列化 TileEntity
// 在返回前务必写入必须的数据
// 一定要调用 super.writeToNBT(tag)
tag.setInteger("Progress", this.progress);
tag.setInteger("Fuel", this.fuel);
return super.writeToNBT(tag);
}
}
```
## 我们还需要再深入些
现在我们稍微改造一些 `MyLavaFurnace`,使之可以通过右击的方式接受熔岩作为燃料:
```java
public final class MyLavaFurnace extends Block {
public MyLavaFurnace() {
super(Material.ROCK, MapColor.LIGHT_BLUE);
}
@Override
public boolean hasTileEntity(IBlockState state) {
return true;
}
@Override
public TileEntity createTileEntity(World world, IBlockState state) {
return new MyLavaFurnaceEntity();
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) {
TileEntity tile = world.getTileEntity(pos);
if (tile instanceof MyLavaFurnaceEntity && !world.isRemote) {
player.setHeldItem(hand, ((MyLavaFurnaceEntity)tile).tryAcceptFuel(player.getHeldItem(hand)));
player.sendStatusMessage(new TextComponentString("Fuel: " + ((MyLavaFurnaceEntity) tile).getFuel()), true);
return true;
}
return false;
}
}
```
```java
public final class MyLavaFurnaceEntity extends TileEntity {
private int progress;
private int fuel;
/**
* @param fuel 玩家当前手持的物品(见 MyLavaFurnace.onBlockActivated)
* @return 尝试消耗燃料后的剩余物品,有可能仍然是未经修改的 fuel 实例
*/
public ItemStack tryAcceptFuel(ItemStack fuel) {
if (fuel.getItem() == Items.LAVA_BUCKET) {
this.fuel += 1000;
return new ItemStack(Items.BUCKET);
} else {
return fuel;
}
}
public int getFuel() {
return this.fuel;
}
@Override
public void readFromNBT(NBTTagCompound tag) {
super.readFromNBT(tag);
this.progress = tag.getInteger("Progress");
this.fuel = tag.getInteger("Fuel");
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound tag) {
tag.setInteger("Progress", this.progress);
tag.setInteger("Fuel", this.fuel);
return super.writeToNBT(tag);
}
}
```
|
package phone
import (
"github.com/ecletus/admin"
"github.com/ecletus-pkg/admin"
"github.com/ecletus/db"
"github.com/ecletus/plug"
)
type Plugin struct {
plug.EventDispatcher
db.DBNames
admin_plugin.AdminNames
}
func (p *Plugin) OnRegister() {
admin_plugin.Events(p).InitResources(func(e *admin_plugin.AdminEvent) {
e.Admin.AddResource(&Phone{}, &admin.Config{Setup: PrepareResource, Invisible:true})
})
db.Events(p).DBOnMigrate(func(e *db.DBEvent) error {
return e.AutoMigrate(&Phone{}).Error
})
}
|
#include <fstream>
#include <vector>
#include <iostream>
#include <string.h>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 20005;
const int maxlg = 20;
int n, m, s, father[maxn], level[maxn], ancestor[maxlg][maxn], dp[maxlg][maxn];
vector <pair<int, int> > g[maxn];
vector <pair<int, pair<int, int> > > edges;
inline int find(int x) {
if(father[x] != x)
father[x] = find(father[x]);
return father[x];
}
inline int query(int x, int y) {
if(level[x] < level[y])
swap(x, y);
int log1, log2;
for(log1 = 1 ; (1 << log1) < level[x] ; ++ log1);
for(log2 = 1 ; (1 << log2) < level[y] ; ++ log2);
int ans = 0x3f3f3f3f;
for(int k = log1 ; k >= 0 ; -- k)
if(level[x] - (1 << k) >= level[y]) {
ans = min(ans, dp[k][x]);
x = ancestor[k][x];
}
if(x == y)
return ans;
for(int k = log2 ; k >= 0 ; -- k) {
if(ancestor[k][x] != ancestor[k][y]) {
ans = min(ans, dp[k][x]);
ans = min(ans, dp[k][y]);
x = ancestor[k][x];
y = ancestor[k][y];
}
}
ans = min(ans, dp[0][x]);
ans = min(ans, dp[0][y]);
return ans;
}
inline void dfs(int node) {
level[node] = level[ancestor[0][node]] + 1;
for(vector <pair<int, int> > :: iterator it = g[node].begin() ; it != g[node].end() ; ++ it)
if(it->first != ancestor[0][node]) {
ancestor[0][it->first] = node;
dp[0][it->first] = it->second;
dfs(it->first);
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("uri1476.in", "r", stdin);
freopen("uri1476.out", "w", stdout);
#endif
while(cin >> n >> m >> s) {
for(int i = 1 ; i <= m ; ++ i) {
int x, y, z;
cin >> x >> y >> z;
edges.push_back(make_pair(z, make_pair(x, y)));
}
sort(edges.begin(), edges.end(), greater<pair<int, pair<int, int> > >());
for(int i = 1 ; i <= n ; ++ i) {
vector <pair<int, int> >().swap(g[i]);
father[i] = i;
}
memset(dp, 0, sizeof(dp));
memset(ancestor, 0, sizeof(ancestor));
memset(level, 0, sizeof(level));
for(vector <pair<int, pair<int, int> > > :: iterator it = edges.begin() ; it != edges.end() ; ++ it) {
int tx = find(it->second.first);
int ty = find(it->second.second);
if(tx == ty)
continue;
father[tx] = ty;
g[it->second.first].push_back(make_pair(it->second.second, it->first));
g[it->second.second].push_back(make_pair(it->second.first, it->first));
}
dfs(1);
for(int k = 1 ; (1 << k) <= n ; ++ k)
for(int i = 1 ; i <= n ; ++ i) {
ancestor[k][i] = ancestor[k - 1][ancestor[k - 1][i]];
dp[k][i] = min(dp[k - 1][i], dp[k - 1][ancestor[k - 1][i]]);
}
for(int i = 1 ; i <= s ; ++ i) {
int x, y;
cin >> x >> y;
cout << query(x, y) << '\n';
}
vector<pair<int, pair<int, int> > > ().swap(edges);
}
}
|
package composablearchitecture
fun <E> Iterable<E>.update(index: Int, elem: E) =
mapIndexed { i, existing -> if (i == index) elem else existing }
|
package ca.kieve.yomiyou
import ca.kieve.yomiyou.copydown.CopyDown
import ca.kieve.yomiyou.copydown.Options
import ca.kieve.yomiyou.copydown.style.CodeBlockStyle
import ca.kieve.yomiyou.copydown.style.HeadingStyle
import ca.kieve.yomiyou.copydown.style.LinkReferenceStyle
import ca.kieve.yomiyou.copydown.style.LinkStyle
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import java.lang.IllegalStateException
import java.util.stream.Stream
class CopyDownTest {
companion object {
private fun getFileContents(path: String): String {
return CopyDownTest::class.java.getResource(path)?.readText() ?: ""
}
@JvmStatic
fun testCases(): Stream<Arguments> {
val jsonFile = getFileContents("/copydown/tests.json")
val mapper = jacksonObjectMapper()
val testCases: List<CopyDownTestCase> = mapper.readValue(jsonFile)
val DEBUG = listOf(testCases.get(51))
return testCases.stream().map { test ->
Arguments.of(test.name, test)
}
}
private fun hasProperty(node: JsonNode, key: String, value: String): Boolean {
if (!node.has(key)) {
return false
}
return node.get(key).textValue() == value
}
fun buildOptions(testCase: CopyDownTestCase): Options {
var result = Options()
val optionsJson = testCase.options ?: return result
if (hasProperty(optionsJson, "headingStyle", "atx")) {
result = result.copy(
headingStyle = HeadingStyle.ATX
)
}
if (optionsJson.has("hr")) {
result = result.copy(
hr = optionsJson.get("hr").textValue()
)
}
if (optionsJson.has("br")) {
result = result.copy(
br = optionsJson.get("br").textValue()
)
}
if (hasProperty(optionsJson, "linkStyle", "referenced")) {
result = result.copy(
linkStyle = LinkStyle.REFERENCED
)
if (optionsJson.has("linkReferenceStyle")) {
val linkReferenceStyle = optionsJson.get("linkReferenceStyle").textValue()
result = when (linkReferenceStyle) {
"collapsed" -> {
result.copy(
linkReferenceStyle = LinkReferenceStyle.COLLAPSED
)
}
"shortcut" -> {
result.copy(
linkReferenceStyle = LinkReferenceStyle.SHORTCUT
)
}
else -> {
throw IllegalStateException(
"This linkReferenceStyle is wrong: $linkReferenceStyle")
}
}
}
}
if (hasProperty(optionsJson, "codeBlockStyle", "fenced")) {
result = result.copy(
codeBlockStyle = CodeBlockStyle.FENCED
)
if (optionsJson.has("fence")) {
result = result.copy(
fence = optionsJson.get("fence").textValue()
)
}
}
if (optionsJson.has("bulletListMarker")) {
result = result.copy(
bulletListMarker = optionsJson.get("bulletListMarker").textValue()
)
}
return result
}
}
@ParameterizedTest
@MethodSource("testCases")
fun mainTest(name: String, testCase: CopyDownTestCase) {
val copyDown = CopyDown(buildOptions(testCase))
val markdown = copyDown.convert(testCase.input)
assertEquals(testCase.output, markdown)
}
@Test
fun convertRealWebsiteTest() {
val html = getFileContents("/copydown/gastronomia_y_cia_1.html")
val expected = getFileContents("/copydown/gastronomia_result.md")
val converted = CopyDown().convert(html)
assertEquals(expected, converted + "\n")
}
}
|
# frozen_string_literal: true
require 'spec_helper'
module Uphold
describe Client do
it 'takes a token on initialization' do
token = 'x'
client = Client.new(token: token)
expect(client.bearer_token).to eq token
end
it 'gets the token from the ENV if none is provided' do
token = 'x'
with_modified_env UPHOLD_AUTH_TOKEN: token do
client = Client.new
expect(client.bearer_token).to eq token
end
end
it 'uses the production api by default' do
expect(Uphold.api_base).to eq Uphold::Options::API_BASE
end
it 'uses the sandbox api when asked to' do
Uphold.sandbox = true
expect(Uphold.api_base).to eq Uphold::Options::SANDBOX_API_BASE
Uphold.sandbox = false
end
end
end
|
<?php
Route::group(['middleware' => 'web', 'namespace' => 'Modules\Frontend\Http\Controllers'], function () {
Route::get('/', 'FrontendController@index');
//
// Route::get('/rolunk', 'FrontendController@aboutUs');
//
// Route::get('/kapcsolat', 'FrontendController@contact');
Route::get('/rendeles/{id}/{quantity}', 'FrontendController@orderForm');
Route::post('/rendeles-veglegesites', 'FrontendController@order');
// Route::post('/rendeles-veglegesites-ajax', 'FrontendController@orderAjax');
// Route::get('getProduct/{id}/{type}', 'FrontendController@getProductById');
});
|
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/style.css" />
<meta charset="utf-8">
<title>Presentation of my self in the course software development for the web!</title>
<link rel="icon" href="favicon.ico">
</head>
<body id="bg">
<div style="text-align: center;">
<header>
</header>
<?php require __DIR__ . "../view/header.php" ?>
<article>
<h1 style="text-align: center;">My report page in the course software development for the web</h1>
<p style="text-align: center;"><img src="img/me.jpg" width="250" alt="Me on an image"></p>
<p>My name is Oskar Karström, born and raised in Rinkaby, Skåne, just outside of Kristianstad. I studied to
a
woodworker at Wendesgymnasiet in Kristianstad but started working as a paver instead. I kept working as
a
paver on different companies for almost 8 years. I then realized that I wanted to do something else and
started my studies at Kristianstad univerity. In a few months I will get my bachelor in software
development.</p>
<p>I have always had an interest in computers and computer games. Programming for me started when I created
cheats and bots for games.</p>
<p>My hobbies outside of computers and programming is hiking and hanging out with my friends. I also like
movies
a lot.</p>
<p>Thanks for reading my short presentation!</p>
</article>
<div id="duck" class="duck"></div>
<?php require __DIR__ . "../view/footer.php" ?>
<script type="text/javascript" src="js/duck.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
|
using UnityEngine;
/// <summary>
/// Allows the user to quit the application.
/// </summary>
[CreateAssetMenu]
public class ApplicationManager : ScriptableObject
{
/// <summary>
/// Quits the application. This method only functions when the application
/// is built.
/// </summary>
public void Quit()
{
Application.Quit();
}
}
|
module CommandLine where
import Options.Applicative
data Options
= AST { optFileA :: FilePath
}
| Diff { optFileA :: FilePath
, optFileB :: FilePath
}
astOpts :: Parser Options
astOpts = AST <$> strArgument (metavar "FILE")
diffOpts :: Parser Options
diffOpts =
Diff <$> strArgument (metavar "OLDFILE")
<*> strArgument (metavar "NEWFILE")
parseOptions :: Parser Options
parseOptions = subparser
( command "ast" (info astOpts ( progDesc "Parses and displays an AST"))
<> command "diff" (info diffOpts (progDesc "Runs Diff on targets"))
) <|> diffOpts
cmdOptions :: ParserInfo Options
cmdOptions = info (parseOptions <**> helper)
( fullDesc
<> progDesc "Runs hdiff with specified command, 'diff' is the default command"
)
|
/*
* tbounce1d.c: controlled animation using two threads
*
* note: one thread handles animation, other thread handles keyboard input
*
*/
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <curses.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
// shared variables both threads use. These need a mutex
#define MESSAGE "hello"
#define BLANK " "
#define LEN strlen(MESSAGE)
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int row;
int col;
int dir;
int delay;
void * moving_msg(void *);
int main(void) {
int ndelay; // new delay
int c; // user input
pthread_t msg_thread;
initscr();
crmode();
noecho();
clear();
pthread_mutex_lock(&lock);
row = 10;
col = 0;
dir = 1;
delay = 200;
move(row, col);
pthread_mutex_unlock(&lock);
addstr(MESSAGE);
refresh();
if (pthread_create(&msg_thread, NULL, moving_msg, (void*)MESSAGE) != 0) {
fprintf(stderr, "error creating thread");
endwin();
exit(0);
}
while (1) {
ndelay = 0;
c = getch();
if (c == 'Q') break;
if (c == ' ') {
pthread_mutex_lock(&lock);
dir = -dir;
pthread_mutex_unlock(&lock);
}
if (c == 'f' && delay > 2){
pthread_mutex_lock(&lock);
ndelay = delay/2;
pthread_mutex_unlock(&lock);
}
if (c == 's') {
pthread_mutex_lock(&lock);
ndelay = delay * 2;
pthread_mutex_unlock(&lock);
}
if (ndelay > 0){
pthread_mutex_lock(&lock);
delay = ndelay;
pthread_mutex_unlock(&lock);
}
}
pthread_cancel(msg_thread);
endwin();
}
void * moving_msg(void * m) {
char * msg = (char *)m;
while (1) {
usleep(delay * 1000);
pthread_mutex_lock(&lock);
move(row, col);
addstr(BLANK);
col += dir;
move(row, col);
pthread_mutex_unlock(&lock);
addstr(msg);
refresh();
if (col <= 0 && dir==-1) {
pthread_mutex_lock(&lock);
dir = 1;
pthread_mutex_unlock(&lock);
}
else if (col + (int)LEN >= COLS && dir==1) {
pthread_mutex_lock(&lock);
dir = -1;
pthread_mutex_unlock(&lock);
}
}
}
|
# Changelog
- [Changelog](#changelog)
- [Description](#description)
- [2021.12.13 - Little Fixes](#20211213---little-fixes)
- [2021.12.12 - Statusbar](#20211212---statusbar)
- [Statusbar fixes](#statusbar-fixes)
- [2021.12.10 - Checkboxes](#20211210---checkboxes)
## Description
I did not start a Changelog up until now, so please excuse the missing updates before `1.8.0`.
## 2021.12.13 - Little Fixes
- Fix Task List Jumpiness - [#48](https://github.com/nikbrunner/obsidian-deep-work-theme/issues/48)
- Remove checkbox animation - [#50](https://github.com/nikbrunner/obsidian-deep-work-theme/issues/50)
- Made unchecked checkbox color white
- Changed font family in statusbar to monospace-font
## 2021.12.12 - Statusbar

Restyled the status-bar
- Placed absolute center-bottom center
- Takes only the width it needs
- Takes no space from the sides
Related issue: [#25](https://github.com/nikbrunner/obsidian-deep-work-theme/issues/25)
### Statusbar fixes
- Fixes [#43](https://github.com/nikbrunner/obsidian-deep-work-theme/issues/43)
- Removed bottom border
## 2021.12.10 - Checkboxes

- Inspired by GitHub Design
- Clean and minimalistic
- Rounded edges
- A little animation to have a little fun crossing things off
Related issue: [#23](https://github.com/nikbrunner/obsidian-deep-work-theme/issues/23)
|
import 'caching_filespan.dart';
abstract class AstNode {
CachingFileSpan get span;
}
|
package com.kuding.web;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
public interface CurrentRequetBodyResolver extends RequestBodyAdvice {
default String getRequestBody() {
return "";
}
void remove();
}
|
use crate::Result;
use crate::cargo::Cargo;
use crate::meta::Meta;
use failure::ResultExt;
use log::info;
use std::fs;
use std::process::Command;
pub(crate) fn build(cargo: &Cargo, meta: &Meta, targets: &[impl AsRef<str>]) -> Result<()> {
for package in meta.packages() {
let lib_name = format!("lib{}.a", package.lib_name());
let mut inputs = vec![];
for target in targets {
let target = target.as_ref();
info!("Building {:?} for {:?}", package.name(), target);
cargo.build_lib(package.name(), target).with_context(|e| {
format!("Failed to build {:?} for {:?}: {}", package.name(), target, e)
})?;
let mut input = meta.target_dir().to_owned();
input.push(target);
input.push(cargo.profile());
input.push(&lib_name);
inputs.push(input);
}
let mut output = meta.target_dir().to_owned();
output.push("universal");
output.push(cargo.profile());
fs::create_dir_all(&output).with_context(|e| {
format!("Creating output directory \"{}\" failed: {}", output.display(), e)
})?;
output.push(&lib_name);
let mut cmd = Command::new("lipo");
cmd.arg("-create").arg("-output").arg(output);
cmd.args(inputs);
info!("Creating universal library for {}", package.name());
crate::exec::run(cmd)?;
}
Ok(())
}
|
import { Console } from '@omnia/fx';
import Component from 'vue-class-component';
import { Prop, Emit } from 'vue-property-decorator';
import * as tsx from 'vue-tsx-support';
import { JourneyInstance, Blade, BladeSizes } from '@omnia/fx/ux';
import { $outputname$Destinations } from '../$outputname$';
export interface HomeBladeProps {
journey: () => JourneyInstance;
}
export interface HomeBladeEvents {
}
export interface HomeBladeScopedSlots {
}
@Component
export default class HomeBlade extends tsx.Component<
HomeBladeProps,
HomeBladeEvents,
HomeBladeScopedSlots
> {
@Prop() journey: () => JourneyInstance;
public mounted() {
}
public render(h) {
return <v-layout width="100%">
<v-card width="100%">
<v-toolbar card prominent>
<v-toolbar-title >$outputname$</v-toolbar-title>
<v-spacer></v-spacer>
<v-btn icon onClick={() => { this.journey().travelTo($outputname$Destinations.create); }}>
<v-icon>add</v-icon>
</v-btn>
</v-toolbar>
<v-divider></v-divider>
<v-card-text>
Put some content here
</v-card-text>
</v-card>
</v-layout>
}
}
|
/*
return kendall tau ties-correction value
FORMAT: ps = kendtaupairsign(m, d);
Input fields:
m matrix
d dim
Output fields:
ps sign of all pairs
Note: the order in which pairs are made is (1;2), (1;3), ..., (1;n),
(2;3), ... (n-1;n)
% Version: v0.9a
% Build: 11102110
% Date: May-17 2010, 10:48 AM EST
% Author: Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://neuroelf.net/
Copyright (c) 2010, Jochen Weber
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 Columbia University 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 HOLDERS 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.
*/
#include "mex.h"
#include "isinfnan.h"
#define OPEN_SIGN_LOOP(DTYPE, PTR1, PTR2) \
PTR1 = (const DTYPE *) mxGetData(*prhs); \
for (c1 = 0; c1 < nepre; ++c1) { \
for (c2 = c1, tc2 = c1; c2 < ne; c2 += inc, tc2 += tinc) { \
PTR2 = &PTR1[c2]; \
otg = &odbl[tc2]; \
for (i1 = 0; i1 < len; i1 += nepre) { \
for (i2 = i1 + nepre; i2 < len; i2 += nepre) {
#define OPEN_SIGN_LOOP_FL(DTYPE, PTR1, PTR2) \
OPEN_SIGN_LOOP(DTYPE, PTR1, PTR2) \
dv = ((double) PTR2[i2]) - ((double) PTR2[i1]); \
IF_IS_NAN(dv) \
dv = 0.0; \
else if (dv < 0.0) \
dv = -1.0; \
else if (dv > 0.0) \
dv = 1.0; \
#define OPEN_SIGN_LOOP_INT(DTYPE, PTR1, PTR2) \
OPEN_SIGN_LOOP(DTYPE, PTR1, PTR2) \
dv = ((double) PTR2[i2]) - ((double) PTR2[i1]); \
if (dv < 0.0) \
dv = -1.0; \
else if (dv > 0.0) \
dv = 1.0;
#define CLOSE_SIGN_LOOP \
*otg = dv; \
otg = &otg[nepre]; \
} \
} \
} \
} \
break;
#define SIGN_LOOP_FL(DTYPE, PTR1, PTR2) \
OPEN_SIGN_LOOP_FL(DTYPE, PTR1, PTR2) \
CLOSE_SIGN_LOOP
#define SIGN_LOOP_INT(DTYPE, PTR1, PTR2) \
OPEN_SIGN_LOOP_INT(DTYPE, PTR1, PTR2) \
CLOSE_SIGN_LOOP
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
const int *dim;
int odim[64];
const double *dbl, *idbl;
const float *sng, *isng;
const signed char *si8, *isi8;
const unsigned char *ui8, *iui8;
const signed short *si16, *isi16;
const unsigned short *ui16, *iui16;
const signed int *si32, *isi32;
const unsigned int *ui32, *iui32;
int td, cid, nd, ne, len, nepre, inc, tinc, c1, c2, tc2, i1, i2;
double *odbl, *otg;
double dv;
VARS_FOR_ISINFNAN
if (nrhs != 2 || nlhs != 1)
mexErrMsgTxt("Bad number of input/output arguments.");
INIT_INF_NAN_BAD_VAL()
if ((mxGetClassID(prhs[1]) != mxDOUBLE_CLASS) ||
(mxGetNumberOfElements(prhs[1]) != 1) ||
(!mxIsNumeric(*prhs)))
mexErrMsgTxt("Invalid dim argument dims/class.");
dv = *((const double *) mxGetPr(prhs[1]));
IF_IS_BAD_VAL(dv) {
mexErrMsgTxt("Bad dim argument.");
}
if ((dv < 1) ||
(dv > mxGetNumberOfDimensions(*prhs)))
mexErrMsgTxt("Bad dim argument.");
td = ((int) dv) - 1;
cid = mxGetClassID(*prhs);
nd = mxGetNumberOfDimensions(*prhs);
ne = mxGetNumberOfElements(*prhs);
dim = mxGetDimensions(*prhs);
len = dim[td];
nepre = inc = tinc = 1;
c2 = (int) (0.5 * ((double) len) * (((double) len) - 1.0));
for (c1 = 0; c1 <= nd; ++c1) {
odim[c1] = dim[c1];
if (c1 < td)
nepre *= dim[c1];
else if (c1 == td) {
odim[c1] = c2;
inc = nepre * dim[c1];
tinc = nepre * c2;
}
}
len *= nepre;
*plhs = mxCreateNumericArray(nd, odim, mxDOUBLE_CLASS, mxREAL);
/* return early if no ties possible */
if (c2 < 1)
return;
/* get output pointer */
odbl = (double *) mxGetPr(*plhs);
/* switch over class */
switch (cid) {
case mxDOUBLE_CLASS: SIGN_LOOP_FL(double, idbl, dbl)
case mxSINGLE_CLASS: SIGN_LOOP_FL(float, isng, sng)
case mxINT8_CLASS: SIGN_LOOP_INT(signed char, isi8, si8)
case mxUINT8_CLASS: SIGN_LOOP_INT(unsigned char, iui8, ui8)
case mxINT16_CLASS: SIGN_LOOP_INT(signed short, isi16, si16)
case mxUINT16_CLASS: SIGN_LOOP_INT(unsigned short, iui16, ui16)
case mxINT32_CLASS: SIGN_LOOP_INT(signed int, isi32, si32)
case mxUINT32_CLASS: SIGN_LOOP_INT(unsigned int, iui32, ui32)
default:
mexErrMsgTxt("Invalid input class.");
}
}
|
CREATE TABLE globalchat(id SERIAL PRIMARY KEY,
username VARCHAR NOT NULL,
message VARCHAR(100));
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _fs = require('fs');
var _fs2 = _interopRequireDefault(_fs);
var _os = require('os');
var _os2 = _interopRequireDefault(_os);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = [{
type: 'input',
name: 'clientData',
message: 'Client data directory',
default: function () {
if (process.platform === 'win32') {
return 'C:/Program Files (x86)/World of Warcraft/Data';
}
return '/Applications/World of Warcraft/Data';
},
validate: function (value) {
var done = this.async();
_fs2.default.lstat(value, function (err, stats) {
if (err) {
done('Invalid path');
} else if (stats.isDirectory()) {
done(true);
} else {
done('Please provide path to a directory');
}
});
}
}, {
type: 'input',
name: 'serverPort',
message: 'Server port',
default: '3000'
}, {
type: 'input',
name: 'clusterWorkerCount',
message: 'Number of cluster workers',
default: Math.ceil(_os2.default.cpus().length / 2)
}];
module.exports = exports['default'];
|
!*************************************************
! WINDOW
! Calculate the Spectral window-function
! of a timeseries.
!
! Input:
! window [options] [inputfile] [outputfile]
!
! Options:
! -tday Treat times as days (default)
! -tsec Treat times as seconds
! -kplrraw Input file is a Kepler data file (use raw columns)
! -kplrpdc Input file is a Kepler data file (use PDC columns)
! -kplrwg Input file is a Kepler data file (use WG columns)
! -quiet Print nothing to screen
! -version Print program version information
!
! Written by
! Rasmus Handberg
! Department of Physics and Astronomy
! Aarhus University
!*************************************************
program window
use kind_defs
use numinteg
use timeseries
implicit none
real(dbl) :: nuw, dnu, dF
real(dbl) :: nu_min, nu_max, nu
integer :: N, j, Nspec, err
logical :: bolUseWeights
character(200) :: buffer, inputfile = "", outputfile = ""
integer :: TimeType = 1 ! Default time type is days
integer :: inputtype = 0
real(dbl) :: t1, t2, Psum, Pint, omegaw
real(dbl), allocatable :: win(:), fs(:), fc(:)
integer :: nargs, iargc
! Extract parameters from command-line:
nargs = iargc()
do j = 1,nargs
call getarg(j, buffer)
select case (trim(buffer))
case ("-tsec")
TimeType = 0
case ("-tday")
TimeType = 1
case ("-kplrraw")
TimeType = 1
inputtype = 1
case ("-kplrpdc")
TimeType = 1
inputtype = 2
case ("-kplrwg")
TimeType = 1
inputtype = 3
case ("-quiet")
quiet = .true.
case ("-version")
print *, "Current version:"
print *, "$Revision: 119 $"
print *, "$Date: 2016-02-09 09:57:56 +0100 (ti, 09 feb 2016) $"
stop
case default
if (.not. buffer(1:1) == "-" .and. inputfile == "") then
inputfile = trim(buffer)
elseif (.not. buffer(1:1) == "-" .and. outputfile == "") then
outputfile = trim(buffer)
else
print *, "UNKNOWN ARGUMENT: " // trim(buffer)
stop
endif
end select
enddo
if (.not. quiet) then
print *, "--------------------------------"
print *, " WINDOW "
print *, " Calculate window-function "
print *, "--------------------------------"
endif
! If no files were given, ask for input and make output:
if (inputfile == '') then
print *, 'Enter input-file:'
read '(a50)', inputfile
endif
if (outputfile == '') then
j = scan(inputfile, '/', back=.true.)
if (j /= 0) then
outputfile = trim(inputfile(j+1:))
else
outputfile = trim(inputfile)
endif
j = scan(outputfile, '.', back=.true.)
if (j > 1) then
outputfile = trim(outputfile(1:j-1)) // '.window'
else
outputfile = trim(outputfile) // '.window'
endif
endif
! Import data:
if (.not. quiet) then
print *, "Reading data..."
endif
open(50, file=inputfile, status='old', action='read')
! New count:
call CountData(50, N, bolUseWeights, inputtype)
! Allocate the data:
allocate(t(1:N), f(1:N), w(1:N), fs(1:N), fc(1:N), stat=err)
if (err /= 0) stop "Couldn''t allocate memory!"
! Ask to use the statistical weights:
if (bolUseWeights) then
print *, "Do you want to use the statistical weights? (1=yes,0=no)"
read(*, '(i1)') j
if (j == 0) bolUseWeights = .false.
endif
if (.not. quiet) then
if (bolUseWeights) then
print *, "Using weights"
else
print *, "Not using weights"
endif
endif
! Import the data:
call ImportData(50, bolUseWeights, t, f, w, inputtype)
close(50)
! Convert time vector to seconds, based on the selected input:
if (TimeType == 1) then
t = t*86400_dbl
endif
! Print information about series:
call print_info(t)
! Frequencies to calculate the window for:
print *, ""
print *, "Windowfunction Frequency (microHz):"
read *, nuw
print *, "Frequency interval (microHz):"
read *, dnu
print *, "Frequency resolution (microHz):"
read *, dF
print *, ""
! A bit of frequency-calculations:
call cpu_time(t1)
nu_min = nuw - dnu
Nspec = ceiling(dnu/dF)
if (Nspec <= 0 .or. dnu <= 0 .or. nu_min < 0) stop "Wrong frequencies!"
! Allocate space for windowfunction:
allocate(win(1:(2*Nspec+1)), stat=err)
if (err /= 0) stop "Couldn't allocate memory!"
! Calculate fake datasets:
omegaw = pi*nuw*2e-6_dbl
fs(:) = w(:)*sin(omegaw*t(:)) ! Sine-function "dataset"
fc(:) = w(:)*cos(omegaw*t(:)) ! Cosine-function "dataset"
! Write the windowfunction to the outputfile:
if (.not. quiet) then
print *, "--------------------------------"
endif
!$OMP PARALLEL DO DEFAULT(SHARED) PRIVATE(nu,j) SCHEDULE(STATIC)
do j = -Nspec,Nspec
nu = nuw+j*dF
win(Nspec+1+j) = windowfunction(t, w, nuw, nu, fs, fc)
call Progress2(2*Nspec+1)
enddo
!$OMP END PARALLEL DO
! Calculate sum and integral of window:
if (.not. quiet) then
Psum = sum(win)
Pint = simpson(dF, win)
print *, ''
print *, "--------------------------------"
print *, 'Psum = ', Psum
print *, 'Pint = ', Pint
endif
! Write spectrum to file:
open(51, file=outputfile, status='replace', action='write')
write(51, '(a)') '#-----------------------------------------'
write(51, '(a)') '# WINDOW'
write(51, '(a)') '# ' // trim(inputfile)
write(51, '(a,f8.2,a)') '# Window frequency: ', nuw, ' microHz'
write(51, '(a,f6.4,a)') '# Resolution: ', dF, ' microHz'
write(51, '(a)') '# Frequencies in microHz, Window (power)'
write(51, '(a)') '#-----------------------------------------'
do j = -Nspec,Nspec
nu = j*dF
write(51, '(f17.10,ES26.16E3)') nu, win(Nspec+1+j)
enddo
close(51)
! Clean the memory:
deallocate(t,f,w,win,fs,fc)
call cpu_time(t2)
call print_time(t2-t1)
end program window
|
use abstutil::prettyprint_usize;
use geom::Duration;
use map_gui::tools::{InputWaypoints, WaypointID};
use map_model::connectivity::WalkingOptions;
use synthpop::{TripEndpoint, TripMode};
use widgetry::mapspace::{ObjectID, World, WorldOutcome};
use widgetry::{
Color, EventCtx, GfxCtx, HorizontalAlignment, Key, Line, Outcome, Panel, State, Text,
Transition, VerticalAlignment, Widget,
};
use crate::isochrone::{Isochrone, MovementOptions, Options};
use crate::App;
pub struct BusExperiment {
panel: Panel,
waypoints: InputWaypoints,
world: World<ID>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum ID {
Waypoint(WaypointID),
// Starting from this waypoint and going to the next
BusRoute(usize),
}
impl ObjectID for ID {}
impl BusExperiment {
pub fn new_state(ctx: &mut EventCtx, app: &App) -> Box<dyn State<App>> {
let mut state = BusExperiment {
panel: Panel::empty(ctx),
waypoints: InputWaypoints::new(app),
world: World::unbounded(),
};
state.recalculate_everything(ctx, app);
Box::new(state)
}
fn recalculate_everything(&mut self, ctx: &mut EventCtx, app: &App) {
let map = &app.map;
let mut world = World::bounded(map.get_bounds());
self.waypoints
.rebuild_world(ctx, &mut world, ID::Waypoint, 1);
for (idx, pair) in self.waypoints.get_waypoints().windows(2).enumerate() {
// TODO Pathfind for buses
if let Some(path) = TripEndpoint::path_req(pair[0], pair[1], TripMode::Drive, map)
.and_then(|req| map.pathfind(req).ok())
{
let duration = path.estimate_duration(map, None);
if let Ok(hitbox) = path.trace_v2(map) {
world
.add(ID::BusRoute(idx))
.hitbox(hitbox)
.zorder(0)
.draw_color(self.waypoints.get_waypoint_color(idx))
.hover_alpha(0.8)
.tooltip(Text::from(Line(format!("Freeflow time is {duration}"))))
.build(ctx);
}
}
}
let stops = self
.waypoints
.get_waypoints()
.into_iter()
.filter_map(|endpt| match endpt {
TripEndpoint::Building(b) => Some(b),
_ => None,
})
.collect::<Vec<_>>();
let isochrone = Isochrone::new(
ctx,
app,
stops,
Options {
movement: MovementOptions::Walking(WalkingOptions::default()),
thresholds: vec![(Duration::minutes(15), Color::grey(0.3).alpha(0.5))],
// TODO The inner colors overlap the outer; this doesn't look right yet
/*thresholds: vec![
(Duration::minutes(5), Color::grey(0.3).alpha(0.5)),
(Duration::minutes(10), Color::grey(0.3).alpha(0.3)),
(Duration::minutes(15), Color::grey(0.3).alpha(0.2)),
],*/
},
);
world.draw_master_batch_built(isochrone.draw);
world.initialize_hover(ctx);
world.rebuilt_during_drag(&self.world);
self.world = world;
self.panel = Panel::new_builder(Widget::col(vec![
map_gui::tools::app_header(ctx, app, "Bus planner"),
ctx.style()
.btn_back("15-minute neighborhoods")
.hotkey(Key::Escape)
.build_def(ctx),
Text::from_multiline(vec![
Line("Within a 15 min walk of all stops:"),
Line(format!(
"Population: {}",
prettyprint_usize(isochrone.population)
)),
Line(format!(
"Shops: {}",
prettyprint_usize(
isochrone
.amenities_reachable
.borrow()
.values()
.map(|x| x.len())
.sum()
)
)),
])
.into_widget(ctx),
self.waypoints.get_panel_widget(ctx),
]))
.aligned(HorizontalAlignment::Left, VerticalAlignment::Top)
.ignore_initial_events()
.build(ctx);
}
}
impl State<App> for BusExperiment {
fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition<App> {
let panel_outcome = self.panel.event(ctx);
if let Outcome::Clicked(ref x) = panel_outcome {
if x == "15-minute neighborhoods" {
return Transition::Pop;
}
}
let world_outcome = self.world.event(ctx);
let world_outcome_for_waypoints = world_outcome
.maybe_map_id(|id| match id {
ID::Waypoint(id) => Some(id),
_ => None,
})
.unwrap_or(WorldOutcome::Nothing);
if self
.waypoints
.event(app, panel_outcome, world_outcome_for_waypoints)
{
self.recalculate_everything(ctx, app);
}
Transition::Keep
}
fn draw(&self, g: &mut GfxCtx, _: &App) {
self.panel.draw(g);
self.world.draw(g);
}
}
|
package shopping.order
import scala.concurrent.Future
import org.slf4j.LoggerFactory
import shopping.order.proto.OrderRequest
import shopping.order.proto.OrderResponse
class ShoppingOrderServiceImpl extends proto.ShoppingOrderService {
private val logger = LoggerFactory.getLogger(getClass)
override def order(in: OrderRequest): Future[OrderResponse] = {
val totalNumberOfItems =
in.items.iterator.map(_.quantity).sum
logger.info("Order {} items from cart {}.", totalNumberOfItems, in.cartId)
Future.successful(OrderResponse(ok = true))
}
}
|
import React, { Component } from 'react';
import md5 from 'crypto-js/md5';
import { Link } from 'react-router-dom';
import Header from '../components/Header';
class Feedback extends Component {
constructor() {
super();
this.state = {
totalQuestion: 0,
score: 0,
};
this.handleAssertions = this.handleAssertions.bind(this);
}
componentDidMount() {
this.handleAssertions();
}
handleAssertions() {
const finalResult = JSON.parse(localStorage.getItem('state'));
const { assertions, score, gravatarEmail, name } = finalResult.player;
const emailConvertido = md5(gravatarEmail);
const requestGravatar = `https://www.gravatar.com/avatar/${emailConvertido}`;
const ranking = JSON.parse(localStorage.getItem('ranking'));
if (!ranking) {
localStorage.setItem('ranking',
JSON.stringify([{ name, score, picture: requestGravatar }]));
} else {
const newRanking = [...ranking, { name, score, picture: requestGravatar }];
localStorage.setItem('ranking',
JSON.stringify(newRanking));
}
this.setState({
totalQuestion: assertions,
score,
});
}
render() {
const { totalQuestion, score } = this.state;
const TRES = 3;
return (
<div>
<Header />
<h2 data-testid="feedback-text">
{ totalQuestion >= TRES ? 'Mandou bem!' : 'Podia ser melhor...' }
</h2>
<p data-testid="feedback-total-score">{ score }</p>
<p data-testid="feedback-total-question">{ totalQuestion }</p>
<Link to="/" data-testid="btn-play-again">Jogar novamente</Link>
<Link to="/ranking" data-testid="btn-ranking">Ver Ranking</Link>
</div>
);
}
}
export default Feedback;
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Horology;
using Brigadier.NET;
using Brigadier.NET.Builder;
using Brigadier.NET.Tree;
[MarkdownExporterAttribute.GitHub]
public class ParsingBenchmarks {
private CommandDispatcher<object> subject;
[GlobalSetup]
public void setup() {
subject = new CommandDispatcher<object>();
subject.Register(r =>
r.Literal("a")
.Then(
r.Literal("1")
.Then(r.Literal("i").Executes(c => 0))
.Then(r.Literal("ii").Executes(c => 0))
)
.Then(
r.Literal("2")
.Then(r.Literal("i").Executes(c => 0))
.Then(r.Literal("ii").Executes(c => 0))
)
);
subject.Register(r => r.Literal("b").Then(r.Literal("1").Executes(c => 0)));
subject.Register(r => r.Literal("c").Executes(c => 0));
subject.Register(r => r.Literal("d").Requires(s => false).Executes(c => 0));
subject.Register(r =>
r.Literal("e")
.Executes(c => 0)
.Then(
r.Literal("1")
.Executes(c => 0)
.Then(r.Literal("i").Executes(c => 0))
.Then(r.Literal("ii").Executes(c => 0))
)
);
subject.Register(r =>
r.Literal("f")
.Then(
r.Literal("1")
.Then(r.Literal("i").Executes(c => 0))
.Then(r.Literal("ii").Executes(c => 0).Requires(s => false))
)
.Then(
r.Literal("2")
.Then(r.Literal("i").Executes(c => 0).Requires(s => false))
.Then(r.Literal("ii").Executes(c => 0))
)
);
subject.Register(r =>
r.Literal("g")
.Executes(c => 0)
.Then(r.Literal("1").Then(r.Literal("i").Executes(c => 0)))
);
LiteralCommandNode<Object> h = subject.Register(r =>
r.Literal("h")
.Executes(c => 0)
.Then(r.Literal("1").Then(r.Literal("i").Executes(c => 0)))
.Then(r.Literal("2").Then(r.Literal("i").Then(r.Literal("ii").Executes(c => 0))))
.Then(r.Literal("3").Executes(c => 0))
);
subject.Register(r =>
r.Literal("i")
.Executes(c => 0)
.Then(r.Literal("1").Executes(c => 0))
.Then(r.Literal("2").Executes(c => 0))
);
subject.Register(r =>
r.Literal("j")
.Redirect(subject.GetRoot())
);
subject.Register(r =>
r.Literal("k")
.Redirect(h)
);
}
[Benchmark]
[MemoryDiagnoser]
public void parse_a1i() {
subject.Parse("a 1 i", new Object());
}
[Benchmark]
[MemoryDiagnoser]
public void parse_c() {
subject.Parse("c", new Object());
}
[Benchmark]
[MemoryDiagnoser]
public void parse_k1i() {
subject.Parse("k 1 i", new Object());
}
[Benchmark]
[MemoryDiagnoser]
public void parse_() {
subject.Parse("c", new Object());
}
}
|
package objektwerks.poolmate
import objektwerks.poolmate.Resources._
import objektwerks.poolmate.model.Model
import objektwerks.poolmate.repository.Repository
import objektwerks.poolmate.view.View
import scalafx.application.JFXApp
object App extends JFXApp {
val repository = Repository("repository.conf")
val model = Model(repository)
val view = View(conf, model)
stage = new JFXApp.PrimaryStage {
scene = view.sceneGraph
title = conf.getString("title")
icons.add(appImage)
}
sys.addShutdownHook {
repository.close()
}
}
|
| Command | Mean [s] | Min [s] | Max [s] | Relative |
|:---|---:|---:|---:|---:|
| `3.0.5` | 17.594 ± 0.151 | 17.361 | 17.801 | 1.46 ± 0.02 |
| `3.1.1` | 29.878 ± 0.387 | 29.215 | 30.325 | 2.47 ± 0.04 |
| `3.2.5` | 30.348 ± 0.260 | 29.876 | 30.670 | 2.51 ± 0.03 |
| `3.3.9` | 30.274 ± 0.255 | 29.900 | 30.679 | 2.51 ± 0.03 |
| `3.5.4` | 24.517 ± 0.247 | 24.164 | 24.854 | 2.03 ± 0.02 |
| `3.6.3` | 24.630 ± 0.115 | 24.448 | 24.776 | 2.04 ± 0.02 |
| `3.8.1` | 24.630 ± 0.171 | 24.426 | 24.911 | 2.04 ± 0.02 |
| `3.8.2` | 22.022 ± 0.133 | 21.872 | 22.267 | 1.82 ± 0.02 |
| `3.8.3` | 12.140 ± 0.143 | 11.991 | 12.388 | 1.00 ± 0.01 |
| `3.8.4` | 12.080 ± 0.073 | 11.917 | 12.165 | 1.00 |
| `4.0.0-alpha-1` | 13.075 ± 0.231 | 12.753 | 13.546 | 1.08 ± 0.02 |
|
"""
core APIs of the data models
"""
from collections import defaultdict
import numpy as np
import pandas as pd
class FeatureSet:
"""
currently, just a named list of feature names
"""
def __init__(self, feature_names=None, name=None):
self.feature_names = feature_names
self.name = name
def __getitem__(self, key):
return self.feature_names[key]
class DataSource:
def __init__(self, dataframe):
self.data = dataframe
@property
def entities(self):
return self.data.index
@property
def features(self):
return self.data.columns
def __getitem__(self, key):
return DataSource(self.data[key])
@property
def loc(self):
return self.data.loc
class DataStore:
def __init__(self):
self.data_store = {}
def register_features(self, features):
# check for valid features
print('ingested features: {}'.format(len(features)))
def register_entities(self, entities):
# check for valid entities
print('ingested entities: {}'.format(len(entities)))
def register_data(self, name, data):
if name in self.data_store:
raise '{} is already registered'.format(name)
print('ingested data source name: {}'.format(name))
self.register_features(data.features)
self.register_entities(data.entities)
self.data_store[name] = data
def ingest(self, name, dataframe, entity_idx=None):
_data = dataframe
if entity_idx:
# todo: do not change the original dataframe ???
_data.set_index(entity_idx, inplace=True)
self.register_data(name=name,
data=DataSource(_data))
def __getitem__(self, key):
return self.data_store[key]
class FeatureStore:
def __init__(self, data_source, features=None, name='unnamed'):
if features is None:
features = data_source.features
self.features = features
self.data = data_source[features]
self.name = name
# TODO: add timestamp for feature context sorting
@property
def entities(self):
return self.data.entities
def __getitem__(self, key):
return self.data[key]
@property
def loc(self):
return self.data.loc
def __repr__(self):
return '{} [feature store]'.format(self.name)
class FeatureContext:
"""
store and manage the feature context in a first-in-last-out manner
"""
def __init__(self):
# each feature is mapped to a list of feature stores
# in a first-in-last-out manner
self.feature_context = defaultdict(list)
def append(self, feature_store, features=None):
if features is None:
features = feature_store.features
for feature in features:
self.feature_context[feature].append(feature_store)
def pop(self, feature_store, features=None):
if features is None:
features = feature_store.features
for feature in features:
if self.feature_context[feature][-1] is feature_store:
self.feature_context[feature].pop()
def __getitem__(self, feature):
feature_stores = self.feature_context[feature]
if len(feature_stores) == 0:
return None
else:
return self.feature_context[feature][-1]
@property
def features(self):
return [feature_name for feature_name, feature_stores in self.feature_context.items()
if len(feature_stores) > 0]
class SampleStore:
def __init__(self, samples=None):
self.samples = set()
if samples is not None:
self.add_samples(samples)
self.feature_context = FeatureContext()
def add_samples(self, samples):
self.samples.update(samples)
def filter(self, condition):
filter_samples = condition[condition].index
self.samples.difference_update(filter_samples)
def get_data(self, features=None):
if features is None:
features = self.feature_context.features
collected_stores = defaultdict(list)
for feature in features:
fs = self.feature_context[feature]
if fs is not None:
collected_stores[fs].append(feature)
data = [fs.loc[list(self.samples), features] for fs, features in collected_stores.items()]
return pd.concat(data, axis=1)
def add_features(self, feature_store, features=None):
self.feature_context.append(feature_store=feature_store,
features=features)
def remove_features(self, feature_store, features=None):
self.feature_context.pop(feature_store=feature_store,
features=features)
def __getitem__(self, feature):
feature_store = self.feature_context[feature]
if feature_store is None:
raise 'No such feature for in this sample store: {}'.format(feature)
return feature_store.loc[list(self.samples), feature]
class DataSet:
def __init__(self, X, y=None):
self.samples = X.index
self.features = X.columns
self.X = X
self.y = None
if y is not None:
self.set_y(y)
def set_y(self, y):
assert y.index.equals(self.samples)
self.y = y.loc[self.samples]
def get_data(self, with_y=True):
if with_y:
if self.y is None:
y = pd.Series(np.nan, index=self.samples)
else:
y = self.y
return pd.concat([self.X, y], axis=1)
else:
return self.X
class FeatureManager:
def __init__(self, feature_store, sample_store, features=None, verbose=1):
self.feature_store = feature_store
self.sample_store = sample_store
self.verbose = verbose
if features is None:
self.features = feature_store.features
def __enter__(self):
self.sample_store.add_features(self.feature_store, features=self.features)
if self.verbose > 0:
print('>>> {} features are added with {}'.format(len(self.features), repr(self.feature_store)))
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.sample_store.remove_features(self.feature_store, features=self.features)
if self.verbose > 0:
print('<<< {} features are removed with {}'.format(len(self.features), repr(self.feature_store)))
|
<?php
namespace SQRT\QueryBuilder;
abstract class Condition
{
protected $values;
protected $not;
function __toString()
{
return $this->asSQL();
}
abstract public function asSQL();
abstract public function asStatement($prefix = null);
abstract public function getBindedValues($prefix = null);
public function setValues($values)
{
$this->values = $values;
return $this;
}
public function getValues()
{
return $this->values;
}
/** Инверсия логического выражения NOT ... */
public function setNot($not = true)
{
$this->not = (bool)$not;
return $this;
}
/** Инверсия логического выражения NOT ... */
public function getNot()
{
return (bool)$this->not;
}
}
|
<?php
namespace App\Http\Controllers;
use App\Models\Company;
use Illuminate\Http\Request;
use RealRashid\SweetAlert\Facades\Alert;
class CompanyController extends Controller
{
public function All()
{
$Companys = Company::all();
return view('Dashboard.Company.All')->with(['Companys' => $Companys]);
}
public function Add()
{
return view('Dashboard.Company.Add');
}
public function Create(Request $request)
{
$request->validate([
'Name' => 'required|string|unique:companies'
]);
Company::create([
'Name' => $request->Name
]);
Alert::toast('کارخانه با موفقیت ساخته شد' , 'success');
return redirect()->route('Dashboard.Company.All');
}
public function Edit($id)
{
$Company = Company::find($id);
return view('Dashboard.Company.Edit')->with(['Company' => $Company]);
}
public function Update($id , Request $request)
{
$request->validate([
'Name' => 'required|string|unique:companies'
]);
$Company = Company::find($id);
$Company->update($request->all());
Alert::toast('کارخانه با موفقیت بروزرسانی شد' , 'success');
return redirect()->route('Dashboard.Company.All');
}
public function Delete($id)
{
Company::find($id)->delete();
Alert::toast('کارخانه با موفقیت حذف شد' , 'success');
return redirect()->back();
}
}
|
## Testing with a proxy
Using a SUSE manager proxy with the testsuite is not mandatory.
If you do not want a proxy, do not define `$PROXY` environment variable
before you run the testsuite. That's all.
If you want a proxy, make this variable point to the machine that will be
the proxy:
```bash
export PROXY=myproxy.example.com
```
and then run the testsuite.
### With sumaform
Sumaform can prepare a proxy virtual machine and declare the `$PROXY`
variable on the controller (in `/root/.bashrc`).
For details on how to declare a proxy in your `main.tf` file,
refer to the "Proxies" chapter of the
[advanced instructions](https://github.com/moio/sumaform/blob/master/README_ADVANCED.md)
for sumaform.
|
using bundle-adjustment-primer
using Test
@testset "bundle-adjustment-primer.jl" begin
# Write your tests here.
end
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <folly/Synchronized.h>
#include <condition_variable>
#include <mutex>
#include "watchman/InMemoryView.h"
#include "watchman/root/Root.h"
#include "watchman/watcher/WatcherRegistry.h"
#include "watchman/watcher/fsevents.h"
#include "watchman/watcher/kqueue.h"
#include "watchman/watchman_cmd.h"
#include "watchman/watchman_file.h"
#if HAVE_FSEVENTS && defined(HAVE_KQUEUE)
namespace watchman {
class PendingEventsCond {
public:
/**
* Notify that some events are pending.
*
* Return true if this thread should stop, false otherwise.
*/
bool notifyOneOrStop() {
auto lock = stop_.lock();
if (lock->shouldStop) {
return true;
}
lock->hasPending = true;
cond_.notify_one();
return false;
}
/**
* Whether this thread should stop.
*/
bool shouldStop() {
return stop_.lock()->shouldStop;
}
/**
* Wait for a change from a nested watcher. Return true if some events are
* pending.
*/
bool waitAndClear(int timeoutms) {
auto lock = stop_.lock();
cond_.wait_until(
lock.as_lock(),
std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutms),
[&] { return lock->hasPending || lock->shouldStop; });
return std::exchange(lock->hasPending, false);
}
/**
* Notify all the waiting threads to stop.
*/
void stopAll() {
auto lock = stop_.lock();
lock->shouldStop = true;
cond_.notify_all();
}
private:
struct Inner {
bool shouldStop = false;
bool hasPending = false;
};
folly::Synchronized<Inner, std::mutex> stop_;
std::condition_variable cond_;
};
/**
* Watcher that uses both kqueue and fsevents to watch a hierarchy.
*
* The kqueue watches are used on the root directory and all the files at the
* root, while the fsevents one is used on the subdirectories.
*/
class KQueueAndFSEventsWatcher : public Watcher {
public:
explicit KQueueAndFSEventsWatcher(
const w_string& root_path,
const Configuration& config);
bool start(const std::shared_ptr<Root>& root) override;
folly::SemiFuture<folly::Unit> flushPendingEvents() override;
std::unique_ptr<DirHandle> startWatchDir(
const std::shared_ptr<Root>& root,
struct watchman_dir* dir,
const char* path) override;
bool startWatchFile(struct watchman_file* file) override;
Watcher::ConsumeNotifyRet consumeNotify(
const std::shared_ptr<Root>& root,
PendingChanges& coll) override;
bool waitNotify(int timeoutms) override;
void stopThreads() override;
/**
* Force a recrawl to be injected in the stream. Used in the
* 'debug-kqueue-and-fsevents-recrawl' command.
*/
void injectRecrawl(w_string path);
private:
folly::Synchronized<
std::unordered_map<w_string, std::shared_ptr<FSEventsWatcher>>>
fseventWatchers_;
std::shared_ptr<KQueueWatcher> kqueueWatcher_;
std::shared_ptr<PendingEventsCond> pendingCondition_;
folly::Synchronized<std::optional<w_string>> injectedRecrawl_;
};
KQueueAndFSEventsWatcher::KQueueAndFSEventsWatcher(
const w_string& root_path,
const Configuration& config)
: Watcher("kqueue+fsevents", WATCHER_HAS_SPLIT_WATCH),
kqueueWatcher_(std::make_shared<KQueueWatcher>(root_path, config, false)),
pendingCondition_(std::make_shared<PendingEventsCond>()) {}
namespace {
bool startThread(
const std::shared_ptr<Root>& root,
const std::shared_ptr<Watcher>& watcher,
const std::shared_ptr<PendingEventsCond>& cond) {
std::weak_ptr<Watcher> weakWatcher(watcher);
std::thread thr([weakWatcher, root, cond]() {
while (true) {
auto watcher = weakWatcher.lock();
if (!watcher) {
break;
}
if (watcher->waitNotify(86400)) {
if (cond->notifyOneOrStop()) {
return;
}
} else if (cond->shouldStop()) {
return;
}
}
});
thr.detach();
return true;
}
} // namespace
bool KQueueAndFSEventsWatcher::start(const std::shared_ptr<Root>& root) {
root->cookies.addCookieDir(root->root_path);
return startThread(root, kqueueWatcher_, pendingCondition_);
}
folly::SemiFuture<folly::Unit> KQueueAndFSEventsWatcher::flushPendingEvents() {
// Flush the kqueue watcher outside of the lock, because it may need to
// change the set of watchers.
auto kqueueFlush = kqueueWatcher_->flushPendingEvents();
// But we know KQueueWatcher doesn't implement flushPendingEvents, so to
// avoid having to chain the futures here, just assert.
w_check(
!kqueueFlush.valid(),
"This code needs to be updated to handle KQueueWatcher implementing flushPendingEvents");
auto fseventsWatchers = *fseventWatchers_.rlock();
std::vector<folly::SemiFuture<folly::Unit>> futures;
futures.reserve(fseventsWatchers.size());
for (auto& [name, watcher] : fseventsWatchers) {
auto future = watcher->flushPendingEvents();
if (future.valid()) {
futures.push_back(std::move(future));
}
}
return folly::collect(futures).unit();
}
std::unique_ptr<DirHandle> KQueueAndFSEventsWatcher::startWatchDir(
const std::shared_ptr<Root>& root,
struct watchman_dir* dir,
const char* path) {
if (!dir->parent) {
logf(DBG, "Watching root directory with kqueue\n");
// This is the root, let's watch it with kqueue.
kqueueWatcher_->startWatchDir(root, dir, path);
} else if (dir->parent->getFullPath() == root->root_path) {
auto fullPath = dir->getFullPath();
auto wlock = fseventWatchers_.wlock();
if (wlock->find(fullPath) == wlock->end()) {
logf(
DBG,
"Creating a new FSEventsWatcher for top-level directory {}\n",
dir->name);
root->cookies.addCookieDir(fullPath);
auto [it, _] = wlock->emplace(
fullPath,
std::make_shared<FSEventsWatcher>(
false, root->config, std::optional(fullPath)));
const auto& watcher = it->second;
if (!watcher->start(root)) {
throw std::runtime_error("couldn't start fsEvent");
}
if (!startThread(root, watcher, pendingCondition_)) {
throw std::runtime_error("couldn't start fsEvent");
}
}
}
return openDir(path);
}
bool KQueueAndFSEventsWatcher::startWatchFile(struct watchman_file* file) {
if (file->parent->parent == nullptr) {
// File at the root, watch it with kqueue.
return kqueueWatcher_->startWatchFile(file);
}
// FSEvent by default watches all the files recursively, we don't need to do
// anything.
return true;
}
Watcher::ConsumeNotifyRet KQueueAndFSEventsWatcher::consumeNotify(
const std::shared_ptr<Root>& root,
PendingChanges& coll) {
{
auto guard = injectedRecrawl_.wlock();
if (guard->has_value()) {
const auto& injectedDir = guard->value();
auto now = std::chrono::system_clock::now();
coll.add(
injectedDir,
now,
W_PENDING_VIA_NOTIFY | W_PENDING_RECURSIVE | W_PENDING_IS_DESYNCED);
guard->reset();
}
}
{
auto fseventWatches = fseventWatchers_.wlock();
for (auto& [watchpath, fsevent] : *fseventWatches) {
auto [cancelSelf] = fsevent->consumeNotify(root, coll);
if (cancelSelf) {
fsevent->stopThreads();
root->cookies.removeCookieDir(watchpath);
fseventWatches->erase(watchpath);
continue;
}
}
}
return kqueueWatcher_->consumeNotify(root, coll);
}
bool KQueueAndFSEventsWatcher::waitNotify(int timeoutms) {
return pendingCondition_->waitAndClear(timeoutms);
}
void KQueueAndFSEventsWatcher::stopThreads() {
pendingCondition_->stopAll();
{
auto fseventWatches = fseventWatchers_.rlock();
for (auto& [_, fsevent] : *fseventWatches) {
fsevent->stopThreads();
}
}
kqueueWatcher_->stopThreads();
}
void KQueueAndFSEventsWatcher::injectRecrawl(w_string path) {
*injectedRecrawl_.wlock() = path;
pendingCondition_->notifyOneOrStop();
}
namespace {
std::shared_ptr<InMemoryView> makeKQueueAndFSEventsWatcher(
const w_string& root_path,
const w_string& /*fstype*/,
const Configuration& config) {
if (config.getBool("prefer_split_fsevents_watcher", false)) {
return std::make_shared<InMemoryView>(
root_path,
config,
std::make_shared<KQueueAndFSEventsWatcher>(root_path, config));
} else {
throw std::runtime_error(
"Not using the kqueue+fsevents watcher as the \"prefer_split_fsevents_watcher\" config isn't set");
}
}
} // namespace
static WatcherRegistry reg("kqueue+fsevents", makeKQueueAndFSEventsWatcher, 5);
namespace {
std::shared_ptr<KQueueAndFSEventsWatcher> watcherFromRoot(
const std::shared_ptr<Root>& root) {
auto view = std::dynamic_pointer_cast<watchman::InMemoryView>(root->view());
if (!view) {
return nullptr;
}
return std::dynamic_pointer_cast<KQueueAndFSEventsWatcher>(
view->getWatcher());
}
static void cmd_debug_kqueue_and_fsevents_recrawl(
struct watchman_client* client,
const json_ref& args) {
/* resolve the root */
if (json_array_size(args) != 3) {
send_error_response(
client,
"wrong number of arguments for 'debug-kqueue-and-fsevents-recrawl'");
return;
}
auto root = resolveRoot(client, args);
auto watcher = watcherFromRoot(root);
if (!watcher) {
send_error_response(
client, "root is not using the kqueue+fsevents watcher");
return;
}
/* Get the path that the recrawl should be triggered on */
const auto& json_path = args.at(2);
auto path = json_string_value(json_path);
if (!path) {
send_error_response(
client,
"invalid value for argument 2, expected a string naming the path to trigger a recrawl on");
}
watcher->injectRecrawl(path);
auto resp = make_response();
send_and_dispose_response(client, std::move(resp));
}
} // namespace
W_CMD_REG(
"debug-kqueue-and-fsevents-recrawl",
cmd_debug_kqueue_and_fsevents_recrawl,
CMD_DAEMON,
w_cmd_realpath_root)
} // namespace watchman
#endif
|
package otoroshi.ssl
import java.io._
import java.lang.reflect.Field
import java.net.Socket
import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets
import java.nio.charset.StandardCharsets.US_ASCII
import java.security._
import java.security.cert._
import java.security.spec.{KeySpec, PKCS8EncodedKeySpec}
import java.util.concurrent.{Executors, TimeUnit}
import java.util.concurrent.atomic.{AtomicBoolean, AtomicLong, AtomicReference}
import java.util.regex.Pattern.CASE_INSENSITIVE
import java.util.regex.{Matcher, Pattern}
import java.util.{Base64, Date}
import otoroshi.actions.ApiAction
import akka.http.scaladsl.util.FastFuture
import akka.stream.{Materializer, TLSClientAuth}
import akka.stream.scaladsl.{Flow, Sink, Source}
import akka.util.ByteString
import com.google.common.hash.Hashing
import com.typesafe.sslconfig.ssl.SSLConfigSettings
import otoroshi.env.Env
import otoroshi.events.{Alerts, CertExpiredAlert, CertRenewalAlert}
import otoroshi.gateway.Errors
import javax.crypto.Cipher.DECRYPT_MODE
import javax.crypto.spec.PBEKeySpec
import javax.crypto.{Cipher, EncryptedPrivateKeyInfo, SecretKey, SecretKeyFactory}
import javax.net.ssl._
import otoroshi.models._
import org.apache.commons.codec.binary.Hex
import org.apache.commons.codec.digest.DigestUtils
import org.bouncycastle.asn1.x509.{ExtendedKeyUsage, KeyPurposeId}
import org.bouncycastle.openssl.jcajce.{JcaPEMKeyConverter, JcePEMDecryptorProviderBuilder}
import org.bouncycastle.openssl.{PEMEncryptedKeyPair, PEMKeyPair, PEMParser}
import org.bouncycastle.pkcs.PKCS10CertificationRequest
import org.bouncycastle.util.io.pem.PemReader
import org.joda.time.{DateTime, Interval}
import otoroshi.ssl.pki.models.{GenCertResponse, GenCsrQuery, GenKeyPairQuery}
import otoroshi.utils.letsencrypt.LetsEncryptHelper
import otoroshi.utils.{RegexPool, TypedMap}
import play.api.libs.json._
import play.api.libs.ws.WSProxyServer
import play.api.mvc._
import play.api.{Configuration, Logger}
import play.core.ApplicationProvider
import play.server.api.SSLEngineProvider
import redis.RedisClientMasterSlaves
import otoroshi.security.IdGenerator
import otoroshi.storage.{BasicStore, RedisLike, RedisLikeStore}
import otoroshi.utils.http.DN
import otoroshi.utils.metrics.{FakeHasMetrics, HasMetrics}
import otoroshi.utils.metrics.FakeHasMetrics
import otoroshi.utils.syntax.implicits._
import scala.collection.concurrent.TrieMap
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.util.{Failure, Success, Try}
import scala.concurrent.duration._
import otoroshi.utils.syntax.implicits._
import java.util
import java.util.function.BiFunction
/**
* git over http works with otoroshi
* ssh and other => http tunneling like https://github.com/mathieuancelin/node-httptunnel or https://github.com/larsbrinkhoff/httptunnel or https://github.com/luizluca/bridge
*/
sealed trait ClientAuth {
def name: String
def toAkkaClientAuth: TLSClientAuth
}
object ClientAuth {
case object None extends ClientAuth {
def name: String = "None"
def toAkkaClientAuth: TLSClientAuth = TLSClientAuth.None
}
case object Want extends ClientAuth {
def name: String = "Want"
def toAkkaClientAuth: TLSClientAuth = TLSClientAuth.Want
}
case object Need extends ClientAuth {
def name: String = "Need"
def toAkkaClientAuth: TLSClientAuth = TLSClientAuth.Need
}
def values: Seq[ClientAuth] = Seq(None, Want, Need)
def apply(name: String): Option[ClientAuth] = {
name.toLowerCase match {
case "None" => Some(None)
case "none" => Some(None)
case "Want" => Some(Want)
case "want" => Some(Want)
case "Need" => Some(Need)
case "need" => Some(Need)
case _ => scala.None
}
}
}
case class OCSPCertProjection(
revoked: Boolean,
valid: Boolean,
expired: Boolean,
revocationReason: String,
from: Date,
to: Date
)
case class Cert(
id: String,
name: String,
description: String,
chain: String,
privateKey: String,
caRef: Option[String],
domain: String = "--",
selfSigned: Boolean = false,
ca: Boolean = false,
valid: Boolean = false,
exposed: Boolean = false,
revoked: Boolean,
autoRenew: Boolean = false,
letsEncrypt: Boolean = false,
client: Boolean = false,
keypair: Boolean = false,
subject: String = "--",
from: DateTime = DateTime.now(),
to: DateTime = DateTime.now(),
sans: Seq[String] = Seq.empty,
entityMetadata: Map[String, String] = Map.empty,
tags: Seq[String] = Seq.empty,
password: Option[String] = None,
location: otoroshi.models.EntityLocation = otoroshi.models.EntityLocation()
) extends otoroshi.models.EntityLocationSupport {
def json: JsValue = toJson
def internalId: String = id
def theDescription: String = description
def theMetadata: Map[String, String] = entityMetadata
def theName: String = name
def theTags: Seq[String] = tags
lazy val cleanChain: String = {
val matcher: Matcher = DynamicSSLEngineProvider.CERT_PATTERN.matcher(chain)
var certificates = Seq.empty[String]
var start = 0
while ({ matcher.find(start) }) {
certificates = certificates :+ matcher.group(1)
start = matcher.end
}
certificates
.map(c => s"${PemHeaders.BeginCertificate}\n$c${PemHeaders.EndCertificate}")
.flatMap(_.split("\\n"))
.filterNot(_.trim.isEmpty)
.mkString("\n")
}
lazy val certType = {
if (client) "client"
else if (ca) "ca"
else if (letsEncrypt) "letsEncrypt"
else if (keypair) "keypair"
else if (selfSigned) "selfSigned"
else "certificate"
}
lazy val notRevoked: Boolean = !revoked
lazy val cacheKey: String = s"$id###$contentHash"
lazy val contentHash: String = Hashing.sha256().hashString(s"$chain:$privateKey", StandardCharsets.UTF_8).toString
lazy val allDomains: Seq[String] = {
val enriched = enrich()
(Seq(enriched.domain) ++ enriched.sans).filter(_.trim.nonEmpty).filterNot(_ == "--").distinct
}
def signature: Option[String] = this.metadata.map(v => (v \ "signature").as[String])
def serialNumber: Option[String] = this.metadata.map(v => (v \ "serialNumber").as[String])
def serialNumberLng: Option[java.math.BigInteger] =
this.metadata.map(v => (v \ "serialNumberLng").as[java.math.BigInteger])
def matchesDomain(dom: String): Boolean = allDomains.exists(d => RegexPool.apply(d).matches(dom))
def renew(
_duration: Option[FiniteDuration] = None
)(implicit env: Env, ec: ExecutionContext, mat: Materializer): Future[Cert] = {
import SSLImplicits._
val duration = _duration.getOrElse(FiniteDuration(365, TimeUnit.DAYS))
this match {
case original if original.letsEncrypt => LetsEncryptHelper.renew(this)
case _ => {
env.datastores.certificatesDataStore.findAll().map { certificates =>
val cas = certificates.filter(cert => cert.ca)
caRef.flatMap(ref => cas.find(_.id == ref)) match {
case None if ca =>
val resp = FakeKeyStore
.createCA(subject, duration, Some(cryptoKeyPair), certificate.map(_.getSerialNumber.longValue()))
copy(chain = resp.cert.asPem, privateKey = resp.key.asPem).enrich()
case None if selfSigned =>
val resp = FakeKeyStore.createSelfSignedCertificate(
domain,
duration,
Some(cryptoKeyPair),
certificate.map(_.getSerialNumber.longValue())
)
copy(chain = resp.cert.asPem, privateKey = resp.key.asPem).enrich()
case None if keypair =>
val resp = FakeKeyStore.createSelfSignedCertificate(
domain,
duration,
Some(cryptoKeyPair),
certificate.map(_.getSerialNumber.longValue())
)
copy(chain = resp.cert.asPem, privateKey = resp.key.asPem).enrich()
case None => // should not happens
val resp = FakeKeyStore.createSelfSignedCertificate(
domain,
duration,
Some(cryptoKeyPair),
certificate.map(_.getSerialNumber.longValue())
)
copy(chain = resp.cert.asPem, privateKey = resp.key.asPem).enrich()
case Some(caCert) if ca =>
val resp = FakeKeyStore.createSubCa(
domain,
duration,
Some(cryptoKeyPair),
certificate.map(_.getSerialNumber.longValue()),
caCert.certificate.get,
caCert.certificates.tail,
caCert.cryptoKeyPair
)
copy(chain = resp.cert.asPem + "\n" + caCert.chain, privateKey = resp.key.asPem).enrich()
case Some(caCert) =>
val resp = FakeKeyStore.createCertificateFromCA(
domain,
duration,
Some(cryptoKeyPair),
certificate.map(_.getSerialNumber.longValue()),
caCert.certificate.get,
caCert.certificates.tail,
caCert.cryptoKeyPair
)
copy(chain = resp.cert.asPem + "\n" + caCert.chain, privateKey = resp.key.asPem).enrich()
case _ =>
// println("wait what ???")
val resp = FakeKeyStore.createSelfSignedCertificate(
domain,
duration,
Some(cryptoKeyPair),
certificate.map(_.getSerialNumber.longValue())
)
copy(chain = resp.cert.asPem, privateKey = resp.key.asPem).enrich()
}
}
}
}
}
// def password: Option[String] = None
def save()(implicit ec: ExecutionContext, env: Env) = {
val current = this.enrich()
env.datastores.certificatesDataStore.set(current)
}
lazy val notExpired: Boolean = from.isBefore(org.joda.time.DateTime.now()) && to.isAfter(org.joda.time.DateTime.now())
lazy val expired: Boolean = !notExpired
def enrich() = {
val meta = this.metadata.get
this.copy(
domain = (meta \ "domain").asOpt[String].getOrElse("--"),
selfSigned = (meta \ "selfSigned").asOpt[Boolean].getOrElse(false),
ca = (meta \ "ca").asOpt[Boolean].getOrElse(false),
// client = (meta \ "client").asOpt[Boolean].getOrElse(false),
valid = this.isValid,
subject = (meta \ "subjectDN").as[String],
from = (meta \ "notBefore").asOpt[Long].map(v => new DateTime(v)).getOrElse(DateTime.now()),
to = (meta \ "notAfter").asOpt[Long].map(v => new DateTime(v)).getOrElse(DateTime.now()),
sans = (meta \ "subAltNames").asOpt[Seq[String]].getOrElse(Seq.empty)
)
}
def delete()(implicit ec: ExecutionContext, env: Env) = env.datastores.certificatesDataStore.delete(this)
def exists()(implicit ec: ExecutionContext, env: Env) = env.datastores.certificatesDataStore.exists(this)
def toJson = Cert.toJson(this)
lazy val certificatesRaw: Seq[String] = Try {
cleanChain
.split(PemHeaders.BeginCertificate)
.toSeq
.tail
.map(_.replace(PemHeaders.EndCertificate, "").trim())
.map(c => s"${PemHeaders.BeginCertificate}\n$c\n${PemHeaders.EndCertificate}")
}.toOption.toSeq.flatten
lazy val certificates: Seq[X509Certificate] = certificatesChain.toSeq /*{
val certificateFactory: CertificateFactory = CertificateFactory.getInstance("X.509")
certificatesRaw
.map(
content =>
Try(
certificateFactory
.generateCertificate(new ByteArrayInputStream(DynamicSSLEngineProvider.base64Decode(content)))
.asInstanceOf[X509Certificate]
)
)
.collect {
case Success(cert) => cert
}
}*/
lazy val certificatesChain: Array[X509Certificate] = { //certificates.toArray
Try {
cleanChain
.split(PemHeaders.BeginCertificate)
.toSeq
.map(_.trim)
.filterNot(_.isEmpty)
.map { content =>
content.replace(PemHeaders.BeginCertificate, "").replace(PemHeaders.EndCertificate, "")
}
.map { content =>
val certificateFactory: CertificateFactory = CertificateFactory.getInstance("X.509")
certificateFactory
.generateCertificate(new ByteArrayInputStream(DynamicSSLEngineProvider.base64Decode(content)))
.asInstanceOf[X509Certificate]
}
.toArray
}.getOrElse(Array.empty)
}
lazy val certificate: Option[X509Certificate] = Try {
cleanChain.split(PemHeaders.BeginCertificate).toSeq.tail.headOption.map { cert =>
val content: String = cert.replace(PemHeaders.EndCertificate, "")
val certificateFactory: CertificateFactory = CertificateFactory.getInstance("X.509")
certificateFactory
.generateCertificate(new ByteArrayInputStream(DynamicSSLEngineProvider.base64Decode(content)))
.asInstanceOf[X509Certificate]
}
}.toOption.flatten
lazy val caFromChain: Option[X509Certificate] = Try {
cleanChain.split(PemHeaders.BeginCertificate).toSeq.tail.lastOption.map { cert =>
val content: String = cert.replace(PemHeaders.EndCertificate, "")
val certificateFactory: CertificateFactory = CertificateFactory.getInstance("X.509")
certificateFactory
.generateCertificate(new ByteArrayInputStream(DynamicSSLEngineProvider.base64Decode(content)))
.asInstanceOf[X509Certificate]
}
}.toOption.flatten
lazy val metadata: Option[JsValue] = {
cleanChain.split(PemHeaders.BeginCertificate).toSeq.tail.headOption.map { cert =>
val content: String = cert.replace(PemHeaders.EndCertificate, "")
CertificateData(content)
}
}
lazy val isValid: Boolean = {
Try {
val keyStore: KeyStore = KeyStore.getInstance("JKS")
keyStore.load(null, null)
DynamicSSLEngineProvider.readPrivateKeyUniversal(this.id, this.privateKey, this.password, false).toOption.exists {
key: PrivateKey =>
// val key: PrivateKey = DynamicSSLEngineProvider.readPrivateKey(encodedKeySpec) /*Try(KeyFactory.getInstance("RSA")).map(_.generatePrivate(encodedKeySpec))
// .orElse(Try(KeyFactory.getInstance("EC")).map(_.generatePrivate(encodedKeySpec)))
// .orElse(Try(KeyFactory.getInstance("DSA")).map(_.generatePrivate(encodedKeySpec)))
// .orElse(Try(KeyFactory.getInstance("DiffieHellman")).map(_.generatePrivate(encodedKeySpec)))
// .get*/
val certificateChain: Seq[X509Certificate] =
DynamicSSLEngineProvider.readCertificateChain(this.id, this.cleanChain, false)
if (certificateChain.isEmpty) {
DynamicSSLEngineProvider.logger.error(s"[${this.id}] Certificate file does not contain any certificates :(")
false
} else {
keyStore.setKeyEntry(
this.id,
key,
this.password.getOrElse("").toCharArray,
certificateChain.toArray[java.security.cert.Certificate]
)
true
}
}
} recover { case e =>
DynamicSSLEngineProvider.logger.error(s"Error while checking certificate validity (${name})")
false
} getOrElse false
}
lazy val cryptoKeyPair: KeyPair = {
val privkey = DynamicSSLEngineProvider.readPrivateKeyUniversal(domain, privateKey, password).right.get
//val privkey: PrivateKey = DynamicSSLEngineProvider.readPrivateKey(privkeySpec) /*Try(KeyFactory.getInstance("RSA"))
// .orElse(Try(KeyFactory.getInstance("DSA")))
// .map(_.generatePrivate(privkeySpec))
// .get
val pubkey: PublicKey = certificate.get.getPublicKey
new KeyPair(pubkey, privkey)
}
def toGenCertResponse(implicit env: Env): GenCertResponse = {
val query = GenCsrQuery(
hosts = Seq(domain),
subject = Some(subject)
)
GenCertResponse(
serial = serialNumberLng.get,
cert = certificate.get,
csr = Await
.result(env.pki.genCsr(query, None)(env.otoroshiExecutionContext), 10.seconds)
.right
.get
.csr,
csrQuery = query.some,
key = cryptoKeyPair.getPrivate,
ca = caFromChain.get,
caChain = certificates.tail
)
}
}
object Cert {
import SSLImplicits._
val OtoroshiCaDN = s"CN=Otoroshi Default Root CA Certificate, OU=Otoroshi Certificates, O=Otoroshi"
val OtoroshiCA = "otoroshi-root-ca"
val OtoroshiIntermediateCaDN =
s"CN=Otoroshi Default Intermediate CA Certificate, OU=Otoroshi Certificates, O=Otoroshi"
val OtoroshiIntermediateCA = "otoroshi-intermediate-ca"
val OtoroshiJwtSigningDn = s"CN=Otoroshi Default Jwt Signing Keypair, OU=Otoroshi Certificates, O=Otoroshi"
val OtoroshiJwtSigning = "otoroshi-jwt-signing"
val OtoroshiWildcard = "otoroshi-wildcard"
val OtoroshiClientDn = s"CN=Otoroshi Default Client Certificate, OU=Otoroshi Certificates, O=Otoroshi"
val OtoroshiClient = "otoroshi-client"
lazy val logger = Logger("otoroshi-cert")
def apply(name: String, cert: String, privateKey: String): Cert = {
Cert(
id = IdGenerator.token(32),
name = name,
description = name,
chain = cert,
privateKey = privateKey,
caRef = None,
autoRenew = false,
client = false,
exposed = false,
revoked = false
).enrich()
}
def apply(cert: X509Certificate, keyPair: KeyPair, caRef: Option[String], client: Boolean): Cert = {
val c = Cert(
id = IdGenerator.token(32),
name = "none",
description = "none",
chain = cert.asPem,
privateKey = keyPair.getPrivate.asPem,
caRef = caRef,
autoRenew = false,
client = client,
exposed = false,
revoked = false
).enrich()
c.copy(name = c.domain, description = s"Certificate for ${c.subject}")
}
def apply(cert: X509Certificate, keyPair: KeyPair, ca: Cert, client: Boolean): Cert = {
val c = Cert(
id = IdGenerator.token(32),
name = "none",
description = "none",
chain = cert.asPem + "\n" + ca.chain,
privateKey = keyPair.getPrivate.asPem,
caRef = Some(ca.id),
autoRenew = false,
client = client,
exposed = false,
revoked = false
).enrich()
c.copy(name = c.domain, description = s"Certificate for ${c.subject}")
}
def apply(cert: X509Certificate, keyPair: KeyPair, ca: X509Certificate, client: Boolean): Cert = {
val c = Cert(
id = IdGenerator.token(32),
name = "none",
description = "none",
chain = cert.asPem + "\n" + ca.asPem,
//s"${PemHeaders.BeginCertificate}\n${Base64.getEncoder
//.encodeToString(cert.getEncoded)}\n${PemHeaders.EndCertificate}\n${PemHeaders.BeginCertificate}\n${Base64.getEncoder
//.encodeToString(ca.getEncoded)}\n${PemHeaders.EndCertificate}\n",
privateKey = keyPair.getPrivate.asPem,
// s"${PemHeaders.BeginPrivateKey}\n${Base64.getEncoder.encodeToString(keyPair.getPrivate.getEncoded)}\n${PemHeaders.EndPrivateKey}",
caRef = None,
autoRenew = false,
client = client,
exposed = false,
revoked = false
).enrich()
c.copy(name = c.domain, description = s"Certificate for ${c.subject}")
}
val _fmt: Format[Cert] = new Format[Cert] {
override def writes(cert: Cert): JsValue =
cert.location.jsonWithKey ++ Json.obj(
"id" -> cert.id,
"domain" -> cert.domain,
"name" -> cert.name,
"description" -> cert.description,
"chain" -> cert.chain,
"caRef" -> cert.caRef,
"privateKey" -> cert.privateKey,
"selfSigned" -> cert.selfSigned,
"ca" -> cert.ca,
"valid" -> cert.valid,
"exposed" -> cert.exposed,
"revoked" -> cert.revoked,
"autoRenew" -> cert.autoRenew,
"letsEncrypt" -> cert.letsEncrypt,
"subject" -> cert.subject,
"from" -> cert.from.getMillis,
"to" -> cert.to.getMillis,
"client" -> cert.client,
"keypair" -> cert.keypair,
"sans" -> JsArray(cert.sans.map(JsString.apply)),
"certType" -> cert.certType,
"password" -> cert.password,
"metadata" -> cert.entityMetadata,
"tags" -> JsArray(cert.tags.map(JsString.apply))
)
override def reads(json: JsValue): JsResult[Cert] =
Try {
Cert(
location = otoroshi.models.EntityLocation.readFromKey(json),
id = (json \ "id").as[String],
name = (json \ "name").asOpt[String].orElse((json \ "domain").asOpt[String]).getOrElse("none"),
description = (json \ "description")
.asOpt[String]
.orElse((json \ "domain").asOpt[String].map(v => s"Certificate for $v"))
.getOrElse("none"),
domain = (json \ "domain").as[String],
sans = (json \ "sans").asOpt[Seq[String]].getOrElse(Seq.empty),
chain = (json \ "chain").as[String],
caRef = (json \ "caRef").asOpt[String],
password = (json \ "password").asOpt[String].filter(_.trim.nonEmpty),
privateKey = (json \ "privateKey").asOpt[String].getOrElse(""),
selfSigned = (json \ "selfSigned").asOpt[Boolean].getOrElse(false),
ca = (json \ "ca").asOpt[Boolean].getOrElse(false),
client = (json \ "client").asOpt[Boolean].getOrElse(false),
keypair = (json \ "keypair").asOpt[Boolean].getOrElse(false),
valid = (json \ "valid").asOpt[Boolean].getOrElse(false),
exposed = (json \ "exposed").asOpt[Boolean].getOrElse(false),
revoked = (json \ "revoked").asOpt[Boolean].getOrElse(false),
autoRenew = (json \ "autoRenew").asOpt[Boolean].getOrElse(false),
letsEncrypt = (json \ "letsEncrypt").asOpt[Boolean].getOrElse(false),
subject = (json \ "subject").asOpt[String].getOrElse("--"),
from = (json \ "from").asOpt[Long].map(v => new DateTime(v)).getOrElse(DateTime.now()),
to = (json \ "to").asOpt[Long].map(v => new DateTime(v)).getOrElse(DateTime.now()),
entityMetadata = (json \ "metadata").asOpt[Map[String, String]].getOrElse(Map.empty),
tags = (json \ "tags").asOpt[Seq[String]].getOrElse(Seq.empty[String])
)
} map { case sd =>
JsSuccess(sd)
} recover { case t =>
logger.error("Error while reading Cert", t)
JsError(t.getMessage)
} get
}
def toJson(value: Cert): JsValue = _fmt.writes(value)
def fromJsons(value: JsValue): Cert =
try {
_fmt.reads(value).get
} catch {
case e: Throwable => {
logger.error(s"Try to deserialize ${Json.prettyPrint(value)}")
throw e
}
}
def fromJsonSafe(value: JsValue): JsResult[Cert] = _fmt.reads(value)
def createFromServices()(implicit ec: ExecutionContext, env: Env, mat: Materializer): Future[Unit] = {
env.datastores.certificatesDataStore.findAll().flatMap { certificates =>
env.datastores.serviceDescriptorDataStore.findAll().flatMap { services =>
val certs = certificates.filterNot(_.letsEncrypt)
val letsEncryptServicesHosts = services
.filter(_.issueCert)
.flatMap(s => s.allHosts.map(h => (s, h)))
.filterNot(s => certs.exists(c => RegexPool(c.domain).matches(s._2)))
Source(letsEncryptServicesHosts.toList)
.mapAsync(1) { case (service, host) =>
env.datastores.rawDataStore.get(s"${env.storageRoot}:certs-issuer:local:create:$host").flatMap {
case Some(_) =>
logger.warn(s"Certificate already in creating process: $host")
FastFuture.successful(())
case None => {
env.datastores.rawDataStore
.set(
s"${env.storageRoot}:certs-issuer:local:create:$host",
ByteString("true"),
Some(1.minutes.toMillis)
)
.flatMap { _ =>
val cert = certs.find(c => RegexPool(c.domain).matches(host)).get
if (cert.autoRenew) {
cert.renew()
} else {
FastFuture.successful(cert)
}
}
.andThen { case _ =>
env.datastores.rawDataStore.del(Seq(s"${env.storageRoot}:certs-issuer:local:create:$host"))
}
}
}
}
.map {
case (host, Left(err)) => logger.error(s"Error while creating certificate for $host. $err")
case (host, Right(_)) => logger.info(s"Successfully created certificate for $host")
}
.runWith(Sink.ignore)
.map(_ => ())
}
}
}
}
trait CertificateDataStore extends BasicStore[Cert] {
def nakedTemplate(env: Env): Cert = {
Cert(
id = IdGenerator.namedId("cert", env),
name = "a new certificate",
description = "a new certificate",
chain = "",
privateKey = "",
caRef = None,
revoked = false
)
}
def template(implicit ec: ExecutionContext, env: Env): Future[Cert] = {
env.pki
.genSelfSignedCert(
GenCsrQuery(
hosts = Seq("www.oto.tools"),
subject = Some("C=FR, OU=Foo, O=Bar")
)
)
.map { c =>
c.toOption.get.toCert.copy(
id = IdGenerator.namedId("cert", env),
name = "a new certificate",
description = "a new certificate",
chain = "",
privateKey = ""
)
}
}
def renewCertificates()(implicit ec: ExecutionContext, env: Env, mat: Materializer): Future[Unit] = {
def willBeInvalidSoon(cert: Cert): Boolean = {
val enriched = cert.enrich()
val globalInterval = new Interval(enriched.from, enriched.to)
val nowInterval = new Interval(DateTime.now(), enriched.to)
val percentage: Long = (nowInterval.toDurationMillis * 100) / globalInterval.toDurationMillis
percentage < 20
}
def renewCAs(certificates: Seq[Cert]): Future[Unit] = {
val renewableCas = certificates
.filter(_.notRevoked)
.filter(_.autoRenew)
.filter(cert => cert.ca)
.filter(willBeInvalidSoon)
.filterNot(c =>
c.entityMetadata.get("untilExpiration").contains("true") || c.name.startsWith("[UNTIL EXPIRATION] ")
)
Source(renewableCas.toList)
.mapAsync(1) { case c =>
c.renew()
.flatMap(d =>
c.copy(
id = IdGenerator.token,
name = "[UNTIL EXPIRATION] " + c.name,
entityMetadata = c.entityMetadata ++ Map(
"untilExpiration" -> "true",
"nextCertificate" -> c.id
)
).save()
.map(_ => d)
)
.flatMap(c => c.save().map(_ => c))
}
.map { c =>
Alerts.send(
CertRenewalAlert(
env.snowflakeGenerator.nextIdStr(),
env.env,
c
)
)
}
.runWith(Sink.ignore)
.map(_ => ())
}
def renewNonCaCertificates(certificates: Seq[Cert]): Future[Unit] = {
val renewableCertificates = certificates
.filter(_.notRevoked)
.filter(_.autoRenew)
.filterNot(_.ca)
.filter(willBeInvalidSoon) // TODO: fix
.filterNot(c =>
c.entityMetadata.get("untilExpiration").contains("true") || c.name.startsWith("[UNTIL EXPIRATION] ")
)
Source(renewableCertificates.toList)
.mapAsync(1) { case c =>
c.renew()
.flatMap(d =>
c.copy(
id = IdGenerator.token,
name = "[UNTIL EXPIRATION] " + c.name,
entityMetadata = c.entityMetadata ++ Map(
"untilExpiration" -> "true",
"nextCertificate" -> c.id
)
).save()
.map(_ => d)
)
.flatMap(c => c.save().map(_ => c))
}
.map { c =>
Alerts.send(
CertRenewalAlert(
env.snowflakeGenerator.nextIdStr(),
env.env,
c
)
)
}
.runWith(Sink.ignore)
.map(_ => ())
}
def markExpiredCertsAsExpired(certificates: Seq[Cert]): Future[Unit] = {
val expiredCertificates = certificates
.filter(_.notRevoked)
.filterNot { cert =>
cert.from.isBefore(org.joda.time.DateTime.now()) && cert.to.isAfter(org.joda.time.DateTime.now())
}
Source(expiredCertificates.toList)
.mapAsync(1) {
case c if c.entityMetadata.get("expired").contains("true") || c.name.startsWith("[EXPIRED] ") =>
c.applyOn(d => d.save().map(_ => d))
case c if !(c.entityMetadata.get("expired").contains("true") || c.name.startsWith("[EXPIRED] ")) =>
c.copy(name = "[EXPIRED] " + c.name, entityMetadata = c.entityMetadata ++ Map("expired" -> "true"))
.applyOn(d => d.save().map(_ => d))
}
.map { c =>
Alerts.send(
CertExpiredAlert(
env.snowflakeGenerator.nextIdStr(),
env.env,
c
)
)
}
.runWith(Sink.ignore)
.map(_ => ())
}
for {
certificates <- findAll()
_ <- renewCAs(certificates)
ncertificates <- findAll()
_ <- renewNonCaCertificates(ncertificates)
nncertificates <- findAll()
_ <- markExpiredCertsAsExpired(nncertificates)
} yield ()
}
def readCertOrKey(conf: Configuration, path: String, env: Env): Option[String] = {
conf.getOptionalWithFileSupport[String](path).flatMap { cacert =>
if (
(cacert.contains(PemHeaders.BeginCertificate) && cacert.contains(PemHeaders.EndCertificate)) ||
(cacert.contains(PemHeaders.BeginPrivateKey) && cacert.contains(PemHeaders.EndPrivateKey)) ||
(cacert.contains(PemHeaders.BeginPrivateECKey) && cacert.contains(PemHeaders.EndPrivateECKey)) ||
(cacert.contains(PemHeaders.BeginPrivateRSAKey) && cacert.contains(PemHeaders.EndPrivateRSAKey))
) {
Some(cacert)
} else {
val file = new File(cacert)
if (file.exists()) {
val content = new String(java.nio.file.Files.readAllBytes(file.toPath))
if (
(content.contains(PemHeaders.BeginCertificate) && content.contains(PemHeaders.EndCertificate)) ||
(content.contains(PemHeaders.BeginPrivateKey) && content.contains(PemHeaders.EndPrivateKey)) ||
(content.contains(PemHeaders.BeginPrivateECKey) && content.contains(PemHeaders.EndPrivateECKey)) ||
(content.contains(PemHeaders.BeginPrivateRSAKey) && content.contains(PemHeaders.EndPrivateRSAKey))
) {
Some(content)
} else {
None
}
} else {
None
}
}
}
}
def importOneCert(
conf: Configuration,
caPath: String,
certPath: String,
keyPath: String,
logger: Logger,
id: Option[String] = None
)(implicit
env: Env,
ec: ExecutionContext
): Unit = {
readCertOrKey(conf, caPath, env).foreach { cacert =>
val _cert = Cert(
id = IdGenerator.uuid,
name = "none",
description = "none",
chain = cacert,
privateKey = "",
caRef = None,
ca = true,
client = false,
exposed = false,
revoked = false
).enrich()
val cert = _cert.copy(name = _cert.domain, description = s"Certificate for ${_cert.subject}")
findAll().map { certs =>
val found = certs
.map(_.enrich())
.exists(c =>
(c.signature.isDefined && c.signature == cert.signature) && (c.serialNumber.isDefined && c.serialNumber == cert.serialNumber)
)
if (!found) {
cert.save()(ec, env).andThen {
case Success(e) => logger.info("Successful import of initial cacert !")
case Failure(e) => logger.error("Error while storing initial cacert ...", e)
}
}
}
}
for {
certContent <- readCertOrKey(conf, certPath, env)
keyContent <- readCertOrKey(conf, keyPath, env)
} yield {
val _cert = Cert(
id = IdGenerator.uuid,
name = "none",
description = "none",
chain = certContent,
privateKey = keyContent,
caRef = None,
client = false,
exposed = false,
revoked = false
).enrich()
val cert = _cert.copy(name = _cert.domain, description = s"Certificate for ${_cert.subject}")
findAll().map { certs =>
val found = certs
.map(_.enrich())
.exists(c =>
(c.signature.isDefined && c.signature == cert.signature) && (c.serialNumber.isDefined && c.serialNumber == cert.serialNumber)
)
if (!found) {
cert.save()(ec, env).andThen {
case Success(e) => logger.info("Successful import of initial cert !")
case Failure(e) => logger.error("Error while storing initial cert ...", e)
}
}
}
}
}
def importInitialCerts(logger: Logger)(implicit env: Env, ec: ExecutionContext) = {
importOneCert(
env.configuration,
"otoroshi.ssl.rootCa.ca",
"otoroshi.ssl.rootCa.cert",
"otoroshi.ssl.rootCa.key",
logger,
Some(Cert.OtoroshiCA)
)(env, ec)
importOneCert(
env.configuration,
"otoroshi.ssl.initialCacert",
"otoroshi.ssl.initialCert",
"otoroshi.ssl.initialCertKey",
logger
)(env, ec)
env.configuration
.getOptionalWithFileSupport[Seq[Configuration]]("otoroshi.ssl.initialCerts")
.getOrElse(Seq.empty[Configuration])
.foreach { conf =>
importOneCert(conf, "ca", "cert", "key", logger)(env, ec)
}
}
def hasInitialCerts()(implicit env: Env, ec: ExecutionContext): Boolean = {
val hasInitialCert =
env.configuration.has("otoroshi.ssl.initialCacert") &&
env.configuration.has("otoroshi.ssl.initialCert") &&
env.configuration.has("otoroshi.ssl.initialCertKey")
val hasInitialCerts = env.configuration.has("otoroshi.ssl.initialCerts")
val hasRootCA = env.configuration.has("otoroshi.ssl.rootCa.cert") && env.configuration.has(
"otoroshi.ssl.rootCa.key"
)
hasInitialCert || hasInitialCerts || hasRootCA
}
def autoGenerateCertificateForDomain(
domain: String
)(implicit env: Env, ec: ExecutionContext): Future[Option[Cert]] = {
env.datastores.globalConfigDataStore.latestSafe match {
case None => FastFuture.successful(None)
case Some(config) => {
config.autoCert match {
case AutoCert(true, Some(ref), allowed, notAllowed, replyNicely) => {
env.datastores.certificatesDataStore.findById(ref).flatMap {
case None =>
DynamicSSLEngineProvider.logger.error(s"CA cert not found to generate certificate for $domain")
FastFuture.successful(None)
case Some(cert) => {
!notAllowed.exists(p => otoroshi.utils.RegexPool.apply(p).matches(domain)) && allowed
.exists(p => RegexPool.apply(p).matches(domain)) match {
case true => {
env.datastores.certificatesDataStore.findAll().flatMap { certificates =>
certificates.find(c => (c.sans :+ c.domain).contains(domain)) match {
case Some(_) => FastFuture.successful(None)
case _ => {
env.pki
.genCert(
GenCsrQuery(
hosts = Seq(domain),
subject = Some(
s"CN=$domain,OU=Auto Generated Certificates, OU=Otoroshi Certificates, O=Otoroshi"
)
),
cert.certificate.get,
cert.certificates.tail,
cert.cryptoKeyPair.getPrivate
)
.flatMap {
case Left(err) =>
DynamicSSLEngineProvider.logger
.error(s"error while generating certificate for $domain: $err")
FastFuture.successful(None)
case Right(resp) => {
val cert = resp.toCert
.copy(
name = s"Certificate for $domain",
description = s"Auto Generated Certificate for $domain",
autoRenew = true
)
cert.save().map { _ =>
Some(cert)
}
}
}
}
}
}
}
case false if replyNicely => {
env.pki
.genCert(
GenCsrQuery(
hosts = Seq(domain),
subject = Some(SSLSessionJavaHelper.BadDN)
),
cert.certificate.get,
cert.certificates.tail,
cert.cryptoKeyPair.getPrivate
)
.flatMap {
case Left(err) =>
DynamicSSLEngineProvider.logger.error(s"error while generating certificate for $domain: $err")
FastFuture.successful(None)
case Right(resp) => {
val cert = resp.toCert
.copy(
name = s"Certificate for $domain",
description = s"Auto Generated Certificate for $domain",
autoRenew = true
)
FastFuture.successful(Some(cert))
}
}
}
case _ => FastFuture.successful(None)
}
}
}
}
case _ => FastFuture.successful(None)
}
}
}
}
def jautoGenerateCertificateForDomain(domain: String, env: Env): Option[Cert] = {
import scala.concurrent.duration._
Try {
// TODO: blocking ec
implicit val ec = env.otoroshiExecutionContext
implicit val ev = env
Await.result(env.datastores.certificatesDataStore.autoGenerateCertificateForDomain(domain), 10.seconds)
} match {
case Failure(e) => None
case Success(opt) => opt
}
}
}
object DynamicSSLEngineProvider {
import org.bouncycastle.jce.provider.BouncyCastleProvider
import java.security.Security
Security.addProvider(new BouncyCastleProvider())
type KeyStoreError = String
private val EMPTY_PASSWORD: Array[Char] = Array.emptyCharArray
val logger = Logger("otoroshi-ssl-provider")
private[ssl] val CERT_PATTERN: Pattern = Pattern.compile(
"-+BEGIN\\s+.*CERTIFICATE[^-]*-+(?:\\s|\\r|\\n)+" + // Header
"([a-z0-9+/=\\r\\n]+)" + // Base64 text
"-+END\\s+.*CERTIFICATE[^-]*-+", // Footer
CASE_INSENSITIVE
)
val PRIVATE_KEY_PATTERN: Pattern = Pattern.compile(
"-+BEGIN\\s+.*PRIVATE\\s+KEY[^-]*-+(?:\\s|\\r|\\n)+" + "([a-z0-9+/=\\r\\n]+)" + "-+END\\s+.*PRIVATE\\s+KEY[^-]*-+",
CASE_INSENSITIVE
)
val PUBLIC_KEY_PATTERN: Pattern = Pattern.compile(
"-+BEGIN\\s+.*PUBLIC\\s+KEY[^-]*-+(?:\\s|\\r|\\n)+" + "([a-z0-9+/=\\r\\n]+)" + "-+END\\s+.*PUBLIC\\s+KEY[^-]*-+",
CASE_INSENSITIVE
)
val _certificates = new TrieMap[String, Cert]()
val _ocspProjectionCertificates = new TrieMap[java.math.BigInteger, OCSPCertProjection]()
def certificates: TrieMap[String, Cert] = _certificates.filter(_._2.notRevoked)
private lazy val firstSetupDone = new AtomicBoolean(false)
private lazy val currentContextServer = new AtomicReference[SSLContext](setupContext(FakeHasMetrics, true, Seq.empty))
private lazy val currentContextClient = new AtomicReference[SSLContext](setupContext(FakeHasMetrics, true, Seq.empty))
private lazy val currentSslConfigSettings = new AtomicReference[SSLConfigSettings](null)
private val currentEnv = new AtomicReference[Env](null)
private val defaultSslContext = SSLContext.getDefault
def isFirstSetupDone: Boolean = firstSetupDone.get()
def setCurrentEnv(env: Env): Unit = {
currentEnv.set(env)
}
def getCurrentEnv(): Env = {
currentEnv.get()
}
private def setupContext(env: HasMetrics, includeJdkCa: Boolean, trustedCerts: Seq[String]): SSLContext =
env.metrics.withTimer("otoroshi.core.tls.setup-global-context") {
val certificates = _certificates.filter(_._2.notRevoked)
val trustedCertificates: TrieMap[String, Cert] = if (trustedCerts.nonEmpty) {
new TrieMap[String, Cert]() ++ trustedCerts
.flatMap(k => _certificates.get(k))
.filter(_.notRevoked)
.map(c => (c.id, c))
.toMap
} else {
_certificates.filter(_._2.notRevoked)
}
// println(s"building context with ${trustedCertificates.size} trusted certificates")
val optEnv = Option(currentEnv.get)
val trustAll: Boolean =
optEnv
.flatMap(e => e.configuration.getOptionalWithFileSupport[Boolean]("otoroshi.ssl.trust.all"))
.getOrElse(false)
val cacertPath = optEnv
.flatMap(e => e.configuration.getOptionalWithFileSupport[String]("otoroshi.ssl.cacert.path"))
.map(path =>
path
.replace("${JAVA_HOME}", System.getProperty("java.home"))
.replace("$JAVA_HOME", System.getProperty("java.home"))
)
.getOrElse(System.getProperty("java.home") + "/lib/security/cacerts")
val cacertPassword = optEnv
.flatMap(e => e.configuration.getOptionalWithFileSupport[String]("otoroshi.ssl.cacert.password"))
.getOrElse("changeit")
val dumpPath: Option[String] =
optEnv.flatMap(e => e.configuration.getOptionalWithFileSupport[String]("play.server.https.keyStoreDumpPath"))
logger.debug("Setting up SSL Context ")
val sslContext: SSLContext = SSLContext.getInstance("TLS")
val keyStore: KeyStore = createKeyStore(certificates.values.toSeq) //.filterNot(_.ca))
val trustedKeyStore: KeyStore = createKeyStore(trustedCertificates.values.toSeq) //.filterNot(_.ca))
dumpPath.foreach { path =>
logger.debug(s"Dumping keystore at $dumpPath")
keyStore.store(new FileOutputStream(path), EMPTY_PASSWORD)
}
val keyManagerFactory: KeyManagerFactory =
Try(KeyManagerFactory.getInstance("X509")).orElse(Try(KeyManagerFactory.getInstance("SunX509"))).get
keyManagerFactory.init(keyStore, EMPTY_PASSWORD)
val trustedkeyManagerFactory: KeyManagerFactory =
Try(KeyManagerFactory.getInstance("X509")).orElse(Try(KeyManagerFactory.getInstance("SunX509"))).get
trustedkeyManagerFactory.init(trustedKeyStore, EMPTY_PASSWORD)
logger.debug("SSL Context init ...")
val keyManagers: Array[KeyManager] = keyManagerFactory.getKeyManagers.map(m =>
KeyManagerCompatibility.keyManager(
() => certificates.values.toSeq,
false,
m.asInstanceOf[X509KeyManager],
optEnv.get
) // new X509KeyManagerSnitch(m.asInstanceOf[X509KeyManager]).asInstanceOf[KeyManager]
)
val tm: Array[TrustManager] =
optEnv
.flatMap(e =>
e.configuration.getOptionalWithFileSupport[Boolean]("play.server.https.trustStore.noCaVerification")
)
.map {
case true => Array[TrustManager](noCATrustManager)
case false if includeJdkCa => createTrustStoreWithJdkCAs(trustedKeyStore, cacertPath, cacertPassword)
case false if !includeJdkCa => createTrustStore(trustedKeyStore)
} getOrElse {
if (trustAll) {
Array[TrustManager](
new VeryNiceTrustManager(Seq.empty[X509TrustManager])
)
} else {
if (includeJdkCa) {
createTrustStoreWithJdkCAs(trustedKeyStore, cacertPath, cacertPassword)
} else {
createTrustStore(trustedKeyStore)
}
}
}
sslContext.init(keyManagers, tm, null)
// dumpPath match {
// case Some(path) => {
// currentSslConfigSettings.set(
// SSLConfigSettings()
// //.withHostnameVerifierClass(classOf[OtoroshiHostnameVerifier])
// .withKeyManagerConfig(
// KeyManagerConfig().withKeyStoreConfigs(
// List(KeyStoreConfig(None, Some(path)).withPassword(Some(String.valueOf(EMPTY_PASSWORD))))
// )
// )
// .withTrustManagerConfig(
// TrustManagerConfig().withTrustStoreConfigs(
// certificates.values.toList.map(c => TrustStoreConfig(Option(c.chain).map(_.trim), None))
// )
// )
// )
// }
// case None => {
// currentSslConfigSettings.set(
// SSLConfigSettings()
// //.withHostnameVerifierClass(classOf[OtoroshiHostnameVerifier])
// .withKeyManagerConfig(
// KeyManagerConfig().withKeyStoreConfigs(
// certificates.values.toList.map(c => KeyStoreConfig(Option(c.chain).map(_.trim), None))
// )
// )
// .withTrustManagerConfig(
// TrustManagerConfig().withTrustStoreConfigs(
// certificates.values.toList.map(c => TrustStoreConfig(Option(c.chain).map(_.trim), None))
// )
// )
// )
// }
// }
logger.debug(s"SSL Context init done ! (${keyStore.size()})")
SSLContext.setDefault(sslContext)
sslContext
}
/*
def setupSslContextFor(cert: Cert, env: Env): SSLContext =
env.metrics.withTimer("otoroshi.core.tls.setup-single-context") {
val optEnv = Option(currentEnv.get)
val trustAll: Boolean =
optEnv.flatMap(e => e.configuration.getOptionalWithFileSupport[Boolean]("otoroshi.ssl.trust.all")).getOrElse(false)
val cacertPath = optEnv
.flatMap(e => e.configuration.getOptionalWithFileSupport[String]("otoroshi.ssl.cacert.path"))
.map(
path =>
path
.replace("${JAVA_HOME}", System.getProperty("java.home"))
.replace("$JAVA_HOME", System.getProperty("java.home"))
)
.getOrElse(System.getProperty("java.home") + "/lib/security/cacerts")
val cacertPassword = optEnv
.flatMap(e => e.configuration.getOptionalWithFileSupport[String]("otoroshi.ssl.cacert.password"))
.getOrElse("changeit")
logger.debug("Setting up SSL Context ")
val sslContext: SSLContext = SSLContext.getInstance("TLS")
val keyStore: KeyStore = createKeyStore(Seq(cert))
val keyManagerFactory: KeyManagerFactory =
Try(KeyManagerFactory.getInstance("X509")).orElse(Try(KeyManagerFactory.getInstance("SunX509"))).get
keyManagerFactory.init(keyStore, EMPTY_PASSWORD)
logger.debug("SSL Context init ...")
val keyManagers: Array[KeyManager] = keyManagerFactory.getKeyManagers.map(
m => new X509KeyManagerSnitch(m.asInstanceOf[X509KeyManager]).asInstanceOf[KeyManager]
)
val tm: Array[TrustManager] =
optEnv.flatMap(e => e.configuration.getOptionalWithFileSupport[Boolean]("play.server.https.trustStore.noCaVerification")).map {
case true => Array[TrustManager](noCATrustManager)
case false => createTrustStore(keyStore, cacertPath, cacertPassword)
} getOrElse {
if (trustAll) {
Array[TrustManager](
new VeryNiceTrustManager(Seq.empty[X509TrustManager])
)
} else {
createTrustStore(keyStore, cacertPath, cacertPassword)
}
}
sslContext.init(keyManagers, tm, null)
logger.debug(s"SSL Context init done ! (${keyStore.size()})")
SSLContext.setDefault(sslContext)
sslContext
}
*/
def setupSslContextFor(
_certs: Seq[Cert],
_trustedCerts: Seq[Cert],
forceTrustAll: Boolean,
client: Boolean,
env: Env
): SSLContext =
env.metrics.withTimer("otoroshi.core.tls.setup-single-context") {
val includeJdkCa: Boolean = if (client) {
env.datastores.globalConfigDataStore.latestSafe.map(_.tlsSettings.includeJdkCaClient).getOrElse(true)
} else {
env.datastores.globalConfigDataStore.latestSafe.map(_.tlsSettings.includeJdkCaServer).getOrElse(true)
}
val certs = _certs.filter(_.notRevoked)
val trustedCerts = _trustedCerts.filter(_.notRevoked)
val optEnv = Option(env)
val trustAll: Boolean =
if (forceTrustAll) true
else
optEnv
.flatMap(e => e.configuration.getOptionalWithFileSupport[Boolean]("otoroshi.ssl.trust.all"))
.getOrElse(false)
val cacertPath = optEnv
.flatMap(e => e.configuration.getOptionalWithFileSupport[String]("otoroshi.ssl.cacert.path"))
.map(path =>
path
.replace("${JAVA_HOME}", System.getProperty("java.home"))
.replace("$JAVA_HOME", System.getProperty("java.home"))
)
.getOrElse(System.getProperty("java.home") + "/lib/security/cacerts")
val cacertPassword = optEnv
.flatMap(e => e.configuration.getOptionalWithFileSupport[String]("otoroshi.ssl.cacert.password"))
.getOrElse("changeit")
logger.debug("Setting up SSL Context ")
val sslContext: SSLContext = SSLContext.getInstance("TLS")
val keyStore1: KeyStore = createKeyStore(certs)
val keyManagerFactory: KeyManagerFactory =
Try(KeyManagerFactory.getInstance("X509")).orElse(Try(KeyManagerFactory.getInstance("SunX509"))).get
keyManagerFactory.init(keyStore1, EMPTY_PASSWORD)
logger.debug("SSL Context init ...")
val keyManagers: Array[KeyManager] = keyManagerFactory.getKeyManagers.map(m =>
KeyManagerCompatibility.keyManager(
() => certs,
client,
m.asInstanceOf[X509KeyManager],
optEnv.get
) // new X509KeyManagerSnitch(m.asInstanceOf[X509KeyManager]).asInstanceOf[KeyManager]
)
val keyStore2: KeyStore = if (trustedCerts.nonEmpty) createKeyStore(trustedCerts) else keyStore1
val tm: Array[TrustManager] =
optEnv
.flatMap(e =>
e.configuration.getOptionalWithFileSupport[Boolean]("play.server.https.trustStore.noCaVerification")
)
.map {
case true => Array[TrustManager](noCATrustManager)
case false if includeJdkCa => createTrustStoreWithJdkCAs(keyStore2, cacertPath, cacertPassword)
case false if !includeJdkCa => createTrustStore(keyStore2)
} getOrElse {
if (trustAll) {
Array[TrustManager](
new VeryNiceTrustManager(Seq.empty[X509TrustManager])
)
} else {
if (includeJdkCa) {
createTrustStoreWithJdkCAs(keyStore2, cacertPath, cacertPassword)
} else {
createTrustStore(keyStore2)
}
}
}
sslContext.init(keyManagers, tm, null)
logger.debug(s"SSL Context init done ! (${keyStore1.size()} - ${keyStore2.size()})")
SSLContext.setDefault(sslContext)
sslContext
}
def currentServer = currentContextServer.get()
def currentClient = currentContextClient.get()
def sslConfigSettings: SSLConfigSettings = currentSslConfigSettings.get()
def getHostNames(): Seq[String] = {
_certificates.values.filter(_.notRevoked).map(_.domain).toSet.toSeq
}
def addCertificates(certs: Seq[Cert], env: Env): Unit = {
firstSetupDone.compareAndSet(false, true)
certs.filter(_.notRevoked).foreach(crt => _certificates.put(crt.id, crt))
val ctxClient = setupContext(
env,
env.datastores.globalConfigDataStore.latestSafe.map(_.tlsSettings.includeJdkCaClient).getOrElse(true),
env.datastores.globalConfigDataStore.latestSafe.map(_.tlsSettings.trustedCAsServer).getOrElse(Seq.empty)
)
val ctxServer = setupContext(
env,
env.datastores.globalConfigDataStore.latestSafe.map(_.tlsSettings.includeJdkCaServer).getOrElse(true),
env.datastores.globalConfigDataStore.latestSafe.map(_.tlsSettings.trustedCAsServer).getOrElse(Seq.empty)
)
currentContextClient.set(ctxClient)
currentContextServer.set(ctxServer)
}
def setCertificates(certs: Seq[Cert], env: Env): Unit = {
firstSetupDone.compareAndSet(false, true)
_certificates.clear()
certs.filter(_.notRevoked).foreach(crt => _certificates.put(crt.id, crt))
certs
.filter(r => r.serialNumberLng.isDefined && CertParentHelper.fromOtoroshiRootCa(r.certificate.get))
.foreach(crt =>
_ocspProjectionCertificates.put(
crt.serialNumberLng.get,
OCSPCertProjection(
crt.revoked,
crt.isValid,
crt.expired,
crt.entityMetadata.getOrElse("revocationReason", "VALID"),
crt.from.toDate,
crt.to.toDate
)
)
)
val ctxClient = setupContext(
env,
env.datastores.globalConfigDataStore.latestSafe.map(_.tlsSettings.includeJdkCaClient).getOrElse(true),
env.datastores.globalConfigDataStore.latestSafe.map(_.tlsSettings.trustedCAsServer).getOrElse(Seq.empty)
)
val ctxServer = setupContext(
env,
env.datastores.globalConfigDataStore.latestSafe.map(_.tlsSettings.includeJdkCaServer).getOrElse(true),
env.datastores.globalConfigDataStore.latestSafe.map(_.tlsSettings.trustedCAsServer).getOrElse(Seq.empty)
)
currentContextClient.set(ctxClient)
currentContextServer.set(ctxServer)
}
def forceUpdate(env: Env): Unit = {
firstSetupDone.compareAndSet(false, true)
val ctxClient = setupContext(
env,
env.datastores.globalConfigDataStore.latestSafe.map(_.tlsSettings.includeJdkCaClient).getOrElse(true),
env.datastores.globalConfigDataStore.latestSafe.map(_.tlsSettings.trustedCAsServer).getOrElse(Seq.empty)
)
val ctxServer = setupContext(
env,
env.datastores.globalConfigDataStore.latestSafe.map(_.tlsSettings.includeJdkCaServer).getOrElse(true),
env.datastores.globalConfigDataStore.latestSafe.map(_.tlsSettings.trustedCAsServer).getOrElse(Seq.empty)
)
currentContextClient.set(ctxClient)
currentContextServer.set(ctxServer)
}
def createKeyStore(certificates: Seq[Cert]): KeyStore = {
import SSLImplicits._
logger.debug(s"Creating keystore ...")
val keyStore: KeyStore = KeyStore.getInstance("JKS")
keyStore.load(null, null)
certificates.foreach {
case cert if cert.ca => {
cert.certificate.foreach { certificate =>
val id = "ca-" + certificate.getSerialNumber.toString(16)
if (!keyStore.containsAlias(id)) {
keyStore.setCertificateEntry(id, certificate)
}
}
}
case cert if cert.privateKey.trim.isEmpty => {
cert.certificate.foreach { certificate =>
val id = "trusted-" + certificate.getSerialNumber.toString(16)
val certificateChain: Seq[X509Certificate] = readCertificateChain(cert.domain, cert.cleanChain)
val domain = Try {
certificateChain.head.maybeDomain.getOrElse(cert.domain)
}.toOption.getOrElse(cert.domain)
// not sure it's actually needed
if (!keyStore.containsAlias(domain)) {
keyStore.setCertificateEntry(domain, certificate)
}
// Handle SANs, not sure it's actually needed
cert.sans
.filter(name => !keyStore.containsAlias(name))
.foreach(name => {
keyStore.setCertificateEntry(name, certificate)
})
}
}
case cert => {
cert.certificate.foreach { certificate =>
Try {
readPrivateKeyUniversal(cert.domain, cert.privateKey, cert.password).foreach { key: PrivateKey =>
// val key: PrivateKey = readPrivateKey(encodedKeySpec)
val certificateChain: Seq[X509Certificate] = readCertificateChain(cert.domain, cert.cleanChain)
if (certificateChain.isEmpty) {
logger.error(s"[${cert.id}] Certificate file does not contain any certificates :(")
} else {
logger.debug(s"Adding entry for ${cert.domain} with chain of ${certificateChain.size}")
val domain = Try {
certificateChain.head.maybeDomain.getOrElse(cert.domain)
}.toOption.getOrElse(cert.domain)
keyStore.setKeyEntry(
if (cert.client) "client-cert-" + certificate.getSerialNumber.toString(16) else domain,
key,
cert.password.getOrElse("").toCharArray,
certificateChain.toArray[java.security.cert.Certificate]
)
// Handle SANs
if (!cert.client) {
cert.sans
.filter(name => !keyStore.containsAlias(name))
.foreach { name =>
keyStore.setKeyEntry(
name,
key,
cert.password.getOrElse("").toCharArray,
certificateChain.toArray[java.security.cert.Certificate]
)
}
}
certificateChain.tail.foreach { cert =>
val id = "ca-" + cert.getSerialNumber.toString(16)
if (!keyStore.containsAlias(id)) {
keyStore.setCertificateEntry(id, cert)
}
}
}
}
} match {
case Failure(e) => logger.error(s"Error while handling certificate: ${cert.name}: " + e.getMessage)
case Success(e) =>
}
}
}
}
keyStore
}
def createTrustStoreWithJdkCAs(
keyStore: KeyStore,
cacertPath: String,
cacertPassword: String
): Array[TrustManager] = {
logger.debug(s"Creating truststore ...")
val tmf = TrustManagerFactory.getInstance("SunX509")
tmf.init(keyStore)
val javaKs = KeyStore.getInstance("JKS")
// TODO: optimize here: avoid reading file all the time
javaKs.load(new FileInputStream(cacertPath), cacertPassword.toCharArray)
val tmf2 = TrustManagerFactory.getInstance("SunX509")
tmf2.init(javaKs)
Array[TrustManager](
new FakeTrustManager((tmf.getTrustManagers ++ tmf2.getTrustManagers).map(_.asInstanceOf[X509TrustManager]).toSeq)
)
}
def createTrustStore(keyStore: KeyStore): Array[TrustManager] = {
logger.debug(s"Creating truststore ...")
val tmf = TrustManagerFactory.getInstance("SunX509")
tmf.init(keyStore)
Array[TrustManager](
new FakeTrustManager(tmf.getTrustManagers.map(_.asInstanceOf[X509TrustManager]).toSeq)
)
}
def readCertificateChain(id: String, certificateChain: String, log: Boolean = true): Seq[X509Certificate] = {
if (log) logger.debug(s"Reading cert chain for $id")
val matcher: Matcher = CERT_PATTERN.matcher(certificateChain)
val certificateFactory: CertificateFactory = CertificateFactory.getInstance("X.509")
var certificates = Seq.empty[X509Certificate]
var start = 0
while ({ matcher.find(start) }) {
val buffer: Array[Byte] = base64Decode(matcher.group(1))
certificates = certificates :+ certificateFactory
.generateCertificate(new ByteArrayInputStream(buffer))
.asInstanceOf[X509Certificate]
start = matcher.end
}
certificates
}
def _readPrivateKey(encodedKeySpec: KeySpec): Try[PrivateKey] = {
Try(KeyFactory.getInstance("RSA").generatePrivate(encodedKeySpec))
.orElse(Try(KeyFactory.getInstance("EC").generatePrivate(encodedKeySpec)))
.orElse(Try(KeyFactory.getInstance("DSA").generatePrivate(encodedKeySpec)))
//.orElse(Try(KeyFactory.getInstance("DiffieHellman")).map(_.generatePrivate(encodedKeySpec)))
//.get
}
def _readPrivateKeySpec(
id: String,
content: String,
keyPassword: Option[String],
log: Boolean = true
): Either[KeyStoreError, KeySpec] = {
if (log) logger.debug(s"Reading private key for $id")
val matcher: Matcher = PRIVATE_KEY_PATTERN.matcher(content)
if (!matcher.find) {
logger.debug(s"[$id] Found no private key :(")
Left(s"[$id] Found no private key")
} else {
val encodedKey: Array[Byte] = base64Decode(matcher.group(1))
keyPassword
.map { kpv =>
val encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(encodedKey)
val keyFactory: SecretKeyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName)
val secretKey: SecretKey = keyFactory.generateSecret(new PBEKeySpec(kpv.toCharArray))
val cipher: Cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName)
cipher.init(DECRYPT_MODE, secretKey, encryptedPrivateKeyInfo.getAlgParameters)
Right(encryptedPrivateKeyInfo.getKeySpec(cipher))
}
.getOrElse {
Right(new PKCS8EncodedKeySpec(encodedKey))
}
}
}
def readPrivateKeyUniversal(
id: String,
content: String,
keyPassword: Option[String],
log: Boolean = true
): Either[KeyStoreError, PrivateKey] = {
if (log) logger.debug(s"Reading private key for $id")
val matcher: Matcher = PRIVATE_KEY_PATTERN.matcher(content)
if (!matcher.find) {
logger.debug(s"[$id] Found no private key :(")
Left(s"[$id] Found no private key")
} else {
import otoroshi.utils.syntax.implicits._
Try {
// val reader = new PemReader(new StringReader(privateKey))
val parser = new PEMParser(new StringReader(content))
val converter = new JcaPEMKeyConverter().setProvider("BC")
parser.readObject() match {
case ckp: PEMEncryptedKeyPair if keyPassword.isEmpty => None
case ckp: PEMEncryptedKeyPair if keyPassword.isDefined =>
val decProv = new JcePEMDecryptorProviderBuilder().build(keyPassword.get.toCharArray)
val kp = converter.getKeyPair(ckp.decryptKeyPair(decProv))
kp.getPrivate.some
case ukp: PEMKeyPair =>
val kp = converter.getKeyPair(ukp)
kp.getPrivate.some
case _ => None
}
} match {
case Failure(e) =>
// Left(s"[$id] error while reading private key: ${e.getMessage}".debugPrintln)
_readPrivateKeySpec(id, content, keyPassword, log).flatMap(ks =>
_readPrivateKey(ks).toEither match {
case Left(r) => Left(r.getMessage)
case Right(r) => Right(r)
}
)
case Success(None) =>
// Left(s"[$id] no valid key found".debugPrintln)
_readPrivateKeySpec(id, content, keyPassword, log).flatMap(ks =>
_readPrivateKey(ks).toEither match {
case Left(r) => Left(r.getMessage)
case Right(r) => Right(r)
}
)
case Success(Some(key)) => Right(key)
}
}
}
def isSelfSigned(cert: X509Certificate): Boolean = {
Try { // Try to verify certificate signature with its own public key
val key: PublicKey = cert.getPublicKey
cert.verify(key)
true
} recover { case e =>
false
} get
}
def base64Decode(base64: String): Array[Byte] = Base64.getMimeDecoder.decode(base64.getBytes(US_ASCII))
def createSSLEngine(
clientAuth: ClientAuth,
cipherSuites: Option[Seq[String]],
protocols: Option[Seq[String]]
): SSLEngine = {
val context: SSLContext = DynamicSSLEngineProvider.currentServer
DynamicSSLEngineProvider.logger.debug(s"Create SSLEngine from: $context")
val rawEngine = context.createSSLEngine()
val rawEnabledCipherSuites = rawEngine.getEnabledCipherSuites.toSeq
val rawEnabledProtocols = rawEngine.getEnabledProtocols.toSeq
cipherSuites.foreach(s => rawEngine.setEnabledCipherSuites(s.toArray))
protocols.foreach(p => rawEngine.setEnabledProtocols(p.toArray))
val engine = new CustomSSLEngine(rawEngine)
val sslParameters = new SSLParameters
val matchers = new java.util.ArrayList[SNIMatcher]()
engine.setUseClientMode(false)
clientAuth match {
case ClientAuth.Want =>
engine.setWantClientAuth(true)
sslParameters.setWantClientAuth(true)
case ClientAuth.Need =>
engine.setNeedClientAuth(true)
sslParameters.setNeedClientAuth(true)
case _ =>
}
matchers.add(new SNIMatcher(0) {
override def matches(sniServerName: SNIServerName): Boolean = {
sniServerName match {
case hn: SNIHostName =>
val hostName = hn.getAsciiName
DynamicSSLEngineProvider.logger.debug(s"createSSLEngine - for $hostName")
engine.setEngineHostName(hostName)
case _ =>
DynamicSSLEngineProvider.logger.debug(s"Not a hostname :( $sniServerName")
}
true
}
})
sslParameters.setSNIMatchers(matchers)
cipherSuites.orElse(Some(rawEnabledCipherSuites)).foreach(s => sslParameters.setCipherSuites(s.toArray))
protocols.orElse(Some(rawEnabledProtocols)).foreach(p => sslParameters.setProtocols(p.toArray))
engine.setSSLParameters(sslParameters)
engine.locked()
}
}
/*class OtoroshiHostnameVerifier() extends HostnameVerifier {
override def verify(s: String, sslSession: SSLSession): Boolean = {
true
}
}*/
class DynamicSSLEngineProvider(appProvider: ApplicationProvider) extends SSLEngineProvider {
lazy val cipherSuites =
appProvider.get.get.configuration
.getOptionalWithFileSupport[Seq[String]]("otoroshi.ssl.cipherSuites")
.filterNot(_.isEmpty)
lazy val protocols =
appProvider.get.get.configuration
.getOptionalWithFileSupport[Seq[String]]("otoroshi.ssl.protocols")
.filterNot(_.isEmpty)
lazy val clientAuth = {
val auth = appProvider.get.get.configuration
.getOptionalWithFileSupport[String]("otoroshi.ssl.fromOutside.clientAuth")
.flatMap(ClientAuth.apply)
.getOrElse(ClientAuth.None)
DynamicSSLEngineProvider.logger.debug(s"Otoroshi client auth: ${auth}")
auth
}
override def createSSLEngine(): SSLEngine = {
DynamicSSLEngineProvider.createSSLEngine(clientAuth, cipherSuites, protocols)
}
private def setupSslContext(): SSLContext = {
new SSLContext(
new SSLContextSpi() {
override def engineCreateSSLEngine(): SSLEngine = createSSLEngine()
override def engineCreateSSLEngine(s: String, i: Int): SSLEngine = engineCreateSSLEngine()
override def engineInit(
keyManagers: Array[KeyManager],
trustManagers: Array[TrustManager],
secureRandom: SecureRandom
): Unit = ()
override def engineGetClientSessionContext(): SSLSessionContext =
DynamicSSLEngineProvider.currentServer.getClientSessionContext
override def engineGetServerSessionContext(): SSLSessionContext =
DynamicSSLEngineProvider.currentServer.getServerSessionContext
override def engineGetSocketFactory(): SSLSocketFactory =
DynamicSSLEngineProvider.currentServer.getSocketFactory
override def engineGetServerSocketFactory(): SSLServerSocketFactory =
DynamicSSLEngineProvider.currentServer.getServerSocketFactory
},
new Provider(
"Otoroshi SSlEngineProvider delegate",
1d,
"A provider that delegates calls to otoroshi dynamic one"
) {},
"Otoroshi SSLEngineProvider delegate"
) {}
}
override def sslContext(): SSLContext = setupSslContext()
}
object noCATrustManager extends X509TrustManager {
val nullArray = Array[X509Certificate]()
def checkClientTrusted(x509Certificates: Array[X509Certificate], s: String): Unit = {}
def checkServerTrusted(x509Certificates: Array[X509Certificate], s: String): Unit = {}
def getAcceptedIssuers() = nullArray
}
object CertificateData {
import otoroshi.ssl.SSLImplicits._
import collection.JavaConverters._
private val logger = Logger("otoroshi-cert-data")
private val encoder = Base64.getEncoder
private val certificateFactory: CertificateFactory = CertificateFactory.getInstance("X.509")
private def base64Decode(base64: String): Array[Byte] = Base64.getMimeDecoder.decode(base64.getBytes(US_ASCII))
def apply(pemContent: String): JsValue = {
val finContent = PemHeaders.BeginCertificate + "\n" + pemContent + "\n" + PemHeaders.EndCertificate
val buffer = base64Decode(
pemContent.replace(PemHeaders.BeginCertificate, "").replace(PemHeaders.EndCertificate, "")
)
val cert = certificateFactory.generateCertificate(new ByteArrayInputStream(buffer)).asInstanceOf[X509Certificate]
val altNames = cert.altNames
val rawDomain = cert.rawDomain
val domain: String = cert.domain
val pemReader = new org.bouncycastle.openssl.PEMParser(new StringReader(finContent))
val holder = pemReader.readObject().asInstanceOf[org.bouncycastle.cert.X509CertificateHolder]
pemReader.close()
val usages: Array[KeyPurposeId] = Option(holder.getExtensions)
.flatMap(exts => Option(ExtendedKeyUsage.fromExtensions(exts)))
.map(_.getUsages)
.getOrElse(Array.empty)
val client: Boolean = usages.contains(KeyPurposeId.id_kp_clientAuth)
// val client: Boolean = Try(cert.getExtensionValue("2.5.29.37")) match {
Json.obj(
"issuerDN" -> DN(cert.getIssuerDN.getName).stringify,
"notAfter" -> cert.getNotAfter.getTime,
"notBefore" -> cert.getNotBefore.getTime,
"serialNumber" -> cert.getSerialNumber.toString(16),
"serialNumberLng" -> cert.getSerialNumber,
"sigAlgName" -> cert.getSigAlgName,
"sigAlgOID" -> cert.getSigAlgOID,
"_signature" -> new String(encoder.encode(cert.getSignature)),
"signature" -> DigestUtils.sha256Hex(cert.getSignature).toUpperCase().grouped(2).mkString(":"),
"subjectDN" -> DN(cert.getSubjectDN.getName).stringify,
"domain" -> domain,
"rawDomain" -> rawDomain.map(JsString.apply).getOrElse(JsNull).as[JsValue],
"version" -> cert.getVersion,
"type" -> cert.getType,
"publicKey" -> cert.getPublicKey.asPem, // new String(encoder.encode(cert.getPublicKey.getEncoded)),
"selfSigned" -> DynamicSSLEngineProvider.isSelfSigned(cert),
"constraints" -> cert.getBasicConstraints,
"ca" -> (cert.getBasicConstraints != -1),
"client" -> client,
"subAltNames" -> JsArray(altNames.map(JsString.apply)),
"cExtensions" -> JsArray(
Option(cert.getCriticalExtensionOIDs).map(_.asScala.toSeq).getOrElse(Seq.empty[String]).map { oid =>
val ext: String =
Option(cert.getExtensionValue(oid)).map(bytes => ByteString(bytes).utf8String).getOrElse("--")
Json.obj(
"oid" -> oid,
"value" -> ext
)
}
),
"ncExtensions" -> JsArray(
Option(cert.getNonCriticalExtensionOIDs).map(_.asScala.toSeq).getOrElse(Seq.empty[String]).map { oid =>
val ext: String =
Option(cert.getExtensionValue(oid)).map(bytes => ByteString(bytes).utf8String).getOrElse("--")
Json.obj(
"oid" -> oid,
"value" -> ext
)
}
)
)
}
}
object PemHeaders {
val BeginCertificate = "-----BEGIN CERTIFICATE-----"
val EndCertificate = "-----END CERTIFICATE-----"
val BeginPublicKey = "-----BEGIN PUBLIC KEY-----"
val EndPublicKey = "-----END PUBLIC KEY-----"
val BeginPrivateKey = "-----BEGIN PRIVATE KEY-----"
val EndPrivateKey = "-----END PRIVATE KEY-----"
val BeginPrivateRSAKey = "-----BEGIN RSA PRIVATE KEY-----"
val BeginPrivateECKey = "-----BEGIN EC PRIVATE KEY-----"
val EndPrivateRSAKey = "-----END RSA PRIVATE KEY-----"
val EndPrivateECKey = "-----END EC PRIVATE KEY-----"
val BeginCertificateRequest = "-----BEGIN CERTIFICATE REQUEST-----"
val EndCertificateRequest = "-----END CERTIFICATE REQUEST-----"
}
object FakeKeyStore {
import otoroshi.ssl.SSLImplicits._
private val EMPTY_PASSWORD = Array.emptyCharArray
private val encoder = Base64.getEncoder
object SelfSigned {
object Alias {
val trustedCertEntry = "otoroshi-selfsigned-trust"
val PrivateKeyEntry = "otoroshi-selfsigned"
}
def DistinguishedName(host: String) = s"CN=$host, OU=Otoroshi Certificates, O=Otoroshi"
def SubDN(host: String) = s"CN=$host"
}
object KeystoreSettings {
val SignatureAlgorithmName = "SHA256withRSA"
val KeyPairAlgorithmName = "RSA"
val KeyPairKeyLength = 2048 // 2048 is the NIST acceptable key length until 2030
val KeystoreType = "JKS"
}
private implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(4))
def generateKeyStore(host: String)(implicit env: Env): KeyStore = {
val keyStore: KeyStore = KeyStore.getInstance(KeystoreSettings.KeystoreType)
val (cert, keyPair) = generateX509Certificate(host)
keyStore.load(null, EMPTY_PASSWORD)
keyStore.setKeyEntry(SelfSigned.Alias.PrivateKeyEntry, keyPair.getPrivate, EMPTY_PASSWORD, Array(cert))
keyStore.setCertificateEntry(SelfSigned.Alias.trustedCertEntry, cert)
keyStore
}
def generateX509Certificate(host: String)(implicit env: Env): (X509Certificate, KeyPair) = {
val resp = createSelfSignedCertificate(host, 365.days, None, None)
(resp.cert, resp.keyPair)
}
def generateCert(host: String)(implicit env: Env): Cert = {
val (cert, keyPair) = generateX509Certificate(host)
Cert(
id = IdGenerator.token(32),
name = host,
description = s"Certificate for $host",
domain = host,
chain = cert.asPem,
privateKey = keyPair.getPrivate.asPem,
caRef = None,
autoRenew = false,
client = false,
exposed = false,
revoked = false
)
}
def createSelfSignedCertificate(host: String, duration: FiniteDuration, kp: Option[KeyPair], serial: Option[Long])(
implicit env: Env
): GenCertResponse = {
val f = env.pki.genSelfSignedCert(
GenCsrQuery(
hosts = Seq(host),
key = GenKeyPairQuery(KeystoreSettings.KeyPairAlgorithmName, KeystoreSettings.KeyPairKeyLength),
name = Map("CN" -> host),
duration = duration,
existingKeyPair = kp,
existingSerialNumber = serial
)
)
val resp = Await.result(f, 30.seconds)
resp.right.get
}
def createClientCertificateFromCA(
dn: String,
duration: FiniteDuration,
kp: Option[KeyPair],
serial: Option[Long],
ca: X509Certificate,
caChain: Seq[X509Certificate],
caKeyPair: KeyPair
)(implicit env: Env): GenCertResponse = {
val f = env.pki.genCert(
GenCsrQuery(
hosts = Seq.empty,
key = GenKeyPairQuery(KeystoreSettings.KeyPairAlgorithmName, KeystoreSettings.KeyPairKeyLength),
subject = Some(dn),
duration = duration,
existingKeyPair = kp,
existingSerialNumber = serial,
client = true
),
ca,
caChain,
caKeyPair.getPrivate
)
val resp = Await.result(f, 30.seconds)
resp.right.get
}
def createSelfSignedClientCertificate(
dn: String,
duration: FiniteDuration,
kp: Option[KeyPair],
serial: Option[Long]
)(implicit env: Env): GenCertResponse = {
val f = env.pki.genSelfSignedCert(
GenCsrQuery(
hosts = Seq.empty,
key = GenKeyPairQuery(KeystoreSettings.KeyPairAlgorithmName, KeystoreSettings.KeyPairKeyLength),
subject = Some(dn),
duration = duration,
existingKeyPair = kp,
existingSerialNumber = serial,
client = true
)
)
val resp = Await.result(f, 30.seconds)
resp.right.get
}
def createCertificateFromCA(
host: String,
duration: FiniteDuration,
kp: Option[KeyPair],
serial: Option[Long],
ca: X509Certificate,
caChain: Seq[X509Certificate],
caKeyPair: KeyPair
)(implicit env: Env): GenCertResponse = {
val f = env.pki.genCert(
GenCsrQuery(
hosts = Seq(host),
key = GenKeyPairQuery(KeystoreSettings.KeyPairAlgorithmName, KeystoreSettings.KeyPairKeyLength),
name = Map("CN" -> host),
duration = duration,
existingKeyPair = kp,
existingSerialNumber = serial
),
ca,
caChain,
caKeyPair.getPrivate
)
val resp = Await.result(f, 30.seconds)
resp.right.get
}
def createSubCa(
cn: String,
duration: FiniteDuration,
kp: Option[KeyPair],
serial: Option[Long],
ca: X509Certificate,
caChain: Seq[X509Certificate],
caKeyPair: KeyPair
)(implicit env: Env): GenCertResponse = {
val f = env.pki.genSubCA(
GenCsrQuery(
hosts = Seq.empty,
key = GenKeyPairQuery(KeystoreSettings.KeyPairAlgorithmName, KeystoreSettings.KeyPairKeyLength),
subject = Some(cn),
duration = duration,
existingKeyPair = kp,
existingSerialNumber = serial,
ca = true
),
ca,
caChain,
caKeyPair.getPrivate
)
val resp = Await.result(f, 30.seconds)
resp.right.get
}
def createCA(cn: String, duration: FiniteDuration, kp: Option[KeyPair], serial: Option[Long])(implicit
env: Env
): GenCertResponse = {
val f = env.pki.genSelfSignedCA(
GenCsrQuery(
hosts = Seq.empty,
key = GenKeyPairQuery(KeystoreSettings.KeyPairAlgorithmName, KeystoreSettings.KeyPairKeyLength),
subject = Some(cn),
duration = duration,
existingKeyPair = kp,
existingSerialNumber = serial,
ca = true
)
)
val resp = Await.result(f, 30.seconds)
resp.right.get
}
}
class CustomSSLEngine(delegate: SSLEngine) extends SSLEngine {
// println(delegate.getClass.getName)
// sun.security.ssl.SSLEngineImpl
// sun.security.ssl.X509TrustManagerImpl
// javax.net.ssl.X509ExtendedTrustManager
private val hostnameHolder = new AtomicReference[String]()
private var lock = false
def locked(): CustomSSLEngine = {
// it's fine as the set only appears in the same thread/function as object creation
lock = true
this
}
// TODO: add try to avoid future issue ?
private lazy val field: Field = {
val f = Option(classOf[SSLEngine].getDeclaredField("peerHost")).getOrElse(classOf[SSLEngine].getField("peerHost"))
f.setAccessible(true)
f
}
def setEngineHostName(hostName: String): Unit = {
DynamicSSLEngineProvider.logger.debug(s"Setting current session hostname to $hostName")
hostnameHolder.set(hostName)
// TODO: add try to avoid future issue ? fixed for now with '--add-opens java.base/javax.net.ssl=ALL-UNNAMED' in the java command line
field.set(this, hostName)
field.set(delegate, hostName)
}
override def getPeerHost: String = Option(hostnameHolder.get()).getOrElse(delegate.getPeerHost)
override def getPeerPort: Int = delegate.getPeerPort
override def wrap(byteBuffers: Array[ByteBuffer], i: Int, i1: Int, byteBuffer: ByteBuffer): SSLEngineResult =
delegate.wrap(byteBuffers, i, i1, byteBuffer)
override def unwrap(byteBuffer: ByteBuffer, byteBuffers: Array[ByteBuffer], i: Int, i1: Int): SSLEngineResult =
delegate.unwrap(byteBuffer, byteBuffers, i, i1)
override def getDelegatedTask: Runnable = delegate.getDelegatedTask
override def closeInbound(): Unit = delegate.closeInbound()
override def isInboundDone: Boolean = delegate.isInboundDone
override def closeOutbound(): Unit = delegate.closeOutbound()
override def isOutboundDone: Boolean = delegate.isOutboundDone
override def getSupportedCipherSuites: Array[String] = delegate.getSupportedCipherSuites
override def getEnabledCipherSuites: Array[String] = delegate.getEnabledCipherSuites
override def setEnabledCipherSuites(strings: Array[String]): Unit = {
if (!lock) {
delegate.setEnabledCipherSuites(strings)
}
}
override def getSupportedProtocols: Array[String] = delegate.getSupportedProtocols
override def getEnabledProtocols: Array[String] = delegate.getEnabledProtocols
override def setEnabledProtocols(strings: Array[String]): Unit = {
if (!lock) {
delegate.setEnabledProtocols(strings)
}
}
override def getSession: SSLSession = delegate.getSession
override def beginHandshake(): Unit = delegate.beginHandshake()
override def getHandshakeStatus: SSLEngineResult.HandshakeStatus = delegate.getHandshakeStatus
override def setUseClientMode(b: Boolean): Unit = {
if (!lock) {
delegate.setUseClientMode(b)
}
}
override def getUseClientMode: Boolean = delegate.getUseClientMode
override def setNeedClientAuth(b: Boolean): Unit = {
if (!lock) {
delegate.setNeedClientAuth(b)
}
}
override def getNeedClientAuth: Boolean = delegate.getNeedClientAuth
override def setWantClientAuth(b: Boolean): Unit = {
if (!lock) {
delegate.setWantClientAuth(b)
}
}
override def getWantClientAuth: Boolean = delegate.getWantClientAuth
override def setEnableSessionCreation(b: Boolean): Unit = {
if (!lock) {
delegate.setEnableSessionCreation(b)
}
}
override def getEnableSessionCreation: Boolean = delegate.getEnableSessionCreation
override def wrap(var1: ByteBuffer, var2: ByteBuffer): SSLEngineResult = delegate.wrap(var1, var2)
override def wrap(var1: Array[ByteBuffer], var2: ByteBuffer): SSLEngineResult = delegate.wrap(var1, var2)
override def unwrap(var1: ByteBuffer, var2: ByteBuffer): SSLEngineResult = delegate.unwrap(var1, var2)
override def unwrap(var1: ByteBuffer, var2: Array[ByteBuffer]): SSLEngineResult = delegate.unwrap(var1, var2)
override def getHandshakeSession: SSLSession = delegate.getHandshakeSession
override def getSSLParameters: SSLParameters = delegate.getSSLParameters
override def setSSLParameters(var1: SSLParameters): Unit = {
if (!lock) {
delegate.setSSLParameters(var1)
}
}
override def setHandshakeApplicationProtocolSelector(
selector: BiFunction[SSLEngine, util.List[String], String]
): Unit = {
delegate.setHandshakeApplicationProtocolSelector(selector)
}
override def getHandshakeApplicationProtocolSelector: BiFunction[SSLEngine, util.List[String], String] =
delegate.getHandshakeApplicationProtocolSelector
override def getHandshakeApplicationProtocol: String = delegate.getHandshakeApplicationProtocol
override def getApplicationProtocol: String = delegate.getApplicationProtocol
}
sealed trait ClientCertificateValidationDataStore extends BasicStore[ClientCertificateValidator] {
def getValidation(key: String)(implicit ec: ExecutionContext, env: Env): Future[Option[Boolean]]
def setValidation(key: String, value: Boolean, ttl: Long)(implicit ec: ExecutionContext, env: Env): Future[Boolean]
def removeValidation(key: String)(implicit ec: ExecutionContext, env: Env): Future[Long]
def template: ClientCertificateValidator = {
ClientCertificateValidator(
id = IdGenerator.token,
name = "validator",
description = "A client certificate validator",
url = "https://validator.oto.tools:8443",
host = "validator.oto.tools",
noCache = false,
alwaysValid = false,
proxy = None
)
}
}
class KvClientCertificateValidationDataStore(redisCli: RedisLike, env: Env)
extends ClientCertificateValidationDataStore
with RedisLikeStore[ClientCertificateValidator] {
def dsKey(k: String)(implicit env: Env): String = s"${env.storageRoot}:certificates:clients:$k"
override def getValidation(key: String)(implicit ec: ExecutionContext, env: Env): Future[Option[Boolean]] =
redisCli.get(dsKey(key)).map(_.map(_.utf8String.toBoolean))
override def setValidation(key: String, value: Boolean, ttl: Long)(implicit
ec: ExecutionContext,
env: Env
): Future[Boolean] =
redisCli.set(dsKey(key), value.toString, pxMilliseconds = Some(ttl))
def removeValidation(key: String)(implicit ec: ExecutionContext, env: Env): Future[Long] = redisCli.del(dsKey(key))
override def fmt: Format[ClientCertificateValidator] = ClientCertificateValidator.fmt
override def redisLike(implicit env: Env): RedisLike = redisCli
override def key(id: String): otoroshi.models.Key =
otoroshi.models.Key(s"${env.storageRoot}:certificates:validators:$id")
override def extractId(value: ClientCertificateValidator): String = value.id
}
// https://tools.ietf.org/html/rfc5280
// https://tools.ietf.org/html/rfc2585
// https://tools.ietf.org/html/rfc2560
// https://en.wikipedia.org/wiki/Public_key_infrastructure
// https://en.wikipedia.org/wiki/Validation_authority
// https://en.wikipedia.org/wiki/Online_Certificate_Status_Protocol
object ClientCertificateValidator {
val logger = Logger("otoroshi-client-cert-validator")
val digester = MessageDigest.getInstance("SHA-1")
val fmt = new Format[ClientCertificateValidator] {
override def reads(json: JsValue): JsResult[ClientCertificateValidator] =
Try {
JsSuccess(
ClientCertificateValidator(
location = otoroshi.models.EntityLocation.readFromKey(json),
id = (json \ "id").as[String],
name = (json \ "name").as[String],
description = (json \ "description").asOpt[String].getOrElse("--"),
url = (json \ "url").as[String],
host = (json \ "host").as[String],
goodTtl = (json \ "goodTtl").asOpt[Long].getOrElse(10 * 60000L),
badTtl = (json \ "badTtl").asOpt[Long].getOrElse(1 * 60000L),
method = (json \ "method").asOpt[String].getOrElse("POST"),
path = (json \ "path").asOpt[String].getOrElse("/certificates/_validate"),
timeout = (json \ "timeout").asOpt[Long].getOrElse(10000L),
noCache = (json \ "noCache").asOpt[Boolean].getOrElse(false),
alwaysValid = (json \ "alwaysValid").asOpt[Boolean].getOrElse(false),
headers = (json \ "headers").asOpt[Map[String, String]].getOrElse(Map.empty),
proxy = (json \ "proxy").asOpt[JsValue].flatMap(p => WSProxyServerJson.proxyFromJson(p)),
metadata = (json \ "metadata").asOpt[Map[String, String]].getOrElse(Map.empty),
tags = (json \ "tags").asOpt[Seq[String]].getOrElse(Seq.empty[String])
)
)
} recover { case e =>
JsError(e.getMessage)
} get
override def writes(o: ClientCertificateValidator): JsValue =
o.location.jsonWithKey ++ Json.obj(
"id" -> o.id,
"name" -> o.name,
"description" -> o.description,
"url" -> o.url,
"host" -> o.host,
"goodTtl" -> o.goodTtl,
"badTtl" -> o.badTtl,
"method" -> o.method,
"path" -> o.path,
"timeout" -> o.timeout,
"noCache" -> o.noCache,
"alwaysValid" -> o.alwaysValid,
"headers" -> o.headers,
"proxy" -> WSProxyServerJson.maybeProxyToJson(o.proxy),
"metadata" -> o.metadata,
"tags" -> JsArray(o.tags.map(JsString.apply))
)
}
def fromJson(json: JsValue): Either[Seq[(JsPath, Seq[JsonValidationError])], ClientCertificateValidator] =
ClientCertificateValidator.fmt.reads(json).asEither
def fromJsons(value: JsValue): ClientCertificateValidator =
try {
fmt.reads(value).get
} catch {
case e: Throwable => {
logger.error(s"Try to deserialize ${Json.prettyPrint(value)}")
throw e
}
}
}
case class ClientCertificateValidator(
id: String,
name: String,
description: String,
url: String,
host: String,
goodTtl: Long = 10L * 60000L,
badTtl: Long = 1L * 60000L,
method: String = "POST",
path: String = "/certificates/_validate",
timeout: Long = 10000L,
noCache: Boolean,
alwaysValid: Boolean,
headers: Map[String, String] = Map.empty,
proxy: Option[WSProxyServer],
location: otoroshi.models.EntityLocation = otoroshi.models.EntityLocation(),
tags: Seq[String] = Seq.empty,
metadata: Map[String, String] = Map.empty
) extends otoroshi.models.EntityLocationSupport {
def json: JsValue = asJson
def internalId: String = id
def theDescription: String = description
def theMetadata: Map[String, String] = metadata
def theName: String = name
def theTags: Seq[String] = tags
import otoroshi.utils.http.Implicits._
/*
TEST CODE
const express = require('express');
const bodyParser = require('body-parser');
const x509 = require('x509');
const app = express();
app.use(bodyParser.text());
app.use(bodyParser.json());
app.post('/certificates/_validate', (req, res) => {
console.log('need to validate the following certificate chain');
const service = req.body.service;
const identity = req.body.apikey || req.body.user || { email: 'nobody@oto.tools' };
const cert = x509.parseCert(req.body.chain);
console.log(identity, service, cert);
if (cert.subject.emailAddress === 'john.doe@oto.tools') {
res.send({ status: "good" });
} else {
res.send({ status: "revoked" });
}
});
app.listen(3000, () => console.log('certificate validation server'));
*/
import play.api.http.websocket.{Message => PlayWSMessage}
import otoroshi.ssl.SSLImplicits._
import scala.concurrent.duration._
def save()(implicit ec: ExecutionContext, env: Env) = env.datastores.clientCertificateValidationDataStore.set(this)
def asJson: JsValue = ClientCertificateValidator.fmt.writes(this)
private def validateCertificateChain(
chain: Seq[X509Certificate],
desc: ServiceDescriptor,
apikey: Option[ApiKey] = None,
user: Option[PrivateAppsUser] = None,
config: GlobalConfig
)(implicit ec: ExecutionContext, env: Env): Future[Option[Boolean]] = {
val certPayload = chain
.map { cert =>
cert.asPem
// s"${PemHeaders.BeginCertificate}\n${Base64.getEncoder.encodeToString(cert.getEncoded)}\n${PemHeaders.EndCertificate}"
}
.mkString("\n")
val payload = Json.obj(
"apikey" -> apikey.map(_.toJson.as[JsObject] - "clientSecret").getOrElse(JsNull).as[JsValue],
"user" -> user.map(_.toJson).getOrElse(JsNull).as[JsValue],
"service" -> Json.obj(
"id" -> desc.id,
"name" -> desc.name,
"groups" -> desc.groups,
"domain" -> desc.domain,
"env" -> desc.env,
"subdomain" -> desc.subdomain,
"root" -> desc.root,
"metadata" -> desc.metadata
),
"chain" -> certPayload,
"fingerprints" -> JsArray(chain.map(computeFingerPrint).map(JsString.apply))
)
val finalHeaders: Seq[(String, String)] =
headers.toSeq ++ Seq("Host" -> host, "Content-Type" -> "application/json", "Accept" -> "application/json")
env.Ws // no need for mtls here
.url(url + path)
.withHttpHeaders(finalHeaders: _*)
.withMethod(method)
.withBody(payload)
.withRequestTimeout(Duration(timeout, TimeUnit.MILLISECONDS))
.withMaybeProxyServer(proxy.orElse(config.proxies.authority))
.execute()
.map { resp =>
resp.status match { // TODO: can be good | revoked | unknown
case 200 =>
(resp.json.as[JsObject] \ "status")
.asOpt[String]
.map(_.toLowerCase == "good") // TODO: return custom message, also device identification for logging
case _ =>
resp.ignore()(env.otoroshiMaterializer)
None
}
}
.recover { case e =>
ClientCertificateValidator.logger.error("Error while validating client certificate chain", e)
None
}
}
private def getLocalValidation(key: String)(implicit ec: ExecutionContext, env: Env): Future[Option[Boolean]] = {
env.datastores.clientCertificateValidationDataStore.getValidation(key)
}
private def setGoodLocalValidation(key: String)(implicit ec: ExecutionContext, env: Env): Future[Unit] = {
env.datastores.clientCertificateValidationDataStore.setValidation(key, true, goodTtl).map(_ => ())
}
private def setBadLocalValidation(key: String)(implicit ec: ExecutionContext, env: Env): Future[Unit] = {
env.datastores.clientCertificateValidationDataStore.setValidation(key, false, badTtl).map(_ => ())
}
private def computeFingerPrint(cert: X509Certificate): String = {
Hex.encodeHexString(ClientCertificateValidator.digester.digest(cert.getEncoded())).toLowerCase()
}
private def computeKeyFromChain(chain: Seq[X509Certificate]): String = {
chain.map(computeFingerPrint).mkString("-")
}
private def isCertificateChainValid(
chain: Seq[X509Certificate],
desc: ServiceDescriptor,
apikey: Option[ApiKey] = None,
user: Option[PrivateAppsUser] = None,
config: GlobalConfig
)(implicit ec: ExecutionContext, env: Env): Future[Boolean] = {
val key = computeKeyFromChain(chain) + "-" + apikey
.map(_.clientId)
.orElse(user.map(_.randomId))
.getOrElse("none") + "-" + desc.id
if (noCache) {
validateCertificateChain(chain, desc, apikey, user, config).map {
case Some(bool) => bool
case None => false
}
} else {
getLocalValidation(key).flatMap {
case Some(true) => FastFuture.successful(true)
case Some(false) => FastFuture.successful(false)
case None => {
validateCertificateChain(chain, desc, apikey, user, config).flatMap {
case Some(false) => setBadLocalValidation(key).map(_ => false)
case Some(true) => setGoodLocalValidation(key).map(_ => true)
case None => setBadLocalValidation(key).map(_ => false)
}
}
}
}
}
private def internalValidateClientCertificates[A](
request: RequestHeader,
desc: ServiceDescriptor,
apikey: Option[ApiKey] = None,
user: Option[PrivateAppsUser] = None,
config: GlobalConfig,
attrs: TypedMap
)(
f: => Future[A]
)(implicit ec: ExecutionContext, env: Env): Future[Either[Result, A]] = {
request.clientCertificateChain match {
case Some(chain) if alwaysValid => f.map(Right.apply)
case Some(chain) =>
isCertificateChainValid(chain, desc, apikey, user, config).flatMap {
case true => f.map(Right.apply)
case false =>
Errors
.craftResponseResult(
"You're not authorized here !",
Results.Forbidden,
request,
None,
None,
attrs = attrs
)
.map(Left.apply)
}
case None =>
Errors
.craftResponseResult(
"You're not authorized here !!!",
Results.Forbidden,
request,
None,
None,
attrs = attrs
)
.map(Left.apply)
}
}
def validateClientCertificates(
req: RequestHeader,
desc: ServiceDescriptor,
apikey: Option[ApiKey] = None,
user: Option[PrivateAppsUser] = None,
config: GlobalConfig,
attrs: TypedMap
)(f: => Future[Result])(implicit ec: ExecutionContext, env: Env): Future[Result] = {
internalValidateClientCertificates(req, desc, apikey, user, config, attrs)(f).map {
case Left(badResult) => badResult
case Right(goodResult) => goodResult
}
}
def wsValidateClientCertificates(
req: RequestHeader,
desc: ServiceDescriptor,
apikey: Option[ApiKey] = None,
user: Option[PrivateAppsUser] = None,
config: GlobalConfig,
attrs: TypedMap
)(
f: => Future[Either[Result, Flow[PlayWSMessage, PlayWSMessage, _]]]
)(implicit ec: ExecutionContext, env: Env): Future[Either[Result, Flow[PlayWSMessage, PlayWSMessage, _]]] = {
internalValidateClientCertificates(req, desc, apikey, user, config, attrs)(f).map {
case Left(badResult) => Left[Result, Flow[PlayWSMessage, PlayWSMessage, _]](badResult)
case Right(goodResult) => goodResult
}
}
def validateClientCertificatesGen[A](
req: RequestHeader,
desc: ServiceDescriptor,
apikey: Option[ApiKey] = None,
user: Option[PrivateAppsUser] = None,
config: GlobalConfig,
attrs: TypedMap
)(
f: => Future[Either[Result, A]]
)(implicit ec: ExecutionContext, env: Env): Future[Either[Result, A]] = {
internalValidateClientCertificates(req, desc, apikey, user, config, attrs)(f).map {
case Left(badResult) => Left[Result, A](badResult)
case Right(goodResult) => goodResult
}
}
}
class VeryNiceTrustManager(managers: Seq[X509TrustManager]) extends X509ExtendedTrustManager {
def checkClientTrusted(var1: Array[X509Certificate], var2: String): Unit = ()
def checkServerTrusted(var1: Array[X509Certificate], var2: String): Unit = ()
def getAcceptedIssuers: Array[X509Certificate] = managers.flatMap(_.getAcceptedIssuers).toArray
def checkClientTrusted(var1: Array[X509Certificate], var2: String, var3: Socket): Unit = ()
def checkServerTrusted(var1: Array[X509Certificate], var2: String, var3: Socket): Unit = ()
def checkClientTrusted(var1: Array[X509Certificate], var2: String, var3: SSLEngine): Unit = ()
def checkServerTrusted(var1: Array[X509Certificate], var2: String, var3: SSLEngine): Unit = ()
}
class FakeTrustManager(managers: Seq[X509TrustManager]) extends X509ExtendedTrustManager {
def checkClientTrusted(var1: Array[X509Certificate], var2: String): Unit = {
managers.find(m => Try(m.checkClientTrusted(var1, var2)).isSuccess)
}
def checkServerTrusted(var1: Array[X509Certificate], var2: String): Unit = {
managers.find(m => Try(m.checkServerTrusted(var1, var2)).isSuccess)
}
def getAcceptedIssuers: Array[X509Certificate] = managers.flatMap(_.getAcceptedIssuers).toArray
def checkClientTrusted(var1: Array[X509Certificate], var2: String, var3: Socket): Unit = {
managers.find {
case m: X509ExtendedTrustManager => Try(m.checkClientTrusted(var1, var2, var3)).isSuccess
case m: X509TrustManager => Try(m.checkClientTrusted(var1, var2)).isSuccess
}
}
def checkServerTrusted(var1: Array[X509Certificate], var2: String, var3: Socket): Unit = {
managers.find {
case m: X509ExtendedTrustManager => Try(m.checkServerTrusted(var1, var2, var3)).isSuccess
case m: X509TrustManager => Try(m.checkServerTrusted(var1, var2)).isSuccess
}
}
def checkClientTrusted(var1: Array[X509Certificate], var2: String, var3: SSLEngine): Unit = {
managers.find {
case m: X509ExtendedTrustManager => Try(m.checkClientTrusted(var1, var2, var3)).isSuccess
case m: X509TrustManager => Try(m.checkClientTrusted(var1, var2)).isSuccess
}
}
def checkServerTrusted(var1: Array[X509Certificate], var2: String, var3: SSLEngine): Unit = {
managers.find {
case m: X509ExtendedTrustManager => Try(m.checkServerTrusted(var1, var2, var3)).isSuccess
case m: X509TrustManager => Try(m.checkServerTrusted(var1, var2)).isSuccess
}
}
}
object SSLImplicits {
import collection.JavaConverters._
private val logger = Logger("otoroshi-ssl-implicits")
implicit class EnhancedCertificate(val cert: java.security.cert.Certificate) extends AnyVal {
def asPem: String =
s"${PemHeaders.BeginCertificate}\n${Base64.getEncoder.encodeToString(cert.getEncoded).grouped(64).mkString("\n")}\n${PemHeaders.EndCertificate}\n"
}
implicit class EnhancedX509Certificate(val cert: X509Certificate) extends AnyVal {
def asPem: String =
s"${PemHeaders.BeginCertificate}\n${Base64.getEncoder.encodeToString(cert.getEncoded).grouped(64).mkString("\n")}\n${PemHeaders.EndCertificate}\n"
def altNames: Seq[String] = CertInfo.getSubjectAlternativeNames(cert, logger).asScala.toSeq
def rawDomain: Option[String] = {
Option(DN(cert.getSubjectDN.getName).stringify)
.flatMap(_.split(",").toSeq.map(_.trim).find(_.toLowerCase.startsWith("cn=")))
.map(_.replace("CN=", "").replace("cn=", ""))
}
def maybeDomain: Option[String] = domains.headOption
def domain: String = domains.headOption.getOrElse(cert.getSubjectDN.getName)
def domains: Seq[String] = (rawDomain ++ altNames).toSeq
def asJson: JsObject =
Json.obj(
"subjectDN" -> DN(cert.getSubjectDN.getName).stringify,
"issuerDN" -> DN(cert.getIssuerDN.getName).stringify,
"notAfter" -> cert.getNotAfter.getTime,
"notBefore" -> cert.getNotBefore.getTime,
"serialNumber" -> cert.getSerialNumber.toString(16),
"subjectCN" -> Option(DN(cert.getSubjectDN.getName).stringify)
.flatMap(_.split(",").toSeq.map(_.trim).find(_.startsWith("CN=")))
.map(_.replace("CN=", ""))
.getOrElse(DN(cert.getSubjectDN.getName).stringify)
.asInstanceOf[String],
"issuerCN" -> Option(DN(cert.getIssuerDN.getName).stringify)
.flatMap(_.split(",").toSeq.map(_.trim).find(_.startsWith("CN=")))
.map(_.replace("CN=", ""))
.getOrElse(DN(cert.getIssuerDN.getName).stringify)
.asInstanceOf[String]
)
}
implicit class EnhancedKey(val key: java.security.Key) extends AnyVal {
def asPublicKeyPem: String =
s"${PemHeaders.BeginPublicKey}\n${Base64.getEncoder.encodeToString(key.getEncoded).grouped(64).mkString("\n")}\n${PemHeaders.EndPublicKey}\n"
def asPrivateKeyPem: String =
s"${PemHeaders.BeginPrivateKey}\n${Base64.getEncoder.encodeToString(key.getEncoded).grouped(64).mkString("\n")}\n${PemHeaders.EndPrivateKey}\n"
}
implicit class EnhancedPublicKey(val key: PublicKey) extends AnyVal {
def asPem: String =
s"${PemHeaders.BeginPublicKey}\n${Base64.getEncoder.encodeToString(key.getEncoded).grouped(64).mkString("\n")}\n${PemHeaders.EndPublicKey}\n"
}
implicit class EnhancedPrivateKey(val key: PrivateKey) extends AnyVal {
def asPem: String =
s"${PemHeaders.BeginPrivateKey}\n${Base64.getEncoder.encodeToString(key.getEncoded).grouped(64).mkString("\n")}\n${PemHeaders.EndPrivateKey}\n"
}
implicit class EnhancedPKCS10CertificationRequest(val csr: PKCS10CertificationRequest) extends AnyVal {
def asPem: String =
s"${PemHeaders.BeginCertificateRequest}\n${Base64.getEncoder.encodeToString(csr.getEncoded).grouped(64).mkString("\n")}\n${PemHeaders.EndCertificateRequest}\n"
}
}
object SSLSessionJavaHelper {
val NotAllowed = "CN=NotAllowedCert"
val BadDN = s"$NotAllowed, OU=Auto Generated Certs, OU=Otoroshi Certificates, O=Otoroshi"
def computeKey(session: SSLSession): Option[String] = {
computeKey(session.toString)
}
def computeKey(session: String): Option[String] = {
Try(session.split(",")(0).replace("[", "")).toOption.map { header =>
val idAndAlg = header.replace("Session(", "").replace(")", "")
idAndAlg.contains("|") match {
case true => idAndAlg.split('|').toSeq.head
case false => idAndAlg
}
}
}
}
import scala.util.control.NoStackTrace
case class NoCertificateFoundException(hostname: String)
extends RuntimeException(s"No certificate found for: $hostname !")
with NoStackTrace
case class NoHostFoundException() extends RuntimeException(s"No hostname or aliases found !") with NoStackTrace
case class NoAliasesFoundException() extends RuntimeException(s"No aliases found in SSLContext !") with NoStackTrace
case class NoHostnameFoundException() extends RuntimeException(s"No hostname found in SSLContext !") with NoStackTrace
|
package com.refinedmods.refinedstorage.data.sync
import com.refinedmods.refinedstorage.data.sync.Syncable.Companion.byteBuffers
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.network.PacketByteBuf
import net.minecraft.util.Identifier
/**
* Watches underlying data for changes from the client, and
* sync's changes to the server. The client is the source of truth.
*/
class C2SSyncedData<T>(
identifier: Identifier,
isClient: Boolean,
internalData: T,
player: PlayerEntity
) : BiSyncedData<T>(identifier, isClient, internalData, player)
where T: Trackable<T>, T:SimpleObservable {
override fun send() {
if(!isClient) return
val byteBuffer = byteBuffers.buffer()
val buf = PacketByteBuf(byteBuffer)
internalData.getSerializer().write(buf, internalData)
getClientRegistry().sendToServer(identifier, buf)
}
override fun register() {
if(!isClient) getServerRegistry().register(identifier, this)
}
override fun unregister() {
if(!isClient) getServerRegistry().unregister(identifier)
}
}
|
/*
* Copyright (c) 2021 NetEase, Inc. All rights reserved.
* Use of this source code is governed by a MIT license that can be found in the LICENSE file.
*/
package com.netease.yunxin.app.wisdom.record.model
import androidx.annotation.IntDef
@IntDef(
NERecordEventType.MEMBER_JOIN,
NERecordEventType.MEMBER_LEAVE,
NERecordEventType.ENABLE_AUDIO,
NERecordEventType.DISABLE_AUDIO,
NERecordEventType.ENABLE_VIDEO,
NERecordEventType.DISABLE_VIDEO,
NERecordEventType.ENABLE_SUB_VIDEO,
NERecordEventType.DISABLE_SUB_VIDEO,
)
@kotlin.annotation.Retention(AnnotationRetention.SOURCE)
annotation class NERecordEventType {
companion object {
/**
* 成员进入房间
*/
const val MEMBER_JOIN = 1
/**
* 成员离开房间
*/
const val MEMBER_LEAVE = 2
/**
* 成员打开音频
*/
const val ENABLE_AUDIO = 3
/**
* 成员关闭音频
*/
const val DISABLE_AUDIO = 4
/**
* 成员打开视频
*/
const val ENABLE_VIDEO = 5
/**
* 成员关闭视频
*/
const val DISABLE_VIDEO = 6
/**
* 成员打开屏幕共享
*/
const val ENABLE_SUB_VIDEO = 7
/**
* 成员关闭屏幕共享
*/
const val DISABLE_SUB_VIDEO = 8
/**
* 上台
*/
const val HANDS_UP_ACCEPTED = 9
/**
* 下台
*/
const val HANDS_UP_NOT_ACCEPTED = 10
}
}
|
package catelyn
import "testing"
func Test_ConfluenceClient(t *testing.T) {
}
|
plugins {
id(GradlePluginId.ANDROID_DYNAMIC_FEATURE)
id(GradlePluginId.KOTLIN_ANDROID)
id(GradlePluginId.KOTLIN_ANDROID_EXTENSIONS)
id(GradlePluginId.SAFE_ARGS)
}
android {
compileSdkVersion(AndroidConfig.COMPILE_SDK_VERSION)
defaultConfig {
minSdkVersion(AndroidConfig.MIN_SDK_VERSION)
targetSdkVersion(AndroidConfig.TARGET_SDK_VERSION)
versionCode = AndroidConfig.VERSION_CODE
versionName = AndroidConfig.VERSION_NAME
testInstrumentationRunner = AndroidConfig.TEST_INSTRUMENTATION_RUNNER
}
buildTypes {
getByName(BuildType.RELEASE) {
isMinifyEnabled = BuildTypeRelease.isMinifyEnabled
proguardFiles("proguard-android.txt", "proguard-rules.pro")
}
getByName(BuildType.DEBUG) {
isMinifyEnabled = BuildTypeDebug.isMinifyEnabled
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = JavaVersion.VERSION_1_8.toString()
}
// This "test" source set is a fix for SafeArgs classes not being available when running Unit tests from cmd
// See: https://issuetracker.google.com/issues/139242292
sourceSets {
getByName("test").java.srcDir("${project.rootDir}/app/build/generated/source/navigation-args/debug")
}
// Removes the need to mock need to mock classes that may be irrelevant from test perspective
testOptions {
unitTests.isReturnDefaultValues = TestOptions.IS_RETURN_DEFAULT_VALUES
}
}
dependencies {
implementation(project(ModuleDependency.APP))
addTestDependencies()
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using UnityEngine;
namespace Epitome.LogSystem
{
public delegate void LogCall(string logLevel, string message);
public enum LogLevel
{
ALL, // 最低等级的,用于打开所有日志记录;
TRACE, // 比DEBUG更详细信息事件,很低的日志级别,一般不会使用;
DEBUG, // 主要用于开发过程中打印一些运行信息;
INFO, // 打印一些你感兴趣的或者重要的信息,这个可以用于生产环境中输出程序运行的一些重要信息;
WARN, // 表明会出现潜在错误的情形,给开发人员一些提示;
ERROR, // 虽然发生错误事件,但仍然不影响系统的继续运行,打印错误和异常信息;
FATAL, // 指出每个严重的错误事件将会导致应用程序的退出,重大错误,可以直接停止程序;
OFF, // 最高等级的,用于关闭所有日志记录;
}
public struct LogData
{
public string logID; // 日志ID
public LogLevel logLevel; // 日志级别
public DateTime logTime; // 日志时间
public object logMessage; // 日志消息
public string logBasicData; // 日志基础数据
public string logTrack; // 日志堆栈信息
}
public interface ILogAppender
{
void Log(LogData data);
}
public class AsyncTask<T> : MonoSingleton<T> where T : AsyncTask<T>
{
private void Start()
{
Run();
}
protected override void OnDestroy()
{
Close();
base.OnDestroy();
}
public virtual void Close() { }
public virtual void Run() { }
}
public enum AppenderType
{
File, // 文件输出
GUI, // GUI输出(用于电脑端)
MobileGUI, // 移动GUI输出(用于手机端)
Console, // 控制台输出
Window, // 窗口输出
}
public class Logging : Singleton<Logging>
{
private Dictionary<AppenderType, ILogAppender> allAppender;
private List<ILogAppender> appenders;
public bool EnableLog { get; set; }
public LogLevel logLevel { get; set; }
public LogSystemAsset logSystemAsset { get; private set; }
private List<LogLevel> ignoreLevel;
private Logging()
{
allAppender = new Dictionary<AppenderType, ILogAppender>();
appenders = new List<ILogAppender>();
ignoreLevel = new List<LogLevel>();
logSystemAsset = Resources.Load<LogSystemAsset>("LogSystemAsset");
}
private StackTrace StackTrace
{
get { return new StackTrace(3, true); }
}
public void LoadAppenders(ILogAppender appender)
{
if (appenders.Contains(appender)) return;
appenders.Add(appender);
}
public void UnloadAppenders(ILogAppender appender)
{
if (!appenders.Contains(appender)) return;
appenders.Remove(appender);
}
public void UnloadAppenders(AppenderType type)
{
if (!allAppender.ContainsKey(type)) return;
UnloadAppenders(allAppender.GetValue(type));
}
public void SetLogCall(LogCall logCall) { }
/// <summary>
/// For these added level, the log does not do output.(Except for error output)
/// </summary>
/// <param name="level"></param>
public void IgnoreLevel(LogLevel level)
{
if (!ignoreLevel.Contains(level))
ignoreLevel.Add(level);
}
public void UnIgnoreLevel(LogLevel level)
{
if (ignoreLevel.Contains(level))
ignoreLevel.Remove(level);
}
private bool IsOutputLog(LogLevel level)
{
if (!EnableLog || (int)logLevel > (int)level || ignoreLevel.Contains(level)) return false;
return true;
}
private string GetParameters(System.Reflection.MethodBase methodBase)
{
StringBuilder builder = new StringBuilder(1);
foreach (var item in methodBase.GetParameters())
{
builder.Append(item.ParameterType.Name);
}
return builder.ToString();
}
private string GetRelativePath(string path)
{
path = path.Substring(path.IndexOf("Assets"));
path = path.Replace('\\', '/');
return path;
}
private string GetBriefnessTrack(StackFrame frame)
{
return string.Format("{0}:{1}({2}) (at {3}:{4,3})",
frame.GetMethod().DeclaringType.Name,
frame.GetMethod().Name,
GetParameters(frame.GetMethod()),
GetRelativePath(frame.GetFileName()),
frame.GetFileLineNumber());
}
private string TrackFormatting(StackTrace stackTrace)
{
StringBuilder builder = new StringBuilder(120);
foreach (var item in stackTrace.GetFrames())
{
builder.Append(string.Format(GetBriefnessTrack(item))).Append("\r\n");
}
return builder.ToString();
}
private string GetExceptionTrack(Exception e)
{
StringBuilder builder = new StringBuilder(120);
builder.Append("Error:" + e.Message).Append("\r\n");
if (!string.IsNullOrEmpty(e.StackTrace))
{
builder.Append(e.StackTrace);
}
return builder.ToString();
}
private void LogRecord(LogLevel level, object message, string track = "")
{
if (!IsOutputLog(level)) return;
LogData data = new LogData();
data.logTime = DateTime.Now;
data.logLevel = level;
data.logMessage = message;
data.logBasicData = GetBriefnessTrack(StackTrace.GetFrame(1));
data.logTrack = track;
for (int i = 0; i < appenders.Count; i++)
{
appenders[i].Log(data);
}
}
public void Trace(object message)
{
LogRecord(LogLevel.TRACE, message, TrackFormatting(StackTrace));
}
public void Trace(string format, params object[] args)
{
LogRecord(LogLevel.TRACE, string.Format(format, args), TrackFormatting(StackTrace));
}
public void Debug(object message)
{
LogRecord(LogLevel.DEBUG, message, TrackFormatting(StackTrace));
}
public void Debug(string format, params object[] args)
{
LogRecord(LogLevel.DEBUG, string.Format(format, args), TrackFormatting(StackTrace));
}
public void Debug(object message, string track)
{
LogRecord(LogLevel.DEBUG, message, track);
}
public void Debug(object message, Exception e)
{
LogRecord(LogLevel.DEBUG, message, GetExceptionTrack(e));
}
public void Info(object message)
{
LogRecord(LogLevel.INFO, message);
}
public void Info(string format, params object[] args)
{
LogRecord(LogLevel.INFO, string.Format(format, args), TrackFormatting(StackTrace));
}
public void Info(object message, string track)
{
LogRecord(LogLevel.INFO, message, track);
}
public void Info(object message, Exception e)
{
LogRecord(LogLevel.INFO, message, GetExceptionTrack(e));
}
public void Warn(object message)
{
LogRecord(LogLevel.WARN, message, TrackFormatting(StackTrace));
}
public void Warn(string format, params object[] args)
{
LogRecord(LogLevel.WARN, string.Format(format, args), TrackFormatting(StackTrace));
}
public void Warn(object message, string track)
{
LogRecord(LogLevel.WARN, message, track);
}
public void Warn(object message, Exception e)
{
LogRecord(LogLevel.WARN, message, GetExceptionTrack(e));
}
public void Error(object message)
{
LogRecord(LogLevel.ERROR, message, TrackFormatting(StackTrace));
}
public void Error(string format, params object[] args)
{
LogRecord(LogLevel.ERROR, string.Format(format, args), TrackFormatting(StackTrace));
}
public void Error(object message, string track)
{
LogRecord(LogLevel.ERROR, message, track);
}
public void Error(object message, Exception e)
{
LogRecord(LogLevel.ERROR, message, GetExceptionTrack(e));
}
public void Fatal(object message)
{
LogRecord(LogLevel.FATAL, message, TrackFormatting(StackTrace));
}
public void Fatal(string format, params object[] args)
{
LogRecord(LogLevel.FATAL, string.Format(format, args), TrackFormatting(StackTrace));
}
public void Fatal(object message, string track)
{
LogRecord(LogLevel.FATAL, message, track);
}
public void Fatal(object message, Exception e)
{
LogRecord(LogLevel.FATAL, message, GetExceptionTrack(e));
}
}
}
|
# $Id: 35_SWAP_0000002200000008.pm 10297 2015-12-29 19:04:09Z justme1968 $
package main;
use strict;
use warnings;
use constant { REG_DESIRED => '0D',
REG_TEXT => '0E', };
sub
SWAP_0000002200000008_Initialize($)
{
my ($hash) = @_;
require "$attr{global}{modpath}/FHEM/34_SWAP.pm";
$hash->{SWAP_SetFn} = "SWAP_0000002200000008_Set";
$hash->{SWAP_SetList} = { desired => 1,
text => undef, };
#$hash->{SWAP_GetFn} = "SWAP_0000002200000008_Get";
#$hash->{SWAP_GetList} = { };
#$hash->{SWAP_ParseFn} = "SWAP_0000002200000008_Parse";
my $ret = SWAP_Initialize($hash);
return $ret;
}
sub
SWAP_0000002200000008_Parse($$$$)
{
my ($hash, $reg, $func, $data) = @_;
my $name = $hash->{NAME};
}
sub
SWAP_0000002200000008_Set($@)
{
my ($hash, $name, $cmd, $arg, $arg2, $arg3) = @_;
if( $cmd eq "desired" ) {
$arg += 50;
$arg *= 10;
my $value = sprintf( "%04X", int($arg) );
return( "regSet", REG_DESIRED, $value );
} elsif( $cmd eq "text" ) {
my $text = "000000000000000000000000000000000000000000000000";
$arg .= " ". $arg2 if( defined($arg2) );
$arg .= " ". $arg3 if( defined($arg3) );
for( my $i = 0; $i < length($arg); ++$i) {
last if( $i >= 18 );
substr( $text, 2*$i, 2, sprintf( "%02X", ord(substr($arg, $i, 1) ) ) );
}
return( "regSet", REG_TEXT, "FFFE" . "02" . $text );
}
return undef;
}
sub
SWAP_0000002200000008_Get($@)
{
my ($hash, $name, $cmd, @a) = @_;
return undef;
}
1;
=pod
=begin html
<a name="SWAP_0000002200000008"></a>
<h3>SWAP_0000002200000008</h3>
<ul>
Module for the justme version of the panstamp indoor multi sensor board (sketch product code 0000002200000008).
<br><br>
<a name="SWAP_0000002200000008_Define"></a>
<b>Define</b>
<ul>
<code>define <name> SWAP_0000002200000008 <ID> 0000002200000008</code> <br>
<br>
</ul>
<br>
<a name="SWAP_0000002200000008_Set"></a>
<b>Set </b>
all SWAP set commands and:
<ul>
<li>desired <value><br>
sets the desired temperature to <value></li>
<li>text <text><br>
displays text</li>
</ul><br>
<a name="SWAP_0000002200000008_Get"></a>
<b>Get</b>
all SWAP get commands and:
<ul>
</ul><br>
<a name="SWAP_0000002200000008_Attr"></a>
<b>Attributes</b>
<ul>
<li>ProductCode<br>
must be 0000002200000008</li><br>
</ul><br>
</ul>
=end html
=cut
|
// ======================================================================
// Copyright (c) 2016 by Vladimir Bespalov
// ======================================================================
#include "rsprotocolworker.h"
#include "./../rssockets/udpsocket.h"
#include "./../rssockets/tcpsocket.h"
RsProtocolWorker::RsProtocolWorker(QObject *parent)
: QObject(parent)
{
stateSocket = new UdpSocket();
ctrlSocket = new TcpSocket();
QObject::connect(
this, SIGNAL(setStatePort(quint16)),
stateSocket, SLOT(listen(quint16)));
QObject::connect(
stateSocket, SIGNAL(datagramReceived(QByteArray*)),
this, SIGNAL(statePacketReceived(QByteArray*)));
QObject::connect(
stateSocket, SIGNAL(logMessage(const QString&)),
this, SIGNAL(logMessage(const QString&)));
QObject::connect(
this, SIGNAL(setCtrlHost(const QString&, quint16)),
ctrlSocket, SLOT(connect2Host(const QString&, quint16)));
QObject::connect(
this, SIGNAL(writeCtrlPacket(QByteArray*)),
ctrlSocket, SLOT(writePacket(QByteArray*)));
QObject::connect(ctrlSocket, SIGNAL(connected()), this, SIGNAL(connected()));
QObject::connect(ctrlSocket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
QObject::connect(
ctrlSocket, SIGNAL(logMessage(const QString&)),
this, SIGNAL(logMessage(const QString&)));
}
RsProtocolWorker::~RsProtocolWorker()
{
delete stateSocket;
delete ctrlSocket;
}
|
---
ms.openlocfilehash: c22a264f98abca9df34427fc35f972e6bbcde518
ms.sourcegitcommit: ad203331ee9737e82ef70206ac04eeb72a5f9c7f
ms.translationtype: MT
ms.contentlocale: nb-NO
ms.lasthandoff: 06/18/2019
ms.locfileid: "67217739"
---
Tilgang til Azure Active Directory Authentication Library (ADAL).
|
<?php
Class MProducao extends CI_Model
{
public function get($id)
{
$this->db->select('*');
$this->db->from('view_producao');
$this->db->where('id_producao', $id);
$query = $this->db->get();
return $query->row_array();
}
public function getByProfessor($id)
{
$this->db->select('*');
$this->db->from('view_producao');
$this->db->where('fk_professor', $id);
$this->db->order_by('data_producao','DESC');
$query = $this->db->get();
return $query->result_array();
}
public function getPendentDocument($id, $iniciodata, $fimdata)
{
$this->db->select('*');
$this->db->from('view_producao');
$this->db->where('fk_professor', $id);
$this->db->where('data_producao >', $iniciodata);
$this->db->where('data_producao <', $fimdata);
$this->db->order_by('data_producao','DESC');
$query = $this->db->get();
return $query->result_array();
}
public function getFromInterval($idprofessor, $iniciodata, $fimdata)
{
$this->db->select('*');
$this->db->from('view_producao');
$this->db->where('fk_professor', $idprofessor);
$this->db->where('data_producao >', $iniciodata);
$this->db->where('data_producao <', $fimdata);
$this->db->order_by('pontuacao_producao','desc');
$query = $this->db->get();
return $query->result_array();
}
public function getAllByItem($idprofessor, $iditem)
{
$this->db->select('*');
$this->db->from('view_producao');
$this->db->where('fk_professor', $idprofessor);
$this->db->where('id_item', $iditem);
$query = $this->db->get();
return $query->result_array();
}
public function insert($data)
{
if ($this->db->insert('tb_producao',$data))
{
return $this->db->insert_id();
}
else
{
return false;
}
}
public function updatefield($key, $col, $val)
{
$this->db->set($col, $val);
$this->db->where('id_producao', $key);
$this->db->update('tb_producao');
}
public function delete($id)
{
return $this->db->delete('tb_producao', array('id_producao' => $id ));
}
}
?>
|
{--
https://wiki.haskell.org/Euler_problems/51_to_60#Problem_60
Prime except 3 is congruent to 1 or 2 modulo 3.
If mod 1 primes is combined to mod 2 primes, it's divided by 3.
So, we can combine mod 1 with mod 1, or mod 2 with mod 2.
$ time ./60
26033
real 0m0.473s
user 0m0.470s
sys 0m0.000s
--}
module WikiEuler60 (wikiE60Solve) where
import Data.Char (digitToInt)
import MillerRabin (millerRabinPrimality)
wikiE60Solve :: Integer
wikiE60Solve = sum . head . solve . primesOfMod $ 1
solve :: [Integer] -> [[Integer]]
solve ps = do
a <- ps
let m = f a $ dropWhile (<= a) ps
b <- m
let n = f b $ dropWhile (<= b) m
c <- n
let o = f c $ dropWhile (<= c) n
d <- o
let p = f d $ dropWhile (<= d) o
e <- p
return [a, b, c, d, e]
where
f x = filter (\y -> isPrime (read $ shows x $ show y) && isPrime (read $ shows y $ show x))
isPrime :: Integer -> Bool
isPrime x
| x == 3 = True
| otherwise = and [millerRabinPrimality x n | n <- [2,3]]
primesOfMod :: Int -> [Integer]
primesOfMod m = 3 : filter (\p -> isPrime p && digitSum p `mod` 3 == m) [5,7..9999]
digitSum :: Integer -> Int
digitSum = sum . map digitToInt . show
|
//
// CocoaPhoenix.hpp
// CocoaPhoenix
//
// Created by Bodie Solomon on 3/6/19.
//
// TODO: Refactor docs
// High-level overview
//
// PHXViewController owns the UI-facing components and the Phoenix object.
// The Phoenix object owns all internal Phoenix components and provides
// C++ interfaces, which are wrapped in Objective-C++ event handlers for use by
// the UI components.
//
// PHXViewController -viewDidLoad obtains a factory using its class method
// getPhoenixFactory. This method should be overridden by a user who wants to
// supply their own Game class or other classes, by returning the user's
// implementation of the PhoenixFactory protocol.
//
// Optionally, they may extend PHXDefaultFactory to implement only some of its
// methods, all of which are called from PHXViewController -viewDidLoad.
// Detailed overview
//
// Graphics/MetalGfx is the C++ interface to Phoenix, which is owned and
// controlled by Phoenix.
//
// PHXMetalRenderer is the Objective-C++ interface to Metal, which controls the
// Metal API internally. It is manipulated only by Phoenix, through the
// MetalGfx interface.
//
// In order to provide a MTKViewDelegate and NSResponder so UI events can be
// handled, two Objective-C++ interfaces to Phoenix need to be provided, which
// interface directly with Phoenix, not its owned objects.
//
// This is the job of the CocoaPhoenix framework. CocoaPhoenix provides three
// interfaces, for both Objective-C++ and Swift:
//
// PHXViewController implements NSViewController/UIViewController depending on
// platform. It pauses any work the render thread depends on and draws the view
// as necessary.
//
// PHXResponder implements NSResponder/UIResponder depending on platform. UI
// events are passed to the Input handle of Phoenix by calling its internal
// methods, which parse UI events into input events passed to Phoenix.
//
// PHXViewDelegate implements MTKViewDelegate by calling the appropriate methods
// on an internal reference to the Phoenix object.
#ifndef CocoaPhoenix_hpp
#define CocoaPhoenix_hpp
// PHXApplePrelude.hpp contains the necessary Apple framework @imports and
// definitions to use the CocoaPhoenix UI components.
#import "PHXApplePrelude.hpp"
// PHXCocoaClassNames contains forward declarations of CocoaPhoenix names.
#import "PHXCocoaClassNames.hpp"
//// PHXCoreIncludes.hpp includes the core C++ Phoenix classes.
//#import "PHXCoreIncludes.hpp"
// PHXCppWrappers.hpp defines the pure-C++ wrappers for native Objective-C++
// interfaces which allow them to be used in the core Phoenix engine.
#import "PHXCppWrappers.hpp"
// PHXCoreIncludes.hpp includes the core C++ Phoenix classes.
#import "PHXCoreIncludes.hpp"
// PHXCocoaTemplates defines names for instantiated Phoenix templates using
// CocoaPhoenix interfaces and protocols. This reduces the need for
// CocoaPhoenix classes to use C++ template features.
#import "PHXCocoaTemplates.hpp"
// PHXCocoaClassDefs defines the real interfaces and protocols implemented by
// CocoaPhoenix.
#import "PHXCocoaClassDefs.hpp"
#endif /* CocoaPhoenix_hpp */
|
#ifndef INCLUDE_NAN_HPP
#define INCLUDE_NAN_HPP
// nan
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wcast-function-type"
#include <nan.h>
#pragma GCC diagnostic pop
#endif // INCLUDE_NAN_HPP
|
import React, { useEffect } from 'react';
import { Redirect } from 'react-router-dom';
const Logout = ({ logoutFunc }) => {
useEffect(() => {
logoutFunc()
});
return (
//<div>
// LOGOUT
//</div>
<Redirect to="/" />
);
};
export default Logout;
|
use crate::rayt::*;
struct SimpleScene {}
impl SimpleScene {
fn hit_sphere(&self, center: Point3, radius: f64, ray: &Ray) -> f64 {
let oc = ray.origin - center;
let a = ray.direction.dot(ray.direction);
let b = 2.0 * ray.direction.dot(oc);
let c = oc.dot(oc) - radius.powi(2);
let d = b * b - 4.0 * a * c;
if d < 0.0 {
-1.0
} else {
return (-b - d.sqrt()) / (2.0 * a);
}
}
fn background(&self, d: Vec3) -> Color {
let t = 0.5 * (d.normalize().y() + 1.0);
Color::one().lerp(Color::new(0.5, 0.7, 1.0), t)
}
}
impl Scene for SimpleScene {
fn camera(&self) -> Camera {
Camera::new(
Vec3::new(4.0, 0.0, 0.0),
Vec3::new(0.0, 2.0, 0.0),
Vec3::new(-2.0, -1.0, -1.0),
)
}
fn trace(&self, ray: Ray) -> Color {
let c = Point3::new(0.0, 0.0, -1.0);
let t = self.hit_sphere(c, 0.5, &ray);
if t > 0.0 {
let n = (ray.at(t) - c).normalize();
return 0.5 * (n + Vec3::one());
}
self.background(ray.direction)
}
}
pub fn run() {
render(SimpleScene {});
}
|
<?php
spl_autoload_register('_common_autoloader');
/**
* Automatically loads classes in PHP5 way, using SPL.
* @param string $class The class name, no namespaces are supported.
* @return bool TRUE if a class have been found and loaded, FALSE otherwise.
* @author Ivan Tcholakov, 2013-2020
* @license The MIT License
*/
function _common_autoloader($class) {
$class = (string) $class;
// No class name? Abort.
if ($class == '') {
return false;
}
// Autoload custom classes, non-standard way.
if (is_file($location = APPPATH."Classes/$class.php")) {
require $location;
return true;
}
if (is_file($location = COMMONPATH."Classes/$class.php")) {
require $location;
return true;
}
// PSR-0 autoloading.
if (is_file($location = APPPATH.'Classes/'.str_replace(array('_', '\\'), DIRECTORY_SEPARATOR, $class).'.php')) {
require $location;
return true;
}
if (is_file($location = COMMONPATH.'Classes/'.str_replace(array('_', '\\'), DIRECTORY_SEPARATOR, $class).'.php')) {
require $location;
return true;
}
// Autoload PEAR packages that are integrated in this platform.
if (is_file($location = COMMONPATH.'ThirdParty/Pear/'.str_replace('_', DIRECTORY_SEPARATOR, $class).'.php')) {
require $location;
return true;
}
return false;
}
|
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<title>Email Template</title>
<style>
body{
color:#424141;
font-size:12px;
text-align:left;
margin:10px;
font-family:sans-serif;
}
</style>
</head>
<body>
<?php include("include/analyticstracking.php"); ?>
<table width='65%' border='0' cellspacing='2' cellpadding='5'>
<tr>
<th colspan='2' align='left' scope='row'><strong>Contact Lead from Team Computers Pvt. Ltd</strong></th>
</tr>
<tr>
<th colspan='2' align='left' scope='row'> </th>
</tr>
<tr>
<th width='21%' align='left' scope='row'>Name</th>
<td width='79%' align='left'>: <?php echo $name; ?></td>
</tr>
<tr>
<th align='left' scope='row'>Contact</th>
<td align='left'>: <?php echo $contact; ?></td>
</tr>
<tr>
<th align='left' scope='row'>Email</th>
<td align='left'>: <?php echo $email; ?></td>
</tr>
<tr>
<th align='left' scope='row'>Your Organisation</th>
<td align='left'>: <?php echo $organisation; ?></td>
</tr>
<tr>
<th align='left' scope='row'>Message</th>
<td align='left' valign="top">: <?php echo $message; ?></td>
</tr>
<tr>
<th colspan='2' align='left' scope='row'> </th>
</tr>
<tr>
<th colspan='2' align='left' scope='row'>
- Support Team <br>Team Computers Pvt. Ltd
</th>
</tr>
<tr>
<td colspan='2' align='left' scope='row'> </td>
</tr>
</table>
</body>
</html>
|
module Wobapphelpers
module Helpers
autoload :IconHelper, 'wobapphelpers/helpers/icon_helper.rb'
autoload :ActionViewHelper, 'wobapphelpers/helpers/action_view_helper.rb'
autoload :PolymorphicHelper, 'wobapphelpers/helpers/polymorphic_helper.rb'
# one module to rule all
module All
include IconHelper
include ActionViewHelper
# PolymorphicHelper must be explicit included
end
end
end
|
# frozen_string_literal: true
require 'descriptive_statistics'
require 'reverse_markdown'
require 'nokogiri-styles'
require 'premailer'
require 'rbconfig'
require 'nokogiri'
require 'logger'
require 'tmpdir'
require 'cliver'
require 'open3'
require_relative 'word-to-markdown/version'
require_relative 'word-to-markdown/document'
require_relative 'word-to-markdown/converter'
require_relative 'nokogiri/xml/element'
require_relative 'cliver/dependency_ext'
class WordToMarkdown
attr_reader :document, :converter
# Options to be passed to Reverse Markdown
REVERSE_MARKDOWN_OPTIONS = {
unknown_tags: :bypass,
github_flavored: true
}.freeze
# Minimum version of LibreOffice Required
SOFFICE_VERSION_REQUIREMENT = '> 4.0'
# Paths to look for LibreOffice, in order of preference
PATHS = [
'*', # Sub'd for ENV["PATH"]
'~/Applications/LibreOffice.app/Contents/MacOS',
'/Applications/LibreOffice.app/Contents/MacOS',
'/Program Files/LibreOffice 5/program',
'/Program Files (x86)/LibreOffice 4/program'
].freeze
# Create a new WordToMarkdown object
#
# @param path [string] Path to the Word document
# @param tmpdir [string] Path to a working directory to use
# @return [WordToMarkdown] WordToMarkdown object with the converted document
def initialize(path, tmpdir = nil)
@document = WordToMarkdown::Document.new path, tmpdir
@converter = WordToMarkdown::Converter.new @document
converter.convert!
end
# Helper method to return the document body, as markdown
# @return [string] the document body, as markdown
def to_s
document.to_s
end
class << self
# Run an soffice command
#
# @param args [string] one or more arguments to pass to the sofice command
# @return [string] the command output
def run_command(*args)
raise 'LibreOffice already running' if soffice.open?
output, status = Open3.capture2e(soffice.path, *args)
logger.debug output
raise "Command `#{soffice.path} #{args.join(' ')}` failed: #{output}" if status.exitstatus != 0
output
end
# Returns a Cliver::Dependency object representing our soffice dependency
#
# Attempts to resolve by looking at PATH followed by paths in the PATHS constant
#
# Methods used internally:
# path - returns the resolved path. Raises an error if not satisfied
# version - returns the resolved version
# open - is the dependency currently open/running?
# @return Cliver::Dependency instance
def soffice
@soffice ||= Cliver::Dependency.new('soffice', *soffice_dependency_args)
end
# @return Logger instance
def logger
@logger ||= begin
logger = Logger.new(STDOUT)
logger.level = Logger::ERROR unless ENV['DEBUG']
logger
end
end
private
# Workaround for two upstream bugs:
# 1. `soffice.exe --version` on windows opens a popup and retuns a null string when manually closed
# 2. Even if the second argument to Cliver is nil, Cliver thinks there's a requirement
# and will shell out to `soffice.exe --version`
# In order to support Windows, don't pass *any* version requirement to Cliver
def soffice_dependency_args
args = [path: PATHS.join(File::PATH_SEPARATOR)]
if Gem.win_platform?
args
else
args.unshift SOFFICE_VERSION_REQUIREMENT
end
end
end
end
|
<?php
namespace App\Http\Models;
class Category extends BaseModel{
protected $primaryKey = 'id';
protected $table = 'categories';
protected $fillable = array('name','created_at_ip','updated_at_ip');
}
|
#!/bin/sh -e
echo 'rke up!'
# ubuntu user needs access to the vagrant group to the access shared folder
sudo usermod -a -G vagrant ubuntu
sudo chmod 774 /usr/local/etc
su ubuntu -c '/opt/bin/rke up --config /usr/local/etc/cluster.yml'
|
;; envelopes.lsp -- support functions for envelope editor in jNyqIDE
#| In Nyquist, editable envelopes are saved as one entry in the workspace
named *envelopes*. The entry is an association list where each element
looks like this:
(name type parameters... )
where name is a symbol, e.g. MY-ENVELOPE-1,
type is a function name, e.g. PWL, PWLV, PWE, etc., and
parameters are breakpoint data, e.g. 0.1 1 0.2 0.5 1
Example of two envelopes named FOO and BAR:
((FOO PWL 0.1 1 1) (BAR PWE 0.2 1 1))
To convert envelope data into functions, call (MAKE-ENV-FUNCTIONS).
This function should be on the workspace's list of functions to call.
(See ADD-ACTION-TO-WORKSPACE in Nyquist Manual.)
When the jNyqIDE wants to get the envelope data from the workspace, it
should call (GET-ENV-DATA), which will dump formatted data to Nyquist's
standard output as follows:
get-env-data: begin
name (type parameters...) newline
name (type parameters...) newline
...
get-env-data: end
When the IDE wants to save a definition, it should call
(DEFINE-ENV 'NAME 'EXPRESSION)
To delete a definition, call:
(DELETE-ENV 'NAME)
Envelope data will be loaded when the editor window is opened and saved
whenever the user issues a "save" command. If the user switches envelopes
without saving, there is a prompt to save or ignore.
The user will also be prompted to save when the editor window is closed
or when Nyquist is exited.
Saving the workspace automatically is something that Nyquist should do
(or prompt the user to do) when it exits.
|#
;; WORKSPACE -- the workspace is just a set of variables, typically
;; with scores as values. These are stored in the file workspace.lsp
;; so that you can work on some data and then store it for use later.
(cond ((not (boundp '*workspace*))
(setf *workspace* nil)))
(cond ((not (boundp '*workspace-actions*))
(setf *workspace-actions* nil)))
;; one of the variables in the workspace is *envelopes*
(cond ((not (boundp '*envelopes*))
(setf *envelopes* nil)))
;; DESCRIBE -- add a description to a global variable
;;
(defun describe (symbol &optional description)
(add-to-workspace symbol)
(cond (description
(putprop symbol description 'description))
(t
(get symbol 'description))))
;; ADD-TO-WORKSPACE -- add a global symbol to workspace
;;
(defun add-to-workspace (symbol)
(cond ((not (symbolp symbol))
(format t "add-to-workspace expects a (quoted) symbol~%"))
((not (member symbol *workspace*))
(push symbol *workspace*))))
;; ADD-ACTION-TO-WORKSPACE -- call function when workspace is loaded
;;
(defun add-action-to-workspace (symbol)
(cond ((not (symbolp symbol))
(format t "add-action-to-workspace expects a (quoted) symbol~%"))
((not (member symbol *workspace-actions*))
(push symbol *workspace-actions*))))
;; SAVE-WORKSPACE -- write data to file
;;
(defun save-workspace ()
(let (val (outf (open "workspace.lsp" :direction :output)))
(dolist (sym *workspace*)
(format outf "(add-to-workspace '~A)~%" sym)
(cond ((get sym 'description)
(format outf "(putprop '~A \"~A\" 'description)~%"
sym (get sym 'description))))
(format outf "(setf ~A '" sym)
(setf val (symbol-value sym))
(cond ((listp val)
(format outf "(~%")
(dolist (elem val)
(format outf " ~A~%" elem))
(format outf " ))~%~%"))
(t
(format outf "~A)~%~%" val))))
(dolist (sym *workspace-actions*) ;; call hooks after reading data
(format outf "(add-action-to-workspace '~A)~%" sym)
(format outf "(if (fboundp '~A) (~A))~%" sym sym))
(format outf "(princ \"workspace loaded\\n\")~%")
(close outf)
(princ "workspace saved\n")
nil))
;; DEFINE-ENV -- save the env data and make corresponding function
;;
(defun define-env (name expression)
(delete-env name)
(push (cons name expression) *envelopes*)
(make-env-function name expression)
; make sure envelopes are redefined when workspace is loaded
(add-to-workspace '*envelopes*) ; so *envelopes* will be saved
(describe '*envelopes* "data for envelope editor in jNyqIDE")
(add-action-to-workspace 'make-env-functions)
nil)
;; DELETE-ENV -- delete an envelope definition from workspace
;;
;; note that this will not undefine the corresponding envelope function
;;
(defun delete-env (name)
(setf *envelopes*
(remove name *envelopes*
:test #'(lambda (key item) (eql key (car item))))))
;; MAKE-ENV-FUNCTION -- convert data to a defined function
;;
(defun make-env-function (name expression)
(setf (symbol-function name)
(eval (list 'lambda '() expression))))
;; MAKE-ENV-FUNCTIONS -- convert data to defined functions
;;
(defun make-env-functions ()
(let (name type parameters)
(dolist (env *envelopes*)
(setf name (car env))
(setf type (cadr env))
(setf parameters (cddr env))
(make-env-function name (cons type parameters)))))
;; GET-ENV-DATA -- print env data for IDE
;;
(defun get-env-data ()
(princ "get-env-data: begin\n")
(dolist (env *envelopes*)
(format t "~A ~A~%" (car env) (cdr env)))
(princ "get-env-data: end\n")
nil)
|
use std::process::{self, Child, Stdio};
use std::io::{self, BufRead, BufReader, Error, ErrorKind, Write};
use std::ffi::OsStr;
use std::thread;
/// Convenient wrapper around `process::Command` to make it easier to work with.
pub struct Command<'a> {
cmd: process::Command,
stdin: Option<&'a str>,
}
impl<'a> Command<'a> {
pub fn new<S: AsRef<OsStr>>(program: S) -> Self {
Command { cmd: process::Command::new(program), stdin: None }
}
pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command<'a> {
self.cmd.arg(arg);
self
}
pub fn args<S: AsRef<OsStr>, I: IntoIterator<Item = S>>(&mut self, args: I) -> &mut Command<'a> {
self.cmd.args(args);
self
}
pub fn env(&mut self, key: &str, value: &str) -> &mut Command<'a> {
self.cmd.env(key, value);
self
}
pub fn env_clear(&mut self) {
self.cmd.env_clear();
}
pub fn stdin(&mut self, stdio: Stdio) { self.cmd.stdin(stdio); }
pub fn stderr(&mut self, stdio: Stdio) { self.cmd.stderr(stdio); }
pub fn stdout(&mut self, stdio: Stdio) { self.cmd.stdout(stdio); }
fn redirect<R: io::Read + Send + 'static, F: FnMut(&str) + Send + 'static>(
reader: Option<R>,
mut writer: F
) {
if let Some(reader) = reader {
let mut reader = BufReader::new(reader);
thread::spawn(move || {
let buffer = &mut String::with_capacity(8 * 1024);
loop {
buffer.clear();
match reader.read_line(buffer) {
Ok(0) | Err(_) => break,
Ok(_) => writer(buffer.trim_right())
}
}
});
}
}
/// Run the program, check the status, and get the output of `stdout`
pub fn stdin_input(mut self, input: &'a str) -> Self {
self.stdin = Some(input);
self.stdin(Stdio::piped());
self
}
pub fn stdin_redirect(&mut self, child: &mut Child) -> io::Result<()> {
match self.stdin {
Some(input) => child.stdin.as_mut().unwrap().write_all(input.as_bytes()),
None => Ok(())
}
}
pub fn run_with_stdout(&mut self) -> io::Result<String> {
let cmd = format!("{:?}", self.cmd);
info!("running {}", cmd);
self.cmd.stdout(Stdio::piped());
let mut child = self.cmd.spawn()
.map_err(|why| Error::new(
why.kind(),
format!("failed to spawn process {}: {}", cmd, why)
))?;
self.stdin_redirect(&mut child)?;
child.wait_with_output()
.map_err(|why| Error::new(
why.kind(),
format!("failed to get output of {}: {}", cmd, why)
))
.and_then(|output| {
String::from_utf8(output.stdout)
.map_err(|why| Error::new(
ErrorKind::Other,
format!("command output has invalid UTF-8: {}", why)
))
})
}
/// Run the program and check the status.
pub fn run(&mut self) -> io::Result<()> {
let cmd = format!("{:?}", self.cmd);
info!("running {}", cmd);
let mut child = self.cmd.spawn()
.map_err(|why| Error::new(
why.kind(),
format!("failed to spawn process {}: {}", cmd, why)
))?;
self.stdin_redirect(&mut child)?;
Self::redirect(child.stdout.take(), |msg| info!("{}", msg));
Self::redirect(child.stderr.take(), |msg| warn!("{}", msg));
let status = child.wait()
.map_err(|why| Error::new(
why.kind(),
format!("failed to wait for process {}: {}", cmd, why)
))?;
if status.success() {
Ok(())
} else if let Some(127) = status.code() {
Err(io::Error::new(
io::ErrorKind::NotFound,
format!("command {} was not found", cmd)
))
} else {
Err(io::Error::new(
io::ErrorKind::Other,
format!("command failed with exit status: {}", status)
))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn command_not_found() {
assert!(Command::new("asdfasdf").run().unwrap_err().kind() == io::ErrorKind::NotFound);
}
#[test]
fn command_with_output() {
assert_eq!(
Command::new("echo")
.arg("Hello, Command!")
.run_with_stdout()
.unwrap(),
"Hello, Command!\n".to_owned()
);
}
}
|
<?php
namespace App\Http\Controllers\Admin\Tags;
use App\Repositories\TagRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class ListTagController extends Controller
{
private $tagRepository;
public function __construct(TagRepository $tagRepository)
{
$this->tagRepository = $tagRepository;
}
public function show(){
return view('admin.tags.list')->with([
'tags' => $this->tagRepository->getAll()
]);
}
}
|
// GlennHa 1/23/06
//<Snippet1>
using System;
using System.Reflection;
using System.Security.Permissions;
[assembly:AssemblyVersionAttribute("1.0.2000.0")]
public class Example
{
private int factor;
public Example(int f)
{
factor = f;
}
public int SampleMethod(int x)
{
Console.WriteLine("\nExample.SampleMethod({0}) executes.", x);
return x * factor;
}
public static void Main()
{
Assembly assem = typeof(Example).Assembly;
Console.WriteLine("Assembly Full Name:");
Console.WriteLine(assem.FullName);
// The AssemblyName type can be used to parse the full name.
AssemblyName assemName = assem.GetName();
Console.WriteLine("\nName: {0}", assemName.Name);
Console.WriteLine("Version: {0}.{1}",
assemName.Version.Major, assemName.Version.Minor);
Console.WriteLine("\nAssembly CodeBase:");
Console.WriteLine(assem.CodeBase);
// Create an object from the assembly, passing in the correct number
// and type of arguments for the constructor.
Object o = assem.CreateInstance("Example", false,
BindingFlags.ExactBinding,
null, new Object[] { 2 }, null, null);
// Make a late-bound call to an instance method of the object.
MethodInfo m = assem.GetType("Example").GetMethod("SampleMethod");
Object ret = m.Invoke(o, new Object[] { 42 });
Console.WriteLine("SampleMethod returned {0}.", ret);
Console.WriteLine("\nAssembly entry point:");
Console.WriteLine(assem.EntryPoint);
}
}
/* This code example produces output similar to the following:
Assembly Full Name:
source, Version=1.0.2000.0, Culture=neutral, PublicKeyToken=null
Name: source
Version: 1.0
Assembly CodeBase:
file:///C:/sdtree/AssemblyClass/cs/source.exe
Example.SampleMethod(42) executes.
SampleMethod returned 84.
Assembly entry point:
Void Main()
*/
//</Snippet1>
|
#include "bigint_serialize.h"
char *bigint_tohexstr(const bigint *a) {
char *hex, *nbr;
int j;
/* allocate required memory + 0x + null */
hex = bigint_mm_malloc(16*a->len + 3);
if (!hex) bigint_mm_err();
/* terminating null */
hex[16*a->len+2] = 0;
/* initial 0x */
hex[0] = '0';
hex[1] = 'x';
nbr = (char *)bigint_lu_v(a);
/* loop through all digits */
for (j = a->len*8; j > 0; j--) {
hex[j*2] = ((*nbr & 0xF0) >> 4) + '0';
hex[j*2 + 1] = (*nbr & 0xF) + '0';
/* adjust for > 9 */
if (hex[j*2] > '9') hex[j*2] += 7;
if (hex[j*2+1] > '9') hex[j*2+1] += 7;
nbr++;
}
return hex;
}
|
package Model.OSM;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Representation of a road.
*/
public class OSMWay extends ArrayList<OSMNode> implements Serializable{
/**
* Constructor of OSMWay.
*/
public OSMWay(){ }
/**
* Returns the from node of this way.
* @return OSMNode from.
*/
public OSMNode from() {
return get(0);
}
/**
* Returns the to node of this way.
* @return OSMNode to.
*/
public OSMNode to() {
return get(size()-1);
}
}
|
<?php
namespace App\Models;
use App\Models\NewOrder;
use App\Models\Order;
use App\Models\Product;
use App\Models\ProductOrder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Outlet extends Model
{
use HasFactory;
protected $fillable = [
'number',
'name',
'owner',
];
public function orders()
{
return $this->hasMany(Order::class);
}
public function productOrders()
{
return $this->hasMany(ProductOrder::class);
}
public function products()
{
return $this->belongsToMany(Product::class, 'product_orders')
->withPivot('quantity')->withTimestamps();
}
public function newOrders()
{
return $this->hasMany(NewOrder::class);
}
}
|
require 'test_helper'
class Superstore::Types::DateTypeTest < Superstore::Types::TestCase
test 'serialize' do
assert_equal '2004-04-25', type.serialize(Date.new(2004, 4, 25))
end
test 'deserialize' do
assert_equal Date.new(2004, 4, 25), type.deserialize('2004-04-25')
end
test 'cast_value' do
assert_nil type.cast_value(1000)
assert_nil type.cast_value(1000.0)
assert_nil type.cast_value('')
assert_nil type.cast_value('nil')
assert_nil type.cast_value('bad format')
assert_equal Date.new(2004, 4, 25), type.cast_value('2004-04-25')
assert_equal Date.new(2017, 5, 1), type.cast_value('2017-05-01T21:39:06.796897Z')
my_time = Time.current
assert_equal my_time.to_date, type.cast_value(my_time)
end
end
|
<?php
namespace App\Http\Controllers\SysAdmin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Promocoes;
use App\Sorteios;
use App\Premios;
use Illumniate\Html\HtmlServiceProvider;
use App\Route;
use View;
use Validator;
Use Input;
Use Redirect;
Use Session;
class PromocoesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$promocoes = Promocoes::orderBy('id', 'DESC')->get();
return view('sysadmin.promocoes.index', compact('promocoes'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$sorteios = $this->getSorteiosArray();
return View::make('sysadmin.promocoes.create')
->with('sorteios',$sorteios);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'titulo' => 'required',
//'preco' => 'required | numeric',
'descricao' => 'required',
'imagem' => 'mimes:jpeg,bmp,png'
);
$messages = array(
'required' => 'O campo :attribute é obrigatório',
'numeric' => 'Digite apenas números no campo :attribute.',
'between' => 'Digite valores entre :min e :max.'
);
$validator = Validator::make(Input::all(), $rules, $messages);
// process the login
if ($validator->fails()) {
return Redirect::to('sysadmin/promocoes/create')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// store
$promocao = new Promocoes;
$promocao->titulo = trim(Input::get('titulo'));
$promocao->situacao = trim(Input::get('situacao'));
$promocao->descricao = trim(Input::get('descricao'));
$promocao->url_hotsite = trim(Input::get('url_hotsite'));
$promocao->url_regulamento = trim(Input::get('url_regulamento'));
$promocao->valor_minimo = RealForDecimal(Input::get('valor_minimo'));
// $promocao->valor_premiacao = RealForDecimal(Input::get('valor_premiacao'));
$promocao->regiao = trim(Input::get('regiao'));
$promocao->premiacao = trim(Input::get('premiacao'));
$promocao->data_inicio = DateBRForYMD(Input::get('data_inicio'));
$promocao->data_fim = DateBRForYMD(Input::get('data_fim'));
$promocao->url_ganhadores = trim(Input::get('url_ganhadores'));
$promocao->save();
#UPLOADS DE IMAGEM
$file = Input::file('imagem');
$this->salveImagem( $file, $promocao, $request );
$sorteios = Input::get('sorteios');
$this->setSorteiosUpdate($sorteios,$promocao->id);
// redirect
Session::flash('message', 'Promoção criado com sucesso');
return Redirect::to('sysadmin/promocoes');
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
// get the produto
$promocao = Promocoes::find($id);
// show the view and pass the promocao to it
return View::make('sysadmin.promocoes.show')
->with('promocao', $promocao);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
// get the produto
$promocao = Promocoes::find($id);
$premios = Premios::where('prom_id', $promocao->id)->get();
$sorteios = $this->getSorteiosArray($promocao->id);
// echo "<pre>";
// print_r( $sorteios );
// echo "</pre>";
// show the edit form and pass the produto
return View::make('sysadmin.promocoes.edit')
->with('promocao', $promocao)
->with('premios',$premios )
->with('sorteios',$sorteios);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'titulo' => 'required',
'slug' => 'required',
//'descricao' => 'required'
);
$messages = array(
'required' => 'O campo :attribute é obrigatório',
'numeric' => 'Digite apenas números no campo :attribute.',
'between' => 'Digite valores entre :min e :max.'
);
$validator = Validator::make(Input::all(), $rules,$messages);
// process the login
if ($validator->fails()) {
return Redirect::to('sysadmin/promocoes/' . $id . '/edit')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// store
$promocao = Promocoes::find($id);
$promocao->titulo = Input::get('titulo');
$promocao->situacao = trim(Input::get('situacao'));
$promocao->slug = Input::get('slug');
$promocao->descricao = trim(Input::get('descricao'));
$promocao->url_hotsite = trim(Input::get('url_hotsite'));
$promocao->url_regulamento = trim(Input::get('url_regulamento'));
$promocao->valor_minimo = RealForDecimal(Input::get('valor_minimo'));
// $promocao->valor_premiacao = RealForDecimal(Input::get('valor_premiacao'));
$promocao->regiao = trim(Input::get('regiao'));
$promocao->premiacao = Input::get('premiacao');
$promocao->data_inicio = DateBRForYMD(Input::get('data_inicio'));
$promocao->data_fim = DateBRForYMD(Input::get('data_fim'));
$promocao->url_ganhadores = trim(Input::get('url_ganhadores'));
$promocao->save();
#UPLOADS DE IMAGEM
$file = Input::file('imagem');
$this->salveImagem( $file, $promocao, $request );
$sorteios = Input::get('sorteios');
$this->setSorteiosUpdate($sorteios,$promocao->id);
// redirect
Session::flash('message', 'Promoção atualizado com sucesso');
return Redirect::to('sysadmin/promocoes');
} }
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
// delete
$promocao = Promocoes::find($id);
$promocao->delete();
// redirect
Session::flash('message', 'Promoção excluído com sucesso!');
return Redirect::to('sysadmin/promocoes');
}
function salveImagem($file, $promocao, $request){
if(is_object($file)):
$image_name = str_slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
$extension = pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION); // jpg
$file_name = $promocao->id."_".$image_name.".".$extension;
$request->file('imagem')->move(
base_path() . '/public/uploads/promocoes/', $file_name
);
$promocao = Promocoes::find($promocao->id);
$promocao->imagem = "uploads/promocoes/".$file_name;
$promocao->save();
endif;
}
public function getSorteiosArray($prom_id=false){
if($prom_id == false):
return array();
endif;
$oObject = Sorteios::where('prom_id', $prom_id)->get();
$sorteio_array = array();
$premio_array = array();
if(!empty($oObject)):
foreach($oObject as $sorteio):
$oPremios = Premios::where('sort_id', $sorteio->id)->get();
if(!empty( $oPremios )):
foreach( $oPremios as $premio):
$premio_array[] = array(
'sort_id' => $premio->sort_id,
'quantidade'=> $premio->quantidade,
'nome' => trim($premio->nome),
'descricao' => trim($premio->descricao),
'valor' => DecimalForReal($premio->valor),
'prom_id' => $premio->prom_id
);
endforeach;
endif;
$sorteio_array[] = array(
'id' => $sorteio->id,
'prom_id' => $prom_id,
'observacao' => trim($sorteio->observacao),
'periodo_inicio' => DateYMDforBR($sorteio->periodo_inicio),
'periodo_fim' => DateYMDforBR($sorteio->periodo_fim),
'data_sorteio' => DateYMDforBR($sorteio->data_sorteio),
'premios' => $premio_array
);
$premio_array = array();
endforeach;
endif;
return $sorteio_array;
}
public function setSorteiosUpdate($sorteios, $prom_id){
Sorteios::where('prom_id', $prom_id)->delete();
Premios::where('prom_id', $prom_id)->delete();
if(!empty($sorteios)):
foreach($sorteios as $sorteio):
if( is_array($sorteio) ):
$oSorteio = new Sorteios;
$oSorteio->prom_id = $prom_id;
$oSorteio->observacao = trim($sorteio['observacao']);
$oSorteio->periodo_inicio = DateBRForYMD($sorteio['periodo_inicio']);
$oSorteio->periodo_fim = DateBRForYMD($sorteio['periodo_fim']);
$oSorteio->data_sorteio = DateBRForYMD($sorteio['data_sorteio']);
$oSorteio->save();
if(!empty($sorteio['premios'])):
foreach($sorteio['premios'] as $premio):
if( is_array($premio) ):
$oPremios = new Premios;
$oPremios->sort_id = $oSorteio->id;
$oPremios->quantidade = $premio['quantidade'];
$oPremios->nome = trim($premio['nome']);
$oPremios->descricao = trim($premio['descricao']);
$oPremios->valor = RealForDecimal($premio['valor']);
$oPremios->prom_id = $prom_id;
$oPremios->save();
endif;
endforeach;
endif;
endif;
endforeach;
// exit;
endif;
}
}
|
export { default as getPastelColor } from "./getPastelColor";
export { default as getHsl } from "./getHsl";
export { default as getHsla } from "./getHsla";
export { default as getRgb } from "./getRgb";
export { default as getRgba } from "./getRgba";
export { default as getHex } from "./getHex";
|
<footer class="main-footer">
<div class="pull-right hidden-xs">
<b>Desarrollado por</b>
<a href="http://iot-eng.com" target="_blank"> IoT Engineering</a>
</div>
<strong>Copyright © IoT Engineering S.L.</strong> Todos los derechos resesrvados.
</footer>
|
class Thumb < ApplicationRecord
belongs_to :thumbable, polymorphic: true
belongs_to :user
validates :user, uniqueness: { scope: [ :thumbable_id, :thumbable_type] }
end
|
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
class Home extends Component {
constructor(props) {
super(props)
this.state = {}
}
componentDidMount() {
fetch('/labels')
.then((resp) => resp.json())
.then((labels) => this.setState({labels}))
}
render() {
const alphabeticalSorter = (a, b) => a.Name > b.Name
if (this.state.labels) {
return (
<div>
<ul>
{this.state.labels.slice().sort(alphabeticalSorter).map((label) =>
<li key={label.ID}>
<NavLink to={`/label/${label.ID}`}>{label.Name}</NavLink>
</li>)}
</ul>
</div>
)
}
return <div>loading...</div>
}
}
export default Home
|
require "date"
require "thwait"
require "teecket/page_requester"
require "teecket/selectors/air_asia"
require "teecket/selectors/malaysia_airlines"
require "teecket/selectors/malindo_air"
require "teecket/selectors/firefly"
require "teecket/flight"
require "teecket/air_asia"
require "teecket/malaysia_airlines"
require "teecket/malindo_air"
require "teecket/firefly"
class Teecket
def self.search(params)
flights = [
"AirAsia",
"Firefly",
"MalaysiaAirlines",
"MalindoAir"
]
results = []
threads = []
flights.each do |flight|
threads << Thread.new do
klass = Object.const_get(flight)
scrapper = klass.new(from: params[:from],
to: params[:to],
date: params[:date])
scrapper.search
results = results + scrapper.fares
end
end
ThreadsWait.all_waits(*threads)
results
end
end
|
package com.fjbg.weather.data.repository
import com.fjbg.weather.data.local.CityEntity
import com.fjbg.weather.data.model.CityDto
import kotlinx.coroutines.flow.Flow
interface CityRepository {
suspend fun getCity(city: String): Flow<List<CityDto>?>
suspend fun clearAll()
suspend fun saveCity(city: CityDto)
suspend fun getCitiesFromLocal(): Flow<List<CityEntity>?>
suspend fun deleteCity(city: CityDto)
}
|
import 'package:flutter_getx_template/common/utility/utils/injection_utils.dart';
import 'package:flutter_getx_template/data_access/repositories/product_repository/product_repository.dart';
import 'package:flutter_getx_template/data_access/repositories/product_repository/product_repository_impl.dart';
import 'package:get/get.dart';
void setupRepositories() {
registerDep<ProductRepository>(
ProductRepositoryImpl(
restClient: Get.find(),
),
);
}
|
-- file:numeric.sql ln:299 expect:true
INSERT INTO num_exp_div VALUES (6,8,'1.25401073209839612184')
|
/**
* @Auther: fanshu
* @Date: 2020/12/16
* @Description: kafka源表打入mysql结果表--已验证
*/
CREATE TABLE MyTable(
id int,
name varchar,
age int
)WITH(
type ='kafka11',
bootstrapServers ='172.16.100.241:9092',
zookeeperQuorum ='172.16.100.241:2181/kafka',
offsetReset ='latest',
topic ='fanshu10',
charsetName ='utf-8',
timezone='Asia/Shanghai',
updateMode ='append',
enableKeyPartitions ='false',
topicIsPattern ='false',
parallelism ='1'
);
CREATE TABLE MyResult(
runoob_id INT,
runoob_name VARCHAR,
runoob_age INT
)WITH(
type ='mysql',
url ='jdbc:mysql://172.16.8.193:3306/test',
userName ='root',
password = '123456',
tableName ='runoob_tbl2',
updateMode ='append',
parallelism ='1',
batchSize ='100',
batchWaitInterval ='1000'
);
INSERT
INTO
MyResult
SELECT
id AS runoob_id,
name AS runoob_name,
age AS runoob_age
FROM
MyTable;
|
# P9
> Vue 数据显隐
**⚡题目**:
❓ v-if、v-show、v-html 的原理是什么
## 优解 🔥
- v-if会调用addIfCondition方法,生成vnode的时候会忽略对应节点,render的时候就不会渲染;
- v-show会生成vnode,render的时候也会渲染成真实节点,只是在render过程中会在节点的属性中修改show属性值,也就是常说的display
- v-html会先移除节点下的所有节点,调用html方法,通过addProp添加innerHTML属性,归根结底还是设置innerHTML为v-html的值
|
!git clone https://github.com/RAY-GAN/pytorch-CycleGAN-and-pix2pix.git
\\ clone the repo
import os
os.chdir('pytorch-CycleGAN-and-pix2pix/')
!pip install -r requirements.txt
\\ install all the required API
!bash ./datasets/download_cyclegan_dataset.sh horse2zebra
\\down load the datasets for the horse2zebra translation
!python train.py --dataroot ./datasets/horse2zebra --name horse2zebra --model cycle_gan
\\ start the training process
!python test.py --dataroot datasets/horse2zebra/testA --name horse2zebra --model test
\\ start the testing process
\\ Make sure the dataroot is consistent with the desired datasets you want to train
\\ Check out the option files to further explore the possible flags for different training and test options
The majority of the codes are originated from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix.git
I added custom dataset to the dataset folder: maskchange & animatedface.
|
/*
// Copyright (c) 1998-2008 Joe Bertolami. All Right Reserved.
//
// opcodes.h
//
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Additional Information:
//
// For more information, visit http://www.bertolami.com.
*/
#ifndef __OP_TABLES_H__
#define __OP_TABLES_H__
#include "base.h"
#include "cpu.h"
#include "bus.h"
#define ADDRESS_MODE_INVALID (0x0) //
#define ADDRESS_MODE_ABSOLUTE (0x1) // [pc + 1]
#define ADDRESS_MODE_ABSOLUTE_X_INDEXED (0x2) // [pc + 1] + x
#define ADDRESS_MODE_ABSOLUTE_Y_INDEXED (0x3) // [pc + 1] + y
#define ADDRESS_MODE_ACCUMULATOR (0x4) //
#define ADDRESS_MODE_IMMEDIATE (0x5) // pc + 1
#define ADDRESS_MODE_IMPLIED (0x6) //
#define ADDRESS_MODE_INDIRECT (0x7) // [[pc + 1]] - only used for JMP
#define ADDRESS_MODE_INDIRECT_PRE_X_INDEXED (0x8) // [[pc + 1] + x] - addr is zero page
#define ADDRESS_MODE_INDIRECT_POST_Y_INDEXED (0x9) // [[pc + 1]] + y - addr is zero page
#define ADDRESS_MODE_RELATIVE (0xA) // pc + [pc + 1]
#define ADDRESS_MODE_ZERO_PAGE (0xB) // [pc + 1]
#define ADDRESS_MODE_ZERO_PAGE_X_INDEXED (0xC) // [pc + 1] + x
#define ADDRESS_MODE_ZERO_PAGE_Y_INDEXED (0xD) // [pc + 1] + y
namespace nes {
using namespace base;
static const char *op_name_table[256] =
{
"BRK", "OR ", "INV", "INV", "INV", "OR ", "ASL", "INV",
"PHP", "OR ", "ASL", "INV", "INV", "OR ", "ASL", "INV",
"BPL", "OR ", "INV", "INV", "INV", "OR ", "ASL", "INV",
"CLC", "OR ", "INV", "INV", "INV", "OR ", "ASL", "INV",
"JSR", "AND", "INV", "INV", "BIT", "AND", "ROL", "INV",
"PLP", "AND", "ROL", "INV", "BIT", "AND", "ROL", "INV",
"BMI", "AND", "INV", "INV", "INV", "AND", "ROL", "INV",
"SEC", "AND", "INV", "INV", "INV", "AND", "ROL", "INV",
"RTI", "EOR", "INV", "INV", "INV", "EOR", "LSR", "INV",
"PHA", "EOR", "LSR", "INV", "JMP", "EOR", "LSR", "INV",
"BVC", "EOR", "INV", "INV", "INV", "EOR", "LSR", "INV",
"CLI", "EOR", "INV", "INV", "INV", "EOR", "LSR", "INV",
"RTS", "ADC", "INV", "INV", "INV", "ADC", "ROR", "INV",
"PLA", "ADC", "ROR", "INV", "JMP", "ADC", "ROR", "INV",
"BVS", "ADC", "INV", "INV", "INV", "ADC", "ROR", "INV",
"SEI", "ADC", "INV", "INV", "INV", "ADC", "ROR", "INV",
"INV", "STA", "INV", "INV", "STY", "STA", "STX", "INV",
"DEY", "INV", "TXA", "INV", "STY", "STA", "STX", "INV",
"BCC", "STA", "INV", "INV", "STY", "STA", "STX", "INV",
"TYA", "STA", "TXS", "INV", "INV", "STA", "INV", "INV",
"LDY", "LDA", "LDX", "INV", "LDY", "LDA", "LDX", "INV",
"TAY", "LDA", "TAX", "INV", "LDY", "LDA", "LDX", "INV",
"BCS", "LDA", "INV", "INV", "LDY", "LDA", "LDX", "INV",
"CLV", "LDA", "TSX", "INV", "LDY", "LDA", "LDX", "INV",
"CPY", "CMP", "INV", "INV", "CPY", "CMP", "DEC", "INV",
"INY", "CMP", "DEX", "INV", "CPY", "CMP", "DEC", "INV",
"BNE", "CMP", "INV", "INV", "INV", "CMP", "DEC", "INV",
"CLD", "CMP", "INV", "INV", "INV", "CMP", "DEC", "INV",
"CPX", "SBC", "INV", "INV", "CPX", "SBC", "INC", "INV",
"INX", "SBC", "NOP", "INV", "CPX", "SBC", "INC", "INV",
"BEQ", "SBC", "INV", "INV", "INV", "SBC", "INC", "INV",
"SED", "SBC", "INV", "INV", "INV", "SBC", "INC", "INV",
};
static const uint8 op_length_table[256] =
{
0x1, 0x2, 0x0, 0x0, 0x2, 0x2, 0x2, 0x0, 0x1, 0x2, 0x1, 0x0, 0x3, 0x3, 0x3, 0x0,
0x2, 0x2, 0x0, 0x0, 0x2, 0x2, 0x2, 0x0, 0x1, 0x3, 0x1, 0x0, 0x3, 0x3, 0x3, 0x0,
0x3, 0x2, 0x0, 0x0, 0x2, 0x2, 0x2, 0x0, 0x1, 0x2, 0x1, 0x0, 0x3, 0x3, 0x3, 0x0,
0x2, 0x2, 0x0, 0x0, 0x2, 0x2, 0x2, 0x0, 0x1, 0x3, 0x1, 0x0, 0x3, 0x3, 0x3, 0x0,
0x1, 0x2, 0x0, 0x0, 0x2, 0x2, 0x2, 0x0, 0x1, 0x2, 0x1, 0x0, 0x3, 0x3, 0x3, 0x0,
0x2, 0x2, 0x0, 0x0, 0x2, 0x2, 0x2, 0x0, 0x1, 0x3, 0x1, 0x0, 0x3, 0x3, 0x3, 0x0,
0x1, 0x2, 0x0, 0x0, 0x2, 0x2, 0x2, 0x0, 0x1, 0x2, 0x1, 0x0, 0x3, 0x3, 0x3, 0x0,
0x2, 0x2, 0x0, 0x0, 0x2, 0x2, 0x2, 0x0, 0x1, 0x3, 0x1, 0x0, 0x3, 0x3, 0x3, 0x0,
0x2, 0x2, 0x0, 0x0, 0x2, 0x2, 0x2, 0x0, 0x1, 0x0, 0x1, 0x0, 0x3, 0x3, 0x3, 0x0,
0x2, 0x2, 0x0, 0x0, 0x2, 0x2, 0x2, 0x0, 0x1, 0x3, 0x1, 0x0, 0x0, 0x3, 0x0, 0x0,
0x2, 0x2, 0x2, 0x0, 0x2, 0x2, 0x2, 0x0, 0x1, 0x2, 0x1, 0x0, 0x3, 0x3, 0x3, 0x0,
0x2, 0x2, 0x0, 0x0, 0x2, 0x2, 0x2, 0x0, 0x1, 0x3, 0x1, 0x0, 0x3, 0x3, 0x3, 0x0,
0x2, 0x2, 0x0, 0x0, 0x2, 0x2, 0x2, 0x0, 0x1, 0x2, 0x1, 0x0, 0x3, 0x3, 0x3, 0x0,
0x2, 0x2, 0x0, 0x0, 0x2, 0x2, 0x2, 0x0, 0x1, 0x3, 0x1, 0x0, 0x3, 0x3, 0x3, 0x0,
0x2, 0x2, 0x0, 0x0, 0x2, 0x2, 0x2, 0x0, 0x1, 0x2, 0x1, 0x0, 0x3, 0x3, 0x3, 0x0,
0x2, 0x2, 0x0, 0x0, 0x2, 0x2, 0x2, 0x0, 0x1, 0x3, 0x1, 0x0, 0x3, 0x3, 0x3, 0x0,
};
static const uint8 op_cycle_table[256] =
{
0x7, 0x6, 0x0, 0x0, 0x0, 0x3, 0x5, 0x0, 0x3, 0x2, 0x2, 0x0, 0x0, 0x4, 0x6, 0x0,
0x2, 0x5, 0x0, 0x0, 0x0, 0x4, 0x6, 0x0, 0x2, 0x4, 0x0, 0x0, 0x0, 0x4, 0x7, 0x0,
0x6, 0x6, 0x0, 0x0, 0x3, 0x3, 0x5, 0x0, 0x4, 0x2, 0x2, 0x0, 0x4, 0x4, 0x6, 0x0,
0x2, 0x5, 0x0, 0x0, 0x0, 0x4, 0x6, 0x0, 0x2, 0x4, 0x0, 0x0, 0x0, 0x4, 0x7, 0x0,
0x6, 0x6, 0x0, 0x0, 0x0, 0x3, 0x5, 0x0, 0x3, 0x2, 0x2, 0x0, 0x3, 0x4, 0x6, 0x0,
0x2, 0x5, 0x0, 0x0, 0x0, 0x4, 0x6, 0x0, 0x2, 0x4, 0x0, 0x0, 0x0, 0x4, 0x7, 0x0,
0x6, 0x6, 0x0, 0x0, 0x0, 0x3, 0x5, 0x0, 0x4, 0x2, 0x2, 0x0, 0x5, 0x4, 0x6, 0x0,
0x2, 0x5, 0x0, 0x0, 0x0, 0x4, 0x6, 0x0, 0x2, 0x4, 0x0, 0x0, 0x0, 0x4, 0x7, 0x0,
0x0, 0x6, 0x0, 0x0, 0x3, 0x3, 0x3, 0x0, 0x2, 0x0, 0x2, 0x0, 0x4, 0x4, 0x4, 0x0,
0x2, 0x6, 0x0, 0x0, 0x4, 0x4, 0x4, 0x0, 0x2, 0x5, 0x2, 0x0, 0x0, 0x5, 0x0, 0x0,
0x2, 0x6, 0x2, 0x0, 0x3, 0x3, 0x3, 0x0, 0x2, 0x2, 0x2, 0x0, 0x4, 0x4, 0x4, 0x0,
0x2, 0x5, 0x0, 0x0, 0x4, 0x4, 0x4, 0x0, 0x2, 0x4, 0x2, 0x0, 0x4, 0x4, 0x4, 0x0,
0x2, 0x6, 0x0, 0x0, 0x3, 0x3, 0x5, 0x0, 0x2, 0x2, 0x2, 0x0, 0x4, 0x4, 0x6, 0x0,
0x2, 0x5, 0x0, 0x0, 0x0, 0x4, 0x6, 0x0, 0x2, 0x4, 0x0, 0x0, 0x0, 0x4, 0x7, 0x0,
0x2, 0x6, 0x0, 0x0, 0x3, 0x3, 0x5, 0x0, 0x2, 0x2, 0x2, 0x0, 0x4, 0x4, 0x6, 0x0,
0x2, 0x5, 0x0, 0x0, 0x0, 0x4, 0x6, 0x0, 0x2, 0x4, 0x0, 0x0, 0x0, 0x4, 0x7, 0x0,
};
static const uint8 op_address_mode_table[256] =
{
0x6, 0x8, 0x0, 0x0, 0x0, 0xB, 0xB, 0x0, 0x6, 0x5, 0x4, 0x0, 0x0, 0x1, 0x1, 0x0,
0xA, 0x9, 0x0, 0x0, 0x0, 0xC, 0xC, 0x0, 0x6, 0x3, 0x0, 0x0, 0x0, 0x2, 0x2, 0x0,
0x1, 0x8, 0x0, 0x0, 0xB, 0xB, 0xB, 0x0, 0x6, 0x5, 0x4, 0x0, 0x1, 0x1, 0x1, 0x0,
0xA, 0x9, 0x0, 0x0, 0x0, 0xC, 0xC, 0x0, 0x6, 0x3, 0x0, 0x0, 0x0, 0x2, 0x2, 0x0,
0x6, 0x8, 0x0, 0x0, 0x0, 0xB, 0xB, 0x0, 0x6, 0x5, 0x4, 0x0, 0x1, 0x1, 0x1, 0x0,
0xA, 0x9, 0x0, 0x0, 0x0, 0xC, 0xC, 0x0, 0x6, 0x3, 0x0, 0x0, 0x0, 0x2, 0x2, 0x0,
0x6, 0x8, 0x0, 0x0, 0x0, 0xB, 0xB, 0x0, 0x6, 0x5, 0x4, 0x0, 0x7, 0x1, 0x1, 0x0,
0xA, 0x9, 0x0, 0x0, 0x0, 0xC, 0xC, 0x0, 0x6, 0x3, 0x0, 0x0, 0x0, 0x2, 0x2, 0x0,
0x0, 0x8, 0x0, 0x0, 0xB, 0xB, 0xB, 0x0, 0x6, 0x0, 0x6, 0x0, 0x1, 0x1, 0x1, 0x0,
0xA, 0x9, 0x0, 0x0, 0xC, 0xC, 0xD, 0x0, 0x6, 0x3, 0x6, 0x0, 0x0, 0x2, 0x0, 0x0,
0x5, 0x8, 0x5, 0x0, 0xB, 0xB, 0xB, 0x0, 0x6, 0x5, 0x6, 0x0, 0x1, 0x1, 0x1, 0x0,
0xA, 0x9, 0x0, 0x0, 0xC, 0xC, 0xD, 0x0, 0x6, 0x3, 0x6, 0x0, 0x2, 0x2, 0x3, 0x0,
0x5, 0x8, 0x0, 0x0, 0xB, 0xB, 0xB, 0x0, 0x6, 0x5, 0x6, 0x0, 0x1, 0x1, 0x1, 0x0,
0xA, 0x9, 0x0, 0x0, 0x0, 0xC, 0xC, 0x0, 0x6, 0x3, 0x0, 0x0, 0x0, 0x2, 0x2, 0x0,
0x5, 0x8, 0x0, 0x0, 0xB, 0xB, 0xB, 0x0, 0x6, 0x5, 0x6, 0x0, 0x1, 0x1, 0x1, 0x0,
0xA, 0x9, 0x0, 0x0, 0x0, 0xC, 0xC, 0x0, 0x6, 0x3, 0x0, 0x0, 0x0, 0x2, 0x2, 0x0,
};
// arithmetic opcodes
void _execute_opcode_adc(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_and(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_asl(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_cmp(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_cpx(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_cpy(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_dec(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_dex(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_dey(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_eor(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_inc(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_inx(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_iny(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_lsr(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_ora(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_rol(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_ror(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_sbc(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_acc_asl(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_acc_lsr(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_acc_rol(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_acc_ror(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
// branch opcodes
void _execute_opcode_bcc(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_bcs(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_beq(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_bmi(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_bne(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_bpl(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_bvc(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_bvs(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
// control opcodes
void _execute_opcode_bit(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_brk(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_jmp(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_jsr(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_pha(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_php(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_pla(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_plp(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_rti(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_rts(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_int(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
// transfer opcodes
void _execute_opcode_lda(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_ldx(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_ldy(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_sta(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_stx(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_sty(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_tax(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_tay(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_tsx(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_txa(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_txs(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
void _execute_opcode_tya(uint16 operand_address, system_bus *bus, cpu_register_set ®isters);
} // namespace nes
#endif // __OP_TABLES_H__
|
package com.yzy.example.repository.model
import androidx.lifecycle.MutableLiveData
import com.yzy.baselibrary.base.BaseViewModel
import com.yzy.baselibrary.extention.request
import com.yzy.example.repository.GankRepository
import com.yzy.example.repository.bean.CollectUrlBean
class CollectUrlViewModel : BaseViewModel<GankRepository>() {
//收藏de网址数据
// var urlDataState: MutableLiveData<ListDataUiState<CollectUrlBean>> = MutableLiveData()
fun getCollectUrlData() {
request({ repository.collectUrlData() }, {
//请求成功
// val listDataUiState =
// ListDataUiState(
// isRefresh = true,
// isSuccess = true,
// hasMore = false,
// isEmpty = it.isEmpty(),
// listData = it
// )
// urlDataState.postValue(listDataUiState)
}, {
//请求失败
// val listDataUiState =
// ListDataUiState(
// isSuccess = false,
// errMessage = it.errMsg,
// listData = arrayListOf<CollectUrlBean>()
// )
// urlDataState.postValue(listDataUiState)
})
}
// fun loadData() {
// pageNo++
// getCollectAriticleData(false)
// }
}
|
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{ Layout = "FestivalStarterKit.cshtml"; }
@section HtmlBodyContent
{
<table class="table table-bordered table-striped table-hover">
@{ var maxSessions = Model.Content.Children.Max(x => x.Children.Count()); }
@foreach (var timeslot in Model.Content.Children)
{
<tr>
<th>@timeslot.Name</th>
@{ var numSessions = timeslot.Children.Count(); }
@foreach (var session in timeslot.Children)
{
if (session.IsDocumentType("SessionPage"))
{
<td>
<a href="@session.Url">@session.Name</a>
</td>
if (session.IsLast())
{
for (int i = 0; i < maxSessions - numSessions; i++)
{
<td>
<span> </span>
</td>
}
}
}
else if (session.IsDocumentType("SessionTimeout"))
{
<td colspan="@maxSessions">
<em>@session.Name</em>
</td>
}
}
</tr>
}
</table>
}
|
package aurora.cesium.element.property;
import cesiumlanguagewriter.*;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
/**
* @author hanhaoran
* @date 2020/8/27
*/
class PositionListPropertyImpl extends PropertyAdapter<PositionListProperty> implements PositionListProperty {
private Iterable<Cartesian> cartesians;
private Iterable<Cartographic> cartographicDegrees;
private Iterable<Cartographic> cartographicRadians;
@Override
public void dispatch(Supplier<PositionListCesiumWriter> supplier) {
try (PositionListCesiumWriter writer = supplier.get()) {
Optional.ofNullable(getCartesians()).ifPresent(writer::writeCartesian);
Optional.ofNullable(getCartographicDegrees()).ifPresent(writer::writeCartographicDegrees);
Optional.ofNullable(getCartographicRadians()).ifPresent(writer::writeCartographicRadians);
dispatchDelete(writer);
dispatchInterval(writer, (intervalWriterSupplier, property) -> property.dispatch(intervalWriterSupplier));
dispatchReferences(writer);
}
}
@Override
public Iterable<Cartesian> getCartesians() {
return cartesians;
}
public void setCartesians(Iterable<Cartesian> cartesians) {
this.cartesians = cartesians;
}
@Override
public Iterable<Cartographic> getCartographicDegrees() {
return cartographicDegrees;
}
public void setCartographicDegrees(Iterable<Cartographic> cartographicDegrees) {
this.cartographicDegrees = cartographicDegrees;
}
@Override
public Iterable<Cartographic> getCartographicRadians() {
return cartographicRadians;
}
public void setCartographicRadians(Iterable<Cartographic> cartographicRadians) {
this.cartographicRadians = cartographicRadians;
}
@Override
public Boolean getDelete() {
return delete;
}
public void setDelete(Boolean delete) {
this.delete = delete;
}
@Override
public TimeInterval getInterval() {
return interval;
}
public void setInterval(TimeInterval interval) {
this.interval = interval;
}
@Override
public List<PositionListProperty> getIntervals() {
return intervals;
}
public void setIntervals(List<PositionListProperty> intervals) {
this.intervals = intervals;
}
@Override
public Iterable<Reference> getReferences() {
return referenceList;
}
public void setReferences(Iterable<Reference> references) {
this.referenceList = references;
}
public static final class Builder {
private Iterable<Cartesian> cartesians;
private Iterable<Cartographic> cartographicDegrees;
private Iterable<Cartographic> cartographicRadians;
private Boolean delete;
private TimeInterval interval;
private List<PositionListProperty> intervals;
private Iterable<Reference> references;
private Builder() {
}
public static Builder newBuilder() {
return new Builder();
}
public Builder withCartesians(Iterable<Cartesian> cartesians) {
this.cartesians = cartesians;
return this;
}
public Builder withCartographicDegrees(Iterable<Cartographic> cartographicDegrees) {
this.cartographicDegrees = cartographicDegrees;
return this;
}
public Builder withCartographicRadians(Iterable<Cartographic> cartographicRadians) {
this.cartographicRadians = cartographicRadians;
return this;
}
public Builder withDelete(Boolean delete) {
this.delete = delete;
return this;
}
public Builder withInterval(TimeInterval interval) {
this.interval = interval;
return this;
}
public Builder withIntervals(List<PositionListProperty> intervals) {
this.intervals = intervals;
return this;
}
public Builder withReferences(Iterable<Reference> references) {
this.references = references;
return this;
}
public PositionListPropertyImpl build() {
PositionListPropertyImpl positionListPropertyImpl = new PositionListPropertyImpl();
positionListPropertyImpl.setCartesians(cartesians);
positionListPropertyImpl.setCartographicDegrees(cartographicDegrees);
positionListPropertyImpl.setCartographicRadians(cartographicRadians);
positionListPropertyImpl.setDelete(delete);
positionListPropertyImpl.setInterval(interval);
positionListPropertyImpl.setIntervals(intervals);
positionListPropertyImpl.setReferences(references);
return positionListPropertyImpl;
}
}
}
|
require 'git'
require 'colorize'
require 'trollop'
require "git/status_all/version"
require "git/status_all/extensions"
require "git/status_all/git"
module Git
module StatusAll
class App
def main
# we want to disable the text coloring if we are printing to a
# file, or on a platform (like windows) that likely doesn't support
# the colors
String.disable_colorization = !$stdout.isatty
opts = Trollop::options do
version "git-status-all #{Git::StatusAll::VERSION} (c) 2016 @reednj (reednj@gmail.com)"
banner "Usage: git-status-all [options] [path]"
opt :fetch, "perform fetch for each repository before getting status", :default => false
end
repo_paths = []
begin
dev_dir = ARGV.last || '.'
repo_paths = Dir.entries(dev_dir).
map {|p| { :name => p, :path => File.expand_path(p, dev_dir) } }.
select { |p| Git.repo? p[:path] }
rescue => e
$stderr.puts "Could not read repositories in '#{dev_dir}': #{e}"
end
repo_paths.each do |p|
name = p[:name]
begin
g = Git.open p[:path]
if opts[:fetch]
print "#{name}".right_align("[#{"fetching...".yellow}]") + "\r"
if !g.remotes.empty?
remote = g.remotes.select{|r| r.name.downcase == 'origin' }.first || g.remotes.first
g.fetch remote
end
end
s = file_status(g)
r = remote_status(g)
s = " #{s} ".black.on_yellow unless s.empty?
n = s.empty? ? name : name.yellow
puts "#{n}".pad_to_col(24).append(s).right_align("#{r} [#{g.branches.current.to_s.blue}]")
rescue => e
if e.to_s.include? "ambiguous argument 'HEAD'"
err ='ERROR: NO HEAD'
else
err ='ERROR'
end
puts "#{name}".right_align("[#{err}]".red)
puts e.to_s if err == 'ERROR'
end
end
end
def file_status(g)
result = ""
result += "A#{g.status.added.length}" if g.status.added.length > 0
result += "D#{g.status.deleted.length}" if g.status.deleted.length > 0
result += "M#{g.status.changed.length}" if g.status.changed.length > 0
result += "U#{g.status.untracked.length}" if g.status.untracked.length > 0
return result
end
def remote_status(g)
if g.remotes.empty?
return "no remotes".black.on_red
end
if g.remotes.select{|r| r.name.downcase == 'origin' }.empty?
return "no origin".black.on_yellow
end
if !g.branches[:master].up_to_date?
b = g.branches[:master]
s = ''
s += "#{b.behind_count}\u2193" if b.behind_count > 0
s += "#{b.ahead_count}\u2191" if b.ahead_count > 0
return s.green
end
return ''
end
def term_width
@term_width ||= `tput cols`.to_i
end
end
end
end
|
<?php
$virtualHost = '%2f'; // This is the default / virtual host URL quoted
$username = 'guest';
$password = 'guest';
$exchange = 'test';
$routingKey = 'foo.bar.baz';
$url = 'http://localhost:8000/' . $virtualHost . '/' . $exchange . '/' . $routingKey;
$message = array('body' => 'This is a message body published through statelessd',
'app_id' => 'PHP Example',
'content_type' => 'text/plain',
'timestamp' => time(),
'type' => 'Example message',
'user_id' => $username);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $message);
curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);
$result = curl_exec($curl);
$headers = curl_getinfo($curl);
if ($headers['http_code'] === 204)
{
echo "Success\n\n";
} else {
echo "Failed:\n\n";
var_dump($headers);
echo $result;
}
|
#!/bin/sh
set -ex
TARGET=x86_64-elf
${TARGET}-as boot.s -o boot.o
${TARGET}-as base.s -o base.o
${TARGET}-gcc -c kernel.c -o kernel.o -std=gnu99 -ffreestanding -O2 -Wall -Wextra
${TARGET}-gcc -T linker.ld -o myos.bin -ffreestanding -O2 -nostdlib boot.o base.o kernel.o -lgcc
|
// @filename: tsconfig.json
{
"compilerOptions": {
"module": "AmD"
}
}
// @filename: other.ts
export default 42;
// @filename: index.ts
import Answer from "./other.js";
const x = 10 + Answer;
export {
x
};
|
#!/usr/bin/env bash
# Copyright (c) 2021 maminjie <maminjie1@huawei.com>
# SPDX-License-Identifier: MulanPSL-2.0
readonly LD_INFO="INFO"
readonly LD_DEBUG="DEBUG"
readonly LD_WARN="WARN"
readonly LD_ERROR="ERROR"
readonly LD_FATAL="FATAL"
# __log message level lineno
__log() {
local dt="$(date +"%y-%m-%d %H:%M:%S")"
local message=$1
local level=$2
local lineno=$3
if [ -n "$lineno" ]; then
lineno=":$lineno"
fi
local format="[$dt][$level][${FUNCNAME[2]}$lineno] $message"
local funcname="TRACE: ${FUNCNAME[*]}"
# print log
case "$level" in
"$LD_DEBUG")
color_print "$CLR_GREEN" "$format"
;;
"$LD_WARN")
color_print "$CLR_YELLOW" "$format"
;;
"$LD_ERROR")
color_print "$CLR_RED" "$format"
color_print "$CLR_RED" "$funcname"
;;
"$LD_FATAL")
color_print "$CLR_RED_WHITE" "$format"
color_print "$CLR_RED_WHITE" "$funcname"
;;
*)
color_print "" "$format"
;;
esac
}
# log_xxx message
log_info() {
__log "$1" "$LD_INFO" "$BASH_LINENO"
}
log_debug() {
__log "$1" "$LD_DEBUG" "$BASH_LINENO"
}
log_warn() {
__log "$1" "$LD_WARN" "$BASH_LINENO"
}
log_error() {
__log "$1" "$LD_ERROR" "$BASH_LINENO"
}
log_fatal() {
__log "$1" "$LD_FATAL" "$BASH_LINENO"
}
|
library r_router;
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart' hide SearchDelegate;
import 'package:path_tree/path_tree.dart';
import '../page/custom_page_route.dart';
import '../page/error_page.dart';
import '../utils/string.dart';
import 'web_config/path_strategy_io.dart'
if (dart.library.html) 'web_config/path_strategy_web.dart';
import '../translate_builder/transaction_builder.dart';
part 'context.dart';
part 'navigator_route.dart';
part 'params.dart';
part 'r_router_delegate.dart';
part 'r_router_information_parse.dart';
part 'r_router_observer.dart';
part 'r_router_register.dart';
part 'redirect.dart';
RRouterBasic RRouter = RRouterBasic();
typedef PopHome = Future<bool> Function();
typedef PageBuilder = Page<dynamic> Function(Context ctx, WidgetBuilder builder,
PageTransitionsBuilder pageTransitionsBuilder);
//Custom Page Builder
CustomPage<dynamic> _kDefaultCustomPageBuilder(Context ctx,
WidgetBuilder builder, PageTransitionsBuilder pageTransitionsBuilder) =>
CustomPage<dynamic>(
child:
Builder(builder: (BuildContext context) => builder.call(context)),
buildCustomRoute: (BuildContext context, CustomPage<dynamic> page) =>
PageBasedCustomPageRoute(
page: page, pageTransitionsBuilder: pageTransitionsBuilder),
key: ValueKey(ctx.at.microsecondsSinceEpoch),
name: ctx.path,
arguments: ctx.toJson(),
restorationId: ctx.path);
Future<bool> _kDefaultPopHome() => Future.value(false);
class RRouterBasic {
final RRouterRegister _register = RRouterRegister();
final RRouterObserver _observer = RRouterObserver();
final RRouterDelegate _delegate = RRouterDelegate();
late final RRouterInformationParser _informationParser =
RRouterInformationParser();
PageTransitionsBuilder _defaultTransitionBuilder;
final List<RouteInterceptor> _interceptor;
NavigatorObserver get observer {
addComplete();
return _observer;
}
RRouterDelegate get delegate {
addComplete();
return _delegate;
}
RRouterInformationParser get informationParser {
return _informationParser;
}
NavigatorState get navigator {
assert(_observer.navigator != null, 'please add the observer into app');
return _observer.navigator!;
}
BuildContext get context {
assert(_observer.navigator != null, 'please add the observer into app');
return navigator.context;
}
ErrorPage _errorPage;
PageBuilder _pageBuilder;
PopHome _popHome;
RRouterBasic(
{ErrorPage? errorPage,
List<RouteInterceptor>? interceptor,
PageBuilder? pageBuilder,
PopHome? popHome})
: _errorPage = errorPage ?? DefaultErrorPage(),
_defaultTransitionBuilder = DefaultTransitionBuilder(),
_interceptor = interceptor ?? <RouteInterceptor>[],
_pageBuilder = pageBuilder ?? _kDefaultCustomPageBuilder,
_popHome = popHome ?? _kDefaultPopHome;
/// path strategy mode
///
/// if true ? will use http://localhost:8080/index.html
/// if false ? will use http://localhost:8080/#/index.html
RRouterBasic setPathStrategy(bool isUsePath) {
setUrlPathStrategy(isUsePath);
return this;
}
/// default transition builder
///
/// [pageTransitionsBuilder] default page Transition builder
RRouterBasic setDefaultTransitionBuilder(
PageTransitionsBuilder pageTransitionsBuilder) {
_defaultTransitionBuilder = pageTransitionsBuilder;
return this;
}
/// default print
///
/// [msg] you want to print msg.
void _print(Object msg) {
debugPrint(msg.toString());
}
/// set Error Page
///
/// [errorPage] found in ErrorPage Class
RRouterBasic setErrorPage(ErrorPage errorPage) {
_errorPage = errorPage;
return this;
}
/// set default page builder
///
/// [pageBuilder] generate page.
RRouterBasic setPageBuilder(PageBuilder pageBuilder) {
_pageBuilder = pageBuilder;
return this;
}
/// set pop home method
///
/// [popHome] if return false will did pop home.
/// or if true will hold.
RRouterBasic setPopHome(PopHome popHome) {
_popHome = popHome;
return this;
}
/// add Routes
///
/// [routes] You want to add routes.
RRouterBasic addRoutes(Iterable<NavigatorRoute> routes) {
_register.add(routes);
return this;
}
/// add Route
///
/// [route] You want to add route
/// [isReplaceRouter] if ture will replace route
RRouterBasic addRoute(NavigatorRoute route, {bool? isReplaceRouter}) {
_register.addRoute(route, isReplaceRouter: isReplaceRouter);
return this;
}
/// add route observer
///
/// [observer] Navigator Observer
RRouterBasic addObserver(NavigatorObserver observer) {
_delegate.addObserver(observer);
return this;
}
/// add route observers
///
/// [observers] Navigator Observer List
RRouterBasic addObservers(Iterable<NavigatorObserver> observers) {
_delegate.addObservers(observers);
return this;
}
/// add interceptor
///
/// [interceptor] add interceptor.
RRouterBasic addInterceptor(RouteInterceptor interceptor) {
_interceptor.add(interceptor);
return this;
}
/// add interceptors
///
/// [interceptors] add interceptor list.
RRouterBasic addInterceptors(List<RouteInterceptor> interceptors) {
_interceptor.addAll(interceptors);
return this;
}
/// When you add Route complete ,you should use it
void addComplete() {
_register._build();
ErrorWidget.builder = (FlutterErrorDetails flutterErrorDetails) {
return Material(
child: Builder(
builder: (BuildContext context) =>
_errorPage.errorPage(context, flutterErrorDetails)),
);
};
}
/// Navigate to Route
/// [path] page path
/// [body] page require arguments
/// [replace] if ture will replace current page to navigate new page.
/// [clearTrace] if ture will clear all page to navigate new page.
/// [isSingleTop] if ture will only path is not current path navigate.
/// [result] went replace is true, this will able.
/// [pageTransitions] you navigate transition , if null will use default page transitions builder.
Future<dynamic> navigateTo<T extends Object?, TO extends Object?>(String path,
{dynamic body,
bool? replace,
bool? clearTrace,
bool? isSingleTop,
TO? result,
PageTransitionsBuilder? pageTransitions}) async {
PageTransitionsBuilder? _pageTransitions;
WidgetBuilder? builder;
final ctx = Context(
path,
body: body,
);
if (_interceptor.isNotEmpty) {
dynamic result;
for (final interceptor in _interceptor) {
result = await interceptor(ctx);
if (result == true) {
return;
}
}
}
NavigatorRoute? handler = _register.match(ctx.uri);
if (handler != null) {
final interceptor = handler.getInterceptor();
if (interceptor.isNotEmpty) {
dynamic result;
for (final interceptor in interceptor) {
result = await interceptor(ctx);
if (result == true) {
return;
}
}
}
final result = await handler(ctx);
if (result is WidgetBuilder) {
builder = result;
_pageTransitions = pageTransitions ?? handler.defaultPageTransaction;
} else if (result is Redirect) {
return await navigateTo(result.path,
body: body,
replace: replace,
clearTrace: clearTrace,
isSingleTop: isSingleTop,
result: result,
pageTransitions: pageTransitions);
} else {
return SynchronousFuture(result);
}
} else {
builder = (BuildContext context) => _errorPage.notFoundPage(context, ctx);
}
_pageTransitions ??= _defaultTransitionBuilder;
dynamic navigateResult;
if (isSingleTop == true && _observer.topPath == path) {
return null;
}
if (clearTrace == true) {
navigateResult = await _delegate
.clearTracePush(_pageNamed(ctx, builder, _pageTransitions));
} else if (replace == true) {
navigateResult = await _delegate.replacePush<T, TO>(
_pageNamed(ctx, builder, _pageTransitions), result);
} else {
navigateResult =
await _delegate.push(_pageNamed(ctx, builder, _pageTransitions));
}
return SynchronousFuture(navigateResult);
}
/// generate page by name(Navigation2.0)
///
/// [ctx] route context
/// [builder] widget builder
/// [pageTransitionsBuilder] page transactions builder
Page<dynamic> _pageNamed(Context ctx, WidgetBuilder builder,
PageTransitionsBuilder pageTransitionsBuilder) {
return _pageBuilder(ctx, builder, pageTransitionsBuilder);
}
/// Pop the top-most route off the navigator.
///
/// [result] you want to pop value.
pop<T extends Object?>([T? result]) {
return _delegate.pop<T>(result);
}
/// Whether the navigator can be popped.
///
/// {@macro flutter.widgets.navigator.canPop}
///
/// See also:
///
/// * [Route.isFirst], which returns true for routes for which [canPop]
/// returns false.
bool canPop() {
return _delegate.canPop();
}
/// Consults the current route's [Route.willPop] method, and acts accordingly,
/// potentially popping the route as a result; returns whether the pop request
/// should be considered handled.
///
/// {@macro flutter.widgets.navigator.maybePop}
///
/// See also:
///
/// * [Form], which provides an `onWillPop` callback that enables the form
/// to veto a [pop] initiated by the app's back button.
/// * [ModalRoute], which provides a `scopedWillPopCallback` that can be used
/// to define the route's `willPop` method.
Future<bool> maybePop<T extends Object?>([T? result]) {
return _delegate.maybePop<T>(result);
}
/// run route method
///
/// [path] your register path.
/// [body] post body
Future<WidgetBuilder?> runRoute(String path, dynamic body) async {
final ctx = Context(
path,
body: body,
);
NavigatorRoute? handler = _register.match(ctx.uri);
if (handler != null) {
final result = await handler(ctx);
if (result is WidgetBuilder) {
return result;
} else if (result is Redirect) {
return runRoute(result.path, body);
}
}
return null;
}
}
extension RRouterBuildContextExtension on BuildContext {
/// get ctx from route
Context get readCtx {
final modal = ModalRoute.of(this);
assert(modal != null, 'Please use RRoute navigateTo');
assert(modal!.settings.arguments is Map, 'Please use RRoute navigateTo');
return Context.fromJson(modal!.settings.arguments as Map);
}
}
|
require 'spec_helper'
describe 'shellinabox' do
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) do
facts
end
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_class('shellinabox::config') }
it { is_expected.to contain_class('shellinabox::install') }
it { is_expected.to contain_class('shellinabox::service') }
it { is_expected.to contain_package('shellinabox') }
it { is_expected.to contain_service('shellinaboxd') }
it { is_expected.to contain_file('/etc/sysconfig/shellinaboxd').with_content(<<-EOS.gsub(/^ {8}/, '')) }
# !!! Managed by Puppet !!!
USER=shellinabox
GROUP=shellinabox
CERTDIR=/var/lib/shellinabox
PORT=4200
OPTS="--disable-ssl-menu --service '/:LOGIN'"
EOS
end
end
end
|
export class Skills {
pathImage: string;
nomeSkill: string;
linkDoc: string;
constructor(pathImage: string, nomeSkill: string, linkDoc: string) {
this.pathImage = pathImage;
this.nomeSkill = nomeSkill;
this.linkDoc = linkDoc;
}
}
|
package header
// Valid logtype values for logtype.
const (
Config = "config"
System = "system"
Threat = "threat"
Traffic = "traffic"
HipMatch = "hip-match"
Url = "url"
Data = "data"
Wildfire = "wildfire"
Tunnel = "tunnel"
UserId = "userid"
Gtp = "gtp"
Auth = "auth"
Sctp = "sctp"
Iptag = "iptag"
)
const (
singular = "http header"
plural = "http headers"
)
|
c-------------------------------------------------------------
c taper phase matched signal
c-------------------------------------------------------------
subroutine tgauss(fsnr,gt0,t0,dw,dt,n,fmatch,seis,
* ss)
implicit none
integer*4 n, i,ism,nn,nnn
double complex czero,seis(n),ss(n)
real*8 smax(32768)
real*8 pi, dt, gt0, t0, dw, fsnr,sm,smw,fmatch
integer*4 nc,ii,nnl,nnnl,nnr,nnnr,nleft,nright,left(100),right(100)
real*8 freq,dzer,dl,dr,vleft(100),vright(100),tre,tresh
dw = dw
ism = 1
dzer = 0.0d0
czero = (0.0d0,0.0d0)
pi = datan(1.0d0)*4.0d0
nc = nint(gt0/dt)+1
c find global max, sm, and index ism
sm = 0.0d0
do i = 1,n
smw = cdabs(seis(i))
if(smw.ge.sm) then
sm = smw
ism = i
endif
smax(i) = smw
ss(i) = seis(i)
enddo
write(*,*) 'Distance between maximas=',gt0-(ism-1)*dt-t0,
* ' in sec,',
* ' Spectra point= ',ism
c find some local minima,# < 100 from left and right side of central max ism
c left side
nleft = 0
do i = ism-1,2,-1
dl = smax(i)-smax(i-1)
dr = smax(i+1)-smax(i)
if((dl.lt.dzer.and.dr.ge.dzer).or.(dl.le.dzer.and.dr.gt.dzer)) then
nleft = nleft+1
left(nleft) = i
vleft(nleft) = smax(i)
endif
if(nleft.ge.100) goto 10
enddo
10 continue
c right side
nright = 0
do i = ism+1,n-1
dl = smax(i)-smax(i-1)
dr = smax(i+1)-smax(i)
if((dl.lt.dzer.and.dr.ge.dzer).or.(dl.le.dzer.and.dr.gt.dzer)) then
nright = nright+1
right(nright) = i
vright(nright) = smax(i)
endif
if(nright.ge.100) goto 20
enddo
20 continue
c left side, apply cutting
ii = 0
nnl = 0
nnnl = 0
if(nleft.eq.0) goto 21
do i = 1,nleft
if(abs(ism-left(i))*dt.gt.5.0d0) then
if(vleft(i) .lt. fsnr*sm) then
nnnl = left(i)
ii = i
goto 21
endif
endif
enddo
21 continue
if(nnnl.ne.0) then
if(ii.ne.nleft) then
nnl = left(ii+1)
else
nnl = 1
endif
endif
c right side, apply cutting
ii = 0
nnr = 0
nnnr = 0
if(nright.eq.0) goto 31
do i = 1,nright
if(abs(ism-right(i))*dt.gt.5.0d0) then
if(vright(i) .lt. fsnr*sm) then
nnr = right(i)
ii = i
goto 31
endif
endif
enddo
31 continue
if(nnr.ne.0) then
if(ii.ne.nright) then
nnnr = right(ii+1)
else
nnnr = n
endif
endif
c ---
if(nnnr.ne.0.and.nnnl.ne.0) then
nn = max0(iabs(ism-nnnl),iabs(ism-nnr))
nnn = max0(iabs(nnnl-nnl),iabs(nnnr-nnr))
nnnl = ism -nn
nnl = nnnl-nnn
nnr = ism +nn
nnnr = nnr+nnn
endif
c setup cutting point for gaussian
tresh = dlog(sm)-24.0d0
if(nnl.eq.0.or.nnnl.eq.0) goto 30
c expand left end by factor fmatch
nnl = nint((nnl-ism)*fmatch)+ism
nnnl = nint((nnnl-ism)*fmatch)+ism
nnl = max0(1,nnl)
nnnl = max0(1,nnnl)
freq =(nnnl-nnl)+1
do i = 1,nnnl
tre = -(i-nnnl)/freq*(i-nnnl)/freq/2.0d0
if(tre .gt. tresh) then
ss(i) = ss(i)*dexp(tre)
else
ss(i) = czero
endif
enddo
30 continue
if(nnr.eq.0.or.nnnr.eq.0) goto 40
c expand right end by factor fmatch
nnr = nint((nnr-ism)*fmatch)+ism
nnnr = nint((nnnr-ism)*fmatch+ism)
nnr = min0(n,nnr)
nnnr = min0(n,nnnr)
freq =(nnnr-nnr)+1
do i = nnr,n
tre = -(i-nnr)/freq*(i-nnr)/freq/2.0d0
if(tre .gt. tresh) then
ss(i) = ss(i)*dexp(tre)
else
ss(i) = czero
endif
enddo
40 continue
write(*,*) nnl,nnnl,ism,nnr,nnnr
return
end
|
mod common;
mod read;
mod write;
pub use common::read_gzip_json;
#[cfg(feature = "io_ipc_write_async")]
mod write_stream_async;
#[cfg(feature = "io_ipc_write_async")]
mod write_file_async;
#[cfg(feature = "io_ipc_read_async")]
mod read_stream_async;
#[cfg(feature = "io_ipc_read_async")]
mod read_file_async;
|
// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Update github releases tarballs.
import 'dart:io';
import 'package:cronet/src/constants.dart';
import 'package:path/path.dart';
void main() {
final pwd = Directory.current;
Directory.current =
Directory.current.uri.resolve(join('.dart_tool', 'cronet')).path;
for (final platform in desktopPlatforms) {
if (File(join(platform, getCronetName(platform))).existsSync()) {
final result =
Process.runSync('tar', ['-czvf', '$platform.tar.gz', platform]);
print(result.stdout);
print(result.stderr);
} else {
print('${getCronetName(platform)} not found in' +
join('.dart_tool', 'cronet', platform));
}
}
// Make tarball for android releases.
Directory.current = pwd;
if (!Directory(androidPaths['cronet.jar']!).existsSync()) return;
Directory(tempAndroidDownloadPath['cronet.jar']!).createSync(recursive: true);
Directory(androidPaths['cronet.jar']!).listSync().forEach((jar) {
if (jar is File) {
jar.copySync(
join(tempAndroidDownloadPath['cronet.jar']!, basename(jar.path)));
}
});
Directory(tempAndroidDownloadPath['cronet.so']!).createSync(recursive: true);
Directory(androidPaths['cronet.so']!)
.listSync(recursive: true)
.forEach((cronet) {
if (cronet is File) {
Directory(join(tempAndroidDownloadPath['cronet.so']!,
basename(cronet.parent.path)))
.createSync(recursive: true);
cronet.copySync(join(tempAndroidDownloadPath['cronet.so']!,
basename(cronet.parent.path), basename(cronet.path)));
}
});
Directory.current =
Directory.current.uri.resolve(join('.dart_tool', 'cronet')).path;
final result = Process.runSync('tar', ['-czvf', 'android.tar.gz', 'android']);
print(result.stdout);
print(result.stderr);
}
|
module Main (main) where
import Criterion.Main
import Bcc.Crypto.Libsodium.Init
import qualified Bench.Crypto.VRF (benchmarks)
import qualified Bench.Crypto.KES (benchmarks)
main :: IO ()
main = do
sodiumInit
defaultMain benchmarks
benchmarks :: [Benchmark]
benchmarks =
[ Bench.Crypto.VRF.benchmarks
, Bench.Crypto.KES.benchmarks
]
|
"""
====================
Using LIME Explainer
====================
This example illustrates how to use the LIME tabular explainer to explain a
prediction.
This example shows how to use the tabular LIME implementation --
:class:`fatf.transparency.predictions.surrogate_explainers.TabularBlimeyLime`
-- to explain a prediction of a black-box probabilistic model.
"""
# Author: Kacper Sokol <k.sokol@bristol.ac.uk>
# License: new BSD
from pprint import pprint
import fatf
import fatf.utils.data.datasets as fatf_datasets
import fatf.utils.models as fatf_models
import fatf.transparency.predictions.surrogate_explainers as fatf_surrogates
import fatf.vis.lime as fatf_vis_lime
print(__doc__)
# Fix random seed
fatf.setup_random_seed(42)
# Load data
iris_data_dict = fatf_datasets.load_iris()
iris_X = iris_data_dict['data']
iris_y = iris_data_dict['target']
iris_feature_names = iris_data_dict['feature_names'].tolist()
iris_class_names = iris_data_dict['target_names'].tolist()
# Train a model
clf = fatf_models.KNN()
clf.fit(iris_X, iris_y)
# Create a LIME explainer
lime = fatf_surrogates.TabularBlimeyLime(
iris_X,
clf,
feature_names=iris_feature_names,
class_names=iris_class_names)
# Choose an index of the instance to be explained
index_to_explain = 42
# Explain an instance
lime_explanation = lime.explain_instance(
iris_X[index_to_explain, :], samples_number=500)
# Display the textual explanation
pprint(lime_explanation)
# Plot the explanation
fatf_vis_lime.plot_lime(lime_explanation)
|
"""Top-level package for pySCTransform."""
__author__ = """Saket Choudhary"""
__email__ = "saketkc@gmail.com"
__version__ = "0.1.1"
from .pysctransform import get_hvg_residuals, vst, SCTransform
|
#!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import copy
import os
import sys
import unittest
root_dir = os.path.abspath(os.path.join(
os.path.dirname(__file__), os.path.pardir,
os.path.pardir, os.path.pardir, os.path.pardir))
sys.path.insert(0, os.path.join(root_dir, 'third_party', 'mock-1.0.1'))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.path.pardir))
import mock
import auto_bisect.bisector
import auto_bisect.depot_config
class MockRevisionClass(object): # pragma: no cover
def __init__(
self, bisector, commit_hash,
depot_name='chromium', base_revision=None):
self.bisector = bisector
self.commit_hash = commit_hash
self.depot_name = depot_name
self.base_revision = base_revision
self.previous_revision = None
self.next_revision = None
self.values = []
self.overall_return_code = None
self.deps = {}
self.status = ''
def read_deps(self, tester_name):
pass
def retest(self):
self.bisector.last_tested_revision = self
self.values.append(3)
@mock.patch.object(auto_bisect.bisector.Bisector, 'ensure_sync_master_branch',
mock.MagicMock())
class BisectorTest(unittest.TestCase): # pragma: no cover
def setUp(self):
self.bisect_config = {
'test_type': 'perf',
'command': ('tools/perf/run_benchmark -v '
'--browser=release page_cycler.intl_ar_fa_he'),
'good_revision': 'abcd5678abcd5678abcd5678abcd5678abcd5678',
'bad_revision': 'def05678def05678def05678def05678def05678',
'metric': 'warm_times/page_load_time',
'repeat_count': '2',
'max_time_minutes': '5',
'bug_id': '425582',
'gs_bucket': 'chrome-perf',
'builder_host': 'master4.golo.chromium.org',
'builder_port': '8341',
'dummy_builds': True,
}
self.dummy_api = mock.MagicMock()
self.dummy_api.internal_bisect = False
def test_improvement_direction_default(self):
# By default, no improvement direction should be set
bisector = auto_bisect.bisector.Bisector(self.dummy_api, self.bisect_config,
MockRevisionClass)
self.assertIsNone(bisector.improvement_direction)
def test_improvement_direction_greater_is_better_fail(self):
# Improvement up, bad > good: should fail
self.bisect_config['improvement_direction'] = 1
bisector = auto_bisect.bisector.Bisector(self.dummy_api, self.bisect_config,
MockRevisionClass)
bisector.good_rev.mean_value = 10
bisector.bad_rev.mean_value = 100
self.assertFalse(bisector.check_improvement_direction())
self.assertIn('direction of improvement', ''.join(bisector.warnings))
def test_improvement_direction_greater_is_better_pass(self):
# Improvement up, bad < good: should not fail
self.bisect_config['improvement_direction'] = 1
bisector = auto_bisect.bisector.Bisector(self.dummy_api, self.bisect_config,
MockRevisionClass)
bisector.good_rev.mean_value = 100
bisector.bad_rev.mean_value = 10
self.assertTrue(bisector.check_improvement_direction())
self.assertNotIn('direction of improvement', ''.join(bisector.warnings))
def test_improvement_direction_lower_is_better_fail(self):
# Improvement down, bad < good: should fail
self.bisect_config['improvement_direction'] = -1
bisector = auto_bisect.bisector.Bisector(self.dummy_api, self.bisect_config,
MockRevisionClass)
bisector.good_rev.mean_value = 100
bisector.bad_rev.mean_value = 10
self.assertFalse(bisector.check_improvement_direction())
self.assertIn('direction of improvement', ''.join(bisector.warnings))
def test_improvement_direction_lower_is_better_pass(self):
# Improvement down, bad > good: should not fail
self.bisect_config['improvement_direction'] = -1
bisector = auto_bisect.bisector.Bisector(self.dummy_api, self.bisect_config,
MockRevisionClass)
bisector.good_rev.mean_value = 10
bisector.bad_rev.mean_value = 100
self.assertTrue(bisector.check_improvement_direction())
self.assertNotIn('direction of improvement', ''.join(bisector.warnings))
def test_improvement_direction_return_code(self):
# The improvement direction check doesn't apply for return code bisects.
bisect_config = copy.deepcopy(self.bisect_config)
bisect_config['test_type'] = 'return_code'
bisector = auto_bisect.bisector.Bisector(self.dummy_api, bisect_config,
MockRevisionClass)
bisector.good_rev.mean_value = 1
bisector.bad_rev.mean_value = 0
self.assertTrue(bisector.is_return_code_mode())
self.assertTrue(bisector.check_improvement_direction())
@mock.patch.object(auto_bisect.bisector.Bisector, 'significantly_different',
mock.MagicMock(return_value=True))
def test_check_initial_confidence_pass(self):
# patch bisector.significantly_different with true
# assert both revisions have > 5 samples
bisector = auto_bisect.bisector.Bisector(self.dummy_api, self.bisect_config,
MockRevisionClass)
bisector.good_rev.values = [3, 3, 3, 3, 3, 3]
bisector.bad_rev.values = [3, 3, 3, 3]
self.assertTrue(bisector.check_initial_confidence())
self.assertTrue(len(bisector.bad_rev.values) >= 5)
@mock.patch.object(auto_bisect.bisector.Bisector, 'significantly_different',
mock.MagicMock(return_value=False))
def test_check_initial_confidence_non_diverging(self):
bisector = auto_bisect.bisector.Bisector(self.dummy_api, self.bisect_config,
MockRevisionClass)
bisector.good_rev.values = [3, 3, 3, 3, 3, 3]
bisector.bad_rev.values = [3, 3, 3, 3]
self.assertFalse(bisector.check_initial_confidence())
self.assertTrue(len(bisector.bad_rev.values) >=
auto_bisect.bisector.MAX_REQUIRED_SAMPLES or
len(bisector.good_rev.values) >=
auto_bisect.bisector.MAX_REQUIRED_SAMPLES)
def test_check_initial_confidence_return_code_pass(self):
return_code_config = self.bisect_config
return_code_config['test_type'] = 'return_code'
bisector = auto_bisect.bisector.Bisector(self.dummy_api, return_code_config,
MockRevisionClass)
bisector.good_rev.overall_return_code = 0
bisector.bad_rev.overall_return_code = 1
self.assertTrue(bisector.check_initial_confidence())
def test_check_initial_confidence_return_code_fail(self):
return_code_config = self.bisect_config
return_code_config['test_type'] = 'return_code'
bisector = auto_bisect.bisector.Bisector(self.dummy_api, return_code_config,
MockRevisionClass)
bisector.good_rev.overall_return_code = 0
bisector.bad_rev.overall_return_code = 0
self.assertFalse(bisector.check_initial_confidence())
bisector.good_rev.overall_return_code = 1
bisector.bad_rev.overall_return_code = 1
self.assertFalse(bisector.check_initial_confidence())
def test_commit_log_from_gitiles(self):
self.dummy_api.internal_bisect = True
commits = [
{'commit': 'def05678def05678def05678def05678def05678'}, # bad revision
{'commit': 'bbbbb'},
{'commit': 'ccccc'},
]
self.dummy_api.m.gitiles.log = mock.MagicMock(return_value=(commits, None))
auto_bisect.depot_config.DEPOT_DEPS_NAME['android-chrome'] = {
'src' : 'src/internal',
'recurse' : True,
'depends' : None,
'from' : [],
'deps_file': '.DEPS.git',
'url': 'https://dummy-internal-url'
}
bisector = auto_bisect.bisector.Bisector(
self.dummy_api, self.bisect_config, MockRevisionClass)
for r in bisector.revisions:
self.assertIn(r.commit_hash,
[bisector.good_rev.commit_hash,
'bbbbb',
'ccccc',
bisector.bad_rev.commit_hash])
if __name__ == '__main__':
unittest.main() # pragma: no cover
|
package com.italankin.lintchecks
import com.android.tools.lint.client.api.IssueRegistry
import com.android.tools.lint.detector.api.CURRENT_API
import com.android.tools.lint.detector.api.Issue
import com.italankin.lintchecks.detectors.ActivityResultDetector
import com.italankin.lintchecks.detectors.DescriptorJsonDetector
import com.italankin.lintchecks.detectors.PrefsDetector
@Suppress("unused")
class LnchIssueRegistry : IssueRegistry() {
override val api = CURRENT_API
override val issues: List<Issue> = listOf(
DescriptorJsonDetector.ISSUE,
PrefsDetector.ISSUE,
ActivityResultDetector.ISSUE
)
}
|
#!/bin/bash
echo ""
echo "Must set environmental variable:"
echo "export GDAL_DATA=$PREFIX/share/gdal"
|
package io.github.tomplum.aoc.raft.cards
import java.util.*
/**
* A deck of space cards used in a [CombatGame] or a [RecursiveCombatGame].
* @param startingOrder The starting cards for the deck in order.
*/
class SpaceCardDeck(startingOrder: List<Int>) {
private val cards = LinkedList<Int>()
init {
startingOrder.forEach { card -> cards.addLast(card) }
}
/**
* Adds a pair of cards to the bottom of the deck.
* The first card in the pair is added first, and the second last.
* @param pair The cards to be added.
*/
fun add(pair: Pair<Int, Int>) {
cards.addLast(pair.first)
cards.addLast(pair.second)
}
/**
* Draws a single card from the deck.
* The card is removed upon drawing.
* @return The value of the card.
*/
fun draw(): Int = cards.pollFirst()
/**
* Checks if the deck is empty.
* @return true if empty, else false.
*/
fun isEmpty(): Boolean = cards.isEmpty()
/**
* Checks how many cards are currently in the deck.
* @return The number of cards.
*/
fun size(): Int = cards.size
/**
* Creates a new deck by cutting the first [n] cards from the current deck.
* The cut cards are removed from this deck.
* @param n The number of cards to take.
* @return A new deck containing only the cut cards.
*/
fun getCards(n: Int) = SpaceCardDeck(cards.take(n))
/**
* Gets all the cards from the deck.
* @return A list of all the card values, in order.
*/
fun getCards(): List<Int> = cards.toList()
/**
* Calculates the score of the deck in its current state.
* The bottom card in their deck is worth the value of the card multiplied by 1, the second-from-the-bottom
* card is worth the value of the card multiplied by 2, and so on.
* @return The score of the deck.
*/
fun getDeckScore(): Int = cards.reversed().mapIndexed { i, card -> card * (i + 1) }.sum()
override fun equals(other: Any?): Boolean {
if (other !is SpaceCardDeck) return false
return cards == other.cards
}
override fun hashCode(): Int {
return cards.hashCode()
}
override fun toString(): String = cards.toString().removeSurrounding("[", "]")
}
|
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// Author: ddriver
// Date: April 2000
//
namespace System.EnterpriseServices
{
using System;
using System.Runtime.InteropServices;
/// <include file='doc\IObjectConstruct.uex' path='docs/doc[@for="IObjectConstruct"]/*' />
[
ComImport,
Guid("41C4F8B3-7439-11D2-98CB-00C04F8EE1C4"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)
]
internal interface IObjectConstruct
{
/// <include file='doc\IObjectConstruct.uex' path='docs/doc[@for="IObjectConstruct.Construct"]/*' />
void Construct([In, MarshalAs(UnmanagedType.Interface)] Object obj);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.