text
stringlengths 27
775k
|
|---|
CREATE TABLE users (
id uuid PRIMARY KEY,
username varchar(255) not null unique,
email varchar(255) not null unique,
password_hash varchar(255) not null
);
|
package domain
import "sync"
// GracefulShutdown used for a graceful finish usecases
type GracefulShutdown struct {
sync.Mutex
ShutdownNow bool
UsecasesJobs int
}
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.envers.internal.entities.mapper.relation;
import org.hibernate.envers.internal.entities.mapper.relation.component.MiddleComponentMapper;
/**
* A data holder for a middle relation component (which is either the collection element or index):
* - component mapper used to map the component to and from versions entities
* - an index, which specifies in which element of the array returned by the query for reading the collection the data
* of the component is
*
* @author Adam Warski (adam at warski dot org)
*/
public final class MiddleComponentData {
private final MiddleComponentMapper componentMapper;
private final int componentIndex;
public MiddleComponentData(MiddleComponentMapper componentMapper, int componentIndex) {
this.componentMapper = componentMapper;
this.componentIndex = componentIndex;
}
public MiddleComponentMapper getComponentMapper() {
return componentMapper;
}
public int getComponentIndex() {
return componentIndex;
}
}
|
// -*- C++ -*-
//
// Package: Services
// Class : CheckTransitions
//
// Implementation:
// <Notes on implementation>
//
// Original Author: Chris Jones
// Created: Thu Sep 8 14:17:58 EDT 2005
//
#include "FWCore/ServiceRegistry/interface/ServiceMaker.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ServiceRegistry/interface/ActivityRegistry.h"
#include "FWCore/ServiceRegistry/interface/SystemBounds.h"
#include "FWCore/Utilities/interface/Exception.h"
#include "DataFormats/Provenance/interface/EventID.h"
#include "DataFormats/Provenance/interface/LuminosityBlockID.h"
#include "DataFormats/Provenance/interface/RunID.h"
#include "DataFormats/Provenance/interface/Timestamp.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/ServiceRegistry/interface/GlobalContext.h"
#include "FWCore/ServiceRegistry/interface/PathContext.h"
#include "FWCore/ServiceRegistry/interface/ProcessContext.h"
#include "FWCore/ServiceRegistry/interface/StreamContext.h"
#include <vector>
#include <string>
#include "tbb/concurrent_vector.h"
#include <iostream>
namespace edm {
namespace service {
class CheckTransitions {
public:
enum class Phase { kBeginRun, kBeginLumi, kEvent, kEndLumi, kEndRun };
enum class Transition { IsInvalid, IsStop, IsFile, IsRun, IsLumi, IsEvent };
CheckTransitions(const ParameterSet&, ActivityRegistry&);
~CheckTransitions() noexcept(false);
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
void preallocate(service::SystemBounds const&);
void preBeginJob(PathsAndConsumesOfModulesBase const&, ProcessContext const&);
void postEndJob();
void preOpenFile(std::string const&, bool);
void preCloseFile(std::string const& lfn, bool primary);
void preGlobalBeginRun(GlobalContext const&);
void preGlobalEndRun(GlobalContext const&);
void preStreamBeginRun(StreamContext const&);
void preStreamEndRun(StreamContext const&);
void preGlobalBeginLumi(GlobalContext const&);
void preGlobalEndLumi(GlobalContext const&);
void preStreamBeginLumi(StreamContext const&);
void preStreamEndLumi(StreamContext const&);
void preEvent(StreamContext const&);
private:
tbb::concurrent_vector<std::tuple<Phase, edm::EventID, int>> m_seenTransitions;
std::vector<std::pair<Transition, edm::EventID>> m_expectedTransitions;
int m_nstreams = 0;
bool m_failed = false;
};
} // namespace service
} // namespace edm
using namespace edm::service;
namespace {
using Phase = CheckTransitions::Phase;
using Transition = CheckTransitions::Transition;
Transition stringToType(const std::string& iTrans) {
if (iTrans == "IsStop") {
return Transition::IsStop;
}
if (iTrans == "IsFile") {
return Transition::IsFile;
}
if (iTrans == "IsRun") {
return Transition::IsRun;
}
if (iTrans == "IsLumi") {
return Transition::IsLumi;
}
if (iTrans == "IsEvent") {
return Transition::IsEvent;
}
throw edm::Exception(edm::errors::Configuration) << "Unknown transition type \'" << iTrans << "\'";
return Transition::IsInvalid;
}
std::vector<std::tuple<Phase, edm::EventID, int>> expectedValues(
std::vector<std::pair<Transition, edm::EventID>> const& iTrans, int iNStreams) {
std::vector<std::tuple<Phase, edm::EventID, int>> returnValue;
returnValue.reserve(iTrans.size());
const edm::RunNumber_t maxIDValue = edm::EventID::maxRunNumber();
edm::EventID lastRun = {maxIDValue, 0, 0};
edm::EventID lastLumi = {maxIDValue, maxIDValue, 0};
for (auto const& tran : iTrans) {
switch (tran.first) {
case Transition::IsFile: {
break;
}
case Transition::IsRun: {
if (tran.second != lastRun) {
if (lastRun.run() != maxIDValue) {
//end transitions
for (int i = 0; i < iNStreams; ++i) {
returnValue.emplace_back(Phase::kEndRun, lastRun, i);
}
returnValue.emplace_back(Phase::kEndRun, lastRun, 1000);
}
//begin transitions
returnValue.emplace_back(Phase::kBeginRun, tran.second, -1);
for (int i = 0; i < iNStreams; ++i) {
returnValue.emplace_back(Phase::kBeginRun, tran.second, i);
}
lastRun = tran.second;
}
break;
}
case Transition::IsLumi: {
if (tran.second != lastLumi) {
if (lastLumi.run() != maxIDValue) {
//end transitions
for (int i = 0; i < iNStreams; ++i) {
returnValue.emplace_back(Phase::kEndLumi, lastLumi, i);
}
returnValue.emplace_back(Phase::kEndLumi, lastLumi, 1000);
}
//begin transitions
returnValue.emplace_back(Phase::kBeginLumi, tran.second, -1);
for (int i = 0; i < iNStreams; ++i) {
returnValue.emplace_back(Phase::kBeginLumi, tran.second, i);
}
lastLumi = tran.second;
}
break;
}
case Transition::IsEvent: {
returnValue.emplace_back(Phase::kEvent, tran.second, -2);
}
case Transition::IsStop:
case Transition::IsInvalid: {
break;
}
}
}
if (lastLumi.run() != maxIDValue) {
//end transitions
for (int i = 0; i < iNStreams; ++i) {
returnValue.emplace_back(Phase::kEndLumi, lastLumi, i);
}
returnValue.emplace_back(Phase::kEndLumi, lastLumi, 1000);
}
if (lastRun.run() != maxIDValue) {
//end transitions
for (int i = 0; i < iNStreams; ++i) {
returnValue.emplace_back(Phase::kEndRun, lastRun, i);
}
returnValue.emplace_back(Phase::kEndRun, lastRun, 1000);
}
return returnValue;
}
} // namespace
CheckTransitions::CheckTransitions(ParameterSet const& iPS, ActivityRegistry& iRegistry) {
for (auto const& p : iPS.getUntrackedParameter<std::vector<edm::ParameterSet>>("transitions")) {
m_expectedTransitions.emplace_back(stringToType(p.getUntrackedParameter<std::string>("type")),
p.getUntrackedParameter<EventID>("id"));
}
iRegistry.watchPreallocate(this, &CheckTransitions::preallocate);
iRegistry.watchPostEndJob(this, &CheckTransitions::postEndJob);
iRegistry.watchPreOpenFile(this, &CheckTransitions::preOpenFile);
iRegistry.watchPreCloseFile(this, &CheckTransitions::preCloseFile);
iRegistry.watchPreGlobalBeginRun(this, &CheckTransitions::preGlobalBeginRun);
iRegistry.watchPreGlobalEndRun(this, &CheckTransitions::preGlobalEndRun);
iRegistry.watchPreStreamBeginRun(this, &CheckTransitions::preStreamBeginRun);
iRegistry.watchPreStreamEndRun(this, &CheckTransitions::preStreamEndRun);
iRegistry.watchPreGlobalBeginLumi(this, &CheckTransitions::preGlobalBeginLumi);
iRegistry.watchPreGlobalEndLumi(this, &CheckTransitions::preGlobalEndLumi);
iRegistry.watchPreStreamBeginLumi(this, &CheckTransitions::preStreamBeginLumi);
iRegistry.watchPreStreamEndLumi(this, &CheckTransitions::preStreamEndLumi);
iRegistry.watchPreEvent(this, &CheckTransitions::preEvent);
}
CheckTransitions::~CheckTransitions() noexcept(false) {
if (m_failed) {
throw edm::Exception(errors::EventProcessorFailure) << "incorrect transtions";
}
}
void CheckTransitions::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
ParameterSetDescription desc;
desc.setComment("Checks that the transitions specified occur during the job.");
ParameterSetDescription trans;
trans.addUntracked<std::string>("type");
trans.addUntracked<edm::EventID>("id");
desc.addVPSetUntracked("transitions", trans, {{}});
descriptions.add("CheckTransitions", desc);
}
void CheckTransitions::preallocate(service::SystemBounds const& bounds) { m_nstreams = bounds.maxNumberOfStreams(); }
void CheckTransitions::postEndJob() {
auto expectedV = expectedValues(m_expectedTransitions, m_nstreams);
std::vector<std::tuple<Phase, edm::EventID, int>> orderedSeen;
orderedSeen.reserve(m_seenTransitions.size());
for (auto const& i : m_seenTransitions) {
// std::cout <<i.first.m_run<<" "<<i.first.m_lumi<<" "<<i.first.m_event<<" "<<i.second<<std::endl;
auto s = std::get<2>(i);
if (std::get<1>(i).event() > 0) {
s = -2;
}
orderedSeen.emplace_back(std::get<0>(i), std::get<1>(i), s);
}
std::sort(orderedSeen.begin(), orderedSeen.end());
auto orderedExpected = expectedV;
std::sort(orderedExpected.begin(), orderedExpected.end());
/* for(auto const& i: expectedV) {
std::cout <<i.first.m_run<<" "<<i.first.m_lumi<<" "<<i.first.m_event<<" "<<i.second<<std::endl;
} */
auto itOS = orderedSeen.begin();
for (auto itOE = orderedExpected.begin(); itOE != orderedExpected.end(); ++itOE) {
if (itOS == orderedSeen.end()) {
break;
}
if (*itOE != *itOS) {
auto syncOE = std::get<1>(*itOE);
auto syncOS = std::get<1>(*itOS);
std::cout << "Different ordering " << syncOE << " " << std::get<2>(*itOE) << "\n"
<< " " << syncOS << " " << std::get<2>(*itOS) << "\n";
m_failed = true;
}
++itOS;
}
if (orderedSeen.size() != orderedExpected.size()) {
std::cout << "Wrong number of transition " << orderedSeen.size() << " " << orderedExpected.size() << std::endl;
m_failed = true;
return;
}
}
void CheckTransitions::preOpenFile(std::string const& lfn, bool b) {}
void CheckTransitions::preCloseFile(std::string const& lfn, bool b) {}
void CheckTransitions::preGlobalBeginRun(GlobalContext const& gc) {
auto id = gc.luminosityBlockID();
m_seenTransitions.emplace_back(Phase::kBeginRun, edm::EventID{id.run(), 0, 0}, -1);
}
void CheckTransitions::preGlobalEndRun(GlobalContext const& gc) {
auto id = gc.luminosityBlockID();
m_seenTransitions.emplace_back(Phase::kEndRun, edm::EventID{id.run(), 0, 0}, 1000);
}
void CheckTransitions::preStreamBeginRun(StreamContext const& sc) {
m_seenTransitions.emplace_back(Phase::kBeginRun, sc.eventID(), sc.streamID());
}
void CheckTransitions::preStreamEndRun(StreamContext const& sc) {
m_seenTransitions.emplace_back(Phase::kEndRun, sc.eventID(), sc.streamID());
}
void CheckTransitions::preGlobalBeginLumi(GlobalContext const& gc) {
auto id = gc.luminosityBlockID();
m_seenTransitions.emplace_back(Phase::kBeginLumi, edm::EventID{id.run(), id.luminosityBlock(), 0}, -1);
}
void CheckTransitions::preGlobalEndLumi(GlobalContext const& gc) {
auto id = gc.luminosityBlockID();
m_seenTransitions.emplace_back(Phase::kEndLumi, edm::EventID{id.run(), id.luminosityBlock(), 0}, 1000);
}
void CheckTransitions::preStreamBeginLumi(StreamContext const& sc) {
m_seenTransitions.emplace_back(Phase::kBeginLumi, sc.eventID(), sc.streamID());
}
void CheckTransitions::preStreamEndLumi(StreamContext const& sc) {
m_seenTransitions.emplace_back(Phase::kEndLumi, sc.eventID(), sc.streamID());
}
void CheckTransitions::preEvent(StreamContext const& sc) {
m_seenTransitions.emplace_back(Phase::kEvent, sc.eventID(), sc.streamID());
}
using edm::service::CheckTransitions;
DEFINE_FWK_SERVICE(CheckTransitions);
|
package routes
import (
"time"
"github.com/skyareas/skyjet"
)
func NewAuthRouter() *skyjet.Router {
r := skyjet.NewRouter()
r.Get("/login", getLogin)
r.Post("/login", postLogin)
r.Post("/logout", logout)
return r
}
func getLogin(_ *skyjet.HttpRequest, res *skyjet.HttpResponse) error {
year := time.Now().Format("2006")
return res.Render("login.html", skyjet.D{"CurrentYear": year})
}
func postLogin(req *skyjet.HttpRequest, res *skyjet.HttpResponse) error {
err := req.Request.ParseForm()
if err != nil {
return err
}
skyjet.App().Log().Printf("%v\n", req.Request.Form)
req.Session.Set("username", req.Request.Form.Get("username"))
res.Redirect("/")
return nil
}
func logout(_ *skyjet.HttpRequest, res *skyjet.HttpResponse) error {
res.Redirect("/")
return nil
}
|
package eventInput
type EventInput int
func (el EventInput) String() string {
return eventInputString[el]
}
var eventInputString = [...]string{
"input",
}
const (
// KInput
// en: The event occurs when an element gets user input
KInput EventInput = iota
)
|
import { Service, $log } from "@tsed/common";
import EmployeeRepository from "./../../repositories/EmployeeRepository";
import Employee from "../../models/Employee";
@Service()
export class EmployeeService {
constructor(private readonly empRepo: EmployeeRepository) {}
/**
* Return ALl the Employees Stored in the database.
*/
public async getAll(): Promise<Employee[]> {
/*const [ allEmployees, noOfEmployess ] = await this.empRepo.findAndCount({
where : {}, select : "*",
take : 100, skip : 0
});*/
const allEmployees = await this.empRepo.find();
const finalSetOfEmployees: Employee[] = [];
allEmployees.forEach((emp) => {
const empModel = new Employee();
empModel.id = emp.id;
empModel.name = emp.name;
finalSetOfEmployees.push(empModel);
});
return finalSetOfEmployees;
}
}
|
from tornado.web import RequestHandler
import json
import socketio
from socketio import AsyncNamespace
# WebSocket Namespaces
from routes.api.guids import Guilds
sio = socketio.AsyncServer(async_mode="tornado")
_Handler = socketio.get_tornado_handler(sio)
config = json.load(open("config/web.json"))
CORS_ORGINS = config["CORS_ORGINS"]
class PrimaryHandler(RequestHandler):
def get_current_user(self):
userIDCookie = self.get_secure_cookie("userauthtoken")
if userIDCookie is not None:
return userIDCookie.decode()
else:
return None
def set_default_headers(self):
for cor_orgin in CORS_ORGINS:
self.set_header("Access-Control-Allow-Origin", cor_orgin)
self.set_header("Access-Control-Allow-Headers", "x-requested-with")
self.set_header("Access-Control-Allow-Credentials", "true")
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
class SocketHandler(_Handler):
def check_origin(self, origin):
if origin in CORS_ORGINS:
return True
else:
return False
class APIMain(AsyncNamespace):
async def on_connect(self, sid, environ):
print("A socket connected!")
await self.emit("api_response",
data = "Hello Dashboard!"
)
sio.register_namespace(APIMain("/api/"))
sio.register_namespace(Guilds("/api/guilds"))
|
# macOS dev environment setup
## Security
### Hard disc encryption
Go to `System preferences > Security & Privacy > FileVault` and make sure the FileVault is ON.
### Firewall
Go to `System preferences > Security & Privacy > Firewall` and make sure the Firewall is ON.
### More
https://blog.bejarano.io/hardening-macos.html
## Keyboard preferences
In `System preferences > Keyboard`:
* `Key Repeat > Fast` (all the way to the right)
* `Delay Until Repeat > Short` (all the way to the right)
* `Modifier Keys... > Caps Lock (⇪) Key` set to `^ Control`
## Apps
#### Text editor
Install VS Code: https://code.visualstudio.com/
##### Configuration
Open VS Code, go to `Code` > `Preferences` > `Settings` and paste:
```yml
{
"editor.rulers": [
120
],
"editor.tabSize": 2,
"workbench.colorTheme": "One Monokai",
"explorer.confirmDragAndDrop": false,
"explorer.confirmDelete": false,
"workbench.startupEditor": "newUntitledFile",
"files.insertFinalNewline": true,
"files.trimTrailingWhitespace": true,
"files.trimFinalNewlines": true,
"terminal.integrated.fontFamily": "Meslo LG S DZ for Powerline",
}
```
Install `One Monokai` extension.
#### Web browser
Install Chrome: https://www.google.com/chrome/browser/desktop/index.html
#### Terminal
Install iTerm2: https://www.iterm2.com/downloads.html
#### Software package manager
Install Homebrew: http://brew.sh/
#### Basic tools
Install some useful packages:
```shell
brew install curl mc gpg gpg2
```
#### Git
Install Git:
```shell
brew install git
```
Set you username and email in Git:
```shell
git config --global user.name "Mona Lisa"
git config --global user.email "email@example.com"
```
:warning: Don't forget to replace _"Mona Lisa"_ and _"email@example.com"_ with your own data.
#### Shell
Install [Zsh] and set it as a default shell:
```shell
brew install zsh zsh-completions
chsh -s /bin/zsh
```
:warning: Reopen terminal window now to load Zsh shell.
Install [Oh My Zsh]:
```shell
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
```
#### Make your terminal look pretty
##### Use Dark Background in iTerm2
* Go to: `iTerm2 > Preferences > Profiles > Colors`
* Use `Color presets...` menu to import and select downloaded `Pastel (Dark Background)` theme
##### Install [Powerline Fonts]
```shell
cd $HOME
git clone https://github.com/powerline/fonts.git
./fonts/install.sh
rm -rf ~/fonts/
```
##### Set font in iTerm2
* Go to: `iTerm2 > Preferences > Profiles > Text > Font > Change Font`
* Select the font: `Fixed Width > Meslo LG S DZ for Powerline > RegularForPowerline > 11`
##### Set [zsh theme]
Edit `~/.zshrc` file and update `ZSH_THEME=` to:
```shell
ZSH_THEME="agnoster"
```
#### Configure Zsh
Install [zsh-autosuggestions]:
```shell
git clone git://github.com/zsh-users/zsh-autosuggestions $ZSH_CUSTOM/plugins/zsh-autosuggestions
```
Edit `~/.zshrc` file and update `plugins=` to:
```shell
plugins=(git bundler osx rake ruby rails zsh-autosuggestions fasd)
```
:mortar_board: List of all available plugins is here: https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins.
Edit `~/.zshrc` file and the following lines at the end:
```shell
export EDITOR='vim'
DEFAULT_USER=`whoami`
HISTFILE=$HOME/.zsh_history
HISTSIZE=10000
SAVEHIST=10000
setopt APPEND_HISTORY # append rather than overwrite history file.
setopt EXTENDED_HISTORY # save timestamp and runtime information
setopt HIST_EXPIRE_DUPS_FIRST # allow dups, but expire old ones when I hit HISTSIZE
setopt HIST_FIND_NO_DUPS # don't find duplicates in history
setopt HIST_IGNORE_ALL_DUPS # ignore duplicate commands regardless of commands in between
setopt HIST_IGNORE_DUPS # ignore duplicate commands
setopt HIST_REDUCE_BLANKS # leave blanks out
setopt HIST_SAVE_NO_DUPS # don't save duplicates
setopt INC_APPEND_HISTORY # write after each command
setopt SHARE_HISTORY # share history between sessions
ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=30'
LC_CTYPE=en_US.UTF-8
LC_ALL=en_US.UTF-8
```
#### Vim
Install [Janus Vim Distribution]:
```shell
curl -L https://bit.ly/janus-bootstrap | bash
```
Map `jj` to `esc`:
```shell
echo ':imap jj <Esc>' >> ~/.vimrc.before
```
### Another apps I recommend
* [Alfred](https://www.alfredapp.com/)
* [Spectacle](https://www.spectacleapp.com/)
* [Monosnap](https://monosnap.com/welcome)
### RoR & web development
#### PostgreSQL
```shell
brew install postgresql
brew services start postgresql
```
#### Redis
```shell
brew install redis
brew services start redis
```
#### Node Version Manager
Install NVM: https://github.com/creationix/nvm
##### Install yarn
```shell
npm install -g yarn
```
#### Ruby version manager
Install RVM: https://rvm.io/rvm/install
[Zsh]: http://www.zsh.org/
[Oh My Zsh]: https://github.com/robbyrussell/oh-my-zsh
[Powerline Fonts]: https://github.com/powerline/fonts
[zsh theme]: https://github.com/robbyrussell/oh-my-zsh/wiki/Themes
[Solarized Theme]: http://ethanschoonover.com/solarized
[zsh-autosuggestions]: https://github.com/zsh-users/zsh-autosuggestions
[Janus Vim Distribution]: https://github.com/carlhuda/janus
|
var stepped = 0;
var start, end;
$(function()
{
$('#submit').click(function()
{
stepped = 0;
var txt = $('#input').val();
var files = $('#files')[0].files;
var config = buildConfig();
if (files.length > 0)
{
start = performance.now();
$('#files').parse({
config: config,
before: function(file, inputElem)
{
console.log("Parsing file:", file);
},
complete: function()
{
console.log("Done with all files.");
}
});
}
else
{
start = performance.now();
var results = Papa.parse(txt, config);
console.log("Synchronous parse results:", results);
}
});
$('#insert-tab').click(function()
{
$('#delimiter').val('\t');
});
});
function buildConfig()
{
return {
delimiter: $('#delimiter').val(),
header: $('#header').prop('checked'),
dynamicTyping: $('#dynamicTyping').prop('checked'),
preview: parseInt($('#preview').val() || 0),
step: $('#stream').prop('checked') ? stepFn : undefined,
encoding: $('#encoding').val(),
worker: $('#worker').prop('checked'),
comments: $('#comments').val(),
complete: completeFn,
download: $('#download').prop('checked')
};
}
function stepFn(results, parser)
{
stepped++;
}
function completeFn()
{
end = performance.now();
console.log("Finished input. Time:", end-start, arguments);
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Authy.Net
{
/// <summary>
/// The result of a request to verify a token
/// </summary>
public class VerifyTokenResult : AuthyResult
{
/// <summary>
/// Confirmation if token is valid or invalid
/// </summary>
public string Token { get; set; }
}
}
|
#! /usr/bin/env bash
#BSUB -J cellranger
#BSUB -o logs/cellranger_%J.out
#BSUB -e logs/cellranger_%J.err
#BSUB -R "select[mem>4] rusage[mem=4]"
#BSUB -q rna
set -o nounset -o pipefail -o errexit -x
mkdir -p logs
run_snakemake() {
local config_file=$1
drmaa_args='
-o {log}.out
-e {log}.err
-J {params.job_name}
-R "{params.memory} span[hosts=1] "
-n {threads} '
snakemake \
--snakefile Snakefile \
--drmaa "$drmaa_args" \
--jobs 50 \
--latency-wait 60 \
--rerun-incomplete \
--configfile $config_file
}
run_snakemake config.yaml
|
//! Skybox rendering
use super::{to_u8_slice, SkyboxVertex};
use wgpu::util::{BufferInitDescriptor, DeviceExt};
const FAR: f32 = 900.0;
const EAST: [[f32; 3]; 4] = [
[FAR, -FAR, -FAR],
[FAR, -FAR, FAR],
[FAR, FAR, -FAR],
[FAR, FAR, FAR],
];
const MESH_INDEX: [u32; 6] = [0, 1, 2, 3, 2, 1];
const WEST: [[f32; 3]; 4] = [
[-FAR, -FAR, -FAR],
[-FAR, -FAR, FAR],
[-FAR, FAR, -FAR],
[-FAR, FAR, FAR],
];
const UP: [[f32; 3]; 4] = [
[-FAR, FAR, -FAR],
[-FAR, FAR, FAR],
[FAR, FAR, -FAR],
[FAR, FAR, FAR],
];
const DOWN: [[f32; 3]; 4] = [
[-FAR, -FAR, -FAR],
[-FAR, -FAR, FAR],
[FAR, -FAR, -FAR],
[FAR, -FAR, FAR],
];
const SOUTH: [[f32; 3]; 4] = [
[-FAR, -FAR, FAR],
[-FAR, FAR, FAR],
[FAR, -FAR, FAR],
[FAR, FAR, FAR],
];
const NORTH: [[f32; 3]; 4] = [
[-FAR, -FAR, -FAR],
[-FAR, FAR, -FAR],
[FAR, -FAR, -FAR],
[FAR, FAR, -FAR],
];
const POS: [[[f32; 3]; 4]; 6] = [EAST, WEST, UP, DOWN, SOUTH, NORTH];
/// Create the vertex and the index buffer for the skybox.
pub fn create_skybox(device: &wgpu::Device) -> (wgpu::Buffer, wgpu::Buffer) {
let mut vertices = Vec::new();
let mut indices = Vec::new();
for i in 0..6 {
for l in 0..4 {
vertices.push(SkyboxVertex {
position: [POS[i][l][0], POS[i][l][1], POS[i][l][2]],
});
}
for l in 0..6 {
indices.push(MESH_INDEX[l] + (i as u32 * 4));
}
}
(
{
let vertices_slice = to_u8_slice(&vertices);
device.create_buffer_init(&BufferInitDescriptor {
label: Some("skybox_vertices"),
usage: wgpu::BufferUsage::COPY_SRC | wgpu::BufferUsage::VERTEX,
contents: &vertices_slice,
})
},
{
let indices_slice = to_u8_slice(&indices);
device.create_buffer_init(&BufferInitDescriptor {
label: Some("skybox_indicies"),
usage: wgpu::BufferUsage::COPY_SRC | wgpu::BufferUsage::INDEX,
contents: &indices_slice,
})
},
)
}
|
#!/usr/bin/env bash
set -e
set +x
cmd_args=()
compose_exec="docker-compose"
if ! command -v "${compose_exec}" &> /dev/null; then
compose_exec="docker"
cmd_args+=("compose")
fi
if ! command -v "${compose_exec}" &> /dev/null; then
echo "Unable to locate or docker."
echo "Please follow the instructios present here: https://docs.docker.com/get-docker/"
exit 1
fi
build_args=("${cmd_args[@]}")
build_args+=(
'build'
'--build-arg'
"UID=$(id -u)"
'--build-arg'
"GID=$(id -g)"
'--progress'
'plain'
'--no-cache'
'download-csv'
)
run_args=("${cmd_args[@]}")
run_args+=(
'run'
'-u'
"$(id -u):$(id -g)"
'-v'
"$(pwd)/repos-csv-output:/repos-csv-output:rw"
'download-csv'
)
echo "Ensuring image is up to date"
"${compose_exec[*]}" "${build_args[@]}"
echo "Executing CSV generation..."
exec "${compose_exec[*]}" "${run_args[@]}"
|
package com.example.android.basicandroidaccessibility.ui.home
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.annotation.Nullable
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import com.example.android.basicandroidaccessibility.R
import com.example.android.basicandroidaccessibility.databinding.FragmentHomeBinding
import com.example.android.basicandroidaccessibility.ui.user.UserDetailFragment
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager
import com.example.android.basicandroidaccessibility.ui.user.LoginFragment
import com.example.android.basicandroidaccessibility.ui.user.SignupFragment
class HomeFragment : Fragment() {
private lateinit var homeViewModel: HomeViewModel
// 该属性仅在 onCreateView 和onDestroyView
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
// 声明执行器来解析 URL
private val executor: ExecutorService = Executors.newSingleThreadExecutor()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
_binding = FragmentHomeBinding.inflate(inflater, container, false)
val root: View = binding.root
// 文本内容
val textView: TextView = binding.textHome
homeViewModel.text.observe(viewLifecycleOwner, Observer {
textView.text = it
})
// 登陆注册
// var tab_toolbar = binding.toolbar
var tab_viewpager = binding.tabViewpager
var tab_tablayout = binding.tabTablayout
// (activity as AppCompatActivity?)!!.setSupportActionBar(tab_toolbar)
setupViewPager(tab_viewpager)
tab_tablayout.setupWithViewPager(tab_viewpager)
return root
}
private fun setupViewPager(viewpager: ViewPager) {
var adapter: ViewPagerAdapter? = fragmentManager?.let { ViewPagerAdapter(it) }
// LoginFragment is the name of Fragment and the Login
// is a title of tab
adapter?.addFragment(LoginFragment(), "博客")
adapter?.addFragment(SignupFragment(), "测验")
// setting adapter to view pager.
viewpager.adapter = adapter
}
class ViewPagerAdapter : FragmentStatePagerAdapter {
// objects of arraylist. One is of Fragment type and
// another one is of String type.*/
private final var fragmentList1: ArrayList<Fragment> = ArrayList()
private final var fragmentTitleList1: ArrayList<String> = ArrayList()
// this is a secondary constructor of ViewPagerAdapter class.
public constructor(supportFragmentManager: FragmentManager)
: super(supportFragmentManager)
// returns which item is selected from arraylist of fragments.
override fun getItem(position: Int): Fragment {
return fragmentList1[position]
}
// returns which item is selected from arraylist of titles.
@Nullable
override fun getPageTitle(position: Int): CharSequence {
return fragmentTitleList1[position]
}
// returns the number of items present in arraylist.
override fun getCount(): Int {
return fragmentList1.size
}
// this function adds the fragment and title in 2 separate arraylist.
fun addFragment(fragment: Fragment, title: String) {
fragmentList1.add(fragment)
fragmentTitleList1.add(title)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
|
import configuration from './configuration';
import * as NodeCache from 'node-cache';
class Cache {
cache: NodeCache.NodeCache
constructor() {
this.cache = new NodeCache({ stdTTL: 0, checkperiod: 60 })
}
setKey(key: string, obj) {
this.cache.set(key, obj);
return Promise.resolve();
}
getKey<T>(key: string): Promise<T> {
return new Promise((resolve, reject) => {
this.cache.get(key, (err, result) => {
if (err) reject(err);
else resolve(result);
})
})
}
removeAll() {
this.cache.flushAll()
}
}
const singleton = new Cache();
export default singleton;
|
function get_tag_info(tag::GitHub.Tag)
str = sprint() do io
Downloads.download(tag.object["url"], io)
end
dict = JSON.parse(str)
parts = splitpath(tag.url.path) # why is this not straight-forward?
repo = GitHub.Repo(parts[3] * "/" * parts[4])
return (
commit = dict["object"]["sha"],
name = dict["tag"],
repo = repo,
message = dict["message"],
)
end
function commits_between(tag1, tag2, auth; repo="JuliaPlots/Makie.jl")
t1 = GitHub.tag(repo, "v0.16.5")
t2 = GitHub.tag(repo, "v0.15.3")
t1info = get_tag_info(t1)
t2info = get_tag_info(t2)
params = Dict("per_page" => 100)
commits, _ = GitHub.commits(repo; auth=auth, params)
idx1 = findfirst(x-> x.sha == t1info.commit, commits)
idx2 = findfirst(x-> x.sha == t2info.commit, commits)
return commits[min(idx1, idx2):max(idx1, idx2)]
end
function JSServe.jsrender(owner::GitHub.Owner)
name = DOM.span(string(owner.login), style="margin: 2px; color: 'gray")
img = DOM.img(src=owner.avatar_url, style="border-radius: 50%", width=22)
img_name = DOM.div(img, name; style="display: flex; align-items: center")
return DOM.span(
DOM.a(img_name, href=owner.html_url; style="color: gray; text-decoration: none");
style="padding: 2px")
end
|
package br.ufmg.cs.systems.fractal.util
import java.io.{ObjectInputStream, ObjectOutputStream}
import org.apache.hadoop.conf.Configuration
class SerializableConfiguration(@transient var value: Configuration) extends Serializable {
private def writeObject(out: ObjectOutputStream): Unit = {
out.defaultWriteObject()
value.write(out)
}
private def readObject(in: ObjectInputStream): Unit = {
value = new Configuration(false)
value.readFields(in)
}
}
|
<?php
namespace tests;
use alexantr\tinymce\TinyMCEAsset;
use yii\web\AssetBundle;
class TinyMCEAssetTest extends TestCase
{
public function testRegister(): void
{
$view = $this->mockView();
$this->assertEmpty($view->assetBundles);
TinyMCEAsset::register($view);
// TinyMCEAsset
$this->assertCount(1, $view->assetBundles);
$this->assertArrayHasKey('alexantr\\tinymce\\TinyMCEAsset', $view->assetBundles);
$this->assertTrue($view->assetBundles['alexantr\\tinymce\\TinyMCEAsset'] instanceof AssetBundle);
$out = $view->renderFile('@tests/data/views/layout.php');
$this->assertRegExp('%"/assets/[0-9a-z]+/tinymce.min.js"%', $out);
}
}
|
package soy.gabimoreno.imagegenerator.domain
private const val COLOR_WHITE = "FFFFFF"
const val CANVAS_WIDTH = 1500
const val CANVAS_HEIGHT = 750
const val POLYGON_WIDTH = 500
const val POLYGON_HEIGHT = 500
const val POLYGON_COLOR = COLOR_WHITE
const val INCLINATION = 25
const val SATURATION = 50
const val BRIGHTNESS = 74
|
#include <array>
#include <iostream>
template <typename T, size_t N>
std::istream& operator >>(std::istream& input, std::array<T, N>& v)
{
for (T& a : v)
input >> a;
return input;
}
void answer(unsigned v)
{
std::cout << v << '\n';
}
void solve(const std::array<unsigned, 5>& m, const std::array<unsigned, 5>& w, unsigned hs, unsigned hu)
{
constexpr unsigned c[5] = { 500, 1000, 1500, 2000, 2500 };
unsigned s = 100 * hs;
for (size_t i = 0; i < 5; ++i) {
const unsigned u = c[i] - c[i] * m[i] / 250;
const unsigned v = 50 * w[i];
s += std::max(c[i] * 3 / 10, v > u ? 0 : u - v);
}
const unsigned d = 50 * hu;
answer(s > d ? s - d : 0);
}
int main()
{
std::array<unsigned, 5> m;
std::cin >> m;
std::array<unsigned, 5> w;
std::cin >> w;
unsigned hs, hu;
std::cin >> hs >> hu;
solve(m, w, hs, hu);
return 0;
}
|
package com.avito.ci.steps
import com.avito.android.plugin.artifactory.artifactoryAppBackupTask
import com.avito.cd.AndroidArtifactType.APK
import com.avito.cd.AndroidArtifactType.BUNDLE
import com.avito.cd.CdBuildConfig
import com.avito.cd.cdBuildConfig
import com.avito.cd.isCdBuildConfigPresent
import com.avito.logger.GradleLoggerFactory
import com.avito.logger.create
import com.avito.upload_to_googleplay.GooglePlayDeploy
import com.avito.upload_to_googleplay.registerDeployToGooglePlayTask
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.tasks.TaskProvider
import java.io.File
class DeployStep(
context: String,
private val artifacts: ArtifactsConfiguration,
name: String
) : SuppressibleBuildStep(context, name) {
override fun registerTask(
project: Project,
rootTask: TaskProvider<out Task>
) {
if (project.isCdBuildConfigPresent) {
registerDeploymentsTasks(
project.cdBuildConfig.get().deployments,
project,
rootTask
)
} else {
val loggerFactory = GradleLoggerFactory.fromProject(project)
val logger = loggerFactory.create<DeployStep>()
logger.debug("Configure deploy step without cd build config")
}
}
// todo есть сомнения в правильности этого места
private fun registerDeploymentsTasks(
deployments: List<CdBuildConfig.Deployment>,
project: Project,
rootTask: TaskProvider<out Task>
) {
val googlePlayDeployments = mapDeploymentsToGooglePlayDeploys(deployments)
if (googlePlayDeployments.isNotEmpty()) {
val uploadToPlayMarketTask = project.tasks.registerDeployToGooglePlayTask(
deploys = googlePlayDeployments
) {
dependsOn(verifyTaskName(context))
dependsOn(project.tasks.artifactoryAppBackupTask())
}
rootTask.configure { it.finalizedBy(uploadToPlayMarketTask) }
}
}
private fun mapDeploymentsToGooglePlayDeploys(
deployments: List<CdBuildConfig.Deployment>
): List<GooglePlayDeploy> {
return deployments
.asSequence()
.filterIsInstance<CdBuildConfig.Deployment.GooglePlay>()
.map { deployment ->
try {
val outputs = artifacts.outputs.values
val mappings = outputs.findOutput<Output.ProguardMapping> { artifact ->
artifact.variant == deployment.buildVariant
}
when (deployment.artifactType) {
APK -> {
val apk = outputs.findOutput<Output.ApkOutput> { output ->
output.variant == deployment.buildVariant
}
GooglePlayDeploy(
binaryType = GooglePlayDeploy.BinaryType.APK,
track = deployment.track.name.toLowerCase(),
applicationId = apk.packageName,
binary = File(apk.path),
mapping = File(mappings.path)
)
}
BUNDLE -> {
val bundle = outputs.findOutput<Output.BundleOutput> { output ->
output.variant == deployment.buildVariant
}
GooglePlayDeploy(
binaryType = GooglePlayDeploy.BinaryType.BUNDLE,
track = deployment.track.name.toLowerCase(),
applicationId = bundle.packageName,
binary = File(bundle.path),
mapping = File(mappings.path)
)
}
}
} catch (e: Exception) {
throw IllegalStateException("Can't configure deployment=$deployment", e)
}
}
.toList()
}
private inline fun <reified O : Output> Iterable<Output>.findOutput(noinline predicate: (O) -> Boolean): O {
val outputs: Sequence<O> = asSequence()
.filterIsInstance<O>()
.filter(predicate)
outputs.ifEmpty { throw IllegalStateException("Cant' find output ${O::class.java} in $this") }
return outputs.singleOrNull()
?: throw IllegalStateException("Too many outputs: $outputs of type ${O::class.java} in $this")
}
}
|
import { Balance } from './../models/balance.model';
import { Exchange } from './../enums/exchange.enum';
export class Investor {
readonly _id: string;
readonly name: string;
readonly trader_id?: string;
readonly tradeKey?: string;
readonly tradeSecret?: string;
readonly email: string;
readonly phone: string;
chart?: any;
available?: number;
btcvalue?: number;
usdvalue?: number;
eurvalue?: number;
gbpvalue?: number;
currency?: string;
status?: string;
group?: string;
balances?: Balance[];
readonly exchange: Exchange;
readonly createdAt?: string;
readonly updatedAt?: number;
}
|
/*
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.sun.corba.ee.impl.copyobject ;
import java.rmi.Remote;
import org.omg.CORBA.ORB ;
import com.sun.corba.ee.impl.util.Utility;
import org.glassfish.pfl.dynamic.copyobject.impl.JavaStreamObjectCopierImpl ;
public class JavaStreamORBObjectCopierImpl extends JavaStreamObjectCopierImpl {
private ORB orb ;
public JavaStreamORBObjectCopierImpl( ORB orb ) {
this.orb = orb ;
}
public Object copy(Object obj, boolean debug ) {
return copy( obj ) ;
}
@Override
public Object copy(Object obj) {
if (obj instanceof Remote) {
// Yes, so make sure it is connected and converted
// to a stub (if needed)...
return Utility.autoConnect(obj,orb,true);
}
return super.copy( obj ) ;
}
}
|
(function ($, Drupal) {
/**
* Add necessary theming hooks.
*/
$.extend(Drupal.theme, /** @lends Drupal.theme */{
commerceAuthorizeNetError: function (message) {
return $('<div class="messages messages--error alert alert-danger alert-dismissible"></div>').html(message);
}
});
})(window.jQuery, window.Drupal);
|
package com.rewardtodo.cache.mapper
import com.rewardtodo.cache.model.UserEntity
import com.rewardtodo.domain.User
object UserMapper: Mapper<UserEntity, User> {
override fun mapToEntity(type: User): UserEntity {
return UserEntity(
type.name,
type.points,
type.id
)
}
override fun mapFromEntity(type: UserEntity): User {
return User(
type.name,
type.points,
type.id
)
}
}
|
// Copyright (c) 2020, 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.
import 'package:kernel/ast.dart';
import 'package:kernel/clone.dart' show CloneVisitorNotMembers;
import 'package:kernel/core_types.dart' show CoreTypes;
import 'package:kernel/library_index.dart' show LibraryIndex;
import 'package:kernel/type_algebra.dart' show Substitution;
import 'utils.dart';
/// Tracks used getters and setters of generated protobuf message
/// classes and prunes metadata declarations.
class ProtobufHandler {
static const String protobufLibraryUri = 'package:protobuf/protobuf.dart';
static const String metadataFieldName = '_i';
// All of those methods have the dart field name as second positional
// parameter.
// Method names are defined in:
// https://github.com/dart-lang/protobuf/blob/master/protobuf/lib/src/protobuf/builder_info.dart
// The code is generated by:
// https://github.com/dart-lang/protobuf/blob/master/protoc_plugin/lib/protobuf_field.dart.
static const Set<String> fieldAddingMethods = const <String>{
'a',
'aOM',
'aOS',
'aQM',
'pPS',
'aQS',
'aInt64',
'aOB',
'e',
'p',
'pc',
'm',
};
final CoreTypes coreTypes;
final Class _generatedMessageClass;
final Class _tagNumberClass;
final Field _tagNumberField;
final Class _builderInfoClass;
final Procedure _builderInfoAddMethod;
// Type of BuilderInfo.add<Null>().
late FunctionType _typeOfBuilderInfoAddOfNull;
final _messageClasses = <Class, _MessageClass>{};
final _invalidatedClasses = <_MessageClass>{};
/// Creates [ProtobufHandler] instance for [component].
/// Returns null if protobuf library is not used.
static ProtobufHandler? forComponent(
Component component, CoreTypes coreTypes) {
final libraryIndex = LibraryIndex(component, [protobufLibraryUri]);
if (!libraryIndex.containsLibrary(protobufLibraryUri)) {
return null;
}
return ProtobufHandler._internal(libraryIndex, coreTypes);
}
ProtobufHandler._internal(LibraryIndex libraryIndex, this.coreTypes)
: _generatedMessageClass =
libraryIndex.getClass(protobufLibraryUri, 'GeneratedMessage'),
_tagNumberClass =
libraryIndex.getClass(protobufLibraryUri, 'TagNumber'),
_tagNumberField =
libraryIndex.getField(protobufLibraryUri, 'TagNumber', 'tagNumber'),
_builderInfoClass =
libraryIndex.getClass(protobufLibraryUri, 'BuilderInfo'),
_builderInfoAddMethod = libraryIndex.getProcedure(
protobufLibraryUri, 'BuilderInfo', 'add') {
final functionType = _builderInfoAddMethod.getterType as FunctionType;
_typeOfBuilderInfoAddOfNull = Substitution.fromPairs(
functionType.typeParameters, const <DartType>[NullType()])
.substituteType(functionType.withoutTypeParameters) as FunctionType;
}
bool usesAnnotationClass(Class cls) => cls == _tagNumberClass;
/// This method is called from summary collector when analysis discovered
/// that [member] is called and needs to construct a summary for its body.
///
/// At this point protobuf handler can
/// - modify static field initializer of metadata field;
/// - track used members of the generated message classes.
void beforeSummaryCreation(Member member) {
// Only interested in members of subclasses of GeneratedMessage class.
final cls = member.enclosingClass;
if (cls == null || cls.superclass != _generatedMessageClass) {
return;
}
final messageClass = (_messageClasses[cls] ??= _MessageClass());
if (member is Field && member.name.text == metadataFieldName) {
// Update contents of static field initializer of metadata field (_i).
// according to the used tag numbers.
assert(member.isStatic);
if (messageClass._metadataField == null) {
messageClass._metadataField = member;
++Statistics.protobufMessagesUsed;
} else {
assert(messageClass._metadataField == member);
}
_updateMetadataField(messageClass);
return;
}
if (member is Procedure && !member.isStatic) {
// Track usage of accessors of protobuf fields: extract tag number
// from annotations and add tag number to the set of used tags.
// This may also add message class to the set of invalidated classes,
// so their metadata field initializers will be revisited.
for (var annotation in member.annotations) {
final constant = (annotation as ConstantExpression).constant;
if (constant is InstanceConstant &&
constant.classReference == _tagNumberClass.reference) {
if (messageClass._usedTags.add((constant
.fieldValues[_tagNumberField.getterReference] as IntConstant)
.value)) {
_invalidatedClasses.add(messageClass);
}
}
}
}
}
List<Field> getInvalidatedFields() {
final fields = <Field>[];
for (var cls in _invalidatedClasses) {
final field = cls._metadataField;
if (field != null) {
fields.add(field);
}
}
_invalidatedClasses.clear();
return fields;
}
/// Updates initializer of metadata field of [cls] message class.
void _updateMetadataField(_MessageClass cls) {
++Statistics.protobufMetadataInitializersUpdated;
Statistics.protobufMetadataFieldsPruned -= cls.numberOfFieldsPruned;
final field = cls._metadataField!;
Expression? originalInitializer = cls._originalInitializer;
if (originalInitializer == null) {
cls._originalInitializer = originalInitializer = field.initializer!;
}
final cloner = CloneVisitorNotMembers();
field.initializer = cloner.clone(originalInitializer)..parent = field;
final transformer = _MetadataTransformer(this, cls);
field.initializer!.accept(transformer);
_invalidatedClasses.remove(cls);
cls.numberOfFieldsPruned = transformer.numberOfFieldsPruned;
Statistics.protobufMetadataFieldsPruned += cls.numberOfFieldsPruned;
}
bool _isUnusedMetadata(_MessageClass cls, InstanceInvocation node) {
if (node.interfaceTarget.enclosingClass == _builderInfoClass &&
fieldAddingMethods.contains(node.name.text)) {
final tagNumber = (node.arguments.positional[0] as IntLiteral).value;
return !cls._usedTags.contains(tagNumber);
}
return false;
}
}
class _MessageClass {
Field? _metadataField;
Expression? _originalInitializer;
final _usedTags = <int>{};
int numberOfFieldsPruned = 0;
}
class _MetadataTransformer extends Transformer {
final ProtobufHandler ph;
final _MessageClass cls;
int numberOfFieldsPruned = 0;
_MetadataTransformer(this.ph, this.cls);
@override
TreeNode visitInstanceInvocation(InstanceInvocation node) {
if (!ph._isUnusedMetadata(cls, node)) {
super.visitInstanceInvocation(node);
return node;
}
// Replace the field metadata method with a dummy call to
// `BuilderInfo.add`. This is to preserve the index calculations when
// removing a field.
// Change the tag-number to 0. Otherwise the decoder will get confused.
++numberOfFieldsPruned;
return InstanceInvocation(
InstanceAccessKind.Instance,
node.receiver,
ph._builderInfoAddMethod.name,
Arguments(
<Expression>[
IntLiteral(0), // tagNumber
NullLiteral(), // name
NullLiteral(), // fieldType
NullLiteral(), // defaultOrMaker
NullLiteral(), // subBuilder
NullLiteral(), // valueOf
NullLiteral(), // enumValues
],
types: <DartType>[const NullType()],
),
interfaceTarget: ph._builderInfoAddMethod,
functionType: ph._typeOfBuilderInfoAddOfNull)
..fileOffset = node.fileOffset;
}
}
|
<?php
namespace JHWEB\FinancieroBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* FroAcuerdoPago
*
* @ORM\Table(name="fro_acuerdo_pago")
* @ORM\Entity(repositoryClass="JHWEB\FinancieroBundle\Repository\FroAcuerdoPagoRepository")
*/
class FroAcuerdoPago
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var \DateTime
*
* @ORM\Column(name="fecha", type="date")
*/
private $fecha;
/**
* @var int
*
* @ORM\Column(name="numero_cuotas", type="integer")
*/
private $numeroCuotas;
/**
* @var string
*
* @ORM\Column(name="numero", type="string", length=10)
*/
private $numero;
/**
* @var int
*
* @ORM\Column(name="consecutivo", type="integer")
*/
private $consecutivo;
/**
* @var \DateTime
*
* @ORM\Column(name="fecha_final", type="date")
*/
private $fechaFinal;
/**
* @var int
*
* @ORM\Column(name="dias_mora_total", type="integer")
*/
private $diasMoraTotal;
/**
* @var float
*
* @ORM\Column(name="valor_bruto", type="float")
*/
private $valorBruto;
/**
* @var float
*
* @ORM\Column(name="valor_mora", type="float")
*/
private $valorMora;
/**
* @var float
*
* @ORM\Column(name="valor_neto", type="float")
*/
private $valorNeto;
/**
* @var float
*
* @ORM\Column(name="porcentaje_inicial", type="float")
*/
private $porcentajeInicial;
/**
* @var float
*
* @ORM\Column(name="valor_cuota_inicial", type="float")
*/
private $valorCuotaInicial;
/**
* @var float
*
* @ORM\Column(name="porcentaje_descuento", type="float")
*/
private $porcentajeDescuento;
/**
* @var float
*
* @ORM\Column(name="valor_descuento", type="float")
*/
private $valorDescuento;
/**
* @var bool
*
* @ORM\Column(name="activo", type="boolean")
*/
private $activo;
/** @ORM\ManyToOne(targetEntity="JHWEB\ContravencionalBundle\Entity\CvCfgInteres", inversedBy="acuerdosPago") */
private $interes;
/** @ORM\ManyToOne(targetEntity="JHWEB\UsuarioBundle\Entity\UserCiudadano", inversedBy="acuerdosPago") */
private $ciudadano;
/** @ORM\ManyToOne(targetEntity="JHWEB\ContravencionalBundle\Entity\CvCdoComparendo", inversedBy="facturas") */
private $comparendo;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set fecha
*
* @param \DateTime $fecha
*
* @return FroAcuerdoPago
*/
public function setFecha($fecha)
{
$this->fecha = $fecha;
return $this;
}
/**
* Get fecha
*
* @return \DateTime
*/
public function getFecha()
{
if ($this->fecha) {
return $this->fecha->format('d/m/Y');
}
return $this->fecha;
}
/**
* Set numeroCuotas
*
* @param integer $numeroCuotas
*
* @return FroAcuerdoPago
*/
public function setNumeroCuotas($numeroCuotas)
{
$this->numeroCuotas = $numeroCuotas;
return $this;
}
/**
* Get numeroCuotas
*
* @return integer
*/
public function getNumeroCuotas()
{
return $this->numeroCuotas;
}
/**
* Set numero
*
* @param string $numero
*
* @return FroAcuerdoPago
*/
public function setNumero($numero)
{
$this->numero = $numero;
return $this;
}
/**
* Get numero
*
* @return string
*/
public function getNumero()
{
return $this->numero;
}
/**
* Set consecutivo
*
* @param integer $consecutivo
*
* @return FroAcuerdoPago
*/
public function setConsecutivo($consecutivo)
{
$this->consecutivo = $consecutivo;
return $this;
}
/**
* Get consecutivo
*
* @return integer
*/
public function getConsecutivo()
{
return $this->consecutivo;
}
/**
* Set fechaFinal
*
* @param \DateTime $fechaFinal
*
* @return FroAcuerdoPago
*/
public function setFechaFinal($fechaFinal)
{
$this->fechaFinal = $fechaFinal;
return $this;
}
/**
* Get fechaFinal
*
* @return \DateTime
*/
public function getFechaFinal()
{
return $this->fechaFinal;
}
/**
* Set diasMoraTotal
*
* @param integer $diasMoraTotal
*
* @return FroAcuerdoPago
*/
public function setDiasMoraTotal($diasMoraTotal)
{
$this->diasMoraTotal = $diasMoraTotal;
return $this;
}
/**
* Get diasMoraTotal
*
* @return integer
*/
public function getDiasMoraTotal()
{
return $this->diasMoraTotal;
}
/**
* Set valorBruto
*
* @param float $valorBruto
*
* @return FroAcuerdoPago
*/
public function setValorBruto($valorBruto)
{
$this->valorBruto = $valorBruto;
return $this;
}
/**
* Get valorBruto
*
* @return float
*/
public function getValorBruto()
{
return $this->valorBruto;
}
/**
* Set valorMora
*
* @param float $valorMora
*
* @return FroAcuerdoPago
*/
public function setValorMora($valorMora)
{
$this->valorMora = $valorMora;
return $this;
}
/**
* Get valorMora
*
* @return float
*/
public function getValorMora()
{
return $this->valorMora;
}
/**
* Set valorNeto
*
* @param float $valorNeto
*
* @return FroAcuerdoPago
*/
public function setValorNeto($valorNeto)
{
$this->valorNeto = $valorNeto;
return $this;
}
/**
* Get valorNeto
*
* @return float
*/
public function getValorNeto()
{
return $this->valorNeto;
}
/**
* Set porcentajeInicial
*
* @param float $porcentajeInicial
*
* @return FroAcuerdoPago
*/
public function setPorcentajeInicial($porcentajeInicial)
{
$this->porcentajeInicial = $porcentajeInicial;
return $this;
}
/**
* Get porcentajeInicial
*
* @return float
*/
public function getPorcentajeInicial()
{
return $this->porcentajeInicial;
}
/**
* Set valorCuotaInicial
*
* @param float $valorCuotaInicial
*
* @return FroAcuerdoPago
*/
public function setValorCuotaInicial($valorCuotaInicial)
{
$this->valorCuotaInicial = $valorCuotaInicial;
return $this;
}
/**
* Get valorCuotaInicial
*
* @return float
*/
public function getValorCuotaInicial()
{
return $this->valorCuotaInicial;
}
/**
* Set porcentajeDescuento
*
* @param float $porcentajeDescuento
*
* @return FroAcuerdoPago
*/
public function setPorcentajeDescuento($porcentajeDescuento)
{
$this->porcentajeDescuento = $porcentajeDescuento;
return $this;
}
/**
* Get porcentajeDescuento
*
* @return float
*/
public function getPorcentajeDescuento()
{
return $this->porcentajeDescuento;
}
/**
* Set valorDescuento
*
* @param float $valorDescuento
*
* @return FroAcuerdoPago
*/
public function setValorDescuento($valorDescuento)
{
$this->valorDescuento = $valorDescuento;
return $this;
}
/**
* Get valorDescuento
*
* @return float
*/
public function getValorDescuento()
{
return $this->valorDescuento;
}
/**
* Set activo
*
* @param boolean $activo
*
* @return FroAcuerdoPago
*/
public function setActivo($activo)
{
$this->activo = $activo;
return $this;
}
/**
* Get activo
*
* @return boolean
*/
public function getActivo()
{
return $this->activo;
}
/**
* Set interes
*
* @param \JHWEB\ContravencionalBundle\Entity\CvCfgInteres $interes
*
* @return FroAcuerdoPago
*/
public function setInteres(\JHWEB\ContravencionalBundle\Entity\CvCfgInteres $interes = null)
{
$this->interes = $interes;
return $this;
}
/**
* Get interes
*
* @return \JHWEB\ContravencionalBundle\Entity\CvCfgInteres
*/
public function getInteres()
{
return $this->interes;
}
/**
* Set ciudadano
*
* @param \JHWEB\UsuarioBundle\Entity\UserCiudadano $ciudadano
*
* @return FroAcuerdoPago
*/
public function setCiudadano(\JHWEB\UsuarioBundle\Entity\UserCiudadano $ciudadano = null)
{
$this->ciudadano = $ciudadano;
return $this;
}
/**
* Get ciudadano
*
* @return \JHWEB\UsuarioBundle\Entity\UserCiudadano
*/
public function getCiudadano()
{
return $this->ciudadano;
}
/**
* Set comparendo
*
* @param \JHWEB\ContravencionalBundle\Entity\CvCdoComparendo $comparendo
*
* @return FroAcuerdoPago
*/
public function setComparendo(\JHWEB\ContravencionalBundle\Entity\CvCdoComparendo $comparendo = null)
{
$this->comparendo = $comparendo;
return $this;
}
/**
* Get comparendo
*
* @return \JHWEB\ContravencionalBundle\Entity\CvCdoComparendo
*/
public function getComparendo()
{
return $this->comparendo;
}
}
|
#!/bin/bash
set -x
export FLAGS_call_stack_level=2
export CUDA_VISIBLE_DEVICES=0,1
python -m paddle.distributed.launch \
inference.py --model_type gpt \
--model_path ../../static/inference_model_pp1mp2/
|
# Line Width

```go
package main
import "github.com/fogleman/gg"
func main() {
const S = 1000
dc := gg.NewContext(S, S)
dc.SetRGB(1, 1, 1)
dc.Clear()
dc.SetRGB(0, 0, 0)
w := 0.1
for i := 100; i <= 900; i += 20 {
x := float64(i)
dc.DrawLine(x+50, 0, x-50, S)
dc.SetLineWidth(w)
dc.Stroke()
w += 0.1
}
dc.SavePNG("out.png")
}
```
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $table = 'projects';
protected $guarded = array('id');
public function customer()
{
return $this->belongsTo(\App\Customer::class, 'id_cust');
}
public function service()
{
return $this->belongsTo(\App\Service::class, 'id_service');
}
public function projectStatus()
{
return $this->belongsTo(\App\Project_status::class, 'project_status');
}
}
|
<?php only_admin_access(); ?>
<?php if((isset($_GET['only_updates']) and $_GET['only_updates']) or isset($params['show_only_updates'])){ ?>
<module type="admin/developer_tools/package_manager/browse_packages" show_only_updates="1" />
<?php } else { ?>
<module type="admin/developer_tools/package_manager/browse_packages" />
<?php } ?>
|
using ESRI.ArcGIS.Geodatabase;
using ProSuite.Commons.Essentials.CodeAnnotations;
using ProSuite.QA.Container.TestSupport;
namespace ProSuite.QA.Container
{
public interface IRelatedTablesProvider
{
[CanBeNull]
RelatedTables GetRelatedTables([NotNull] IRow row);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace GankCompanionDataReader.eventHandler
{
public interface IPartyRepository
{
string GetPartyID();
void SetPartyID(string partyId);
}
}
|
# -*- coding: utf-8 -*-
"""
实现 Ctrl 1 ~ 6 的功能. 主要是宠物的动作条按键. 1 进攻主人目标, 2 撤回, 3 原地待命.
"""
from ._config_and_script import config, script
from .. import act
from .... import keyname
from ....script import (
Hotkey, SendLabel,
)
def build_hk_ctrl_1_6():
return [
Hotkey(
name="Ctrl {}".format(i),
key=keyname.SCROLOCK_ON(keyname.CTRL_(getattr(keyname, "KEY_{}".format(i)))),
actions=[
SendLabel(
name="all",
to=config.lbs_all(),
actions=[
act.Target.TARGET_FOCUS_TARGET,
act.General.TRIGGER,
]
)
],
script=script,
) for i in range(1, 6 + 1)
]
(
hk_ctrl_1,
hk_ctrl_2,
hk_ctrl_3,
hk_ctrl_4,
hk_ctrl_5,
hk_ctrl_6,
) = build_hk_ctrl_1_6()
|
package com.github.kmizu.kollection
data class KBatchedQueue<T>(private val front: KList<T>, private val rear: KList<T>) : KQueue<T> {
constructor() : this(KList.Nil, KList.Nil)
private fun ensureFront(f: KList<T>, r: KList<T>): KBatchedQueue<T> = when {
f.isEmpty -> KBatchedQueue(r.reverse(), KList.Nil)
else -> KBatchedQueue(f, r)
}
override val isEmpty: Boolean
get() = front.isEmpty
override fun enqueue(newElement: T): KBatchedQueue<T> = ensureFront(front, newElement cons rear)
override fun dequeue(): KBatchedQueue<T> = when {
front.isEmpty -> throw IllegalArgumentException("com.github.kmizu.kollection.KBatchedQueue.isEmpty")
else -> ensureFront(front.tl, rear)
}
override fun peek(): T = when {
front.isEmpty -> throw IllegalArgumentException("com.github.kmizu.kollection.KBatchedQueue.isEmpty")
else -> front.hd
}
override fun toList(): KList<T> = front concat rear.reverse()
}
|
#!/bin/bash
file="./db-backup.properties"
# Function to get dateValue as String
function getDateAsStr()
{
dateStr=$(date '+%Y%m%d-%H%M%S');
}
# Function to update properties file
updateBackupCount(){
if [ $incCount -lt $incLimit ]
then newCount=$(($incCount + 1 ));
else
newCount="0"
fi
sed -i -e "/.*inc_count*./ s/.*/inc_count=$newCount/" "$file"
}
# Function to update last incremental backup dir value
updateLastIncDir(){
sed -i -e "/.*last_inc_dir*./ s/.*/last_inc_dir=$1/" "$file"
}
# Function to validate required fields
validateRequiredFields() {
if [ -z "$dbUserName" ]
then echo " ### ERROR! The username for the MariaDB Backup was not found on the db_backup.properties file."
hasErrors=true
fi
if [ -z "$dbPassword" ]
then echo " ### ERROR! The password for the MariaDB Backup was not found on the db_backup.properties file."
hasErrors=true;
fi
if [ -z "$backupDir" ]
then echo " ### ERROR! The value for backup_dir property was not found on the db_properties file."
hasErrors=true
fi
if [ -z "$baseBackupPrefix" ]
then echo " ### ERROR! The value for base_backup_prefix property was not found on the db_backup.properties file."
hasErrors=true
fi
if [ -z "$incBackupPrefix" ]
then echo " ### ERROR! The value for the inc_backup_prefix property was not found on the db_backup.properties file."
hasErrors=true
fi
if [ -z "$incLimit" ]
then echo " ### ERROR! The value for the inc_limit property was not found on the db_backup.properties file."
hasErrors=true
fi
if [ -z "$incCount" ]
then echo " ### ERROR! The value for the inc_count property was not found on the db_backup.properties file."
hasErrors=true
fi
if [ "$hasErrors" = true ]
then
echo "STEP 2 OF 6 FAILED - ERROR! Either required properties are not listed on db-backup.properties or has null values.See errors (above)."
exit 1
else
echo "STEP 2 OF 6 COMPLETED SUCCESSFULLY - verified propoerties listed on db-backup.prperties."
fi
}
# Function to read properties file
readPropertiesFile(){
if [ -f "$file" ]
then
echo "### => $file was found!"
while IFS='=' read -r key value
do
if [ "$key" = "userName" ]
then dbUserName=$value
elif [ "$key" = "password" ]
then dbPassword=$value
elif [ "$key" = "backup_dir" ]
then backupDir=$value
elif [ "$key" = "base_backup_prefix" ]
then baseBackupPrefix=$value
elif [ "$key" = "inc_backup_prefix" ]
then incBackupPrefix=$value
elif [ "$key" = "inc_limit" ]
then incLimit=$value
elif [ "$key" = "inc_count" ]
then incCount=$value
elif [ "$key" = "last_inc_dir" ]
then lastIncDir=$value
fi
done < "$file"
echo "STEP 1 OF 6 COMPLETED SUCCESSFULLY - created the backup directory $backupPath."
else
echo "STEP 1 OF 6 FAILED - ERROR! $file not found!"
exit 1
fi
}
# ########## The backup process starts here ###############
readPropertiesFile
validateRequiredFields
backupPath=""
if [ "$incCount" -eq 0 ]
then
echo " "
echo "Running the full backup job ...."
getDateAsStr
baseBackupDir="${baseBackupPrefix}-${dateStr}"
backupPath="${backupDir}/${baseBackupDir}"
newBaseDir="${baseBackupDir}"
mkdir -p -- "$backupPath"
if [ $? -eq 0 ]
then
echo "STEP 3 OF 6 COMPLETED SUCCESSFULLY - created backup directory: $backupPath."
else
echo "STEP 3 OF 6 FAILED - ERROR! Could not create backup directory: $backupPath."
exit 1
fi
mariabackup --backup --target-dir="$backupPath" --user="$dbUserName" --password="$dbPassword"
if [ $? -eq 0 ]
then
echo "STEP 4 OF 6 COMPLETED SUCCESSFULLY - created full backu-up successfully in $backupPath"
else
echo "STEP 4 OF 6 FAILED - ERROR! An error has occurred when creating a full backup."
echo "Removing directories created by this process because the data could be corrupted....."
rm -r $backupPath
exit 1
fi
else
echo " "
echo "Running the incremental backup job ...."
getDateAsStr
incBackupDir="${incBackupPrefix}-${dateStr}"
backupPath="${backupDir}/${incBackupPrefix}-${dateStr}"
incBaseDir="${backupDir}/${lastIncDir}"
newBaseDir="${incBackupDir}"
if [ -d "$incBaseDir" ]
then
mkdir -p -- "$backupPath"
if [ $? -eq 0 ]
then
echo "STEP 3 OF 6 COMPLETED SUCCESSFULLY - created backup directory: $backupPath."
else
echo "STEP 3 OF 6 FAILED - ERROR! Could not create backup directory: $backupPath."
exit 1
fi
mariabackup --backup --target-dir="$backupPath" --incremental-basedir="$incBaseDir" --user="$dbUserName" --password="$dbPassword"
if [ $? -eq 0 ]
then
echo "STEP 4 OF 6 COMPLETED SUCCESSFULLY - created incremental backu-up successfully in $backupPath"
else
echo "STEP 4 OF 6 FAILED - ERROR! An error has occurred when creating a full backup."
echo "Removing directories created by this process because the data could be corrupted....."
rm -r $backupPath
exit 1
fi
else
echo "## ERROR! The required Base Directory, $incBaseDir, for the Incremental Backup was not found!."
echo "This is might be caused by a failure on the last incremental backup attempt "
echo "or the last_inc_dir value was manually altered after the last incremental backup process run."
exit 1
fi
fi
updateLastIncDir "$newBaseDir"
if [ $? -eq 0 ]
then
echo "STEP 5 OF 6 COMPLETED SUCCESSFULLY - updated the last_inc_dir property to $newBaseDir on db-backup.properties file."
else
echo "STEP 5 OF 6 FAILED - ERROR! An error has occurred when updating last_inc_dir property on db-backup.properties file."
echo "Removing directories created by this process to avoid data integrity issues....."
rm -r $backupPath
exit 1
fi
sudo chown -R mysql $backupPath
updateBackupCount
if [ $? -eq 0 ]
then
echo "STEP 6 OF 6 COMPLETED SUCCESSFULLY - updated the inc_count property to $newCount on db-backup.properties file."
else
echo "STEP 6 OF 6 FAILED - ERROR! An error has occurred when updating inc_count property on db-backup.properties file."
echo "Removing directories created by this process to avoid data integrity issues....."
rm -r $backupPath
exit 1
fi
echo "------------ THE DATABASE BACKUP PROCESS IS COMPLETED -------------------"
exit 0
|
#!/bin/bash
# A wrapper around run_lr.sh, to make it easier to invoke it right with what stereo_gui dumps out
# when selecting a region. This wrapper will take as inputs the following ugly arguments:
# $(pwd) tag corr Crop src win for WV02_20170511151556_103001006882D700_17MAY11151556-P1BS-501479705100_01_P002.ntf: -874 2797 36397 8486 Crop src win for WV02_20170511151722_1030010069726100_17MAY11151722-P1BS-501493169020_01_P002.ntf: -552 6652 36618 7884
# and will launch run_lr.sh while looking up the camera models.
# Here, 'tag' is just a string label, and 'corr' is 0 when we we are working on making
# corrections, and is 1, when corrections are already in wv_correct and we want
# to verify how well they work.
execDir=$(dirname $0)
runDir=$1
shift
cd $runDir
tag=$1
shift
corr=$1
shift
shift; shift; shift; shift; # pass on the text: Crop src win for
left_img=$(echo $1 | perl -p -e "s#:##g")
left_xml=${left_img/.ntf/.xml}
shift
a=$1; shift
b=$1; shift
c=$1; shift
d=$1; shift
shift; shift; shift; shift; # pass on the text: Crop src win for
right_img=$(echo $1 | perl -p -e "s#:##g")
right_xml=${right_img/.ntf/.xml}
shift
e=$1; shift
f=$1; shift
g=$1; shift
h=$1; shift
echo $left_img $left_xml $right_img $right_xml $a $b $c $d $e $f $g $h $tag
echo Working in $runDir
out=output_${tag}_corr${corr}.txt
echo Writing output to $out
$execDir/run_lr.sh "$a $b $c $d" "$e $f $g $h" $left_img $left_xml $right_img $right_xml $tag $corr > $out 2>&1
|
/*
Copyright 2021 Smart Engines Service LLC
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder 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 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.
*/
/**
* @file minimgapi-inl.h
* @brief MinImgAPI inlining interface.
*
* This header contains inline versions of some MinimgAPI functions.
* See description of the functions in file minimgapi.h
*/
#pragma once
#ifndef MINIMGAPI_MINIMGAPI_INL_H_INCLUDED
#define MINIMGAPI_MINIMGAPI_INL_H_INCLUDED
#include <cstring>
#include <cstdlib>
#include <cstddef>
#include <cmath>
#include <algorithm>
#include <minbase/minresult.h>
#include <minbase/crossplat.h>
#include <minbase/min_pp_mintyp.h>
#include <minimgapi/minimgapi.h>
#include <minimgapi/imgguard.hpp>
#include <minimgapi/minimgapi.hpp>
MUSTINLINE int _GetMinImageType(
const MinImg *p_image) {
if (!p_image)
return BAD_ARGS;
return p_image->scalar_type;
}
MUSTINLINE int _SetMinImageType(
MinImg *p_image,
MinTyp element_type) {
if (!p_image || p_image->p_zero_line)
return BAD_ARGS;
p_image->scalar_type = element_type;
return NO_ERRORS;
}
MUSTINLINE int _AssureMinImagePrototypeIsValid(
const MinImg *p_image) {
PROPAGATE_ERROR(_GetMinImageType(p_image));
if (p_image->width < 0 || p_image->height < 0 || p_image->channels < 0)
return BAD_ARGS;
return NO_ERRORS;
}
MUSTINLINE int _GetMinImageBitsPerPixel(
const MinImg *p_image) {
PROPAGATE_ERROR(_AssureMinImagePrototypeIsValid(p_image));
int32_t size_logbits = LogBitSizeOfMinType(p_image->scalar_type);
PROPAGATE_ERROR(size_logbits);
return p_image->channels * (1 << size_logbits);
}
MUSTINLINE int _GetMinImageBytesPerLine(
const MinImg *p_image) {
int bits_per_pixel = GetMinImageBitsPerPixel(p_image);
PROPAGATE_ERROR(bits_per_pixel);
return (p_image->width * bits_per_pixel + 7) >> 3;
}
MUSTINLINE int _AssureMinImageIsValid(
const MinImg *p_image) {
PROPAGATE_ERROR(_AssureMinImagePrototypeIsValid(p_image));
if (!p_image->width || !p_image->height || !p_image->channels)
return NO_ERRORS;
if (!p_image->p_zero_line)
return BAD_ARGS;
if (p_image->height > 1 &&
std::abs(p_image->stride) < _GetMinImageBytesPerLine(p_image))
return BAD_ARGS;
return NO_ERRORS;
}
MUSTINLINE int _AssureMinImageIsEmpty(
const MinImg *p_image) {
PROPAGATE_ERROR(_AssureMinImagePrototypeIsValid(p_image));
return p_image->width && p_image->height && p_image->channels;
}
MUSTINLINE int _AssureMinImageIsSolid(
const MinImg *p_image) {
PROPAGATE_ERROR(_AssureMinImageIsValid(p_image));
int bits_per_pixel = _GetMinImageBitsPerPixel(p_image);
return p_image->height > 1 &&
p_image->stride * 8 != p_image->width * bits_per_pixel;
}
MUSTINLINE int _AssureMinImageFits(
const MinImg *p_image,
MinTyp element_type,
int channels = -1,
int width = -1,
int height = -1) {
PROPAGATE_ERROR(_AssureMinImageIsValid(p_image));
int retVal = 0;
PROPAGATE_ERROR(retVal = _GetMinImageType(p_image));
if (element_type >= 0 && element_type != retVal)
return 1;
if (channels >= 0 && channels != p_image->channels)
return 1;
if (width >= 0 && width != p_image->width)
return 1;
if (height >= 0 && height != p_image->height)
return 1;
return NO_ERRORS;
}
MUSTINLINE int _AssureMinImageIsScalar(
const MinImg *p_image) {
return _AssureMinImageFits(p_image, static_cast<MinTyp>(-1), 1, 1, 1);
}
MUSTINLINE int _AssureMinImageIsPixel(
const MinImg *p_image) {
return _AssureMinImageFits(p_image, static_cast<MinTyp>(-1), -1, 1, 1);
}
MUSTINLINE uint8_t *_GetMinImageLineUnsafe(
const MinImg *p_image,
int y,
BorderOption border = BO_VOID,
void *p_canvas = NULL) {
const int ht = p_image->height;
if (y < 0 || y >= ht)
switch (border) {
case BO_REPEAT: {
y = std::min(std::max(0, y), ht - 1);
break;
}
case BO_CYCLIC: {
y = (y % ht + ht) % ht;
break;
}
case BO_SYMMETRIC: {
int ht2 = ht * 2;
y = (y % ht2 + ht2) % ht2;
y = std::min(y, ht2 - 1 - y);
break;
}
case BO_CONSTANT: {
return reinterpret_cast<uint8_t *>(p_canvas);
}
case BO_VOID: {
return NULL;
}
default: {
}
}
return p_image->p_zero_line + static_cast<ptrdiff_t>(p_image->stride) * y;
}
MUSTINLINE uint8_t *_GetMinImageLine(
const MinImg *p_image,
int y,
BorderOption border = BO_VOID,
void *p_canvas = NULL) {
if (_AssureMinImageIsValid(p_image) != NO_ERRORS)
return NULL;
if (_AssureMinImageIsEmpty(p_image) == NO_ERRORS)
switch (border) {
case BO_CONSTANT:
return reinterpret_cast<uint8_t *>(p_canvas);
case BO_IGNORE:
return p_image->p_zero_line ? p_image->p_zero_line + static_cast<ptrdiff_t>(p_image->stride) * y : NULL;
default:
return NULL;
}
return _GetMinImageLineUnsafe(p_image, y, border, p_canvas);
}
MUSTINLINE int _CloneMinImagePrototype(
MinImg *p_dst_image,
const MinImg *p_src_image,
AllocationOption allocation = AO_PREALLOCATED) {
if (!p_dst_image || !p_src_image)
return BAD_ARGS;
return minimg::ClonePrototype(*p_dst_image, *p_src_image, allocation);
// if (!p_dst_image || !p_src_image || p_dst_image->p_zero_line)
// return BAD_ARGS;
// if (p_dst_image != p_src_image) {
// *p_dst_image = *p_src_image;
// p_dst_image->stride = 0;
// p_dst_image->p_zero_line = 0;
//// p_dst_image->p_landlord = 0;
// }
// if (allocation == AO_PREALLOCATED)
// PROPAGATE_ERROR(AllocMinImage(p_dst_image));
// return NO_ERRORS;
}
MUSTINLINE int _CloneResizedMinImagePrototype(
MinImg *p_dst_image,
const MinImg *p_src_image,
int width,
int height,
AllocationOption allocation = AO_PREALLOCATED) {
if (!p_dst_image || !p_src_image)
return BAD_ARGS;
return minimg::SetupPrototype(*p_dst_image,
width, height, p_src_image->channels, p_src_image->scalar_type,
allocation,
p_src_image->p_alloc_info ? p_src_image->p_alloc_info->address_space_ : 0);
// if (width < 0 || height < 0)
// return BAD_ARGS;
// PROPAGATE_ERROR(_CloneMinImagePrototype(p_dst_image, p_src_image, AO_EMPTY));
// p_dst_image->width = width;
// p_dst_image->height = height;
// if (allocation == AO_PREALLOCATED)
// PROPAGATE_ERROR(AllocMinImage(p_dst_image));
// return NO_ERRORS;
}
MUSTINLINE int _CloneTransposedMinImagePrototype(
MinImg *p_dst_image,
const MinImg *p_src_image,
AllocationOption allocation = AO_PREALLOCATED) {
if (!p_dst_image || !p_src_image)
return BAD_ARGS;
return minimg::CloneTransposedPrototype(
*p_dst_image, *p_src_image, allocation);
// PROPAGATE_ERROR(_CloneResizedMinImagePrototype(p_dst_image, p_src_image,
// p_src_image->height, p_src_image->width, allocation));
// return NO_ERRORS;
}
MUSTINLINE int _CloneRetypifiedMinImagePrototype(
MinImg *p_dst_image,
const MinImg *p_src_image,
MinTyp type,
AllocationOption allocation = AO_PREALLOCATED) {
if (!p_dst_image || !p_src_image)
return BAD_ARGS;
return minimg::SetupPrototype(*p_dst_image,
p_src_image->width, p_src_image->height, p_src_image->channels, type,
allocation,
p_src_image->p_alloc_info ? p_src_image->p_alloc_info->address_space_ : 0);
// PROPAGATE_ERROR(_CloneMinImagePrototype(p_dst_image, p_src_image, AO_EMPTY));
// PROPAGATE_ERROR(_SetMinImageType(p_dst_image, type));
// if (allocation == AO_PREALLOCATED)
// PROPAGATE_ERROR(AllocMinImage(p_dst_image));
// return NO_ERRORS;
}
MUSTINLINE int _CloneDimensionedMinImagePrototype(
MinImg *p_dst_image,
const MinImg *p_src_image,
int channels,
AllocationOption allocation = AO_PREALLOCATED) {
if (!p_dst_image || !p_src_image)
return BAD_ARGS;
return minimg::SetupPrototype(*p_dst_image,
p_src_image->width, p_src_image->height, channels,
p_src_image->scalar_type, allocation,
p_src_image->p_alloc_info ? p_src_image->p_alloc_info->address_space_ : 0);
// if (channels < 0)
// return BAD_ARGS;
// PROPAGATE_ERROR(_CloneMinImagePrototype(p_dst_image, p_src_image, AO_EMPTY));
// p_dst_image->channels = channels;
// if (allocation == AO_PREALLOCATED)
// PROPAGATE_ERROR(AllocMinImage(p_dst_image));
// return NO_ERRORS;
}
MUSTINLINE int _CompareMinImagePrototypes(
const MinImg *p_image_a,
const MinImg *p_image_b) {
MinImg prototype_a = {};
PROPAGATE_ERROR(_CloneMinImagePrototype(&prototype_a, p_image_a, AO_EMPTY));
MinImg prototype_b = {};
PROPAGATE_ERROR(_CloneMinImagePrototype(&prototype_b, p_image_b, AO_EMPTY));
return ::memcmp(&prototype_a, &prototype_b, sizeof(prototype_a)) != 0;
}
MUSTINLINE int _CompareMinImage2DSizes(
const MinImg *p_image_a,
const MinImg *p_image_b) {
if (!p_image_a || !p_image_b)
return BAD_ARGS;
return p_image_a->width != p_image_b->width ||
p_image_a->height != p_image_b->height;
}
MUSTINLINE int _CompareMinImage3DSizes(
const MinImg *p_image_a,
const MinImg *p_image_b) {
if (!p_image_a || !p_image_b)
return BAD_ARGS;
return p_image_a->width != p_image_b->width ||
p_image_a->height != p_image_b->height ||
p_image_a->channels != p_image_b->channels;
}
MUSTINLINE int _CompareMinImageTypes(
const MinImg *p_image_a,
const MinImg *p_image_b) {
if (!p_image_a || !p_image_b)
return BAD_ARGS;
return p_image_a->scalar_type != p_image_b->scalar_type;
}
MUSTINLINE int _CompareMinImagePixels(
const MinImg *p_image_a,
const MinImg *p_image_b) {
if (!p_image_a || !p_image_b)
return BAD_ARGS;
return _CompareMinImageTypes(p_image_a, p_image_b) ||
p_image_a->channels != p_image_b->channels;
}
MUSTINLINE int _CompareMinImages(
const MinImg *p_image_a,
const MinImg *p_image_b) {
PROPAGATE_ERROR(_AssureMinImageIsValid(p_image_a));
PROPAGATE_ERROR(_AssureMinImageIsValid(p_image_b));
int proto_res = _CompareMinImagePrototypes(p_image_a, p_image_b);
if (proto_res)
return proto_res;
int height = p_image_a->height;
int byte_line_width = _GetMinImageBytesPerLine(p_image_a);
for (int y = 0; y < height; ++y) {
const uint8_t* p_line_a = minimg_raw::GetLineRaw<uint8_t>(*p_image_a, y);
const uint8_t* p_line_b = minimg_raw::GetLineRaw<uint8_t>(*p_image_b, y);
if (::memcmp(p_line_a, p_line_b, byte_line_width))
return 1;
}
return NO_ERRORS;
}
MUSTINLINE int _WrapAlignedBufferWithMinImage(
MinImg *p_image,
void *p_buffer,
int width,
int height,
int channels,
MinTyp element_type,
int stride,
RulesOption rules = RO_STRICT) {
if (!p_image)
return BAD_ARGS;
if (RO_REUSE_CONTAINER & rules) {
PROPAGATE_ERROR(minimg::FreeImage(*p_image));
*p_image = {};
}
switch (element_type) {
#define MIN_PP_ARG_CASE(type) case MIN_PP_MAP_ctype_MinTyp(type): \
return minimg::WrapAlignedBuffer(*p_image, \
reinterpret_cast<type*>(p_buffer), width, height, channels, stride);
MIN_PP_DO_FOR_ALL_TYPES(MIN_PP_ARG_CASE)
#undef MIN_PP_ARG_CASE
default:
return MR_INTERNAL_ERROR;
}
// if (!p_image || !p_buffer)
// return BAD_ARGS;
// if (width < 0 || height < 0 || channels < 0)
// return BAD_ARGS;
// if (!(rules & RO_REUSE_CONTAINER) && p_image->p_zero_line)
// return BAD_ARGS;
// // TODO: Add check of std::abs(stride);
// // TODO: Add check of stride being >= width * channels (by abs value);
// ::memset(p_image, 0, sizeof(*p_image));
// PROPAGATE_ERROR(_SetMinImageType(p_image, element_type));
// p_image->height = height;
// p_image->width = width;
// p_image->channels = channels;
// p_image->stride = stride ? stride : _GetMinImageBytesPerLine(p_image);
// p_image->p_zero_line = reinterpret_cast<uint8_t *>(p_buffer);
// return NO_ERRORS;
}
MUSTINLINE int _WrapSolidBufferWithMinImage(
MinImg *p_image,
void *p_buffer,
int width,
int height,
int channels,
MinTyp element_type,
RulesOption rules = RO_STRICT) {
return _WrapAlignedBufferWithMinImage(p_image, p_buffer, width, height,
channels, element_type, 0, rules);
}
MUSTINLINE int _WrapScalarWithMinImage(
MinImg *p_image,
void *p_scalar,
MinTyp element_type,
RulesOption rules = RO_STRICT) {
return _WrapSolidBufferWithMinImage(p_image, p_scalar, 1, 1, 1,
element_type, rules);
}
MUSTINLINE int _WrapPixelWithMinImage(
MinImg *p_image,
void *p_pixel,
int channels,
MinTyp element_type,
RulesOption rules = RO_STRICT) {
return _WrapSolidBufferWithMinImage(p_image, p_pixel, 1, 1,
channels, element_type, rules);
}
MUSTINLINE int _WrapScalarVectorWithMinImage(
MinImg *p_image,
void *p_vector,
int size,
DirectionOption direction,
MinTyp element_type,
RulesOption rules = RO_STRICT) {
if (direction == DO_BOTH)
return BAD_ARGS;
return _WrapSolidBufferWithMinImage(p_image, p_vector,
direction == DO_VERTICAL ? 1 : size,
direction == DO_VERTICAL ? size : 1,
1, element_type, rules);
}
MUSTINLINE int _WrapPixelVectorWithMinImage(
MinImg *p_image,
void *p_vector,
int size,
DirectionOption direction,
int channels,
MinTyp element_type,
RulesOption rules = RO_STRICT) {
if (direction == DO_BOTH)
return BAD_ARGS;
return _WrapSolidBufferWithMinImage(p_image, p_vector,
direction == DO_VERTICAL ? 1 : size,
direction == DO_VERTICAL ? size : 1,
channels, element_type, rules);
}
MUSTINLINE int _GetMinImageRegion(
MinImg *p_dst_image,
const MinImg *p_src_image,
int x0,
int y0,
int width,
int height,
RulesOption rules = RO_STRICT) {
if (!p_dst_image || !p_src_image)
return BAD_ARGS;
if (p_dst_image == p_src_image) {
if (RO_REUSE_CONTAINER & rules) {
// DECLARE_GUARDED_MINIMG(tmp);
// tmp = *p_src_image;
// *p_dst_image = {};
// return minimg::GetRegion(*p_dst_image, tmp, x0, y0, width, height);
return minimg::ChangeRegion(*p_dst_image, x0, y0,
width - p_src_image->width + x0, height - p_src_image->height + y0);
} else {
return BAD_ARGS;
}
}
if (RO_REUSE_CONTAINER & rules) {
PROPAGATE_ERROR(minimg::FreeImage(*p_dst_image));
*p_dst_image = {};
}
return minimg::GetRegion(*p_dst_image, *p_src_image, x0, y0, width, height);
// PROPAGATE_ERROR(_AssureMinImageIsValid(p_src_image));
// if (!p_dst_image || width < 0 || height < 0)
// return BAD_ARGS;
// if (!(rules & RO_REUSE_CONTAINER) && p_dst_image->p_zero_line)
// return BAD_ARGS;
// if (!(rules & RO_IGNORE_BORDERS)) {
// if (x0 < 0 || static_cast<uint32_t>(x0) + static_cast<uint32_t>(width) >
// static_cast<uint32_t>(p_src_image->width))
// return BAD_ARGS;
// if (y0 < 0 || static_cast<uint32_t>(y0) + static_cast<uint32_t>(height) >
// static_cast<uint32_t>(p_src_image->height))
// return BAD_ARGS;
// }
// *p_dst_image = *p_src_image;
// p_dst_image->width = width;
// p_dst_image->height = height;
// int bit_shift = x0 * _GetMinImageBitsPerPixel(p_dst_image);
// if (bit_shift & 0x07U)
// return BAD_ARGS;
// p_dst_image->p_zero_line = _GetMinImageLine(p_src_image, y0, BO_IGNORE) +
// (bit_shift >> 3);
// if (!p_dst_image->p_zero_line)
// return INTERNAL_ERROR;
// p_dst_image->stride = p_src_image->stride;
// return NO_ERRORS;
}
MUSTINLINE int _FlipMinImageVertically(
MinImg *p_dst_image,
const MinImg *p_src_image,
RulesOption rules = RO_STRICT) {
if (!p_dst_image || !p_src_image)
return BAD_ARGS;
if (p_dst_image == p_src_image) {
if (RO_REUSE_CONTAINER & rules) {
// DECLARE_GUARDED_MINIMG(tmp);
// tmp = *p_src_image;
// *p_dst_image = {};
// return minimg::GetRegion(
// *p_dst_image, tmp, 0, 0, tmp.width, tmp.height, true);
return minimg::ChangeRegion(*p_dst_image, 0, 0, 0, 0, true);
} else {
return BAD_ARGS;
}
}
if (RO_REUSE_CONTAINER & rules) {
PROPAGATE_ERROR(minimg::FreeImage(*p_dst_image));
*p_dst_image = {};
}
return minimg::GetRegion(*p_dst_image, *p_src_image,
0, 0, p_src_image->width, p_src_image->height, true);
// if (!p_dst_image)
// return BAD_ARGS;
// if (!(rules & RO_REUSE_CONTAINER) && p_dst_image->p_zero_line)
// return BAD_ARGS;
// PROPAGATE_ERROR(_AssureMinImageIsValid(p_src_image));
// *p_dst_image = *p_src_image;
// uint8_t *p = _GetMinImageLine(p_dst_image, p_dst_image->height - 1);
// if (!p)
// return INTERNAL_ERROR;
// p_dst_image->p_zero_line = p;
// p_dst_image->stride *= -1;
// return NO_ERRORS;
}
MUSTINLINE int _UnfoldMinImageChannels(
MinImg *p_dst_image,
const MinImg *p_src_image,
RulesOption rules = RO_STRICT) {
if (!p_dst_image || !p_src_image)
return BAD_ARGS;
if (p_dst_image == p_src_image) {
if (RO_REUSE_CONTAINER & rules) {
DECLARE_GUARDED_MINIMG(tmp);
/*MinImg*/ tmp = *p_src_image;
*p_dst_image = {};
return minimg::UnfoldChannels(*p_dst_image, tmp);
} else {
return BAD_ARGS;
}
}
if (RO_REUSE_CONTAINER & rules) {
PROPAGATE_ERROR(minimg::FreeImage(*p_dst_image));
*p_dst_image = {};
}
return minimg::UnfoldChannels(*p_dst_image, *p_src_image);
// if (!p_dst_image)
// return BAD_ARGS;
// if (!(rules & RO_REUSE_CONTAINER) && p_dst_image->p_zero_line)
// return BAD_ARGS;
// PROPAGATE_ERROR(_AssureMinImageIsValid(p_src_image));
// *p_dst_image = *p_src_image;
// p_dst_image->width *= p_dst_image->channels;
// p_dst_image->channels = 1;
// return NO_ERRORS;
}
MUSTINLINE int _SliceMinImageVertically(
MinImg *p_dst_image,
const MinImg *p_src_image,
int begin,
int period,
int end = -1,
RulesOption rules = RO_STRICT) {
if (!p_dst_image || !p_src_image)
return BAD_ARGS;
if (p_dst_image == p_src_image) {
if (RO_REUSE_CONTAINER & rules) {
DECLARE_GUARDED_MINIMG(tmp);
/*MinImg*/ tmp = *p_src_image;
*p_dst_image = {};
return minimg::SliceVertically(*p_dst_image, tmp, begin, period, end);
} else {
return BAD_ARGS;
}
}
if (RO_REUSE_CONTAINER & rules) {
PROPAGATE_ERROR(minimg::FreeImage(*p_dst_image));
*p_dst_image = {};
}
return minimg::SliceVertically(
*p_dst_image, *p_src_image, begin, period, end);
// if (!p_dst_image || p_dst_image->p_zero_line)
// return BAD_ARGS;
// if (!(rules & RO_REUSE_CONTAINER) && p_dst_image->p_zero_line)
// return BAD_ARGS;
// PROPAGATE_ERROR(_AssureMinImageIsValid(p_src_image));
// if (end < 0)
// end = p_src_image->height;
// if (begin < 0 || end < begin || p_src_image->height < end || period <= 0)
// return BAD_ARGS;
// *p_dst_image = *p_src_image;
// p_dst_image->p_zero_line = _GetMinImageLine(p_dst_image, begin);
// if (!p_dst_image->p_zero_line)
// return INTERNAL_ERROR;
// p_dst_image->stride *= period;
// p_dst_image->height = (end - begin + period - 1) / period;
// return NO_ERRORS;
}
MUSTINLINE int _UnrollSolidMinImage(
MinImg *p_dst_image,
const MinImg *p_src_image,
RulesOption rules = RO_STRICT) {
if (!p_dst_image || !p_src_image)
return BAD_ARGS;
if (p_dst_image == p_src_image) {
if (RO_REUSE_CONTAINER & rules) {
DECLARE_GUARDED_MINIMG(tmp);
/*MinImg*/ tmp = *p_src_image;
p_dst_image = {};
return minimg::UnrollSolidImage(*p_dst_image, tmp);
} else {
return BAD_ARGS;
}
}
if (RO_REUSE_CONTAINER & rules) {
PROPAGATE_ERROR(minimg::FreeImage(*p_dst_image));
*p_dst_image = {};
}
return minimg::UnrollSolidImage(*p_dst_image, *p_src_image);
// if (!p_dst_image)
// return BAD_ARGS;
// if (!(rules & RO_REUSE_CONTAINER) && p_dst_image->p_zero_line)
// return BAD_ARGS;
// PROPAGATE_ERROR(_AssureMinImageIsValid(p_src_image));
// if (_AssureMinImageIsSolid(p_src_image) != NO_ERRORS)
// return BAD_ARGS;
// *p_dst_image = *p_src_image;
// p_dst_image->width *= p_dst_image->height;
// p_dst_image->height = 1;
// return NO_ERRORS;
}
MUSTINLINE int _SplitImageIntoRegions(
int n_regions,
MinImg *const *pp_regions,
const MinImg *p_image,
DirectionOption split_direction) {
NEED_NO_ERRORS(_AssureMinImageIsValid(p_image));
const int32_t width = p_image->width;
const int32_t height = p_image->height;
switch (split_direction) {
case DO_BOTH: {
return BAD_ARGS;
}
case DO_HORIZONTAL: {
const int32_t shift = (width + n_regions - 1) / n_regions;
for (int k = 0; k < n_regions; ++k) {
const int32_t x0 = k * shift;
PROPAGATE_ERROR(_GetMinImageRegion(pp_regions[k], p_image,
x0, 0, std::min(shift, width - x0), height));
}
break;
}
case DO_VERTICAL: {
const int32_t shift = (height + n_regions - 1) / n_regions;
for (int k = 0; k < n_regions; ++k) {
const int32_t y0 = k * shift;
PROPAGATE_ERROR(_GetMinImageRegion(pp_regions[k], p_image,
0, y0, width, std::min(shift, height - y0)));
}
break;
}
default:
return NOT_IMPLEMENTED;
}
return NO_ERRORS;
}
#endif // #ifndef MINIMGAPI_MINIMGAPI_INL_H_INCLUDED
|
# Turn off HomeAssistant service
echo "Turning off Home Assistant"
sudo systemctl restart home-assistant@pi.service
# Go to HomeAssistant directory
echo "Entering HomeAssistant directory"
cd /home/pi/homeassistant
# Activate venv
echo "Enabling virtualenv"
source bin/activate
# Run upgrade
echo "Upgrading Home Assistant"
python3 -m pip install --upgrade homeassistant
# Exit venv
echo "Exiting..."
deactivate
cd
|
/*
Copyright 2020 caicloud authors. All rights reserved.
*/
// Code generated by lister-gen. DO NOT EDIT.
package v1alpha3
// FlavorListerExpansion allows custom methods to be added to
// FlavorLister.
type FlavorListerExpansion interface{}
// MLNeuronListerExpansion allows custom methods to be added to
// MLNeuronLister.
type MLNeuronListerExpansion interface{}
// MLNeuronNamespaceListerExpansion allows custom methods to be added to
// MLNeuronNamespaceLister.
type MLNeuronNamespaceListerExpansion interface{}
// MLProjectListerExpansion allows custom methods to be added to
// MLProjectLister.
type MLProjectListerExpansion interface{}
// MLProjectNamespaceListerExpansion allows custom methods to be added to
// MLProjectNamespaceLister.
type MLProjectNamespaceListerExpansion interface{}
// MLTaskListerExpansion allows custom methods to be added to
// MLTaskLister.
type MLTaskListerExpansion interface{}
// MLTaskNamespaceListerExpansion allows custom methods to be added to
// MLTaskNamespaceLister.
type MLTaskNamespaceListerExpansion interface{}
|
package com.github.damianreeves.ticketbroker.common.model.domain.reservation
import java.util.UUID
import com.github.damianreeves.ticketbroker.common.model.domain.marketplace.MarketPlaceType
final case class ReservationUrn(uid:UUID, marketplace:MarketPlaceType) {
def asUrn:String = s"urn:reservation:marketplace=$marketplace;uid=$uid"
override def toString:String = asUrn
}
|
module TwitchSushi
class Error < StandardError
class ResponseError < Error
def initialize(arg, url, status, body)
super(arg)
@url = url
@status = status
@body = body
end
attr_reader :url, :status, :body
end
class ClientError < ResponseError
end
class ServerError < ResponseError
end
class FormatError < ResponseError
end
end
end
|
using System;
using System.Reflection;
using FubuCore.Reflection;
using FubuCore.Util;
namespace FubuMVC.Core.Registration
{
public class ActionMethodFilter : CompositeFilter<MethodInfo>
{
public ActionMethodFilter()
{
Excludes += method => method.DeclaringType == typeof(object);
Excludes += method => method.DeclaringType == typeof(MarshalByRefObject);
Excludes += method => method.Name == ReflectionHelper.GetMethod<IDisposable>(x => x.Dispose()).Name;
Excludes += method => method.ContainsGenericParameters;
Excludes += method => method.IsSpecialName;
}
public void IgnoreMethodsDeclaredBy<T>()
{
Excludes += x => x.DeclaringType == typeof (T);
}
}
}
|
//
// Decompiled by Procyon v0.5.36
//
package openjava.ptree;
import openjava.ptree.util.ParseTreeVisitor;
public class MemberInitializer extends NonLeaf implements MemberDeclaration
{
private boolean _isStatic;
public MemberInitializer(final StatementList list) {
this(list, false);
}
public MemberInitializer(final StatementList p2, final boolean isStatic) {
this._isStatic = false;
this._isStatic = isStatic;
this.set(p2);
}
public MemberInitializer() {
this._isStatic = false;
}
public boolean isStatic() {
return this._isStatic;
}
public StatementList getBody() {
return (StatementList)this.elementAt(0);
}
public void setBody(final StatementList p) {
this.setElementAt(p, 0);
}
@Override
public void accept(final ParseTreeVisitor parseTreeVisitor) throws ParseTreeException {
parseTreeVisitor.visit(this);
}
}
|
require "test_helper"
module Sources
class FuraffinityTest < ActiveSupport::TestCase
context "A furaffinity post" do
strategy_should_work(
"https://www.furaffinity.net/view/46821705/",
image_urls: ["https://d.furaffinity.net/art/iwbitu/1650222955/1650222955.iwbitu_yubi.jpg"],
profile_url: "https://www.furaffinity.net/user/iwbitu",
page_url: "https://www.furaffinity.net/view/46821705",
artist_name: "iwbitu",
artist_commentary_title: "Yubi",
artist_commentary_desc: /little gift doodle for/
)
end
context "A furaffinity image" do
strategy_should_work(
"https://d.furaffinity.net/art/iwbitu/1650222955/1650222955.iwbitu_yubi.jpg",
image_urls: ["https://d.furaffinity.net/art/iwbitu/1650222955/1650222955.iwbitu_yubi.jpg"],
profile_url: "https://www.furaffinity.net/user/iwbitu",
artist_name: "iwbitu",
page_url: nil,
artist_commentary_title: nil
)
end
context "An adult age-restricted furaffinity post" do
strategy_should_work(
"https://www.furaffinity.net/view/46590097/",
image_urls: ["https://d.furaffinity.net/art/iwbitu/1648803766/1648803766.iwbitu_nyopu_tori.jpg"],
profile_url: "https://www.furaffinity.net/user/iwbitu",
page_url: "https://www.furaffinity.net/view/46590097",
artist_name: "iwbitu",
tags: [],
artist_commentary_title: "Nyopu and Tori",
artist_commentary_desc: /UwU/
)
end
context "A deleted or non-existing furaffinity post" do
strategy_should_work("https://www.furaffinity.net/view/3404111", deleted: true, profile_url: nil)
end
context "A furaffinity post with non-ascii image url" do
strategy_should_work(
"https://www.furaffinity.net/view/20762907/",
image_urls: ["https://d.furaffinity.net/art/fhedge/1470365580/1470365580.fhedge_ミストランサーまとめアートボード_1.jpg"]
)
end
should "Parse Furaffinity URLs correctly" do
assert(Source::URL.image_url?("https://d.furaffinity.net/art/iwbitu/1650222955/1650222955.iwbitu_yubi.jpg"))
assert(Source::URL.page_url?("https://www.furaffinity.net/view/46821705/"))
assert(Source::URL.page_url?("https://www.furaffinity.net/full/46821705/"))
assert(Source::URL.profile_url?("https://www.furaffinity.net/user/iwbitu"))
assert(Source::URL.profile_url?("https://www.furaffinity.net/gallery/iwbitu"))
assert(Source::URL.profile_url?("https://www.furaffinity.net/gallery/iwbitu/folder/133763/Regular-commissions"))
end
end
end
|
namespace Skight.eLiteWeb.Presentation.Web.FrontControllers
{
public interface CommandFilter
{
bool can_process(WebRequest request);
}
}
|
from recipes.testing import Expect, Throws, mock, expected, ECHO
from recipes.string import Percentage, sub, title
import pytest
test_sub = Expect(sub)(
# basic
{mock.sub('hello world', {'h': 'm', 'o ': 'ow '}):
'mellow world',
mock.sub('hello world', dict(h='m', o='ow', rld='')):
'mellow wow',
mock.sub('hello world', {'h': 'm', 'o ': 'ow ', 'l': ''}):
'meow word',
mock.sub('hello world', dict(hell='lo', wo='', r='ro', d='l')):
'loo roll',
# character permutations
mock.sub('option(A, B)', {'B': 'A', 'A': 'B'}):
'option(B, A)',
mock.sub('AABBCC', {'A': 'B', 'B': 'C', 'C': 'c'}):
'BBCCcc',
mock.sub('hello world', dict(h='m', o='ow', rld='', w='v')):
'mellow vow',
mock.sub('dark-SHOC2-8x8-1MHz 2.5 EM: 30', {' ': '-', "'": '', ': ': ''}):
'dark-SHOC2-8x8-1MHz-2.5-EM30',
mock.sub(r"""\
\begin{equation}[Binary vector potential]
\label{eq:bin_pot_vec}
Ψ\qty(\vb{r}) = - \frac{GM_1}{\abs{\vb{r - r_1}}}
\end{equation}""",
{'_p': 'ₚ', 'eq:bin_pot_vec': 'eq:bin_pot_vec'}):
ECHO
}
)
<<<<<<< HEAD
test_replace = Expect(title)(
=======
test_title = Expect(title)(
>>>>>>> dev
# basic
{mock.title('hello world'): 'Hello World',
mock.title('hello world', 'world'): 'Hello world',
mock.title('internal in inside', 'in'): 'Internal in Inside',
mock.title('words for the win', ('for', 'the')): 'Words for the Win'
}
)
# _unbracket('{{{hello world!}}}', '{}', condition=lambda x: '!' not in x)
# Out[53]: '{{{hello world!}}}'
# _unbracket('{{{hello world? {this my jam!}}}', '{}', condition=lambda x: '!' not in x)
# Out[54]: '{{{hello world? {this my jam!}}}'
# tests = ['root/{ch{{1,2},{4..6}},main{1,2},{1,2}test}*.png',
# ...: 'ch{{1,2},{4..6}},main{1,2},{1,2}test']
# ...: lists(map(bash.splitter, tests))
# [['root/{ch{{1,2},{4..6}},main{1,2},{1,2}test}*.png'],
# ['ch{{1,2},{4..6}}', 'main{1,2}', '{1,2}test']]
@pytest.mark.parametrize(
's, e',
[('20%', 2469),
('100.01%', 12346.2345),
('12.0001 %', 1481.412345)]
)
def test_percentage(s, e):
assert Percentage(s).of(12345.) == e
# @pytest.mark.parametrize('s', ['3r',
# 'some text 100.0.ss',
# '12.0001 %'])
# def test_percentage_raises(s):
# n = Percentage(s).of(12345.)
# print(n)
|
-- file:plpgsql.sql ln:1267 expect:true
insert into PSlot values ('PS.first.a1', 'PF1_1', '', 'WS.101.1a')
|
<?php
/**
*
* PHP Error Checker v0.2
* By AyoobAli.com
*
*/
$path = "";
$site = "";
$Error['Fatal'] = 1;
$Error['Parse'] = 1;
$Error['Warning'] = 1;
$Error['Notice'] = 1;
$custom = 0;
if ( $argv[1] ) {
$path = $argv[1];
}
if ( $argv[2] ) {
$site = $argv[2];
}
if ( count( $argv ) > 3 ) {
$Error['Fatal'] = 0;
$Error['Parse'] = 0;
$Error['Warning'] = 0;
$Error['Notice'] = 0;
$custom = 1;
}
if ( substr( $site, -1 ) != "/" ) {
$site = $site . "/";
}
$spline = str_repeat( "=", 90 ) . "\n";
echo "\n" . $spline . " [ Error Checker v0.1 By AyoobAli.com ]\n";
echo "Usage: errorChecker.php DirPath SiteURL [CustomSearch] [CustomSearch] [CustomSearch] [...]\n";
echo "Ex.: errorChecker.php \"/var/www/script\" \"http://localhost/script\" \"Text To Find\" \"Or This\"\n" .
$spline;
if ( $path && $site ) {
$dir = new RecursiveDirectoryIterator( $path );
$itr = new RecursiveIteratorIterator( $dir );
$ittl = iterator_count( $itr );
$itr->rewind();
$ttl = 0;
$num = 0;
$err = 0;
$ftl = 0;
$prs = 0;
$wrn = 0;
$ntc = 0;
$cst = 0;
$sct = "";
$CustomText = "";
echo "Path: " . $path . "\n";
echo "Site: " . $site . "\n";
if ( $custom ) {
echo "Custom text: ";
for ( $i = 3; $i < count( $argv ); $i++ ) {
$CustomText .= "\"" . strtolower( $argv[$i] ) . "\", ";
}
echo "$CustomText\n";
}
echo $spline;
while ( $itr->valid() ) {
$ttl++;
$filePath = $itr->getSubPathName();
$filePath = str_replace( "\\", "/", $filePath );
echo str_repeat( " ", strlen( $sct ) ) . "\r";
$sct = " Scanning : " . $ttl . " / " . $ittl . " [" . $filePath . "]\r";
echo $sct;
$errMsg = "";
if ( !$itr->isDot() ) {
if ( substr( $filePath, -4 ) != ".png" && substr( $filePath, -4 ) != ".jpg" && substr( $filePath, -4 ) !=
".gif" ) {
$GetData = @file_get_contents( $site . $filePath );
$GetData = strtolower( $GetData );
$ftlErr = strpos( $GetData, "fatal error</b>:" );
$prsErr = strpos( $GetData, "parse error</b>:" );
$wrnErr = strpos( $GetData, "warning</b>:" );
$ntcErr = strpos( $GetData, "notice</b>:" );
if ( $custom ) {
$nErr = 0;
for ( $i = 3; $i < count( $argv ); $i++ ) {
$cstTxt = strpos( $GetData, strtolower( $argv[$i] ) );
if ( $cstTxt ) {
$cst++;
$errMsg .= "\"" . strtolower( $argv[$i] ) . "\", ";
}
}
}
if ( $ftlErr && $Error['Fatal'] ) {
$ftl++;
$errMsg .= "Fatal, ";
}
if ( $prsErr && $Error['Parse'] ) {
$prs++;
$errMsg .= "Parse, ";
}
if ( $wrnErr && $Error['Warning'] ) {
$wrn++;
$errMsg .= "Warning, ";
}
if ( $ntcErr && $Error['Notice'] ) {
$ntc++;
$errMsg .= "Notice, ";
}
if ( $errMsg ) {
$num++;
echo str_repeat( " ", strlen( $sct ) ) . "\r";
echo "\r" . $num . ' - ' . $site . $filePath . " [" . substr( $errMsg, 0, -2 ) . "]\n";
}
}
}
$itr->Next();
}
echo $spline;
echo "Scanned Files\t: " . $ttl . " / " . $ittl . "\n";
if ( $Error['Fatal'] ) {
echo "Fatal error\t: " . $ftl . "\n";
}
if ( $Error['Parse'] ) {
echo "Parse error\t: " . $prs . "\n";
}
if ( $Error['Warning'] ) {
echo "Warning\t\t: " . $wrn . "\n";
}
if ( $Error['Notice'] ) {
echo "Notice\t\t: " . $ntc . "\n";
}
if ( $custom ) {
echo "Custom\t\t: " . $cst . "\n";
}
echo "-----------------\nTotal pages\t: " . $num . "\n";
echo $spline;
}
?>
|
#!/usr/bin/env bash
export LDFLAGS="$LDFLAGS -Wl,-rpath,${PREFIX}/lib -L${PREFIX}/lib -lz"
./autogen.sh
./configure --prefix="${PREFIX}"
make
make test
make -j${CPU_COUNT} install
|
import React, { useEffect } from 'react';
import { useResidentViewState } from '../../../states';
import useAxios from 'axios-hooks';
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
makeStyles
} from '@material-ui/core';
const ResetPasswordDialog = ({ open, onClose }) => {
return (
<Dialog
fullWidth
open={open}
onClose={() => onClose(false)}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">Reset User Password</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
<p>Do you want to Reset user password for this record? The default</p>
<p>password will be "stamesa"</p>
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={() => onClose(false)} color="primary">
Cancel
</Button>
<Button onClick={() => onClose(true)} color="primary" autoFocus>
Confirm
</Button>
</DialogActions>
</Dialog>
);
};
export default ResetPasswordDialog;
|
// Copyright 2012 Henrik Feldt, Chris Patterson, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Transports.AzureServiceBus.Configuration
{
using System;
/// <summary>
/// Implementors of this interface should know how to create a uri based on the credentials supplied.
/// </summary>
public interface SharedAccessSignatureSettings
{
/// <summary>
/// Gets the issuer name as specified by Azure.
/// </summary>
string KeyName { get; }
/// <summary>
/// Gets the base64-encoded key for the service as specified by Azure.
/// </summary>
string Key { get; }
/// <summary>
/// Gets the namespace for the service as specified by Azure.
/// </summary>
string Namespace { get; }
/// <summary>
/// What application is under authorization?
/// </summary>
string Application { get; }
/// <summary>
/// Builds a URI with the passed application (or by default the Application property).
/// </summary>
/// <param name="application">If you wish to have another application</param>
/// <returns>The corresponding uri</returns>
Uri BuildUri(string application = null);
/// <summary>
/// Create a new credential item based on the passed application
/// </summary>
/// <param name="application"></param>
/// <returns></returns>
SharedAccessSignatureSettings WithApplication(string application);
}
}
|
#ifndef IMMAILWIDGET_H
#define IMMAILWIDGET_H
#include <QWidget>
#include <QMap>
#include "model/IMConstant.h"
class QPushButton;
class QTabWidget;
class IMMailButton;
class IMMailOutWidget;
class IMMailInWidget;
class IMMailWriteWidget;
class QLabel;
class IMMailCtrl;
class IMMailInformationWidget;
class IMMailWidget : public QWidget
{
Q_OBJECT
public:
IMMailWidget(const QString & myID, QWidget *parent = 0);
~IMMailWidget();
IMMailCtrl* getMailCtrl();
QString getMyID();
void showMailInformationWidget(const MailInformation & mail);
void showMailInWidget();
void showMailWriteWidget(const QString & address);
signals:
public slots:
private slots:
// 设置收件箱
void setInMailsWidget(const QVector<MailInformation> &);
// 设置发件箱
void setOutMailsWidget(const QVector<MailInformation> &);
// 添加收件箱按钮
bool addInMailButton(const MailInformation &);
// 添加发件箱按钮
bool addOutMailButton(const MailInformation &);
// 删除邮件按钮
void deleteMail(const int &);
// 添加新邮件到发件箱
bool addNewOutMailButton(const MailInformation &);
// 添加新邮件到收件箱
bool addNewInMailButton(const MailInformation &);
private:
void initIMMailWidget();
void linkSignalWithSlot();
void clearContainers();
private:
// QPushButton *m_btnWrite; // 写信
// QPushButton *m_btnIn; // 收件箱
// QPushButton *m_btnOut; // 已发送
// QPushButton *m_btnDrafts; // 草稿箱
// QPushButton *m_btnTrash; // 垃圾箱
QString m_myID;
QLabel *m_labelInformation;
QTabWidget *m_tabWidget;
IMMailOutWidget *m_outWidget;
IMMailInWidget *m_inWidget;
IMMailWriteWidget *m_writeWidget;
IMMailInformationWidget *m_informationWidget;
IMMailCtrl *m_mailCtrl;
QMap<int, IMMailButton*> m_inMailMap;
QMap<int, IMMailButton*> m_outMailMap;
};
#endif // IMMAILWIDGET_H
|
package net.thucydides.core.annotations;
import net.thucydides.core.model.TestTag;
import net.thucydides.core.model.formatters.ReportFormatter;
import net.thucydides.core.tags.TagConverters;
import net.thucydides.core.util.JUnitAdapter;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.Arrays.asList;
import static net.thucydides.core.util.NameConverter.withNoArguments;
/**
* Utility class used to help process annotations on tests and test steps.
*/
public class TestAnnotations {
private final Class<?> testClass;
private TestAnnotations(final Class<?> testClass) {
this.testClass = testClass;
}
public static TestAnnotations forClass(final Class<?> testClass) {
return new TestAnnotations(testClass);
}
public java.util.Optional<String> getAnnotatedTitleForMethod(final String methodName) {
if ((testClass != null) && (testClassHasMethodCalled(methodName))) {
return getAnnotatedTitle(methodName);
}
return java.util.Optional.empty();
}
public boolean isPending(final String methodName) {
java.util.Optional<Method> method = getMethodCalled(methodName);
return method.isPresent() && isPending(method.get());
}
public static boolean isPending(final Method method) {
return method != null && (method.getAnnotation(Pending.class) != null);
}
public static boolean isIgnored(final Method method) {
return JUnitAdapter.isIgnored(method);
}
public static boolean shouldSkipNested(Method method) {
if (method != null) {
Step stepAnnotation = method.getAnnotation(Step.class);
return ((stepAnnotation != null) && (!stepAnnotation.callNestedMethods()));
}
return false;
}
public static boolean isAnExampleStep(Method method) {
if (method != null) {
Step stepAnnotation = method.getAnnotation(Step.class);
return ((stepAnnotation != null) && (stepAnnotation.exampleRow()));
}
return false;
}
public boolean isIgnored(final String methodName) {
java.util.Optional<Method> method = getMethodCalled(methodName);
return method.isPresent() && isIgnored(method.get());
}
private java.util.Optional<String> getAnnotatedTitle(String methodName) {
java.util.Optional<Method> testMethod = getMethodCalled(methodName);
if (testMethod.isPresent()) {
Title titleAnnotation = testMethod.get().getAnnotation(Title.class);
if (titleAnnotation != null) {
return java.util.Optional.of(titleAnnotation.value());
}
}
return java.util.Optional.empty();
}
private boolean testClassHasMethodCalled(final String methodName) {
return (getMethodCalled(methodName).isPresent());
}
private java.util.Optional<Method> getMethodCalled(final String methodName) {
if (testClass == null) {
return java.util.Optional.empty();
}
String baseMethodName = withNoArguments(methodName);
try {
if (baseMethodName == null) {
return java.util.Optional.empty();
} else {
return java.util.Optional.ofNullable(testClass.getMethod(baseMethodName));
}
} catch (NoSuchMethodException e) {
return java.util.Optional.empty();
}
}
/**
* Return a list of the issues mentioned in the title annotation of this method.
*/
List<String> getAnnotatedIssuesForMethodTitle(String methodName) {
java.util.Optional<String> title = getAnnotatedTitleForMethod(methodName);
return title.map(ReportFormatter::issuesIn).orElseGet(() -> ReportFormatter.issuesIn(methodName));
}
private Optional<String> getAnnotatedIssue(String methodName) {
java.util.Optional<Method> testMethod = getMethodCalled(methodName);
if ((testMethod.isPresent()) && (testMethod.get().getAnnotation(Issue.class) != null)) {
return Optional.of(testMethod.get().getAnnotation(Issue.class).value());
}
return Optional.empty();
}
private Optional<String> getAnnotatedVersion(String methodName) {
java.util.Optional<Method> testMethod = getMethodCalled(methodName);
if ((testMethod.isPresent()) && (testMethod.get().getAnnotation(Version.class) != null)) {
return Optional.of(testMethod.get().getAnnotation(Version.class).value());
}
return Optional.empty();
}
private String[] getAnnotatedIssues(String methodName) {
java.util.Optional<Method> testMethod = getMethodCalled(methodName);
if ((testMethod.isPresent()) && (testMethod.get().getAnnotation(Issues.class) != null)) {
return testMethod.get().getAnnotation(Issues.class).value();
}
return new String[]{};
}
/**
* Return a list of the issues mentioned in the Issue annotation of this method.
* @param methodName the name of the test method in the Java test class, if applicable.
* returns
*/
public Optional<String> getAnnotatedIssueForMethod(String methodName) {
return getAnnotatedIssue(methodName);
}
public Optional<String> getAnnotatedVersionForMethod(String methodName) {
return getAnnotatedVersion(methodName);
}
public String[] getAnnotatedIssuesForMethod(String methodName) {
return getAnnotatedIssues(methodName);
}
public String getAnnotatedIssueForTestCase(Class<?> testCase) {
Issue issueAnnotation = testCase.getAnnotation(Issue.class);
if (issueAnnotation != null) {
return issueAnnotation.value();
} else {
return null;
}
}
public String getAnnotatedVersionForTestCase(Class<?> testCase) {
Version versionAnnotation = testCase.getAnnotation(Version.class);
if (versionAnnotation != null) {
return versionAnnotation.value();
} else {
return null;
}
}
public String[] getAnnotatedIssuesForTestCase(Class<?> testCase) {
Issues issueAnnotation = testCase.getAnnotation(Issues.class);
if (issueAnnotation != null) {
return issueAnnotation.value();
} else {
return null;
}
}
List<String> getIssuesForMethod(String methodName) {
List<String> issues = new ArrayList<>();
if (testClass != null) {
addIssuesFromMethod(methodName, issues);
} else {
addIssuesFromTestScenarioName(methodName, issues);
}
return issues;
}
private void addIssuesFromTestScenarioName(String methodName, List<String> issues) {
issues.addAll(getAnnotatedIssuesForMethodTitle(methodName));
}
private void addIssuesFromMethod(String methodName, List<String> issues) {
if (getAnnotatedIssues(methodName) != null) {
issues.addAll(asList(getAnnotatedIssues(methodName)));
}
if (getAnnotatedIssue(methodName).isPresent()) {
issues.add(getAnnotatedIssue(methodName).get());
}
if (getAnnotatedTitle(methodName) != null) {
addIssuesFromTestScenarioName(methodName, issues);
}
}
public List<TestTag> getTagsForMethod(String methodName) {
List<TestTag> allTags = new ArrayList<>(getClassTags());
allTags.addAll(getTagsFor(methodName));
return new ArrayList<>(allTags);
}
public List<TestTag> getClassTags() {
return getClassTags(testClass);
}
public List<TestTag> getAllTags() {
Set<TestTag> classTags = new HashSet<>(getClassTags(testClass));
classTags.addAll(
Arrays.stream(testClass.getMethods())
.filter(method -> method.getDeclaredAnnotation(WithTag.class) != null)
.map(method -> method.getDeclaredAnnotation(WithTag.class).value() )
.map(TestTag::withValue)
.collect(Collectors.toSet()));
classTags.addAll(
Arrays.stream(testClass.getDeclaredMethods())
.filter(method -> method.getDeclaredAnnotation(WithTag.class) != null)
.map(method -> method.getDeclaredAnnotation(WithTag.class).value() )
.map(TestTag::withValue)
.collect(Collectors.toSet()));
return new ArrayList<>(classTags);
}
private final List<TestTag> NO_TAGS = new ArrayList<>();
private List<TestTag> getClassTags(Class<?> testClass) {
List<TestTag> tags = new ArrayList<>();
if (testClass == null) { return NO_TAGS; }
addTagValues(tags, testClass.getAnnotation(WithTagValuesOf.class));
addTags(tags, testClass.getAnnotation(WithTags.class));
addTag(tags, testClass.getAnnotation(WithTag.class));
if (testClass.getSuperclass() != Object.class) {
tags.addAll(getClassTags(testClass.getSuperclass()));
}
return tags;
}
private void addTag(List<TestTag> tags, WithTag tagAnnotation) {
if (tagAnnotation != null) {
tags.add(convertToTestTag(tagAnnotation));
}
}
private void addTags(List<TestTag> tags, WithTags tagSet) {
if (tagSet != null) {
Set<TestTag> newTags = Arrays.stream(tagSet.value())
.map(TagConverters::convertToTestTag)
.collect(Collectors.toSet());
tags.addAll(newTags);
}
}
private void addTagValues(List<TestTag> tags, WithTagValuesOf tagSet) {
if (tagSet != null) {
Set<TestTag> newTags = Arrays.stream(tagSet.value())
.map(TestTag::withValue)
.collect(Collectors.toSet());
tags.addAll(newTags);
}
}
private List<TestTag> getTagsFor(String methodName) {
List<TestTag> tags = new ArrayList<>();
java.util.Optional<Method> testMethod = getMethodCalled(methodName);
if (testMethod.isPresent()) {
addTagValues(tags, testMethod.get().getAnnotation(WithTagValuesOf.class));
addTags(tags, testMethod.get().getAnnotation(WithTags.class));
addTag(tags, testMethod.get().getAnnotation(WithTag.class));
}
return tags;
}
private TestTag convertToTestTag(WithTag withTag) {
if (StringUtils.isEmpty(withTag.value())) {
return TestTag.withName(withTag.name()).andType(withTag.type());
} else {
return TestTag.withValue(withTag.value());
}
}
public List<String> getTestMethodNames() {
return Arrays.stream(testClass.getDeclaredMethods())
.filter(method -> hasAnnotationNamed(method,"Test"))
.map(Method::getName)
.collect(Collectors.toList());
}
private boolean hasAnnotationNamed(Method method, String annotationName) {
return Arrays.stream(method.getAnnotations()).anyMatch(
annotation -> annotation.toString().contains("." + annotationName + "(")
);
}
}
|
<?php
namespace Softonic\Proxy\Guzzle\Middleware\Repositories;
use GuzzleHttp\Client as GuzzleClient;
use Psr\Cache\CacheItemPoolInterface;
use Softonic\Proxy\Guzzle\Middleware\Exceptions\ProxiesNotAvailable;
use Softonic\Proxy\Guzzle\Middleware\Interfaces\ProxyInterface;
use Softonic\Proxy\Guzzle\Middleware\Traits\CacheProxiesList;
class SslPrivateProxy implements ProxyInterface
{
use CacheProxiesList;
const SSLPRIVATEPROXY_API = 'https://www.sslprivateproxy.com/api/v1/';
const SSLPRIVATEPROXY_API_ENDPOINT = '/listproxies/';
const CACHE_KEY = 'ssl_private_proxy_list';
/**
* 4 hours.
*/
const CACHE_TTL = 14400;
/**
* @var GuzzleClient
*/
private $client;
/**
* @var CacheItemPoolInterface
*/
private $cache;
/**
* @var string
*/
private $apiKey;
public function __construct(GuzzleClient $client, CacheItemPoolInterface $cache, string $apiKey)
{
$this->client = $client;
$this->cache = $cache;
$this->apiKey = $apiKey;
}
public function get()
{
return $this->getProxyUsingCache();
}
protected function getFreshProxyList(): array
{
$response = $this->client->get(
self::SSLPRIVATEPROXY_API . $this->apiKey . self::SSLPRIVATEPROXY_API_ENDPOINT
);
$responseContent = $response->getBody()->getContents();
if (empty($responseContent)) {
throw new ProxiesNotAvailable('Proxy response was not successful');
}
$proxiesData = explode("\n", $responseContent);
$proxiesList = [];
foreach ($proxiesData as $proxyData) {
if (!empty($proxyData)) {
list($ip, $port, $username, $password) = explode(':', $proxyData);
$proxiesList[] = "http://$username:$password@$ip:$port";
}
}
return $proxiesList;
}
}
|
import { em, lightgray, percent } from "csx/lib";
import { style } from "typestyle/lib";
import { IStylesheetProvider } from "../interfaces/IStylesheetProvider";
import { addStyles } from "../tools/StyleUtils";
import { AbstractComponent } from "./AbstractComponent";
import { ElementFactory } from "./ElementFactory";
export class OverlayControl extends AbstractComponent {
constructor(rootID: string) {
super(rootID);
}
public renderDOM(div: HTMLElement): void {
addStyles(div, this, "appContainer");
div.appendChild(ElementFactory.div()
.usingStylesheetProvider(this)
.withStyles("appContainer").create());
}
public getDefaultStylesheet(): any {
return {
appContainer: style({
zIndex: 100,
opacity: 0,
margin: 0,
position: "absolute",
width: percent(100),
height: percent(100),
top: 0,
left: 0
}),
};
}
public getProviderName(): string {
return this.rootID;
}
}
|
package com.jcaique.dialetus.data.networking
internal suspend fun <T> executionHandler(func: suspend () -> T): T {
val transformers = listOf(
HttpErrorHandler,
SerializationErrorHandler
)
return try {
func.invoke()
} catch (throwable: Throwable) {
throw transformers
.map { it.transform(throwable) }
.reduce { transformed, current ->
when {
transformed == current -> transformed
current == throwable -> transformed
else -> current
}
}
}
}
|
---
alturls:
- https://twitter.com/bismark/status/12959603936
- https://www.facebook.com/17803937/posts/121434667873157
archive:
- 2010-04
categories:
- blog
date: '2010-04-27T18:58:12'
link: http://timesandseasons.org/index.php/2010/04/this-mormon-life/
oldpaths:
- /post/553947679
- /post/553947679/this-mormon-life
slug: '1272394692'
tags:
- personal
title: This Mormon Life
type: link
---
Links to all *This American Life* episodes with Mormon themes. Saving
this for future listening.
|
using BuildingBlocks.Domain.Event;
namespace BuildingBlocks.Outbox;
public class OutboxMessage
{
public Guid Id { get; private set; }
/// <summary>
/// Gets name of message.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets the date the message occurred.
/// </summary>
public DateTime OccurredOn { get; private set; }
/// <summary>
/// Gets the event type full name.
/// </summary>
public string Type { get; private set; }
/// <summary>
/// Gets the event data - serialized to JSON.
/// </summary>
public string Data { get; private set; }
/// <summary>
/// Gets the date the message processed.
/// </summary>
public DateTime? ProcessedOn { get; private set; }
/// <summary>
/// Gets the type of our event.
/// </summary>
public EventType EventType { get; private set; }
/// <summary>
/// Gets the CorrelationId of our event.
/// </summary>
public Guid? CorrelationId { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="OutboxMessage"/> class.
/// Initializes a new outbox message.
/// </summary>
/// <param name="id">The outbox message identifier.</param>
/// <param name="occurredOn">The outbox message date occurred on.</param>
/// <param name="type">The outbox message type.</param>
/// <param name="name">The name of event type with underscore naming.</param>
/// <param name="data">The outbox message data.</param>
/// <param name="eventType">The outbox event type.</param>
/// <param name="correlationId">The correlationId of our outbox event.</param>
public OutboxMessage(
Guid id,
DateTime occurredOn,
string type,
string name,
string data,
EventType eventType,
Guid? correlationId = null)
{
OccurredOn = occurredOn;
Type = type;
Data = data;
Id = id;
Name = name;
EventType = eventType;
CorrelationId = correlationId;
}
/// <summary>
/// Sets outbox message process date.
/// </summary>
public void MarkAsProcessed()
{
ProcessedOn = DateTime.Now;
}
public bool Validate()
{
if (Id == Guid.Empty)
{
throw new System.ComponentModel.DataAnnotations.ValidationException(
"Id of the Outbox entity couldn't be null.");
}
if (string.IsNullOrEmpty(Type))
{
throw new System.ComponentModel.DataAnnotations.ValidationException(
"Type of the Outbox entity couldn't be null or empty.");
}
if (Data is null)
{
throw new System.ComponentModel.DataAnnotations.ValidationException(
"Payload of the Outbox entity couldn't be null (should be an Avro format).");
}
return true;
}
}
|
use super::token::{
keyword::Keyword,
literal::Literal,
punctuation::Punctuation,
token_variance::{Span, Token, TokenType},
};
use nom::{
branch::alt,
bytes::complete::{tag, take_until},
character::complete::{
alpha1,
alphanumeric1,
char,
digit1,
line_ending,
multispace1,
one_of,
space1,
tab,
},
combinator::{map_res, recognize, value},
multi::{many0, many1},
sequence::{delimited, preceded, terminated, tuple},
IResult,
};
use nom_locate::position;
pub fn keyword(input: Span) -> IResult<Span, Token> {
let (tail, kw) = alt((
value(
Keyword::Const,
terminated(tag(Keyword::Const.as_str()), space1),
),
value(Keyword::Let, terminated(tag(Keyword::Let.as_str()), space1)),
value(Keyword::If, tag(Keyword::If.as_str())),
value(Keyword::Else, tag(Keyword::Else.as_str())),
value(Keyword::Function, tag(Keyword::Function.as_str())),
value(
Keyword::Class,
terminated(tag(Keyword::Class.as_str()), space1),
),
value(
Keyword::Import,
terminated(tag(Keyword::Import.as_str()), space1),
),
value(
Keyword::Export,
terminated(tag(Keyword::Export.as_str()), space1),
),
value(
Keyword::Return,
terminated(tag(Keyword::Return.as_str()), space1),
),
))(input)?;
let (tail, pos) = position(tail)?;
Ok((
tail,
Token {
position: pos,
value: TokenType::Keyword(kw),
},
))
}
pub fn punctuation(input: Span) -> IResult<Span, Token> {
let (tail, punc) = alt((
value(
Punctuation::BracketOpen,
tag(Punctuation::BracketOpen.as_str()),
),
value(
Punctuation::BracketClose,
tag(Punctuation::BracketClose.as_str()),
),
value(
Punctuation::BracketSquareOpen,
tag(Punctuation::BracketSquareOpen.as_str()),
),
value(
Punctuation::BracketSquareClose,
tag(Punctuation::BracketSquareClose.as_str()),
),
value(
Punctuation::BracketCurlyOpen,
tag(Punctuation::BracketCurlyOpen.as_str()),
),
value(
Punctuation::BracketCurlyClose,
tag(Punctuation::BracketCurlyClose.as_str()),
),
value(Punctuation::Equal, tag(Punctuation::Equal.as_str())),
value(
Punctuation::GreaterThan,
tag(Punctuation::GreaterThan.as_str()),
),
value(Punctuation::LessThan, tag(Punctuation::LessThan.as_str())),
value(
Punctuation::QuoteDouble,
tag(Punctuation::QuoteDouble.as_str()),
),
value(
Punctuation::QuoteSingle,
tag(Punctuation::QuoteSingle.as_str()),
),
value(
Punctuation::ExclamationMark,
tag(Punctuation::ExclamationMark.as_str()),
),
value(Punctuation::Colon, tag(Punctuation::Colon.as_str())),
value(Punctuation::Semicolon, tag(Punctuation::Semicolon.as_str())),
value(Punctuation::Dot, tag(Punctuation::Dot.as_str())),
value(Punctuation::Comma, tag(Punctuation::Comma.as_str())),
value(Punctuation::Space, tag(Punctuation::Space.as_str())),
value(Punctuation::Tab, tab),
value(Punctuation::EOL, line_ending),
))(input)?;
let (tail, pos) = position(tail)?;
Ok((
tail,
Token {
position: pos,
value: TokenType::Punctuation(punc),
},
))
}
pub fn decimal(input: Span) -> IResult<Span, Token> {
let (tail, token) = map_res(
recognize(many1(terminated(digit1, many0(char('_'))))),
|token: Span| token.fragment().replace('_', "").parse::<f64>(),
)(input)?;
let (tail, pos) = position(tail)?;
Ok((
tail,
Token {
position: pos,
value: TokenType::Literal(Literal::Number(token)),
},
))
}
pub fn boolean(input: Span) -> IResult<Span, Token> {
let (tail, bool_value) = alt((value(true, tag("true")), value(false, tag("false"))))(input)?;
let (tail, pos) = position(tail)?;
Ok((
tail,
Token {
position: pos,
value: TokenType::Literal(Literal::Bool(bool_value)),
},
))
}
pub fn undefined(input: Span) -> IResult<Span, Token> {
let (tail, undefined_literal) = value(Literal::Undefined, tag("undefined"))(input)?;
let (tail, pos) = position(tail)?;
Ok((
tail,
Token {
position: pos,
value: TokenType::Literal(undefined_literal),
},
))
}
pub fn null(input: Span) -> IResult<Span, Token> {
let (tail, null_literal) = value(Literal::Null, tag("null"))(input)?;
let (tail, pos) = position(tail)?;
Ok((
tail,
Token {
position: pos,
value: TokenType::Literal(null_literal),
},
))
}
pub fn string(input: Span) -> IResult<Span, Token> {
let (tail, token) = alt((
delimited(char('\''), take_until("'"), char('\'')),
delimited(char('"'), take_until("\""), char('"')),
))(input)?;
let (tail, pos) = position(tail)?;
Ok((
tail,
Token {
position: pos,
value: TokenType::Literal(Literal::String(&token)),
},
))
}
pub fn binary(input: Span) -> IResult<Span, Token> {
let (tail, token) = preceded(
tag("0b"),
recognize(many1(terminated(one_of("01"), many0(char('_'))))),
)(input)?;
let (tail, pos) = position(tail)?;
Ok((
tail,
Token {
position: pos,
value: TokenType::Generic(&token),
},
))
}
pub fn identifier(input: Span) -> IResult<Span, Token> {
let (tail, token) = recognize(tuple((
many1(alt((alpha1, tag("_"), tag("$")))),
many0(alt((alphanumeric1, tag("_"), tag("$")))),
)))(input)?;
let (tail, pos) = position(tail)?;
Ok((
tail,
Token {
position: pos,
value: TokenType::Identifier(&token),
},
))
}
pub fn space(input: Span) -> IResult<Span, Token> {
let (tail, token) = multispace1(input)?;
let (tail, pos) = position(tail)?;
Ok((
tail,
Token {
position: pos,
value: TokenType::Generic(&token),
},
))
}
pub fn empty(input: Span) -> IResult<Span, Token> {
let (tail, _token) = tag("")(input)?;
let (tail, pos) = position(tail)?;
Ok((
tail,
Token {
position: pos,
value: TokenType::Empty,
},
))
}
pub fn all_tokens(input: Span) -> IResult<Span, Token> {
// The order here is **critical** as the `alt` function runs them in the order that they appear in
alt((
decimal,
string,
binary,
keyword,
punctuation,
undefined,
null,
space,
identifier,
empty,
))(input)
}
|
# CITYSPIRE
### DATA SCIENCE SYSTEM ARCHITECTURE

https://whimsical.com/cityspire-ds-architecture-QPTz3ZTyw5orFHKcQm7jZv
Create a copy of architecture and then make changes
|
require_relative '../../spec_helper'
require 'spectrum/config/metadata_component'
require 'spectrum/config/quoted_search1_metadata_component'
describe Spectrum::Config::QuotedSearch1MetadataComponent do
subject { described_class.new('Name', config) }
let(:config) {{
'type' => 'quoted_search1',
'variant' => 'filtered',
'scope' => 'SCOPE',
}}
let(:true_result) {{
term: 'Name',
termPlural: 'Names',
description: [
{
text: true,
search: {
type: 'filtered',
scope: 'SCOPE',
value: '"true"',
}
}
]
}}
let(:false_result) {{
term: 'Name',
termPlural: 'Names',
description: [
{
text: false,
search: {
type: 'filtered',
scope: 'SCOPE',
value: '"false"',
}
}
]
}}
context "#resolve" do
it "returns nil when given nil" do
expect(subject.resolve(nil)).to be(nil)
end
it "returns nil when given []" do
expect(subject.resolve([])).to be(nil)
end
it "returns data when given true" do
expect(subject.resolve(true)).to eq(true_result)
end
it "returns data when given false" do
expect(subject.resolve(false)).to eq(false_result)
end
end
end
|
;; Misc extra routines for pgplot - useful higher level functions
(in-package pgplot)
(defun pgplot-encode-float-sci-notation
(x ndigits &key (min-exponent 0) (show-plus-sign nil))
"Encode a number in scientific notation using pgplot escaping
syntax. MIN-EXPONENT is the smallest absolute value exponent that is
expressed in scientific notation. By default it is zero, so all
numbers are expressed in scientific notaton. If SHOW-PLUS-SIGN is T,
then positive numbers have leading plus sign."
(let* ((expnt (if (zerop x)
0
(floor (log (abs x) 10))))
(psign (if (and show-plus-sign (not (minusp x))) "+" ""))
(mant (/ x (expt 10 expnt))))
(if (>= (abs expnt) min-exponent)
(format nil "~A~,vF\\(0727)10\\u~D\\d" psign ndigits mant expnt)
(format nil "~A~,vF" psign ndigits x))))
(defgeneric draw-wedge (p x0 y0 r1 r2 theta1 theta2
&key color line-width line-style fill-area-style
draw-polygon draw-boundary)
(:documentation
"Draw a wedge, meaning a segment of two nested circles, at
X0,YO. Circles are of radii R1 and R2, and extend from degree angle
THETA1 to THETA2, where THETA=0 is the postive X direction. The wedge
is drawn as an outline (if DRAW-BOUNDARY is T) and as polygon (if
DRAW-POLYGON is T). Options LINE-WIDTH, LINE-STYLE, COLOR are passed
to both the line drawing and the polygon drawing command, and
FILL-AREA-STYLE is passed to the polygon drawing command as in
PGPLOT:POLYGON."))
(defmethodL draw-wedge ((p pgplot)
x0 y0 r1 r2 theta1 theta2 &key (color :default)
(line-width nil)
(line-style nil)
(fill-area-style nil)
(draw-polygon t)
(draw-boundary t))
(let* ((deg (float (- theta2 theta1) 1.0))
(ri (min r1 r2))
(ro (max r1 r2))
(x0 (float x0 1.0))
(y0 (float y0 1.0))
(zero-cent (zerop ri)) ;; is the inner radius zero?
(ncirc (max 2 (round (* deg 3)))) ;; 3 line segments per deg
(ntot
(if zero-cent
(+ 2 ncirc)
(+ 1 (* ncirc 2))))
(xvec (make-array ntot :element-type 'single-float :initial-element 0.0))
(yvec (make-array ntot :element-type 'single-float :initial-element 0.0)))
(loop
with dtheta = (/ deg (1- ncirc))
for i below ncirc
for j = (- ntot i 2) then (1- j)
for theta from theta1 by dtheta
for cos = (float (cos (* (/ pi 180) theta)) 1.0)
for sin = (float (sin (* (/ pi 180) theta)) 1.0)
do
(when (not zero-cent) ;; only do 2nd ring if not zero centered
(setf (aref xvec i) (+ x0 (* ri cos))
(aref yvec i) (+ y0 (* ri sin))))
(setf
(aref xvec j) (+ x0 (* ro cos))
(aref yvec j) (+ y0 (* ro sin))))
;;
;; if zero-cent, put in the center point
(when zero-cent
(setf (aref xvec (- ntot 1)) x0)
(setf (aref yvec (- ntot 1)) y0))
;;
;; tie off the end
(setf (aref xvec (1- ntot)) (aref xvec 0))
(setf (aref yvec (1- ntot)) (aref yvec 0))
(when draw-polygon
(pgplot:polygon p xvec yvec :color color
:line-width line-width :line-style line-style
:fill-area-style fill-area-style))
(when draw-boundary
(pgplot:connect p xvec yvec :color color :line-width line-width
:line-style line-style))))
(defun make-2d-transform-matrix (&key (xscale 1.0) (yscale 1.0)
(rotation 0.0)
(ixref 0) (iyref 0)
(xref 0.0) (yref 0.0)
x0 y0)
"Make a transformation matrix (a 2x3 array) as used by IMAGE
and CONTOUR.
For the data array A[I,J], the default coordinate system has
X increasing with J, and Y increasing with I, rescaled to fit
exactly within the user coordinates. If used, the
transformation matrix (TR) changes this to:
X = TR[0,0] + TR[0,1]*J + TR[0,2]*I
Y = TR[1,0] + TR[1,1]*J + TR[1,2]*I
The transformation is construced as
X X0 J
= + ROTATION x SCALING x
Y Y0 I
The sense of the rotation is +X rotates into +Y, and flips can
be accomplished by setting XSCALE to a negative value.
The additive X0,Y0 part of the transformation is defined so that array
elements IXREF,IYREF map into XREF,YREF. Alternatively, if X0 and Y0 are specified,
then IXREF,IYREF,XREF,YREF are ignored.
"
(let ((a (make-array '(2 3) :element-type 'single-float :initial-element 0.0))
(cosr (cos (* (/ pi 180) rotation)))
(sinr (sin (* (/ pi 180) rotation))))
;;
(setf (aref a 0 1) (float (* xscale cosr) 1.0))
(setf (aref a 1 1) (float (* xscale sinr) 1.0))
(setf (aref a 0 2) (float (* yscale sinr -1) 1.0))
(setf (aref a 1 2) (float (* yscale cosr) 1.0))
;;
(if (and x0 y0)
;; if both x0 and are specified use them in transform
(progn
(setf (aref a 0 0) (float x0 1.0))
(setf (aref a 1 0) (float y0 1.0)))
;; otherwise build transform using ixraf, iyref, xref, yref
(progn
(setf (aref a 0 0)
(float (- xref (+ (* (aref a 0 1) ixref)
(* (aref a 0 2) iyref)))))
(setf (aref a 1 0)
(float (- yref (+ (* (aref a 1 1) ixref)
(* (aref a 1 2) iyref)))))))
;;
a))
(defgeneric draw-plot-legend (p x0 y0 legend-list &key x-separation
y-separation character-height
ymax draw-box)
(:documentation "Draw a legend in a plot.
LEGEND-LIST is a list containing the legend lines
((\"text\" :POINT :CIRCLE .. [keyword arguments for PGPLOT:POINTS])
(\"text\" :LINE [keyword arguments for PGPLOT:CONNECT])
(\"text\" :RECTANGLE [keyword arguments for PGPLOT:RECTANGLE])
;; overlapping legend types specified as follows, with lists
(\"text\" (:POINT [keyword arguments for PGPLOT:POINT])
(:LINE [keyword arguments for PGPLOT:LINE])))
see PGPLOT::*SAMPLE-PLOT-LEGEND* for an example
All coordinates are such that the viewport is remapped to x=[0,1],y=[0,YMAX]
where YMAX is 1 by default, but can be set to the aspect ratio ysize/xsize
for non-square plots.
X-SEPARATION is the spacing between the token (point, line, rectangle) and
the text.
Y-SEPARATION is the separation between lines of text
when BLANK-FIRST is set, it first blanks the region with BLANK-COLOR,
and then draws the legend."
))
(defmethodL draw-plot-legend
((p pgplot) x0 y0 legend-list &key (x-separation 0.10)
(y-separation 0.07) (character-height 1.2) (ymax 1.0)
(blank-first nil) (blank-color :background)
(draw-box nil))
(with-window (p 0 1 0 ymax)
(loop
with xmin = x0 and xmax = (+ x0 x-separation)
with ymin = y0 and ymax = y0
for legend in legend-list
for y downfrom y0 by y-separation
for text = (first legend)
;;for type = (second legend)
;;for point-symbol = (if (eq type :point) (third legend))
;;for keyword-args = (if (eq type :point) (cdddr legend) (cddr legend))
do
(when (not blank-first)
(pgplot:write-text p text (+ x0 x-separation) (- y (* 0.2 y-separation))
:character-height character-height))
;; now note the size of the text
(when (or draw-box blank-first)
(multiple-value-bind (xb yb)
(pgplot:text-bounding-box p text
:x0 (+ x0 x-separation)
:y0 (- y (* 0.2 y-separation))
:character-height character-height)
;(print (list xb yb))
(setf xmax (max xmax (aref xb 2)))
(setf ymax (max ymax (aref yb 1)))
(setf ymin (min ymin (aref yb 0)))))
;;
(flet ((draw-legend-marker (type point-symbol keyword-args)
(cond (blank-first ;; do nothing - this is just the blanking phase
nil)
((eq type :point)
(apply 'pgplot:points p (+ x0 (* 0.3 x-separation))
y point-symbol keyword-args))
((eq type :line)
(apply 'pgplot:connect p
(vector x0 (+ x0 (* 0.7 x-separation)))
(vector y y)
keyword-args))
((eq type :rectangle)
(apply 'pgplot:rectangle p
x0 (+ x0 (* 0.7 x-separation))
(+ y (* 0.3 y-separation)) (- y (* 0.3 y-separation))
keyword-args)))))
(let* ((marker-stuff (cdr legend))
(marker-stuff-list
(if (listp (car marker-stuff)) ;; ie, this is a LIST of markers
marker-stuff
(list marker-stuff)))) ;; else listify the singular
;; marker for the loop
(loop for ms in marker-stuff-list
for type = (first ms)
for point-symbol = (if (eq type :point) (second ms))
for keyword-args = (if (eq type :point) (cddr ms) (cdr ms))
do
(draw-legend-marker type point-symbol keyword-args))))
;;
finally
(decf xmin (* 0.02 character-height)) (incf xmax (* 0.02 character-height))
(decf ymin (* 0.02 character-height)) (incf ymax (* 0.02 character-height))
(cond (blank-first
(pgplot:rectangle p xmin xmax ymin ymax :fill-area-style :solid
:color blank-color)
(draw-plot-legend p x0 y0 legend-list
:x-separation x-separation :y-separation y-separation
:character-height character-height :blank-first nil
:blank-color blank-color :draw-box draw-box))
(draw-box
(pgplot:rectangle p xmin xmax ymin ymax
:fill-area-style :outline))))))
;; an example plot legend for draw-plot-legend
(defparameter *sample-plot-legend*
'(("the point" :point :circle-2 :color :red)
("the line" :line :color :green :line-style :dotted)
("the point-line"
(:point :circle-2 :color :red)
(:line :color :red :line-style :dotted))
("the blue rectangle" :rectangle :color :blue :fill-area-style
:solid)
("the red rectangle" :rectangle :color :red :fill-area-style
:cross-hatched)))
(defgeneric write-blanked-text (p text x y
&key fjust angle device-coords
color character-height font center
buffer blanking-color draw-box
box-color)
(:documentation
"Like WRITE-TEXT, but draw a blanking rectangle beforehand. BUFFER
is a buffer factor for expanding the rectangle, and BLANKING-COLOR is
the color of the rectangle"))
(defmethodL write-blanked-text ((p pgplot) (text string) (x real) (y real) &key
(fjust 0.0) (angle 0.0) (device-coords nil)
(color nil) (character-height 1.0) (font nil)
(center nil) ;; are X,Y the center?
(buffer 0.1) (blanking-color :background)
(draw-box nil) (box-color :default))
(if device-coords (multiple-value-setq (x y) (device-to-world p x y)))
;;
;; adjust x,y if CENTER is set
(when center
(multiple-value-bind (xvec yvec)
(text-bounding-box p text :angle angle :fjust fjust
:character-height character-height
:font font)
;; decrement position x,y by mean position of bounding box
(loop for xc across xvec and yc across yvec
do
(decf x (* 0.25 xc))
(decf y (* 0.25 yc)))))
(multiple-value-bind (xb yb)
(pgplot:text-bounding-box p text :x0 x :y0 y :character-height
character-height
:angle angle :fjust fjust :font font)
;; expand the rectangle - we have to define vectors along the horiz and vert sides
;; of the box - corners are l.left, u.left, u.right l.right
(let* ((f (* buffer character-height)) ;; expansion factor
;; vert vector
(xvv (- (aref xb 1) (aref xb 0))) ;; upper left minus bottom left
(yvv (- (aref yb 1) (aref yb 0)))
(vvlen (sqrt (+ (expt xvv 2) (expt yvv 2))))
(xvh (- (aref xb 3) (aref xb 0))) ;; bottom right minus bottom left
(yvh (- (aref yb 3) (aref yb 0)))
(vhlen (sqrt (+ (expt xvh 2) (expt yvh 2))))
(ff (/ (* f character-height) 40.0))) ;; default char is 1/40 max(height,widhth)
;; turn them into unit vectors times f
(setf xvv (* ff (/ xvv vvlen)))
(setf yvv (* ff (/ yvv vvlen)))
(setf xvh (* ff (/ xvh vhlen)))
(setf yvh (* ff (/ yvh vhlen)))
;; and expand the corners by these unit vectors
(loop
for i below 4
for hsign across #(-1 -1 +1 +1)
for vsign across #(-1 +1 +1 -1)
do
;; push corners outward in width
(incf (aref xb i) (* hsign xvh))
(incf (aref yb i) (* hsign yvh))
;; push corners outward in height
(incf (aref xb i) (* vsign xvv))
(incf (aref yb i) (* vsign yvv))))
(pgplot:polygon p xb yb :fill-area-style :solid :color blanking-color)
(when draw-box
(pgplot:polygon p xb yb :fill-area-style nil :line-style :solid
:color box-color))
(pgplot:write-text p text x y :fjust fjust :angle angle :device-coords NIL
:color color
:character-height character-height :font font)))
(defun %vecmin (v)
(loop with xmin = nil
for x across v
when (or (not xmin) (< x xmin))
do (setf xmin x)
finally (return xmin)))
;;
(defun %vecmax (v)
(loop with xmax = nil
for x across v
when (or (not xmax) (> x xmax))
do (setf xmax x)
finally (return xmax)))
#+nil
(defun bin-2d-data (xvals yvals nx ny &key xmin xmax ymin ymax)
(error "Use make-2d-density-image instead~%"))
(defun compute-aspect-ratio-for-panes (nx ny &key
(pane-aspect-ratio 1.0)
(x-separation 0.05)
(y-separation 0.05)
(top-pad 0.02) ;; extra blank space on top
(bottom-pad 0.10) ;; on bottom
(right-pad 0.03) ;; on right
(left-pad 0.15)) ;; on left
"Compute the aspect ratio for a plot necessary to have NXxNY panes
which have their own aspect ratio of PANE-ASPECT-RATIO. Useful for
designing a plot with (for example) square panes. Return
(VALUES ASPECT-RATIO X-SPAN-OF-ONE-PANE"
(let* ((s (/ (- 1.0 (+ left-pad right-pad (* (1- nx) x-separation))) nx))
(a
(/ (* pane-aspect-ratio ny s)
(- 1.0 (+ top-pad bottom-pad (* (1- ny) y-separation))))))
(values a s)))
(defun make-2d-density-image (xseq yseq &key (nx 100) (ny 100)
xmin xmax ymin ymax)
"Given sequences of points XSEQ and YSEQ, bin them into a float
array of size NYxNX, suitable for plotting as an image or a contour
plot.
XMIN XMAX YMIN YMAX, if not given, default to the extrema of
the input arrays.
Return (VALUES ARRAY XMIN XMAX YMIN YMAX N-INSIDE N-OUTSIDE)"
(declare (type (unsigned-byte 20) nx ny)
(type (or null real) xmin xmax ymin ymax)
(type (or array list) xseq yseq))
;;
(let* ((xvec (to-dbl-float-vec xseq))
(yvec (to-dbl-float-vec yseq))
(xmin (or xmin (%vecmin xseq)))
(xmax (or xmax (%vecmax xseq)))
(ymin (or ymin (%vecmin yseq)))
(ymax (or ymax (%vecmax yseq))))
;;
(when (not (= (length xvec) (length yvec)))
(error "XSEQ and YSEQ have a different number of elements"))
;;
(loop
with n-inside = 0 and n-outside = 1
with nx-1 = (1- nx) and ny-1 = (1- ny)
with a of-type (simple-array single-float (* *))
= (make-array (list ny nx) :element-type 'single-float :initial-element 0.0)
for x of-type double-float across xvec
for y of-type double-float across yvec
for ix = (* nx-1 (/ (- x xmin) (- xmax xmin)))
for iy = (* ny-1 (/ (- y ymin) (- ymax ymin)))
do
(cond ((and (<= 0 ix nx-1) (<= 0 iy ny-1))
(incf (aref a iy ix) 1.0)
(incf n-inside 1))
(t
(incf n-outside 1)))
finally
(return (values a xmin xmax ymin ymax n-inside n-outside)))))
(defun generate-linear-tick-intervals (xstart xend)
"Create appropriately chosen intervals for small and large ticks between
xstart and xend.
Return (values big-tick-list small-tick-list) where each tick in the
list is a list (tick-value v-value ndecimals) where v-value is the
fraction of the line from [xstart,xend], and ndecimals is the number
of decimals points that the number should be printed"
(if (= xstart xend)
;; return empty lists
(values nil nil 0)
;; else do the math
(let* ((swap (> xstart xend))
(x1 (if swap xend xstart))
(x2 (if swap xstart xend))
(dx (* 1d0 (- x2 x1)))
(absdx (abs dx))
(ceiling-logabsdx (ceiling (log absdx 10)))
;; scale is the nearest power of 10 to dx
(scale (expt 10.0 ceiling-logabsdx))
;; how many decimals ticks have to be printed at (if not
;; scientific notation)
(ndecimal (cond ((> ceiling-logabsdx 0) 0)
(t (+ 1 (- ceiling-logabsdx)))))
;; span is the span on a 0-1 range
(span (/ dx scale)))
(multiple-value-bind (big small)
(cond
((<= span 0.3)
(incf ndecimal 2) ;; this is ugly
(values (* scale 0.05) (* scale 0.025)))
((<= span 0.5)
(incf ndecimal 1) ;; this is ugly too
(values (* scale 0.1) (* scale 0.05)))
((<= span 1.1) (values (* scale 0.2) (* scale 0.1)))
(t (error "Span=~A is not in [0,1]. This should not happen" span)))
;; xbot is the smallest multiple of 'big' that fits into x1
(let* ((xbot (* big (floor x1 big)))
(big-ticks
(loop for x = xbot then (+ x big)
for vv = (/ (- x x1) dx)
for v = (if swap (- 1d0 vv) vv)
while (<= x x2)
when (<= x1 x x2) collect (list x v ndecimal)))
;; small-ticks depends on assumption that small=big/2
(small-ticks
(loop for x = (+ xbot small) then (+ x big)
for vv = (/ (- x x1) dx)
for v = (if swap (- 1d0 vv) vv)
while (<= x x2)
when (<= x1 x x2) collect (list x v ndecimal))))
(when swap
(setf big-ticks (nreverse big-ticks))
(setf small-ticks (nreverse small-ticks)))
;;
(values big-ticks small-ticks ndecimal))))))
(defun generate-log-tick-intervals (xstart xend)
"Generate logarithmic tick intervals; see GENERATE-LINEAR-TICK-INTERVALS."
(if (or (= xstart xend)
(not (plusp xstart))
(not (plusp xend)))
;; return empty lists
(values nil nil 0)
;; else do the math
(let* ((swap (> xstart xend))
(x1 (if swap xend xstart))
(x2 (if swap xstart xend))
(startlog (floor (log (* 1d0 x1) 10d0)))
(big-ticks nil)
(small-ticks nil)
(xbot (expt 10d0 startlog)))
(loop
for xx = xbot then (* x 10)
for x = (if (> xx 1) (round xx) xx) ;; an integer, if possible
for ndecimal = 1
for v = 1.0
until (> xx x2)
do (push (list x v ndecimal) big-ticks)
(loop for i from 2 to 9
for y = (* i x)
for ndecimal = 1
for v = 1.0
until (> y x2)
do (push (list y v ndecimal) small-ticks)))
;;
(when (not swap) ;; push already reversed them
(setf big-ticks (nreverse big-ticks))
(setf small-ticks (nreverse small-ticks)))
;;
(values big-ticks small-ticks))))
|
import map from 'lodash.map';
import mapKeys from 'lodash.mapkeys';
import camelCase from 'lodash.camelcase';
import kebabCase from 'lodash.kebabcase';
import snakeCase from 'lodash.snakecase';
import startCase from 'lodash.startcase';
import uppercase from 'lodash.uppercase';
import lowercase from 'lodash.lowercase';
import upperfirst from 'lodash.upperfirst';
type Collection = Record<any, any>
type CaseFn = (input: string) => string;
function casifyObject<T>(caseFn: CaseFn, obj: Collection): Collection {
return mapKeys(obj, (value, key) => caseFn(key));
}
function casifyArray<T>(caseFn: CaseFn, array: Array<T>): Array<T> {
return map(array, obj => casifyObject(caseFn, obj));
}
function casify(caseFn: CaseFn, collection: Collection) {
if (Array.isArray(collection)) return casifyArray(caseFn, collection);
return casifyObject(caseFn, collection);
}
function casifyFnFactory(caseFn: CaseFn) {
return (collection: Collection) => casify(caseFn, collection);
}
function bumpyCase(input: string) {
return upperfirst(camelCase(input));
}
export const camelCasify = casifyFnFactory(camelCase);
export const bumpyCasify = casifyFnFactory(bumpyCase);
export const kebabCasify = casifyFnFactory(kebabCase);
export const snakeCasify = casifyFnFactory(snakeCase);
export const startCasify = casifyFnFactory(startCase);
export const upperCasify = casifyFnFactory(uppercase);
export const lowerCasify = casifyFnFactory(lowercase);
export default casify;
|
module Utilities.Number where
import System.Environment
import Numeric
import qualified Utilities.Types
oct2dig x = fst $ head (readOct x)
hex2dig x = fst $ head (readHex x)
bin2dig = bin2dig' 0
bin2dig' digint "" = digint
bin2dig' digint (x:xs) = let old = 2 * (if x == '0' then 0 else 1) in
bin2dig' old xs
toDouble :: Utilities.Types.LispVal -> Double
toDouble(Utilities.Types.Float f) = realToFrac f
toDouble(Utilities.Types.Number n) = fromIntegral n
|
// SPDX-FileCopyrightText: 2019 pancake <pancake@nopcode.org>
// SPDX-License-Identifier: LGPL-3.0-only
static bool rtr_visual(RzCore *core, TextLog T, const char *cmd) {
bool autorefresh = false;
if (cmd) {
rz_cons_break_push(NULL, NULL);
for (;;) {
char *ret;
rz_cons_clear00();
ret = rtrcmd(T, cmd);
rz_cons_println(ret);
free(ret);
rz_cons_flush();
if (rz_cons_is_breaked()) {
break;
}
rz_sys_sleep(1);
}
rz_cons_break_pop();
} else {
const char *cmds[] = { "px", "pd", "pxa", "dr", "sr SP;pxa", NULL };
int cmdidx = 0;
char *ret, ch;
free(rtrcmd(T, "e scr.color=true"));
free(rtrcmd(T, "e scr.html=false"));
for (;;) {
rz_cons_clear00();
ret = rtrcmd(T, cmds[cmdidx]);
if (ret) {
rz_cons_println(ret);
free(ret);
}
rz_cons_flush();
if (autorefresh) {
rz_cons_printf("(auto-refresh)\n");
rz_cons_flush();
rz_cons_break_push(NULL, NULL);
rz_sys_sleep(1);
if (rz_cons_is_breaked()) {
autorefresh = false;
ch = rz_cons_readchar();
} else {
rz_cons_break_pop();
continue;
}
rz_cons_break_pop();
} else {
ch = rz_cons_readchar();
}
#if 0
TODO:
i insert hex/string/asm
0-9 follow jumps
#endif
switch (ch) {
case '?':
rz_cons_clear00();
rz_cons_printf("Remote Visual keys:\n"
" hjkl : move\n"
" HJKL : move faster\n"
" +-*/ : change block size\n"
" pP : rotate print modes\n"
" T : enter TextLog chat console\n"
" @ : enter auto-refresh mode\n"
" i : insert hexpair\n"
" q : quit this mode and go back to the shell\n"
" sS : step / step over\n"
" . : seek entry or pc\n");
rz_cons_flush();
rz_cons_any_key(NULL);
break;
case 'i': {
#if __UNIX__
#define COLORFLAGS (core->print->flags & RZ_PRINT_FLAGS_COLOR)
#else
#define COLORFLAGS 0
#endif
char buf[1024];
if (COLORFLAGS) {
rz_line_set_prompt(Color_RESET ":> ");
} else {
rz_line_set_prompt(":> ");
}
showcursor(core, true);
rz_cons_fgets(buf + 3, sizeof(buf) - 3, 0, NULL);
memcpy(buf, "wx ", 3);
if (buf[3]) {
char *res = rtrcmd(T, buf);
if (res) {
rz_cons_println(res);
free(res);
}
rz_cons_flush();
}
} break;
case 's':
free(rtrcmd(T, "ds;.dr*"));
break;
case 'S':
free(rtrcmd(T, "dso;.dr*"));
break;
case '.':
free(rtrcmd(T, "s entry0;dr?rip;?? sr PC"));
break;
case ':': {
int ret;
eprintf("Press <enter> to return to Visual mode.\n");
do {
char buf[1024];
#if __UNIX__
rz_line_set_prompt(Color_RESET ":> ");
#else
rz_line_set_prompt(":> ");
#endif
showcursor(core, true);
rz_cons_fgets(buf, sizeof(buf), 0, NULL);
if (*buf) {
rz_line_hist_add(buf);
char *res = rtrcmd(T, buf);
if (res) {
rz_cons_println(res);
free(res);
}
rz_cons_flush();
ret = true;
} else {
ret = false;
//rz_cons_any_key ();
rz_cons_clear00();
showcursor(core, false);
}
} while (ret);
} break;
case '@': autorefresh = true; break;
case 'j':
if (cmdidx == 1) {
free(rtrcmd(T, "so"));
break;
} else {
free(rtrcmd(T, "sd +16"));
break;
}
break;
case 'k': free(rtrcmd(T, "sd -16")); break;
case 'h': free(rtrcmd(T, "sd -1")); break;
case 'l': free(rtrcmd(T, "sd +1")); break;
case 'J':
if (cmdidx == 1) {
free(rtrcmd(T, "4so"));
} else {
free(rtrcmd(T, "sd +32"));
}
break;
case 'K': free(rtrcmd(T, "sd -32")); break;
case 'H': free(rtrcmd(T, "sd -2")); break;
case 'L': free(rtrcmd(T, "sd +2")); break;
case '+': free(rtrcmd(T, "b+1")); break;
case '*': free(rtrcmd(T, "b+16")); break;
case '-': free(rtrcmd(T, "b-1")); break;
case '/': free(rtrcmd(T, "b-16")); break;
case 'p':
cmdidx++;
if (!cmds[cmdidx]) {
cmdidx = 0;
}
break;
case 'P':
cmdidx--;
if (cmdidx < 0) {
cmdidx = 2;
}
break;
case 'q': return false;
}
}
}
return true;
}
// XXX: this needs to be moved to use the standard shell like in !=! and support visual+panels
static void __rtr_shell(RzCore *core, int nth) {
char *proto = "http";
char *host = "";
char *port = "";
char *file = "";
char prompt[64], prompt2[64], *str, *ptr;
int len;
const char *res;
RzSocket *s = NULL;
TextLog T = { host, port, file };
snprintf(prompt, sizeof(prompt), "[%s://%s:%s/%s]> ",
proto, host, port, file);
snprintf(prompt2, sizeof(prompt2), "[%s:%s]$ ", host, port);
for (;;) {
rz_line_set_prompt(prompt);
res = rz_line_readline();
if (!res || !*res) {
break;
}
if (*res == 'q') {
break;
}
if (!strcmp(res, "!sh")) {
for (;;) {
rz_line_set_prompt(prompt2);
res = rz_line_readline();
if (!res || !*res || !strcmp(res, "exit")) {
break;
}
ptr = rz_str_uri_encode(res);
char *uri = rz_str_newf("http://%s:%s/%s!%s", host, port, file, res);
str = rz_socket_http_get(uri, NULL, &len);
if (str) {
str[len] = 0;
res = strstr(str, "\n\n");
if (res) {
res = strstr(res + 1, "\n\n");
}
res = res ? res + 2 : str;
const char *tail = (res[strlen(res) - 1] == '\n') ? "" : "\n";
printf("%s%s", res, tail);
rz_line_hist_add(str);
free(str);
}
free(ptr);
free(uri);
}
} else if (res[0] == 'v' || res[0] == 'V') {
if (res[1] == ' ') {
rtr_visual(core, T, res + 1);
} else {
rtr_visual(core, T, NULL);
}
} else {
char *cmdline = rz_str_newf("%d %s", nth, res);
rz_core_rtr_cmd(core, cmdline);
rz_cons_flush();
rz_line_hist_add(res);
}
}
rz_socket_free(s);
}
|
基于 python 的新后端服务器
## 开发环境
python 版本: 3.8
使用 [poetry](https://github.com/python-poetry/poetry) 进行依赖管理。
```shell
git clone https://github.com/bangumi/server bangumi-server
cd bangumi-server
```
进入虚拟环境
```shell
python -m venv .venv # MUST use python 3.8
source .venv/bin/activate # enable virtualenv
```
安装依赖
```shell
poetry install --remove-untracked
```
### 设置
可设置的环境变量
- `MYSQL_HOST` 默认 `127.0.0.1`
- `MYSQL_PORT` 默认 `3306`
- `MYSQL_DB` 默认 `bangumi`
- `MYSQL_USER` 默认 `user`
- `MYSQL_PASS` 默认 `password`
- `REDIS_URI` 默认 `redis://127.0.0.1:6379/0`
你也可以把配置放在 `./env/dev` 文件中,如果在环境变量中找不到对应的值,会在这个文件中查找
example:
```text
MYSQL_HOST="127.0.0.1"
MYSQL_PORT="3306"
MYSQL_USER="user"
MYSQL_PASS="password"
MYSQL_DB="bangumi"
REDIS_URI="redis://:redis-pass@127.0.0.1:6379/1"
```
## 开发
bangumi 相关项目整体说明 [bangumi/dev-docs](https://github.com/bangumi/dev-docs)
### 项目结构
Web 框架 [fastapi](https://github.com/tiangolo/fastapi)
ORM 类定义在 [pol/db/tables.py](./pol/db/tables.py) 文件。
路由位于 [pol/api](./pol/api) 文件夹。
### 后端环境
redis 和 mysql 都在此 docker-compose 内 <https://github.com/bangumi/dev-env> 。
如果你不使用 docker ,请自行启动 mysql 和 redis 并导入 `bangumi/dev-env` 仓库内的数据。
### 运行服务器
默认在 `3000` 端口,在代码修改后会自动重启。
```shell
watchgod scripts.dev.main
```
访问 <http://127.0.0.1:3000/v0/>。
## 提交 Pull Request
如果你的 PR 是新功能,最好先发个 issue 讨论一下要不要实现,避免 PR 提交之后新功能本身被否决的问题。
如果已经存在相关的 issue,可以先在 issue 内回复一下自己的意向,或者创建一个 Draft PR 关联对应的 issue,避免撞车问题。
## [测试](./tests/readme.md)
## 代码风格
### python
基本上,代码格式基于 black 和 isort。
#### Formatter
我们使用 [pre-commit](https://github.com/pre-commit/pre-commit) 来管理代码格式化工具。
你可以手动运行
```shell
pre-commit run # only check changed files
pre-commit run --all-files # check all files
```
也可以安装 git hooks,在每次 commit 时自动运行。
```shell
pre-commit install
```
绝大多数情况下,你不需要因此而手动修改代码,仅需要保证相关格式化工具正常运行即可,
#### Lint
CI 中还会运行 flake8 和 mypy
### 配置文件
非 python 文件(yaml, json, markdown 等)使用 [prettier](https://prettier.io/) 进行格式化。
## License
BSD 3-Clause License
[LICENSE](https://github.com/bangumi/server/blob/master/LICENSE.md)
|
from math import *
import proteus.MeshTools
from proteus import Domain
from proteus.default_n import *
from proteus.Profiling import logEvent
from proteus.ctransportCoefficients import smoothedHeaviside
from proteus.ctransportCoefficients import smoothedHeaviside_integral
from proteus import Gauges
from proteus.Gauges import PointGauges,LineGauges,LineIntegralGauges
##########################AFTER UPDATING PROTEUS CHANGE SIGNS IN RZs#######################
airVent=True
#wave generator
windVelocity = (0.0,0.0)
inflowHeightMean = 1.2
outflowHeightMean = 0.06
#inflowVelocityMean = (0.139,0.0)
#period = 1.94
#omega = 2.0*math.pi/period
#waveheight = 0.0
#amplitude = waveheight/ 2.0
#wavelength = 5.0
#k = 2.0*math.pi/wavelength
inflow_velocity = 0.137
outflow_velocity=2.74
# Discretization -- input options
genMesh=True
movingDomain=False
applyRedistancing=True
useOldPETSc=False
useSuperlu=False
timeDiscretization='be'#'be','vbdf','flcbdf'
spaceOrder = 1
useHex = False
useRBLES = 0.0
useMetrics = 1.0
applyCorrection=True
useVF = 1.0
useOnlyVF = False
useRANS = 0 # 0 -- None
# 1 -- K-Epsilon
# 2 -- K-Omega
# Input checks
if spaceOrder not in [1,2]:
print "INVALID: spaceOrder" + spaceOrder
sys.exit()
if useRBLES not in [0.0, 1.0]:
print "INVALID: useRBLES" + useRBLES
sys.exit()
if useMetrics not in [0.0, 1.0]:
print "INVALID: useMetrics"
sys.exit()
# Discretization
nd = 2
if spaceOrder == 1:
hFactor=1.0
if useHex:
basis=C0_AffineLinearOnCubeWithNodalBasis
elementQuadrature = CubeGaussQuadrature(nd,2)
elementBoundaryQuadrature = CubeGaussQuadrature(nd-1,2)
else:
basis=C0_AffineLinearOnSimplexWithNodalBasis
elementQuadrature = SimplexGaussQuadrature(nd,3)
elementBoundaryQuadrature = SimplexGaussQuadrature(nd-1,3)
elif spaceOrder == 2:
hFactor=0.5
if useHex:
basis=C0_AffineLagrangeOnCubeWithNodalBasis
elementQuadrature = CubeGaussQuadrature(nd,4)
elementBoundaryQuadrature = CubeGaussQuadrature(nd-1,4)
else:
basis=C0_AffineQuadraticOnSimplexWithNodalBasis
elementQuadrature = SimplexGaussQuadrature(nd,4)
elementBoundaryQuadrature = SimplexGaussQuadrature(nd-1,4)
# Domain and mesh
L = (4.0 , 1.8)
#Obstacle or weir dimensions/position
obst_portions = (0.01,1.0) #(width,height)
obst_x_start = 2.0 # start x coordinate of the obstacle; caution to be in the domain's range
obst_x_end = obst_x_start + obst_portions[0] # end x coordinate of the obstacle; caution to be in the domain's range
obst = (obst_x_start,obst_portions[1],obst_x_end) #coordinates of the obstacle to be used to define the boundary
airvent_y1=2.0*obst_portions[1]/4.0
airvent_y2=3.0*obst_portions[1]/4.0
#Background refinement
Refinement = 50
he = L[0]/float(4*Refinement-1)
# Refinement parameters
x_refine = (0.5 , 1.0 , 3.5) #end of zone 1, end of zone 2, end of zone 3 (zone 4 is up to the right wall)
refinementLevel = (4 , 1) #refinemnt level for zone 1 and zone 2 and 4 respectively zone 3 has the basic refinement level
#Left boundary imposed velocity
GenerationZoneLength = 0.5
AbsorptionZoneLength= 0.5
spongeLayer = True
xSponge = GenerationZoneLength
xRelaxCenter = xSponge/2.0
epsFact_solid = xSponge/2.0
#zone 2
xSponge_2 = L[0]-AbsorptionZoneLength
xRelaxCenter_2 = 0.5*(xSponge_2+L[0])
epsFact_solid_2=AbsorptionZoneLength/2.0
weak_bc_penalty_constant = 100.0
nLevels = 1
#parallelPartitioningType = proteus.MeshTools.MeshParallelPartitioningTypes.element
parallelPartitioningType = proteus.MeshTools.MeshParallelPartitioningTypes.node
nLayersOfOverlapForParallel = 0
structured=False
gauge_dx=0.5
PGL=[]
LGL=[]
for i in range(0,int(L[0]/gauge_dx+1)): #+1 only if gauge_dx is an exact
PGL.append([gauge_dx*i,0.5,0])
LGL.append([(gauge_dx*i,0.0,0),(gauge_dx*i,L[1],0)])
gaugeLocations=tuple(map(tuple,PGL))
columnLines=tuple(map(tuple,LGL))
pointGauges = PointGauges(gauges=((('u','v'), gaugeLocations),
(('p',), gaugeLocations)),
activeTime = (0, 1000.0),
sampleRate = 0,
fileName = 'combined_gauge_0_0.5_sample_all.txt')
print gaugeLocations
print columnLines
fields = ('vof',)
columnGauge = LineIntegralGauges(gauges=((fields, columnLines),),
fileName='column_gauge.csv')
#lineGauges = LineGauges(gaugeEndpoints={'lineGauge_y=0':((0.0,0.0,0.0),(L[0],0.0,0.0))},linePoints=24)
#lineGauges_phi = LineGauges_phi(lineGauges.endpoints,linePoints=20)
if useHex:
nnx=ceil(L[0]/he)+1
nny=ceil(L[1]/he)+1
hex=True
domain = Domain.RectangularDomain(L)
else:
boundaries=['left','right','bottom','top','front','back','airvent']
boundaryTags=dict([(key,i+1) for (i,key) in enumerate(boundaries)])
if structured:
nnx=ceil(L[0]/he)+1
nny=ceil(L[1]/he)+1
elif spongeLayer:
vertices=[[0.0,0.0],#0
[obst[0],0.0], #1
[obst[0],obst[1]], #2
[obst[2],obst[1]], #3
[obst[2],0.0],#4
[L[0],0.0],#5
[L[0],L[1]],#6
[0.0,L[1]],#7
[xSponge,0.0],#8
[xSponge,L[1]],#9
[xSponge_2,0.0],#10
[xSponge_2,L[1]],#11
# [x_refine[0],0.0],
# [x_refine[0],L[1]],
[x_refine[1],0.0], #12
[x_refine[1],L[1]], #13
# [x_refine[2],0.0],
# [x_refine[2],L[1]]
[obst[2],airvent_y2], #14
[obst[2],airvent_y1]] #15
vertexFlags=[boundaryTags['bottom'],
boundaryTags['bottom'],
boundaryTags['bottom'],
boundaryTags['bottom'],
boundaryTags['bottom'],
boundaryTags['bottom'],
boundaryTags['top'],
boundaryTags['top'],
boundaryTags['bottom'],
boundaryTags['top'],
boundaryTags['bottom'],
boundaryTags['top'],
boundaryTags['bottom'],
boundaryTags['top'],
boundaryTags['bottom'],
boundaryTags['bottom']]
segments=[[0,8],
[8,12],
[12,1],
[1,2],
[2,3],
[3,14],
[14,15],
[15,4],
[4,10],
[10,5],
[5,6],
[6,11],
[11,13],
[13,9],
[9,7],
[7,0],
[8,9],
[10,11],
[12,13]]
segmentFlags=[boundaryTags['bottom'],
boundaryTags['bottom'],
boundaryTags['bottom'],
boundaryTags['bottom'],
boundaryTags['bottom'],
boundaryTags['bottom'],
boundaryTags['airvent'],
boundaryTags['bottom'],
boundaryTags['bottom'],
boundaryTags['bottom'],
boundaryTags['right'],
boundaryTags['top'],
boundaryTags['top'],
boundaryTags['top'],
boundaryTags['top'],
boundaryTags['left'],
0,
0,
0]
if not airVent:
segmentFlags[6] = boundaryTags['bottom']
regions=[[xRelaxCenter, 0.5*L[1]],
[xRelaxCenter_2, 0.5*L[1]],
[obst_x_start,0.9*L[1]],
[xSponge+0.1,0.5*L[1]]]
regionFlags=[1,2,3,4]
trigArea = 0.5*he**2
refinementArea =(refinementLevel[0]**2 , refinementLevel[1]**2)
regionConstraints = [trigArea*float(refinementArea[1]),trigArea*float(refinementArea[1]),trigArea,trigArea*float(refinementArea[1])]
domain = Domain.PlanarStraightLineGraphDomain(vertices=vertices,
vertexFlags=vertexFlags,
segments=segments,
segmentFlags=segmentFlags,
regions=regions,
regionFlags=regionFlags,
regionConstraints=regionConstraints)
#go ahead and add a boundary tags member
domain.boundaryTags = boundaryTags
domain.writePoly("mesh")
domain.writePLY("mesh")
domain.writeAsymptote("mesh")
triangleOptions="VApq30Dena" #triangleOptions="VApq30Dena%8.8f" % ((he**2)/2.0,)
logEvent("""Mesh generated using: tetgen -%s %s""" % (triangleOptions,domain.polyfile+".poly"))
porosityTypes = numpy.array([1.0,
1.0,
1.0,
1.0,
1.0,
1.0])
dragAlphaTypes = numpy.array([0.0,
0.5/1.004e-6,
0.5/1.004e-6,
0.0,
0.0,
0.0])
dragBetaTypes = numpy.array([0.0,0.0,0.0,0.0,0.0,0.0])
epsFact_solidTypes = np.array([0.0,epsFact_solid,epsFact_solid_2,0.0,0.0,0.0])
else:
vertices=[[0.0,0.0],#0
[L[0],0.0],#1
[L[0],L[1]],#2
[0.0,L[1]]]#3
vertexFlags=[boundaryTags['bottom'],
boundaryTags['bottom'],
boundaryTags['top'],
boundaryTags['top']]
segments=[[0,1],
[1,2],
[2,3],
[3,0]
]
segmentFlags=[boundaryTags['bottom'],
boundaryTags['right'],
boundaryTags['top'],
boundaryTags['left']]
regions=[ [ 0.1*L[0] , 0.1*L[1] ],
[0.95*L[0] , 0.95*L[1] ] ]
regionFlags=[1,2]
domain = Domain.PlanarStraightLineGraphDomain(vertices=vertices,
vertexFlags=vertexFlags,
segments=segments,
segmentFlags=segmentFlags,
regions=regions,
regionFlags=regionFlags)
#go ahead and add a boundary tags member
domain.boundaryTags = boundaryTags
domain.writePoly("mesh")
domain.writePLY("mesh")
domain.writeAsymptote("mesh")
triangleOptions="VApq30Dena%8.8f" % ((he**2)/2.0,)
logEvent("""Mesh generated using: tetgen -%s %s""" % (triangleOptions,domain.polyfile+".poly"))
# Time stepping
T=30.0
dt_fixed = 0.25
dt_init = min(0.1*dt_fixed,0.1)
runCFL=0.75
nDTout = int(round(T/dt_fixed))
# Numerical parameters
ns_forceStrongDirichlet = True
backgroundDiffusionFactor=0.01
if useMetrics:
ns_shockCapturingFactor = 0.75
ns_lag_shockCapturing = True
ns_lag_subgridError = True
ls_shockCapturingFactor = 0.75
ls_lag_shockCapturing = True
ls_sc_uref = 1.0
ls_sc_beta = 1.5
vof_shockCapturingFactor = 0.75
vof_lag_shockCapturing = True
vof_sc_uref = 1.0
vof_sc_beta = 1.5
rd_shockCapturingFactor = 0.75
rd_lag_shockCapturing = False
epsFact_density = 3.0
epsFact_viscosity = epsFact_curvature = epsFact_vof = epsFact_consrv_heaviside = epsFact_consrv_dirac = epsFact_density
epsFact_redistance = 0.33
epsFact_consrv_diffusion = 1.0
redist_Newton = False
kappa_shockCapturingFactor = 0.1
kappa_lag_shockCapturing = True#False
kappa_sc_uref = 1.0
kappa_sc_beta = 1.0
dissipation_shockCapturingFactor = 0.1
dissipation_lag_shockCapturing = True#False
dissipation_sc_uref = 1.0
dissipation_sc_beta = 1.0
else:
ns_shockCapturingFactor = 0.9
ns_lag_shockCapturing = True
ns_lag_subgridError = True
ls_shockCapturingFactor = 0.9
ls_lag_shockCapturing = True
ls_sc_uref = 1.0
ls_sc_beta = 1.0
vof_shockCapturingFactor = 0.9
vof_lag_shockCapturing = True
vof_sc_uref = 1.0
vof_sc_beta = 1.0
rd_shockCapturingFactor = 0.9
rd_lag_shockCapturing = False
epsFact_density = 1.5
epsFact_viscosity = epsFact_curvature = epsFact_vof = epsFact_consrv_heaviside = epsFact_consrv_dirac = epsFact_density
epsFact_redistance = 0.33
epsFact_consrv_diffusion = 10.0
redist_Newton = False
kappa_shockCapturingFactor = 0.9
kappa_lag_shockCapturing = True#False
kappa_sc_uref = 1.0
kappa_sc_beta = 1.0
dissipation_shockCapturingFactor = 0.9
dissipation_lag_shockCapturing = True#False
dissipation_sc_uref = 1.0
dissipation_sc_beta = 1.0
ns_nl_atol_res = max(1.0e-10,0.001*he**2)
vof_nl_atol_res = max(1.0e-10,0.001*he**2)
ls_nl_atol_res = max(1.0e-10,0.001*he**2)
rd_nl_atol_res = max(1.0e-10,0.005*he)
mcorr_nl_atol_res = max(1.0e-10,0.001*he**2)
kappa_nl_atol_res = max(1.0e-10,0.001*he**2)
dissipation_nl_atol_res = max(1.0e-10,0.001*he**2)
#turbulence
ns_closure=2 #1-classic smagorinsky, 2-dynamic smagorinsky, 3 -- k-epsilon, 4 -- k-omega
if useRANS == 1:
ns_closure = 3
elif useRANS == 2:
ns_closure == 4
# Water
rho_0 = 998.2
nu_0 = 1.004e-6
# Air
rho_1 = 1.205
nu_1 = 1.500e-5
# Surface tension
sigma_01 = 0.0
# Gravity
g = [0.0,-9.8]
# Initial condition
waterLine_x = obst_x_start-0.01
waterLine_z = inflowHeightMean
waterLine_z1 = outflowHeightMean
def signedDistance(x):
phi_x = x[0]-waterLine_x
phi_z = x[1]-waterLine_z
phi_z1=x[1]-waterLine_z1
if phi_x < 0.0:
if phi_z < 0.0:
# if(phi_z1<0.0):
# return -sqrt(phi_x**2 + phi_z1**2)
# else:
return max(phi_x,phi_z)
else:
return phi_z
else:
if phi_z1 < 0.0:
return phi_z1
else:
if(phi_z <0.0):
return min(phi_x,phi_z1)
else:
return min(sqrt(phi_x**2 + phi_z**2),phi_z1)
#solution variables
def wavePhi(x,t):
return x[1] - inflowHeightMean
def waveVF(x,t):
return smoothedHeaviside(epsFact_consrv_heaviside*he,wavePhi(x,t))
def twpflowVelocity_u(x,t):
waterspeed = inflow_velocity
H = smoothedHeaviside(epsFact_consrv_heaviside*he,wavePhi(x,t)-epsFact_consrv_heaviside*he)
u = H*windVelocity[0] + (1.0-H)*waterspeed
return u
def twpflowVelocity_v(x,t):
waterspeed = 0.0
H = smoothedHeaviside(epsFact_consrv_heaviside*he,wavePhi(x,t)-epsFact_consrv_heaviside*he)
return H*windVelocity[1]+(1.0-H)*waterspeed
def twpflowVelocity_w(x,t):
return 0.0
def twpflowFlux(x,t):
return -twpflowVelocity_u(x,t)
def outflowPressure(x,t):
# if x[1]>inflowHeightMean:
return (L[1]-x[1])*rho_1*abs(g[1])
# else:
# return (L[1]-inflowHeightMean)*rho_1*abs(g[1])+(inflowHeightMean-x[1])*rho_0*abs(g[1])
#p_L = L[1]*rho_1*g[1]
#phi_L = L[1] - outflowHeight
#phi = x[1] - outflowHeight
#return p_L -g[1]*(rho_0*(phi_L - phi)+(rho_1 -rho_0)*(smoothedHeaviside_integral(epsFact_consrv_heaviside*he,phi_L)
# -smoothedHeaviside_integral(epsFact_consrv_heaviside*he,phi)))
def outflowPhi(x,t):
return x[1] - outflowHeightMean
def outflowVF(x,t):
return smoothedHeaviside(epsFact_consrv_heaviside*he,outflowPhi(x,t))
def outflowVel(x,t):
waterspeed = outflow_velocity
H = smoothedHeaviside(epsFact_consrv_heaviside*he,outflowPhi(x,t)-epsFact_consrv_heaviside*he)
u = (1.0-H)*waterspeed
return u
def zeroVel(x,t):
return 0.0
from collections import namedtuple
RelaxationZone = namedtuple("RelaxationZone","center_x sign u v w")
class RelaxationZoneWaveGenerator(AV_base):
""" Prescribe a velocity penalty scaling in a material zone via a Darcy-Forchheimer penalty
:param zones: A dictionary mapping integer material types to Zones, where a Zone is a named tuple
specifying the x coordinate of the zone center and the velocity components
"""
def __init__(self,zones):
assert isinstance(zones,dict)
self.zones = zones
def calculate(self):
for l,m in enumerate(self.model.levelModelList):
for eN in range(m.coefficients.q_phi.shape[0]):
mType = m.mesh.elementMaterialTypes[eN]
if self.zones.has_key(mType):
for k in range(m.coefficients.q_phi.shape[1]):
t = m.timeIntegration.t
x = m.q['x'][eN,k]
m.coefficients.q_phi_solid[eN,k] = self.zones[mType].sign*(self.zones[mType].center_x - x[0])
m.coefficients.q_velocity_solid[eN,k,0] = self.zones[mType].u(x,t)
m.coefficients.q_velocity_solid[eN,k,1] = self.zones[mType].v(x,t)
#m.coefficients.q_velocity_solid[eN,k,2] = self.zones[mType].w(x,t)
m.q['phi_solid'] = m.coefficients.q_phi_solid
m.q['velocity_solid'] = m.coefficients.q_velocity_solid
rzWaveGenerator = RelaxationZoneWaveGenerator(zones={1:RelaxationZone(xRelaxCenter,
-1.0, #until the proteus is updated
twpflowVelocity_u,
twpflowVelocity_v,
twpflowVelocity_w),
2:RelaxationZone(xRelaxCenter_2,
1.0, #until the proteus is updated
outflowVel,
zeroVel,
zeroVel)})
|
package com.cyrillemartraire.monoids;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
public class MonoidMapTest {
@Test
public void equals() throws Exception {
final MonoidMap config = config1();
assertEquals(config, config);
}
@Test
public void neutral() throws Exception {
final MonoidMap config1 = config1();
final MonoidMap config = config1.append(config1.neutral());
assertEquals(config1, config);
}
@Test
public void append() throws Exception {
final MonoidMap config = config1().append(config2());
assertEquals(config2().append(config1bis()), config);
}
private MonoidMap config1() {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("COLOR", "RED");
map.put("TIMEOUT", 25);
map.put("ENABLE", false);
map.put("MASTERCONF", "Config1");
return new MonoidMap(map);
}
private MonoidMap config2() {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("COLOR", "BLUE");
map.put("TIMEOUT", 35);
map.put("ENABLE", true);
map.put("USER", "Cyrille");
return new MonoidMap(map);
}
private MonoidMap config1bis() {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("MASTERCONF", "Config1");
return new MonoidMap(map);
}
/**
* A monoidal map with an operation defined so that the left-hand value
* always wins (overwrites)
*/
public static class MonoidMap {
private final Map<String, Object> config;
public MonoidMap() {
this(new HashMap<String, Object>());
}
public MonoidMap(Map<String, Object> config) {
this.config = config;
}
/**
* @return A new map with values merged with the other map, where the
* other map values win. It's associative but not commutative.
*/
public MonoidMap append(MonoidMap other) {
final Map<String, Object> map = new HashMap<String, Object>(config);
map.putAll(other.config);
return new MonoidMap(map);
}
public MonoidMap neutral() {
return new MonoidMap();
}
@Override
public int hashCode() {
return config.hashCode();
}
@Override
public boolean equals(Object o) {
final MonoidMap other = (MonoidMap) o;
return config.equals(other.config);
}
@Override
public String toString() {
return config.toString();
}
}
}
|
package main
import "flag"
//Settings used by this build program
type Settings struct {
TinyPNG string
BuildSite bool
BuildFontello bool
BuildBootstrap bool
SendNewsletter bool
}
var settings Settings
func loadSettings() {
key := flag.String("tinypng", "", "tinypng api key")
flag.Parse()
settings.TinyPNG = *key
//Temporary, lets always build the site
settings.BuildSite = true
}
|
package VIC::PIC::Functions::ISR;
use strict;
use warnings;
our $VERSION = '0.32';
$VERSION = eval $VERSION;
use Carp;
use POSIX ();
use Moo::Role;
sub isr_var {
my $self = shift;
return unless $self->doesroles(qw(Chip ISR));
my @common = @{$self->banks->{common}};
my ($cb_start, $cb_end) = @common;
if (ref $cb_start eq 'ARRAY') {
($cb_start, $cb_end) = @$cb_start;
}
$cb_start = 0x70 unless $cb_start;
$cb_start = sprintf "0x%02X", $cb_start;
return << "...";
cblock $cb_start ;; unbanked RAM that is common across all banks
ISR_STATUS
ISR_W
endc
...
}
sub isr_entry {
my $self = shift;
return unless $self->doesroles(qw(Chip ISR));
unless (exists $self->registers->{STATUS}) {
carp $self->type, " has no register named STATUS";
return;
}
#TODO: high/low address ?
my $isr_addr = $self->address->{isr}->[0];
my $reset_addr = $self->address->{reset}->[0];
my $count = $isr_addr - $reset_addr - 1;
my $nops = '';
for my $i (1 .. $count) {
$nops .= "\tnop\n";
}
return << "...";
$nops
\torg $isr_addr
ISR:
_isr_entry:
\tmovwf ISR_W
\tmovf STATUS, W
\tmovwf ISR_STATUS
...
}
sub isr_exit {
my $self = shift;
return unless $self->doesroles(qw(Chip ISR));
unless (exists $self->registers->{STATUS}) {
carp $self->type, " has no register named STATUS";
return;
}
return << "...";
_isr_exit:
\tmovf ISR_STATUS, W
\tmovwf STATUS
\tswapf ISR_W, F
\tswapf ISR_W, W
\tretfie
...
}
sub isr_timer {
my $self = shift;
return unless $self->doesroles(qw(Chip ISR));
my $th = shift;
return unless (defined $th and ref $th eq 'HASH');
my $freg = $th->{freg};
my $ereg = $th->{ereg};
unless (exists $self->registers->{$freg} and exists $self->registers->{$ereg}) {
carp $self->type, " has no register named $freg or $ereg";
return;
}
my $tflag = $th->{flag};
my $tenable = $th->{enable};
my $treg = (ref $th->{reg} eq 'ARRAY') ? $th->{reg}->[0] : $th->{reg};
my %isr = @_;
if (%isr) {
my $action_label = $isr{ISR};
my $end_label = $isr{END};
return unless $action_label;
return unless $end_label;
my $isr_label = '_isr_' . lc($treg);
return << "..."
$isr_label:
\tbtfss $freg, $tflag
\tgoto $end_label
\tbcf $freg, $tflag
\tgoto $action_label
$end_label:
...
} else {
if ($freg eq 'INTCON' and $ereg eq 'INTCON') {
return << "...";
;; enable interrupt servicing for $treg
\tbanksel $freg
\tbsf INTCON, GIE
\tbcf $freg, $tflag
\tbsf $ereg, $tenable
;; end of interrupt servicing
...
} else {
return << "...";
;; enable interrupt servicing for $treg
\tbanksel INTCON
\tbsf INTCON, GIE
\tbanksel $freg
\tbcf $freg, $tflag
\tbanksel $ereg
\tbsf $ereg, $tenable
;; end of interrupt servicing
...
}
}
}
sub isr_ioc {
my $self = shift;
return unless $self->doesroles(qw(Chip ISR));
unless (exists $self->registers->{INTCON}) {
carp $self->type, " has no register named INTCON";
return;
}
my $ioch = shift;
my $ipin = shift;
return unless (defined $ioch and ref $ioch eq 'HASH');
return unless defined $ipin;
my $ioc_reg = $ioch->{reg};
my $ioc_bit = $ioch->{bit};
my $ioc_flag = $ioch->{flag};
my $ioc_enable = $ioch->{enable};
if (@_) {
my ($var, $port, $portbit, %isr) = @_;
my $action_label = $isr{ISR};
my $end_label = $isr{END};
return unless $action_label;
return unless $end_label;
my $isr_label;
if (defined $ioc_bit) {
$isr_label = '_isr_' . lc($ioc_bit);
} elsif (defined $ioc_reg) {
$isr_label = '_isr_' .lc($ioc_reg);
} else {
$isr_label = '_isr_' . lc($ipin);
}
my $code_ioc = '';
if (defined $portbit) {
$code_ioc = "\tbtfsc $port, $portbit\n\taddlw 0x01";
} else {
$code_ioc = "\tmovf $port, W";
}
return << "..."
$isr_label:
\tbtfss INTCON, $ioc_flag
\tgoto $end_label
\tbcf INTCON, $ioc_flag
\tbanksel $port
$code_ioc
\tbanksel $var
\tmovwf $var
\tgoto $action_label
$end_label:
...
} else {
my $code_en = '';
if (defined $ioc_bit and defined $ioc_reg) {
$code_en = "\tbanksel $ioc_reg\n\tbsf $ioc_reg, $ioc_bit";
} elsif (defined $ioc_reg) {
$code_en = "\tbanksel $ioc_reg\n\tclrf $ioc_reg\n\tcomf $ioc_reg, F";
} else {
# if ioc_reg/ioc_bit is not defined just move on
}
return << "...";
;; enable interrupt-on-change setup for $ipin
\tbanksel INTCON
\tbcf INTCON, $ioc_flag
\tbsf INTCON, GIE
\tbsf INTCON, $ioc_enable
$code_en
;; end of interrupt-on-change setup
...
}
}
1;
__END__
|
/**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.packetsamurai.parser.formattree;
import java.util.ArrayList;
import java.util.List;
/**
* @author Nemesiss
* @author Rolandas
*/
public class BitwiseSwitchPart extends AbstractSwitchPart {
public BitwiseSwitchPart(int id, String analyzerName) {
super(id, analyzerName);
}
@Override
public List<SwitchCaseBlock> getCases(int switchCase) {
List<SwitchCaseBlock> result = new ArrayList<SwitchCaseBlock>();
for (SwitchCaseBlock scb : casesMap.values()) {
if ((scb.getSwitchCase() & switchCase) != 0) {
result.add(scb);
break;
}
}
if (result.size() == 0) {
if (_default == null)
return result;
result.add(_default);
}
return result;
}
}
|
;;; -*- coding:utf-8; mode:lisp -*-
;;; covtype.binary: Binary classification
;; dataset:
;; https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary.html#covtype.binary
(in-package :cl-user)
(defpackage :cl-online-learning.examples
(:use :cl :cl-online-learning :cl-online-learning.utils)
(:nicknames :clol.exam))
(in-package :cl-online-learning.examples)
(defparameter covtype-dim 54)
(defparameter covtype (read-data "/home/wiz/datasets/covtype.libsvm.binary.scale" covtype-dim))
(defparameter covtype-data
(mapcar (lambda (datum)
(if (= (car datum) 1.0d0)
(cons -1d0 (cdr datum))
(cons 1d0 (cdr datum))))
covtype))
(defparameter arow-learner (make-arow covtype-dim 10d0))
(loop repeat 100 do
(train arow-learner covtype-data)
(test arow-learner covtype-data))
(defparameter scw-learner (make-scw covtype-dim 0.99d0 0.01d0))
(loop repeat 100 do
(train scw-learner covtype-data)
(test scw-learner covtype-data))
(defparameter lr-adam-learner (make-lr+adam covtype-dim 0.000001d0 0.001d0 1.d-8 0.9d0 0.99d0))
(loop repeat 10 do
(train lr-adam-learner covtype-data)
(test lr-adam-learner covtype-data))
|
Serial port names on Steve's mac:
board2: /dev/cu.usbserial-AG0JV596 (first box sent to Iasos)
board3: /dev/cu.usbserial-AG0JV6J0 (second box sent to Iasos)
board4: /dev/cu.usbserial-AG0JV27K (spare board for testing/support)
uno: /dev/cu.usbserial-AL05OC8S (prototype)
|
export enum VIEW_FILTERS {
ALL = 1,
ACTIVE = 2,
COMPLETED = 3,
DELETED = 4,
}
export const REFRESH_RATE = 1000;
|
package Mojo::Redis::Cache;
use Mojo::Base -base;
use Mojo::JSON;
use Scalar::Util 'blessed';
use Storable ();
use Time::HiRes ();
use constant OFFLINE => $ENV{MOJO_REDIS_CACHE_OFFLINE};
has connection => sub {
OFFLINE ? shift->_offline_connection : shift->redis->_dequeue->encoding(undef);
};
has deserialize => sub { \&Storable::thaw };
has default_expire => 600;
has namespace => 'cache:mojo:redis';
has refresh => 0;
has redis => sub { Carp::confess('redis is required in constructor') };
has serialize => sub { \&Storable::freeze };
sub compute_p {
my $compute = pop;
my $self = shift;
my $key = join ':', $self->namespace, shift;
my $expire = shift || $self->default_expire;
my $p = $self->refresh ? Mojo::Promise->new->resolve : $self->connection->write_p(GET => $key);
return $p->then(sub {
my $data = $_[0] ? $self->deserialize->(shift) : undef;
return $self->_maybe_compute_p($key, $expire, $compute, $data) if $expire < 0;
return $self->_compute_p($key, $expire, $compute) unless $data;
return $data->[0];
});
}
sub memoize_p {
my ($self, $obj, $method) = (shift, shift, shift);
my $args = ref $_[0] eq 'ARRAY' ? shift : [];
my $expire = shift || $self->default_expire;
my $key = join ':', '@M' => (ref($obj) || $obj), $method, Mojo::JSON::encode_json($args);
return $self->compute_p($key, $expire, sub { $obj->$method(@$args) });
}
sub _compute_p {
my ($self, $key, $expire, $compute) = @_;
my $set = sub {
my $data = shift;
my @set
= $expire < 0
? $self->serialize->([$data, _time() + -$expire])
: ($self->serialize->([$data]), PX => 1000 * $expire);
$self->connection->write_p(SET => $key => @set)->then(sub {$data});
};
my $data = $compute->();
return (blessed $data and $data->can('then')) ? $data->then(sub { $set->(@_) }) : $set->($data);
}
sub _maybe_compute_p {
my ($self, $key, $expire, $compute, $data) = @_;
# Nothing in cache
return $self->_compute_p($key => $expire, $compute)->then(sub { ($_[0], {computed => 1}) }) unless $data;
# No need to refresh cache
return ($data->[0], {expired => 0}) if $data->[1] and _time() < $data->[1];
# Try to refresh, but use old data on error
my $p = Mojo::Promise->new;
eval {
$self->_compute_p($key => $expire, $compute)->then(
sub { $p->resolve(shift, {computed => 1, expired => 1}) },
sub { $p->resolve($data->[0], {error => $_[0], expired => 1}) },
);
} or do {
$p->resolve($data->[0], {error => $@, expired => 1});
};
return $p;
}
sub _offline_connection {
state $c = eval <<'HERE' or die $@;
package Mojo::Redis::Connection::Offline;
use Mojo::Base 'Mojo::Redis::Connection';
our $STORE = {}; # Meant for internal use only
sub write_p {
my ($conn, $op, $key) = (shift, shift, shift);
if ($op eq 'SET') {
$STORE->{$conn->url}{$key} = [$_[0], defined $_[2] ? $_[2] + Mojo::Redis::Cache::_time() * 1000 : undef];
return Mojo::Promise->new->resolve('OK');
}
else {
my $val = $STORE->{$conn->url}{$key} || [];
my $expired = $val->[1] && $val->[1] < Mojo::Redis::Cache::_time() * 1000;
delete $STORE->{$conn->url}{$key} if $expired;
return Mojo::Promise->new->resolve($expired ? undef : $val->[0]);
}
}
'Mojo::Redis::Connection::Offline';
HERE
my $redis = shift->redis;
return $c->new(url => $redis->url);
}
sub _time { Time::HiRes::time() }
1;
=encoding utf8
=head1 NAME
Mojo::Redis::Cache - Simple cache interface using Redis
=head1 SYNOPSIS
use Mojo::Redis;
my $redis = Mojo::Redis->new;
my $cache = $redis->cache;
# Cache and expire the data after 60.7 seconds
$cache->compute_p("some:key", 60.7, sub {
my $p = Mojo::Promise->new;
Mojo::IOLoop->timer(0.1 => sub { $p->resolve("some data") });
return $p;
})->then(sub {
my $some_key = shift;
});
# Cache and expire the data after default_expire() seconds
$cache->compute_p("some:key", sub {
return {some => "data"};
})->then(sub {
my $some_key = shift;
});
# Call $obj->get_some_slow_data() and cache the return value
$cache->memoize_p($obj, "get_some_slow_data")->then(sub {
my $data = shift;
});
# Call $obj->get_some_data_by_id({id => 42}) and cache the return value
$cache->memoize_p($obj, "get_some_data_by_id", [{id => 42}])->then(sub {
my $data = shift;
});
See L<https://github.com/jhthorsen/mojo-redis/blob/master/examples/cache.pl>
for example L<Mojolicious> application.
=head1 DESCRIPTION
L<Mojo::Redis::Cache> provides a simple interface for caching data in the
Redis database. There is no "check if exists", "get" or "set" methods in this
class. Instead, both L</compute_p> and L</memoize_p> will fetch the value
from Redis, if the given compute function / method has been called once, and
the cached data is not expired.
If you need to check if the value exists, then you can manually look up the
the key using L<Mojo::Redis::Database/exists>.
=head1 ENVIRONMENT VARIABLES
=head2 MOJO_REDIS_CACHE_OFFLINE
Set C<MOJO_REDIS_CACHE_OFFLINE> to 1 if you want to use this cache without a
real Redis backend. This can be useful in unit tests.
=head1 ATTRIBUTES
=head2 connection
$conn = $cache->connection;
$cache = $cache->connection(Mojo::Redis::Connection->new);
Holds a L<Mojo::Redis::Connection> object.
=head2 default_expire
$num = $cache->default_expire;
$cache = $cache->default_expire(600);
Holds the default expire time for cached data.
=head2 deserialize
$cb = $cache->deserialize;
$cache = $cache->deserialize(\&Mojo::JSON::decode_json);
Holds a callback used to deserialize data from Redis.
=head2 namespace
$str = $cache->namespace;
$cache = $cache->namespace("cache:mojo:redis");
Prefix for the cache key.
=head2 redis
$conn = $cache->redis;
$cache = $cache->redis(Mojo::Redis->new);
Holds a L<Mojo::Redis> object used to create the connection to talk with Redis.
=head2 refresh
$bool = $cache->refresh;
$cache = $cache->refresh(1);
Will force the cache to be computed again if set to a true value.
=head2 serialize
$cb = $cache->serialize;
$cache = $cache->serialize(\&Mojo::JSON::encode_json);
Holds a callback used to serialize before storing the data in Redis.
=head1 METHODS
=head2 compute_p
$promise = $cache->compute_p($key => $expire => $compute_function);
$promise = $cache->compute_p($key => $expire => sub { return "data" });
$promise = $cache->compute_p($key => $expire => sub { return Mojo::Promise->new });
This method will store the return value from the C<$compute_function> the
first time it is called and pass the same value to L<Mojo::Promise/then>.
C<$compute_function> will not be called the next time, if the C<$key> is
still present in Redis, but instead the cached value will be passed on to
L<Mojo::Promise/then>.
C<$key> will be prefixed by L</namespace> resulting in "namespace:some-key".
C<$expire> is the number of seconds before the cache should expire, and will
default to L</default_expire> unless passed in. The last argument is a
callback used to calculate cached value.
C<$expire> can also be a negative number. This will result in serving old cache
in the case where the C<$compute_function> fails. An example usecase would be
if you are fetching Twitter updates for your website, but instead of throwing
an exception if Twitter is down, you will serve old data instead. Note that the
fulfilled promise will get two variables passed in:
$promise->then(sub { my ($data, $info) = @_ });
C<$info> is a hash and can have these keys:
=over 2
=item * computed
Will be true if the C<$compute_function> was called successfully and C<$data>
is fresh.
=item * expired
Will be true if C<$data> is expired. If this key is present and false, it will
indicate that the C<$data> is within the expiration period. The C<expired> key
can be found together with both L</computed> and L</error>.
=item * error
Will hold a string if the C<$compute_function> failed.
=back
Negative C<$expire> is currently EXPERIMENTAL, but unlikely to go away.
=head2 memoize_p
$promise = $cache->memoize_p($obj, $method_name, \@args, $expire);
$promise = $cache->memoize_p($class, $method_name, \@args, $expire);
L</memoize_p> behaves the same way as L</compute_p>, but has a convenient
interface for calling methods on an object. One of the benefits is that you
do not have to come up with your own cache key. This method is pretty much
the same as:
$promise = $cache->compute_p(
join(":", $cache->namespace, "@M", ref($obj), $method_name, serialize(\@args)),
$expire,
sub { return $obj->$method_name(@args) }
);
See L</compute_p> regarding C<$expire>.
=head1 SEE ALSO
L<Mojo::Redis>
=cut
|
#include<stack>
#include<string>
#include<vector>
#include<cmath>
#include<iostream>
#include<algorithm>
// Converts an infix string to postfix string
std::string to_postfix(std::string infix_str);
// evaluates the postfix string
double evaluate_postfix(std::string postfix_str);
|
# frozen_string_literal: true
class ChangeSetPersister
class PreserveResource
attr_reader :change_set_persister, :change_set, :post_save_resource
delegate :metadata_adapter, to: :change_set_persister
def initialize(change_set_persister:, change_set:, post_save_resource: nil)
@change_set = change_set
@change_set_persister = change_set_persister
@post_save_resource = post_save_resource
end
def run
cs = change_set.class.new(post_save_resource)
return unless cs.try(:preserve?)
# It's important that we inline this for parents, to ensure that a race
# condition doesn't happen which makes it so that two jobs get queued up
# that each call PreserveChildrenJob, resulting in multiple file uploads
if cs.try(:member_ids).present?
PreserveResourceJob.perform_now(id: cs.id.to_s)
else
PreserveResourceJob.perform_later(id: cs.id.to_s)
end
end
end
end
|
package kr.heartpattern.spikot.chat
import org.bukkit.ChatColor
import org.bukkit.entity.Player
fun color(text: String, color: ChatColor) = ChatBuilder(text).color(color)
fun black(text: String): ChatBuilder = color(text, ChatColor.BLACK)
fun darkBlue(text: String): ChatBuilder = color(text, ChatColor.DARK_BLUE)
fun darkGreen(text: String): ChatBuilder = color(text, ChatColor.DARK_GREEN)
fun darkAqua(text: String): ChatBuilder = color(text, ChatColor.DARK_AQUA)
fun darkRed(text: String): ChatBuilder = color(text, ChatColor.DARK_RED)
fun darkPurple(text: String): ChatBuilder = color(text, ChatColor.DARK_PURPLE)
fun gold(text: String): ChatBuilder = color(text, ChatColor.GOLD)
fun gray(text: String): ChatBuilder = color(text, ChatColor.GRAY)
fun darkGray(text: String): ChatBuilder = color(text, ChatColor.DARK_GRAY)
fun blue(text: String): ChatBuilder = color(text, ChatColor.BLUE)
fun green(text: String): ChatBuilder = color(text, ChatColor.GREEN)
fun aqua(text: String): ChatBuilder = color(text, ChatColor.AQUA)
fun red(text: String): ChatBuilder = color(text, ChatColor.RED)
fun lightPurple(text: String): ChatBuilder = color(text, ChatColor.LIGHT_PURPLE)
fun yellow(text: String): ChatBuilder = color(text, ChatColor.YELLOW)
fun white(text: String): ChatBuilder = color(text, ChatColor.WHITE)
fun Player.sendJson(block: ChatMessageBuilder.() -> Unit) {
val build = ChatMessageBuilder()
build.block()
sendMessage(build.result.toChatComponent())
}
fun Player.sendJson(message: ChatBuilder) {
sendMessage(message.toChatComponent())
}
class ChatMessageBuilder(val result: ChatBuilder = ChatBuilder("")) {
operator fun ChatBuilder.unaryPlus() {
result += this
}
}
|
/*
*
* Crypto utils
*
*
*/
import crypto from 'crypto'
/**
* Caluclate the assetId based on the metadata text. At the moment no validation is done on the text.
* @param metadataText text to calculate the hash on.
* @returns SHA-256 of the metadata text as hex string.
*/
export function calculateAssetId(metadataText: string): string {
return crypto.createHash('SHA3-256').update(metadataText).digest('hex')
}
/**
* Calculate the content hash of any asset data.
* @param buffer Data to calculate the hash.
* @returns the SHA-256 hash of the data as hex string.
*/
export function calculateAssetDataHash(buffer: Buffer): string {
return crypto.createHash('SHA3-256').update(buffer).digest('hex')
}
|
using System.Text;
using Kaleidoscope.SyntaxObject;
namespace Kaleidoscope.Analysis
{
public sealed class NestedTypeDeclare<T> : NestedInstanceTypeDeclare where T : InstanceTypeDeclare
{
public readonly T Type;
public readonly ClassTypeDeclare ContainerType;
readonly string m_displayName;
public override InstanceTypeDeclare InstanceType => Type;
public NestedTypeDeclare(Builder builder, ClassTypeDeclare containerType)
: base(builder)
{
Type = builder.Type;
ContainerType = containerType;
var text = new StringBuilder();
text.Append("[NestedClassTypeDeclare] ");
if (AccessModifier != AccessModifier.@private) {
text.Append(AccessModifier);
text.Append(' ');
}
if (IsNew) {
text.Append("new ");
}
text.Append(Type.DisplayName);
m_displayName = text.ToString();
}
public override string ToString()
{
return m_displayName;
}
public new sealed class Builder : NestedInstanceTypeDeclare.Builder
{
public T Type;
}
}
}
|
<?php
function cssPath($s){
$path = base_url()."resources/css/".$s;
return $path;
}
function jsPath($s){
$path = base_url()."resources/js/".$s;
return $path;
}
function imagePath($s){
$path = base_url()."resources/images/".$s;
return $path;
}
function fontPath($s){
$path = base_url()."resources/font-awesome/".$s;
return $path;
}
function layersliderPath($s){
$path = base_url()."resources/layerslider/".$s;
return $path;
}
//ADMINISTRATORS NAVIGATION LINKS GOES HERE...
function adminCssPath($s){
$path = base_url()."resources/back/bootstrap/css/".$s;
return $path;
}
function adminDistCssPath($s){
$path = base_url()."resources/back/dist/css/".$s;
return $path;
}
function adminDistPath($s){
$path = base_url()."resources/back/dist/".$s;
return $path;
}
function adminPluginsPath($s){
$path = base_url()."resources/back/plugins/".$s;
return $path;
}
function adminJsPath($s){
$path = base_url()."resources/back/bootstrap/js/".$s;
return $path;
}
function adminImgPath($s){
$path = base_url()."resources/back/dist/img/".$s;
return $path;
}
function adminFontPath($s){
$path = base_url()."resources/back/bootstrap/fonts/".$s;
return $path;
}
|
// ----------------------------------------------------------------------------------------------
// Copyright (c) Mårten Rånge.
// ----------------------------------------------------------------------------------------------
// This source code is subject to terms and conditions of the Microsoft Public License. A
// copy of the license can be found in the License.html file at the root of this distribution.
// If you cannot locate the Microsoft Public License, please send an email to
// dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
// by the terms of the Microsoft Public License.
// ----------------------------------------------------------------------------------------------
// You must not remove this notice, or any other, from this software.
// ----------------------------------------------------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
[assembly: AssemblyTitle ("JsonVisualizer")]
[assembly: Guid ("a88f7f89-0bb6-4a1f-8518-fb06c28720ee")]
[assembly: ThemeInfo (
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
)]
|
---
layout: post
microblog: true
audio:
photo:
date: 2018-01-26 17:52:38 -0800
guid: http://jbwhaley.micro.blog/2018/01/27/call-me-an.html
---
Call me an old crank if you will, but I just am not attracted to the idea of talking to a computer.
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
header("Content-Type: text/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
class Reportes_global extends CI_Controller {
public function index()
{
$this->load->model("Reportes_global_model");
$repoEdad = $this->Reportes_global_model->reporte_por_edad();
$repoEdadAfrica = $this->Reportes_global_model->reporte_edad_africa();
$repoEdadAmerica = $this->Reportes_global_model->reporte_edad_america();
$repoEdadAsia = $this->Reportes_global_model->reporte_edad_asia();
$repoEdadEuropa = $this->Reportes_global_model->reporte_edad_europa();
$repoEdadCaribe = $this->Reportes_global_model->reporte_edad_caribe();
$repoMujeres = $this->Reportes_global_model->reporte_mujer();
echo json_encode(Array(
"repoEdad" => $repoEdad->first_row(),
"repoAfrica" => $repoEdadAfrica->first_row(),
"repoAmerica" => $repoEdadAmerica->first_row(),
"repoAsia" => $repoEdadAsia->first_row(),
"repoEuropa" => $repoEdadEuropa->first_row(),
"repoCaribe" => $repoEdadCaribe->first_row(),
"repoMujer" => $repoMujeres->first_row()
)
);
}
}
/*fin de Reportes_global.php...............*/
|
#ifndef INFO_H
#define INFO_H
//#include "common.h"
#define CARD_SIZE 100
#define CARD_TYPE (CARD_SIZE - 1)
namespace soccer {
typedef struct {
int nGols;
int nFaltas;
int nLaterais;
int nEscanteios;
double Posse;
int nCartoes;
char** Cartoes;
char** Gols;
} SInfo;
struct pass_info {
SInfo *team01;
SInfo *team02;
};
SInfo *createInfo(void);
//OBS: A posição 99 do cartao diz o tipo do cartao v a
void deleteInfo(SInfo *t);
char getCardType(const char *c);
char *newCard(void);
};
#endif
|
package com.ws.worker
import com.uber.cadence.activity.ActivityOptions
import com.uber.cadence.client.WorkflowClient
import com.uber.cadence.common.RetryOptions
import com.uber.cadence.workflow.ActivityStub
import com.uber.cadence.workflow.SignalMethod
import com.uber.cadence.workflow.Workflow
import com.uber.cadence.workflow.WorkflowMethod
import com.ws.worker.configuration.CadenceProperties
import mu.KLogging
import java.time.Duration
import java.util.*
interface IRiskWorkflow {
@WorkflowMethod
fun processRisk(input: String)
@SignalMethod
fun assignTask(user: String, wfId: String, wfRunId: String)
}
class RiskWorkflow(private val cadenceProperties: CadenceProperties) : IRiskWorkflow {
companion object : KLogging()
// ActivityStub to allow untypedActivityStub in Spring
private val defaultTaskListStore: ActivityStub
init {
val ao = ActivityOptions.Builder()
.setScheduleToCloseTimeout(Duration.ofSeconds(30))
.setTaskList(cadenceProperties.taskList)
.build()
// Instead of this.defaultTaskListStore = Workflow.newActivityStub(RiskActivity::class.java, ao)
this.defaultTaskListStore = Workflow.newUntypedActivityStub(ao)
}
override fun assignTask(user: String, wfId: String, wfRunId: String) {
val wfInfo = Workflow.getWorkflowInfo()
wfInfo.taskList
val workflowClient = WorkflowClient.newInstance(cadenceProperties.domain)
val workflowStub = workflowClient.newUntypedWorkflowStub(wfId, Optional.of(wfRunId), Optional.empty<String>())
val execution = workflowStub.execution
val completionClient = workflowClient.newActivityCompletionClient()
completionClient.complete(execution, "2", user)
logger.info { "completed assignTask" }
}
override fun processRisk(input: String) {
logger.info { "received string $input" }
val retryOptions = RetryOptions.Builder()
.setExpiration(Duration.ofSeconds(10))
.setInitialInterval(Duration.ofSeconds(1))
.build()
// Retries the whole sequence on any failure, potentially on a different host.
Workflow.retry(retryOptions) { processRiskImpl(input) }
}
private fun processRiskImpl(input: String) {
val result = defaultTaskListStore.execute("IRiskActivity::process", String::class.java, input)
logger.info { "----------------------------------------------" }
val stringPromise = defaultTaskListStore.executeAsync("IRiskActivity::process2", String::class.java, result)
val res = stringPromise.get()
logger.info { "+++++++++++++++++++ received promised $res" }
}
}
|
/**
* Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.http.impl.model
import java.nio.charset.Charset
import java.util.Optional
import java.{ lang ⇒ jl }
import akka.http.scaladsl.model.Uri.ParsingMode
import akka.http.javadsl.{ model ⇒ jm }
import akka.http.scaladsl.{ model ⇒ sm }
import akka.http.impl.util.JavaMapping.Implicits._
import scala.compat.java8.OptionConverters._
/** INTERNAL API */
case class JavaUri(uri: sm.Uri) extends jm.Uri {
def isRelative: Boolean = uri.isRelative
def isAbsolute: Boolean = uri.isAbsolute
def isEmpty: Boolean = uri.isEmpty
def scheme(): String = uri.scheme
def host(): jm.Host = uri.authority.host
def port(): Int = uri.authority.port
def userInfo(): String = uri.authority.userinfo
def path(): String = uri.path.toString
def pathSegments(): jl.Iterable[String] = {
import sm.Uri.Path._
def gatherSegments(path: sm.Uri.Path): List[String] = path match {
case Empty ⇒ Nil
case Segment(head, tail) ⇒ head :: gatherSegments(tail)
case Slash(tail) ⇒ gatherSegments(tail)
}
import collection.JavaConverters._
gatherSegments(uri.path).asJava
}
def rawQueryString: Optional[String] = uri.rawQueryString.asJava
def queryString(charset: Charset): Optional[String] = uri.queryString(charset).asJava
def query: jm.Query = uri.query().asJava
def query(charset: Charset, mode: ParsingMode): jm.Query = uri.query(charset, mode).asJava
def fragment: Optional[String] = uri.fragment.asJava
// Modification methods
def t(f: sm.Uri ⇒ sm.Uri): jm.Uri = JavaUri(f(uri))
def scheme(scheme: String): jm.Uri = t(_.withScheme(scheme))
def host(host: jm.Host): jm.Uri = t(_.withHost(host.asScala))
def host(host: String): jm.Uri = t(_.withHost(host))
def port(port: Int): jm.Uri = t(_.withPort(port))
def userInfo(userInfo: String): jm.Uri = t(_.withUserInfo(userInfo))
def path(path: String): jm.Uri = t(_.withPath(sm.Uri.Path(path)))
def toRelative: jm.Uri = t(_.toRelative)
def rawQueryString(rawQuery: String): jm.Uri = t(_.withRawQueryString(rawQuery))
def query(query: jm.Query): jm.Uri = t(_.withQuery(query.asScala))
def addPathSegment(segment: String): jm.Uri = t { u ⇒
val newPath =
if (u.path.endsWithSlash) u.path ++ sm.Uri.Path(segment)
else u.path ++ sm.Uri.Path./(segment)
u.withPath(newPath)
}
def fragment(fragment: Optional[String]): jm.Uri = t(_.copy(fragment = fragment.asScala))
def fragment(fragment: String): jm.Uri = t(_.withFragment(fragment))
override def toString: String = uri.toString
}
|
require 'site_list/video_analyze'
require 'requests/request'
require 'progressbars/progressbar'
require 'file_operats/file_operat_chatdata'
class Twitcasting_analyze<Video_analyze
attr_reader :video_id, :user_id, :videoinfo, :videoinfo_request_status
def initialize(url)
@video_url=url
@video_id=videoid_get()
@user_id=userid_get()
@videoinfo_request_body,@videoinfo_request_status=request_html_parse(@video_url,{})
@videoinfo=videoinfo_get()
@chat_request_url="https://twitcasting.tv/"+@user_id+"/moviecomment/"+@video_id
@chat_request_body,@chat_request_status=request_html_parse(@chat_request_url,{})
@chatlog_filepath="./"+@video_id+".txt"
end
def videoid_get()
return @video_url.split("/")[5].split("&")[0]
end
def userid_get()
return @video_url.split("/")[3]
end
def videoinfo_get()
videoinfo={}
videoinfo["user_name"]=@videoinfo_request_body.at_css(".tw-user-nav-name").text.strip
videoinfo["video_title"]=@videoinfo_request_body.at_css("#movie_title_content").text
videoinfo["video_time"]=@videoinfo_request_body.at_css(".tw-player-duration-time").text.strip
videoinfo["video_start_time"]=@videoinfo_request_body.at_css(".tw-player-meta__status_item > time")[:datetime]
videoinfo_polymer=@videoinfo_request_body.css(".tw-player-meta__status").css(".tw-player-meta__status_item")
i=0
videoinfo_polymer.each do |fact|
if i==1 then
videoinfo["total_view"]=fact.text.strip.split(":",2)[1]
return videoinfo
end
i+=1
end
return videoinfo
end
def chat_page_range()
size=@chat_request_body.css(".tw-pager").css("a").size()
range=@chat_request_body.css(".tw-pager").css("a")[size-1].text
return range.to_i
end
def chat_date_get(chatinfo_body)
chat_list=[]
chat_fact_dic={}
chatinfo_body.css(".tw-comment-history-item").each do |chat|
chat_fact_dic["comment"]=chat.at_css(".tw-comment-history-item__content__text").text.strip
chat_fact_dic["user_name"]=chat.at_css(".tw-comment-history-item__details__user-link").text.strip
chat_fact_dic["time"]=chat.at_css(".tw-comment-history-item__info__date")[:datetime]
chat_list.push(chat_fact_dic)
chat_fact_dic={}
end
return chat_list
end
def chat_scrape(log_flag=true,log_path=@chatlog_filepath)
chat_list=[]
chatinfo_body=@chat_request_body
page_range=chat_page_range()
page_count=0
while page_count<=page_range do
begin
chat_list+=chat_date_get(chatinfo_body)
page_count+=1
next_url=@chat_request_url+"-"+"#{page_count}"
chatinfo_body,_=request_html_parse(next_url,{})
progressbar(page_count,page_range)
sleep(1)
rescue
break
end
end
chat_list.reverse!
file_write(chat_list,log_flag,log_path)
return chat_list
end
public :chat_scrape
private :videoid_get, :userid_get, :videoinfo_get, :chat_page_range, :chat_date_get
end
|
<!DOCTYPE html>
<!-- This site was created in Webflow. http://www.webflow.com -->
<!-- Last Published: Wed Oct 16 2019 23:46:02 GMT+0000 (UTC) -->
<html data-wf-page="5da786dd00b10d79c698bf04" data-wf-site="5da766d32783b3459dfbc795">
<head>
<meta charset="utf-8">
<title>Publicações</title>
<meta content="Publicações" property="og:title">
<meta content="width=device-width, initial-scale=1" name="viewport">
<meta content="Webflow" name="generator">
<link href="css/normalize.css" rel="stylesheet" type="text/css">
<link href="css/app.css" rel="stylesheet" type="text/css">
<link href="css/js-snackbar.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="iconfinder-icon.svg" type="image/x-icon">
<style>
body {
background-color: #FFFFFF;
}
.ui.menu .item img.logo {
margin-right: 1.5em;
}
.main.container {
margin-top: 7em;
}
.wireframe {
margin-top: 2em;
}
.ui.footer.segment {
margin: 5em 0em 0em;
padding: 5em 0em;
}
</style>
</head>
<body>
<div class="ui fixed blue inverted menu">
<div class="ui container">
<a href="{{route("home")}}" class="header item">
<img class="logo" src="iconfinder-icon.svg">
Neex Twitter
</a>
<a href="#" class="item">Home</a>
<div class="right menu">
<form action="{{route('logout')}}" method="POST">
@csrf
<a href="javascript:;" class="ui item logout" style="height:100%;">
Sair
</a>
</form>
</div>
</div>
</div>
<div id="app">
@yield('content')
</div>
<script src="{{asset('js/js-snackbar.js')}}"></script>
<script src="{{asset("js/app.js")}}"></script>
<script src="{{asset("js/semantic.min.js")}}"></script>
<script>
$(document).ready(function() {
$(".logout").on("click", function () {
$(this).closest("form").submit();
})
})
</script>
</body>
</html>
|
from typing import List
import collections
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
elements, stack = {}, []
for i in range(len(nums2)):
while stack and nums2[i] > stack[-1]:
elements[stack.pop()] = nums2[i]
stack.append(nums2[i])
res = []
for i in nums1:
if i in elements:
res.append(elements[i])
else:
res.append(-1)
print(res)
# nums1 = [1,3,5,2,4]
# nums2 = [6,5,4,3,2,1,7]
# nums1 = [2,4]
# nums2 = [1,2,3,4]
nums1 = [4,1,2]
nums2 = [1,3,4,2]
t = Solution()
print(t.nextGreaterElement(nums1, nums2))
|
import { combineReducers } from 'redux';
import keycloak from '../reducers/keycloak.reducer';
import layouts from '../reducers/layouts.reducer';
import baseEntity from '../reducers/baseEntity.reducer';
import app from '../reducers/app.reducer';
export default combineReducers({
keycloak,
layouts,
baseEntity,
app
});
|
@extends('layouts.admin')
@section('content')
<h1>Create user</h1>
{!! Form::open([ 'method' => 'POST','url' => 'admin/users', 'files' => true]) !!}
<div class="form-group">
{!! Form::label('name', 'User name'); !!}
{!! Form::text('name',null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('email', 'Email'); !!}
{!! Form::email('email',null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('role', 'role'); !!}
{!! Form::select('role_id',$roles,0,['class' => 'form-control','placeholder' => 'Pick a role...']) !!}
</div>
<div class="form-group">
{!! Form::label('status', 'Status'); !!}
{!! Form::select('is_active',[1 => 'active', 0 => 'diactive'],0, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('password', 'Passsword'); !!}
{!! Form::password('password', ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('file', 'file'); !!}
{!! Form::file('photo_id',null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('create user',['class' => 'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
@include('includes/form_error')
@stop
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Neurotoxin.Godspeed.Shell.Models
{
public struct FileExistenceInfo
{
public readonly bool Exists;
public readonly long Size;
private FileExistenceInfo(bool exists, long size)
{
Exists = exists;
Size = size;
}
public static implicit operator bool(FileExistenceInfo info)
{
return info.Exists;
}
public static implicit operator FileExistenceInfo(bool exists)
{
return new FileExistenceInfo(exists, -1);
}
public static implicit operator long(FileExistenceInfo info)
{
return info.Size;
}
public static implicit operator FileExistenceInfo(long size)
{
return new FileExistenceInfo(size != -1, size);
}
public static implicit operator FileExistenceInfo(long? size)
{
return new FileExistenceInfo(size.HasValue, size ?? -1);
}
}
}
|
require 'natalie/inline'
__inline__ "#include <dirent.h>"
__inline__ "#include <sys/param.h>"
__inline__ "#include <sys/types.h>"
class Dir
class << self
def tmpdir
'/tmp'
end
__define_method__ :pwd, [], <<-END
char buf[MAXPATHLEN + 1];
if(!getcwd(buf, MAXPATHLEN + 1))
env->raise_errno();
return new StringValue { buf };
END
def each_child(dirname)
return enum_for(:each_child, dirname) unless block_given?
children(dirname).each do |name|
yield name
end
end
__define_method__ :children, [:dirname], <<-END
dirname->assert_type(env, Value::Type::String, "String");
auto dir = opendir(dirname->as_string()->c_str());
if (!dir)
env->raise_errno();
dirent *entry;
errno = 0;
auto array = new ArrayValue {};
for (;;) {
entry = readdir(dir);
if (!entry) break;
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue;
array->push(new StringValue { entry->d_name });
}
if (errno) {
closedir(dir);
env->raise_errno();
}
closedir(dir);
return array;
END
end
end
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDesktopWidget>
#include <QByteArray>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "filedownloader.h"
#include <fstream>
#include <QUrl>
#include <QPixmap>
#include <iostream>
#include <QRegExp>
#include <stdlib.h>
#include <ctime>
#include "aboutbox.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void fetch();
void getImageUrl();
void loadImage();
void showAboutBox();
private:
Ui::MainWindow *ui;
aboutBox *ab;
public:
FileDownloader *m_pImgCtrl;
FileDownloader *imageDownloader;
//QDownloader downloader;
};
#endif // MAINWINDOW_H
|
// Pattern match solution
sealed trait TrafficLight {
def next: TrafficLight =
this match {
case RedTrafficLight => YellowTrafficLight
case YellowTrafficLight => GreenTrafficLight
case GreenTrafficLight => RedTrafficLight
}
}
case object RedTrafficLight extends TrafficLight
case object YellowTrafficLight extends TrafficLight
case object GreenTrafficLight extends TrafficLight
|
def _remove_backslashes(latex_str):
return ''.join([letter for letter in latex_str if letter != '\\'])
|
/*
* Copyright (c) 2022.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import path from 'path';
import {
TrainContainerFileName,
TrainContainerPath,
TrainManagerExtractingQueuePayload,
} from '@personalhealthtrain/central-common';
import { extractTrainConfigFromTrainExtractorPayload } from '../../../../src/domains/special/train-manager';
describe('src/domains/train-builder', () => {
it('should build train message', async () => {
const trainConfig = await import(path.join(__dirname, '..', '..', 'data', 'train-config.json'));
const queuePayload : TrainManagerExtractingQueuePayload = {
filePaths: [TrainContainerPath.CONFIG],
files: [
{
name: TrainContainerFileName.CONFIG,
path: TrainContainerPath.CONFIG,
size: 5074,
content: JSON.stringify(trainConfig),
type: 'file',
},
],
mode: 'read',
id: 'e81a773a-161c-43a2-8eee-2e2723bd1c41',
};
const output = extractTrainConfigFromTrainExtractorPayload(queuePayload);
expect(output).toBeDefined();
expect(output.route).toBeDefined();
expect(output.route.length).toEqual(2);
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.