content
stringlengths 3
806k
| option
stringclasses 3
values | score
float64 0.01
1
| __index_level_0__
int64 0
100k
|
---|---|---|---|
(**************************************************************************)
(* *)
(* OCamlFormat *)
(* *)
(* Copyright (c) Facebook, Inc. and its affiliates. *)
(* *)
(* This source code is licensed under the MIT license found in *)
(* the LICENSE file in the root directory of this source tree. *)
(* *)
(**************************************************************************)
type t = {lower: int; upper: int; whole: bool}
open Result.Monad_infix
let make ?range source =
let lines_nb = List.length @@ String.split_lines source in
match range with
| Some (lower, upper)
when 1 <= lower && lower <= upper && upper <= lines_nb + 1 ->
(* the last line of the buffer (lines_nb + 1) should be valid *)
let whole = lower = 1 && upper >= lines_nb in
{lower; upper; whole}
| _ -> {lower= 1; upper= lines_nb; whole= true}
let get t = (t.lower, t.upper)
let is_whole t = t.whole
let conv =
let open Cmdliner in
let pair_conv = Arg.(pair ~sep:'-' int int) in
let parse x = Arg.conv_parser pair_conv x >>| fun range -> make ~range in
let pp fs x =
match x "this string is not important" with
| {whole= true; _} -> Format.fprintf fs "<whole input>"
| {lower; upper; _} -> Arg.conv_printer pair_conv fs (lower, upper)
in
Arg.conv (parse, pp)
| high | 0.559714 | 102 |
{"md5":"b7cad5d5b55eef1a7fdcbcd3e427848e","signature":"7a3d1250526e96e159113d40d8c2ee81ca4db2a514942f93a9b32c1c8dbea0141b1c0fad87e06d65d31bd25ff0360fd55c93f9ccfb8270881d9bca32368eb300","created":1522794599} | low | 0.838755 | 103 |
// Copyright (C) 2020-2021 Andy Kurnia.
use super::{error, game_config, movegen};
// note: only this representation uses -1i8 for blank-as-A (in "board" input
// and "word" response for "action":"play"). everywhere else, use 0x81u8.
#[derive(serde::Serialize, serde::Deserialize, Debug)]
#[serde(tag = "action")]
pub enum JsonPlay {
#[serde(rename = "exchange")]
Exchange { tiles: Box<[u8]> },
#[serde(rename = "play")]
Play {
down: bool,
lane: i8,
idx: i8,
word: Box<[i8]>,
score: i16,
},
}
impl From<&movegen::Play> for JsonPlay {
#[inline(always)]
fn from(play: &movegen::Play) -> Self {
match &play {
movegen::Play::Exchange { tiles } => {
// tiles: array of numbers. 0 for blank, 1 for A.
Self::Exchange {
tiles: tiles[..].into(),
}
}
movegen::Play::Place {
down,
lane,
idx,
word,
score,
} => {
// turn 0x81u8, 0x82u8 into -1i8, -2i8
let word_played = word
.iter()
.map(|&x| {
if x & 0x80 != 0 {
-((x & !0x80) as i8)
} else {
x as i8
}
})
.collect::<Vec<i8>>();
// across plays: down=false, lane=row, idx=col (0-based).
// down plays: down=true, lane=col, idx=row (0-based).
// word: 0 for play-through, 1 for A, -1 for blank-as-A.
Self::Play {
down: *down,
lane: *lane,
idx: *idx,
word: word_played.into(),
score: *score,
}
}
}
}
}
impl From<&JsonPlay> for movegen::Play {
#[inline(always)]
fn from(play: &JsonPlay) -> Self {
match &play {
JsonPlay::Exchange { tiles } => {
// tiles: array of numbers. 0 for blank, 1 for A.
Self::Exchange {
tiles: tiles[..].into(),
}
}
JsonPlay::Play {
down,
lane,
idx,
word,
score,
} => {
// turn -1i8, -2i8 into 0x81u8, 0x82u8
let word_played = word
.iter()
.map(|&x| if x < 0 { 0x81 + !x as u8 } else { x as u8 })
.collect::<Vec<u8>>();
// across plays: down=false, lane=row, idx=col (0-based).
// down plays: down=true, lane=col, idx=row (0-based).
// word: 0 for play-through, 1 for A, -1 for blank-as-A.
Self::Place {
down: *down,
lane: *lane,
idx: *idx,
word: word_played[..].into(),
score: *score,
}
}
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct JsonPlayWithEquity {
pub equity: f32,
#[serde(flatten)]
pub play: JsonPlay,
}
impl From<&movegen::ValuedMove> for JsonPlayWithEquity {
#[inline(always)]
fn from(play: &movegen::ValuedMove) -> Self {
Self {
equity: play.equity,
play: (&play.play).into(),
}
}
}
impl From<&JsonPlayWithEquity> for movegen::ValuedMove {
#[inline(always)]
fn from(play: &JsonPlayWithEquity) -> Self {
Self {
equity: play.equity,
play: (&play.play).into(),
}
}
}
pub struct Kibitzer {
pub available_tally: Vec<u8>,
pub board_tiles: Vec<u8>,
}
impl Kibitzer {
pub fn new() -> Self {
Self {
available_tally: Vec::new(),
board_tiles: Vec::new(),
}
}
pub fn prepare(
&mut self,
game_config: &game_config::GameConfig<'_>,
rack: &[u8],
signed_board_tiles: &[Vec<i8>],
) -> error::Returns<()> {
let alphabet = game_config.alphabet();
let alphabet_len_without_blank = alphabet.len() - 1;
self.available_tally.resize(alphabet.len() as usize, 0);
for tile in 0..alphabet.len() {
self.available_tally[tile as usize] = alphabet.freq(tile);
}
for &tile in rack {
if tile > alphabet_len_without_blank {
return_error!(format!(
"rack has invalid tile {}, alphabet size is {}",
tile, alphabet_len_without_blank
));
}
if self.available_tally[tile as usize] > 0 {
self.available_tally[tile as usize] -= 1;
} else {
return_error!(format!(
"too many tile {} (bag contains only {})",
tile,
alphabet.freq(tile),
));
}
}
let expected_dim = game_config.board_layout().dim();
if signed_board_tiles.len() != expected_dim.rows as usize {
return_error!(format!(
"board: need {} rows, found {} rows",
expected_dim.rows,
signed_board_tiles.len()
));
}
for (row_num, row) in (0..).zip(signed_board_tiles.iter()) {
if row.len() != expected_dim.cols as usize {
return_error!(format!(
"board row {} (0-based): need {} cols, found {} cols",
row_num,
expected_dim.cols,
row.len()
));
}
}
self.board_tiles.clear();
self.board_tiles
.reserve((expected_dim.rows as usize) * (expected_dim.cols as usize));
for (row_num, row) in (0..).zip(signed_board_tiles.iter()) {
for (col_num, &signed_tile) in (0..).zip(row) {
if signed_tile == 0 {
self.board_tiles.push(0);
} else if signed_tile as u8 <= alphabet_len_without_blank {
let tile = signed_tile as u8;
self.board_tiles.push(tile);
if self.available_tally[tile as usize] > 0 {
self.available_tally[tile as usize] -= 1;
} else {
return_error!(format!(
"too many tile {} (bag contains only {})",
tile,
alphabet.freq(tile),
));
}
} else if (!signed_tile as u8) < alphabet_len_without_blank {
// turn -1i8, -2i8 into 0x81u8, 0x82u8
self.board_tiles.push(0x81 + !signed_tile as u8);
// verify usage of blank tile
if self.available_tally[0] > 0 {
self.available_tally[0] -= 1;
} else {
return_error!(format!(
"too many tile {} (bag contains only {})",
0,
alphabet.freq(0),
));
}
} else {
return_error!(format!(
"board row {} col {} (0-based): invalid tile {}, alphabet size is {}",
row_num, col_num, signed_tile, alphabet_len_without_blank
));
}
}
}
Ok(())
}
}
impl Default for Kibitzer {
#[inline(always)]
fn default() -> Self {
Self::new()
}
}
| high | 0.892805 | 104 |
import { Cart as PrismaCart, CartItem as PrismaCartItem, PrismaClient, Product as PrismaProduct, User as PrismaUser } from "@prisma/client";
import { CartGateway } from "../../application/ports";
import { Cart } from "../../domain/cart";
import { UniqueId } from "../../domain/sharedKernel";
type PrismaFullyIncluded = PrismaCart & {
user: PrismaUser;
cartItems: (PrismaCartItem & {
product: PrismaProduct;
})[];
};
export function createCartAdapter(prisma: PrismaClient): CartGateway {
return {
async save(cart: Cart): Promise<Cart> {
if (cart.id === undefined) {
const newCart = await prisma.cart.create({
data: {
user: { connect: { id: cart.owner.id } },
cartItems: {
create: cart.items.map(item => ({
product: { connect: { id: item.product.id } },
quantity: item.quantity
}))
}
},
include: {
user: true,
cartItems: {
include: {
product: true
}
}
}
});
return mapPrismaCartFullyIncludedToDomain(newCart);
}
const existingCart = await prisma.cart.findFirst({
where: {
id: cart.id,
},
include: {
cartItems: {
include: {
product: true,
}
},
},
});
// create cart, then add new cart items or update existing cart items
const existingCartItems = existingCart.cartItems;
const existingCartItemIds = existingCartItems.map((item) => item.id);
const newCartItems = cart.items;
const newCartItemsIds = newCartItems.map((item) => item.id);
const cartItemsToUpdate = newCartItems.filter((item) => existingCartItemIds.includes(item.id));
const cartItemsToCreate = newCartItems.filter((item) => !existingCartItemIds.includes(item.id));
const cartItemsToDelete = existingCartItems.filter((item) => !newCartItemsIds.includes(item.id));
const updatedCart = await prisma.cart.update({
where: { id: cart.id },
data: {
cartItems: {
update: cartItemsToUpdate.map((item) => {
const existingItem = existingCartItems.find((existingItem) => existingItem.id === item.id);
return {
where: { id: item.id },
data: {
quantity: item.quantity === existingItem.quantity
? undefined
: item.quantity,
}
}
}),
create: cartItemsToCreate.map((item) => ({
product: { connect: { id: item.product.id } },
quantity: item.quantity,
})),
delete: cartItemsToDelete.map((item) => ({ id: item.id })),
},
},
include: {
user: true,
cartItems: {
include: {
product: true,
},
}
},
});
return mapPrismaCartFullyIncludedToDomain(updatedCart);
},
async findById(id: UniqueId): Promise<Cart> {
const cart = await prisma.cart.findFirst({
where: { id },
include: {
user: true,
cartItems: {
include: {
product: true,
},
}
}
});
return mapPrismaCartFullyIncludedToDomain(cart);
},
async findByOwnerId(ownerId: UniqueId): Promise<Cart> {
const cart = await prisma.cart.findFirst({
where: { user: { id: ownerId } },
include: {
user: true,
cartItems: {
include: {
product: true,
},
}
}
});
return mapPrismaCartFullyIncludedToDomain(cart);
}
}
}
function mapPrismaCartFullyIncludedToDomain(prismaCart: PrismaFullyIncluded): Cart {
return {
id: prismaCart.id,
owner: prismaCart.user,
items: prismaCart.cartItems.map(item => ({
id: item.id,
product: {
id: item.product.id,
name: item.product.name,
price: Number(item.product.price)
},
quantity: item.quantity
}))
}
} | high | 0.816875 | 105 |
##
## Copyright (c) 2010 The WebM project authors. All Rights Reserved.
##
## Use of this source code is governed by a BSD-style license
## that can be found in the LICENSE file in the root of the source
## tree. An additional intellectual property rights grant can be found
## in the file PATENTS. All contributing project authors may
## be found in the AUTHORS file in the root of the source tree.
##
include $(SRC_PATH_BARE)/$(VP8_PREFIX)vp8_common.mk
VP8_CX_EXPORTS += exports_enc
VP8_CX_SRCS-yes += $(VP8_COMMON_SRCS-yes)
VP8_CX_SRCS-no += $(VP8_COMMON_SRCS-no)
VP8_CX_SRCS_REMOVE-yes += $(VP8_COMMON_SRCS_REMOVE-yes)
VP8_CX_SRCS_REMOVE-no += $(VP8_COMMON_SRCS_REMOVE-no)
ifeq ($(ARCH_ARM),yes)
include $(SRC_PATH_BARE)/$(VP8_PREFIX)vp8cx_arm.mk
endif
VP8_CX_SRCS-yes += vp8_cx_iface.c
# encoder
#INCLUDES += algo/vpx_common/vpx_mem/include
#INCLUDES += common
#INCLUDES += common
#INCLUDES += common
#INCLUDES += algo/vpx_ref/cpu_id/include
#INCLUDES += common
#INCLUDES += encoder
VP8_CX_SRCS-yes += encoder/bitstream.c
VP8_CX_SRCS-yes += encoder/boolhuff.c
VP8_CX_SRCS-yes += encoder/dct.c
VP8_CX_SRCS-yes += encoder/encodeframe.c
VP8_CX_SRCS-yes += encoder/encodeintra.c
VP8_CX_SRCS-yes += encoder/encodemb.c
VP8_CX_SRCS-yes += encoder/encodemv.c
VP8_CX_SRCS-$(CONFIG_MULTITHREAD) += encoder/ethreading.c
VP8_CX_SRCS-yes += encoder/firstpass.c
VP8_CX_SRCS-yes += encoder/generic/csystemdependent.c
VP8_CX_SRCS-yes += encoder/block.h
VP8_CX_SRCS-yes += encoder/boolhuff.h
VP8_CX_SRCS-yes += encoder/bitstream.h
VP8_CX_SRCS-yes += encoder/dct.h
VP8_CX_SRCS-yes += encoder/encodeintra.h
VP8_CX_SRCS-yes += encoder/encodemb.h
VP8_CX_SRCS-yes += encoder/encodemv.h
VP8_CX_SRCS-yes += encoder/firstpass.h
VP8_CX_SRCS-yes += encoder/mcomp.h
VP8_CX_SRCS-yes += encoder/modecosts.h
VP8_CX_SRCS-yes += encoder/onyx_int.h
VP8_CX_SRCS-yes += encoder/pickinter.h
VP8_CX_SRCS-yes += encoder/psnr.h
VP8_CX_SRCS-yes += encoder/quantize.h
VP8_CX_SRCS-yes += encoder/ratectrl.h
VP8_CX_SRCS-yes += encoder/rdopt.h
VP8_CX_SRCS-yes += encoder/tokenize.h
VP8_CX_SRCS-yes += encoder/treewriter.h
VP8_CX_SRCS-yes += encoder/variance.h
VP8_CX_SRCS-yes += encoder/mcomp.c
VP8_CX_SRCS-yes += encoder/modecosts.c
VP8_CX_SRCS-yes += encoder/onyx_if.c
VP8_CX_SRCS-yes += encoder/pickinter.c
VP8_CX_SRCS-yes += encoder/picklpf.c
VP8_CX_SRCS-yes += encoder/psnr.c
VP8_CX_SRCS-yes += encoder/quantize.c
VP8_CX_SRCS-yes += encoder/ratectrl.c
VP8_CX_SRCS-yes += encoder/rdopt.c
VP8_CX_SRCS-yes += encoder/sad_c.c
VP8_CX_SRCS-yes += encoder/segmentation.c
VP8_CX_SRCS-yes += encoder/segmentation.h
VP8_CX_SRCS-$(CONFIG_PSNR) += encoder/ssim.c
VP8_CX_SRCS-yes += encoder/tokenize.c
VP8_CX_SRCS-yes += encoder/treewriter.c
VP8_CX_SRCS-yes += encoder/variance_c.c
VP8_CX_SRCS-$(CONFIG_PSNR) += common/postproc.h
VP8_CX_SRCS-$(CONFIG_PSNR) += common/postproc.c
VP8_CX_SRCS-yes += encoder/temporal_filter.c
VP8_CX_SRCS-yes += encoder/temporal_filter.h
ifeq ($(CONFIG_REALTIME_ONLY),yes)
VP8_CX_SRCS_REMOVE-yes += encoder/firstpass.c
VP8_CX_SRCS_REMOVE-yes += encoder/temporal_filter.c
endif
VP8_CX_SRCS-$(ARCH_X86)$(ARCH_X86_64) += encoder/x86/encodemb_x86.h
VP8_CX_SRCS-$(ARCH_X86)$(ARCH_X86_64) += encoder/x86/dct_x86.h
VP8_CX_SRCS-$(ARCH_X86)$(ARCH_X86_64) += encoder/x86/mcomp_x86.h
VP8_CX_SRCS-$(ARCH_X86)$(ARCH_X86_64) += encoder/x86/variance_x86.h
VP8_CX_SRCS-$(ARCH_X86)$(ARCH_X86_64) += encoder/x86/quantize_x86.h
VP8_CX_SRCS-$(ARCH_X86)$(ARCH_X86_64) += encoder/x86/temporal_filter_x86.h
VP8_CX_SRCS-$(ARCH_X86)$(ARCH_X86_64) += encoder/x86/x86_csystemdependent.c
VP8_CX_SRCS-$(HAVE_MMX) += encoder/x86/variance_mmx.c
VP8_CX_SRCS-$(HAVE_MMX) += encoder/x86/variance_impl_mmx.asm
VP8_CX_SRCS-$(HAVE_MMX) += encoder/x86/sad_mmx.asm
VP8_CX_SRCS-$(HAVE_MMX) += encoder/x86/dct_mmx.asm
VP8_CX_SRCS-$(HAVE_MMX) += encoder/x86/subtract_mmx.asm
VP8_CX_SRCS-$(HAVE_SSE2) += encoder/x86/dct_sse2.asm
VP8_CX_SRCS-$(HAVE_SSE2) += encoder/x86/variance_sse2.c
VP8_CX_SRCS-$(HAVE_SSE2) += encoder/x86/variance_impl_sse2.asm
VP8_CX_SRCS-$(HAVE_SSE2) += encoder/x86/sad_sse2.asm
VP8_CX_SRCS-$(HAVE_SSE2) += encoder/x86/fwalsh_sse2.asm
VP8_CX_SRCS-$(HAVE_SSE2) += encoder/x86/quantize_sse2.asm
VP8_CX_SRCS-$(HAVE_SSE2) += encoder/x86/subtract_sse2.asm
VP8_CX_SRCS-$(HAVE_SSE2) += encoder/x86/temporal_filter_apply_sse2.asm
VP8_CX_SRCS-$(HAVE_SSE3) += encoder/x86/sad_sse3.asm
VP8_CX_SRCS-$(HAVE_SSSE3) += encoder/x86/sad_ssse3.asm
VP8_CX_SRCS-$(HAVE_SSSE3) += encoder/x86/quantize_ssse3.asm
VP8_CX_SRCS-$(HAVE_SSE4_1) += encoder/x86/sad_sse4.asm
VP8_CX_SRCS-$(ARCH_X86)$(ARCH_X86_64) += encoder/x86/quantize_mmx.asm
VP8_CX_SRCS-$(ARCH_X86)$(ARCH_X86_64) += encoder/x86/encodeopt.asm
ifeq ($(CONFIG_REALTIME_ONLY),yes)
VP8_CX_SRCS_REMOVE-$(HAVE_SSE2) += encoder/x86/temporal_filter_apply_sse2.asm
endif
VP8_CX_SRCS-yes := $(filter-out $(VP8_CX_SRCS_REMOVE-yes),$(VP8_CX_SRCS-yes))
| low | 0.753864 | 106 |
module Data.Theme exposing (Theme(..), toStyle)
import Data.Style exposing (Style)
import Data.Style.ElmUiFramework
import Data.Style.Material
import Data.Style.Template
import Widget.Style.Material
type Theme
= ElmUiFramework
| Template
| Material
| DarkMaterial
toStyle : Theme -> Style msg
toStyle theme =
case theme of
ElmUiFramework ->
Data.Style.ElmUiFramework.style
Template ->
Data.Style.Template.style
Material ->
Data.Style.Material.style Widget.Style.Material.defaultPalette
DarkMaterial ->
Data.Style.Material.style Widget.Style.Material.darkPalette
| high | 0.494807 | 107 |
require 'wunderlist'
require 'time'
require 'andand'
require 'active_support/core_ext/numeric/time'
OGWunderlist = Wunderlist
module Metrics
# Check if Wunderlist reports no upcoming tasks due.
class Wunderlist
def initialize(settings)
@cache = {}
@wl = OGWunderlist::API.new(
access_token: settings['access-token'],
client_id: settings['client-id']
)
@ignore_tag = settings['ignore-tag']
@list_times = settings['list-times']
end
def blocks
root = @wl.get 'api/v1/root'
id = root['id']
update_cache(root) unless up_to_date(id, root['revision'])
cached_problems
end
private
def up_to_date(id, revision)
return false unless @cache.key? id
return false unless @cache[id].andand[:revision] == revision
return false unless @cache[id].andand[:expires] > Time.now
true
end
def task_due_date(task, list)
result = Time.parse(task.due_date)
time = @list_times[list.id]
return result if time.nil?
h, m = time.split ':'
result += h.to_i.hours
result += m.to_i.minutes
result
end
def task_if_problematic(list, task)
return if task.due_date.nil?
return if task.title.include? @ignore_tag
due_date = task_due_date(task, list)
return nil unless due_date < 1.days.from_now
"[#{list.title}] #{task.title} (#{due_date.ctime})"
end
def update_cache_for(list)
return if up_to_date(list.id, list.revision)
result = list.tasks.map do |task|
task_if_problematic list, task
end.compact
@cache[list.id] = {
revision: list.revision,
data: result,
expires: rand(10..30).minutes.from_now
}
end
def update_cache(root)
id = root['id']
@wl.lists.each { |list| update_cache_for list }
@cache[id] = {
revision: root['revision'],
expires: rand(10..30).minutes.from_now
}
end
def cached_problems
@cache.values.map { |list| list[:data] } .flatten.compact
end
end
end
| high | 0.750417 | 108 |
program MainDemo;
uses
Forms,
MainForm in 'MainForm.pas' {fwbMainForm};
{$R *.res}
begin
Application.Initialize;
Application.CreateForm(TfwbMainForm, fwbMainForm);
Application.Run;
end.
| low | 0.449357 | 109 |
RES5L
LDDE
BIT4A
INCH
LDDL
LDHn
59
LDDE
INCD
RES6D
ANDB
BIT3D
DECE
LDBB
RES0B
BIT2E
SET0C
LDEC
XORC
INCL
RES4L
BIT6C
RES3D
LDDB
SET5mHL
LDBH
RES6L
BIT0mHL
RES3C
RRCC
LDDA
LDLL
BIT4mHL
RLE
LDAD
LDBD
LDAC
SET2mHL
LDAA
RRH
SET0C
SRAB
SLAD
LDmHLD
LDDB
LDHC
ORL
SLAC
NOP
RES3C
SET6E
XORH
BIT1B
BIT1C
RRA
XORC
RES3C
ORH
LDHD
RRC
BIT4L
BIT5H
ANDE
LDHH
LDHB
BIT6A
BIT2A
LDHmHL
LDEH
ADCAn
4b
BIT2B
XORB
ADCAA
BIT7D
XORD
DECA
RRC
LDmHLL
SET0D
SRAC
SLAH
LDLmHL
ANDD
RES7E
BIT1H
LDDH
DECH
DECA
BIT4A
LDmHLC
ADDAn
ab
LDmHLL
LDEn
ad
LDBE
SET2A
LDBmHL
LDHn
23
BIT5H
RRD
LDAL
LDAL
RES7A
LDLmHL
LDmHLL
RES5A
LDLn
85
RES2E
ADCAH
SET0E
RLD
SLAC
RES5E
ORE
SET1L
ANDE
RRCA
BIT3E
XORD
BIT2D
LDDEnn
9b
34
SRLC
SET0B
DECE
ORmHL
LDDL
SET5L
ORB
LDHH
RRB
ANDL
ORL
BIT7A
SET5C
BIT5B
ORA
ADDAA
DECE
LDEE
LDBD
SET7H
BIT0B
RES7L
SWAPL
SET6mHL
ADDAC
RES7A
BIT5D
ORD
RRC
SET3H
LDBB
LDHB
BIT4L
BIT5A
SRLmHL
RES4mHL
ADCAB
LDEC
LDEL
RLCmHL
BIT3L
LDHE
LDEmHL
RRL
LDBD
LDBE
SCF
RES0E
LDCL
SET5H
RES4L
RES4C
RLH
SET3E
LDDA
BIT4L
ADCAE
LDHH
ADCAH
RRD
LDDEnn
6e
7a
SWAPD
RLA
LDDA
DECD
ORC
ORC
ADCAmHL
LDCL
LDED
LDCn
8c
ORC
SLAL
LDEA
SET6A
RLA
BIT0B
LDDn
d2
LDLn
6
RES7H
LDAC
LDCB
LDBn
e8
SRLE
SET5E
LDDC
LDBD
RLmHL
ADCAB
RLB
SRLH
LDAB
LDmHLC
LDmDEA
ADCAmHL
LDEL
ADCAmHL
BIT7mHL
BIT2H
XORB
BIT2E
SRAA
INCE
SET6mHL
INCD
DECA
ANDC
RLC
BIT1B
LDCC
LDBCnn
c1
c7
ADCAB
XORL
RES7C
SET1L
LDCC
RLA
LDLmHL
RES2B
BIT7B
ADCAE
RES0C
BIT0H
SET5C
LDBCnn
b
19
LDEB
LDBB
RRH
LDEmHL
BIT7A
BIT0E
ADDAmHL
SRLE
RES2C
RES0mHL
SWAPH
LDHH
DECH
BIT3D
RLCC
SRLE
XORH
XORB
LDCL
SET6H
LDLB
SET6E
SET3B
RES7C
SET3H
LDmHLH
RLCE
RES0L
NOT
LDmHLA
LDEn
3e
INCC
RRCB
RES1B
XORD
BIT4C
ORn
87
LDHmHL
SET1L
LDEC
ADCAD
RRCA
BIT0mHL
XORL
ORL
DECH
BIT1mHL
RES6H
LDCE
SET0D
SET1H
SET4L
SET7E
LDEC
LDCA
SRAL
ADDAmHL
LDmHLA
LDDEnn
5f
82
LDmDEA
RES4mHL
LDLB
RES6B
LDEH
RES4B
LDLE
LDLA
LDDL
BIT1D
RRCC
RLA
SET4D
BIT2E
LDDmHL
RES1A
BIT0H
SLAE
DECC
ADDAA
SCF
LDLC
ADCAD
ADCAmHL
BIT6C
ANDC
LDLA
LDEC
RES0C
BIT7C
LDmHLE
ORE
LDHC
RES1L
RES2H
RES2C
ANDL
BIT5B
BIT4D
SET6E
RES6A
LDHA
SET0H
RES1E
RES2H
LDLH
BIT5E
SET7B
ADDAD
LDCn
21
ADDAC
BIT3H
LDCH
RES7B
SET4E
LDEE
XORE
LDmHLL
LDCH
SET1C
RES6A
ORE
BIT0E
RLCH
RLCE
RES2A
LDLmHL
BIT4L
ADCAH
RES2mHL
RRCA
LDCA
ADDAL
ORmHL
BIT1A
BIT0E
ANDmHL
LDEn
a2
LDHH
LDHA
INCE
RRA
SRLB
ANDE
LDCC
BIT7B
LDHB
ADDAn
1e
SET0mHL
LDHB
ANDC
SET5H
LDLB
BIT2C
RLCD
DECE
SET5D
ANDmHL
BIT1L
BIT2mHL
NOT
RES1L
BIT2L
INCC
SET4L
SET4H
LDBmHL
SLAmHL
BIT2L
XORE
SRAA
SRAE
XORE
RES6L
SRLmHL
LDHn
b5
RLmHL
BIT0B
ADCAL
LDHL
ADDAD
RES1C
SET4D
LDCB
BIT4E
RES1A
ADCAD
LDHmHL
RRA
SET5D
BIT6L
DECC
ANDC
DECA
BIT3mHL
BIT7H
LDCmHL
SLAmHL
LDAmHL
LDDE
SRLA
BIT7mHL
ORD
ANDmHL
LDLC
XORD
BIT7E
SWAPL
LDHLnn
cc
db
BIT3C
ANDA
BIT5C
RES0B
BIT1H
BIT5mHL
RRA
LDDL
ADCAL
BIT2H
SET4mHL
ANDn
3b
RLCE
RLA
LDEL
LDHLnn
1d
1f
LDBC
SLAC
ADDAD
LDHB
RES3L
ADDAB
LDLE
RRCmHL
DECL
ADCAA
SET3D
LDDA
ADCAA
LDDC
RLA
RES5B
LDCn
72
RLCE
RES6L
ANDH
SET6A
LDmHLB
NOT
RES5B
SRAmHL
BIT2H
SET7A
ADCAL
SLAH
LDDB
SET4C
LDLD
ORD
LDLL
ORA
DECE
LDLC
RES1E
LDAmDE
ORB
LDBD
RES2E
SWAPB
SLAC
BIT2H
SET2H
INCE
RES0A
LDLH
BIT4B
LDmHLH
NOT
BIT6H
BIT5D
SWAPC
BIT2A
ADDAL
RES2B
SWAPB
SRAC
SRAD
RLmHL
DECB
ANDC
INCL
RES4E
SET5D
SWAPH
ANDL
LDDn
66
SLAmHL
LDCmHL
LDBH
LDHC
XORH
LDDL
BIT6A
LDEmHL
LDBCnn
8b
65
LDBCnn
70
c2
LDCD
RES1D
ADCAL
BIT5C
RES1C
SRLL
LDCmHL
SET4B
INCC
RES5B
RES2B
RES6D
RES4mHL
SET0C
LDLH
LDLn
8a
BIT2C
SWAPC
XORH
BIT5C
DECA
SLAH
LDCB
LDAmHL
LDmHLB
LDLB
XORC
LDmHLA
ORB
ADDAE
SET2mHL
RES2D
SET2L
LDmHLA
LDmHLA
ORL
SET2C
LDEB
SWAPD
DECL
SET2A
ADDAn
1a
LDmHLD
RES0C
LDmHLE
BIT7H
BIT6mHL
ADDAmHL
LDAn
f5
SET5C
RLA
ANDL
RES4L
RES5C
SRAB
LDAB
LDEB
ADDAA
DECD
ADDAE
BIT2A
RES4B
LDAD
LDCL
SET2A
LDCH
RES5mHL
LDEH
LDDEnn
8e
16
SWAPB
DECE
RES1D
SET0D
ADCAB
ORmHL
LDED
SET3A
SET6L
RES3L
BIT7L
CCF
LDEA
RRL
RRH
ADCAmHL
XORmHL
LDmHLE
LDHH
ADDAA
ANDL
LDAH
ADDAH
LDDEnn
ac
c6
LDEE
SET5H
ANDE
LDHC
ADDAC
RLCmHL
SET7L
RES2E
SET2mHL
ADCAmHL
ADDAn
4d
ADCAD
SET2H
ADCAH
RRCC
BIT6L
INCB
LDDn
b9
BIT6B
INCH
RES4B
LDBL
RRCmHL
ANDB
SET6B
LDmHLL
ANDD
BIT3H
LDHmHL
DECC
ANDn
b9
SLAL
SCF
XORH
SWAPE
LDHE
SET0H
BIT2A
RLH
RRCL
BIT4D
ORC
LDCE
ADDAL
SET1B
ADCAE
BIT0D
BIT2B
LDCL
RES4B
RES6mHL
LDBH
LDDEnn
39
62
BIT3B
SET4B
BIT6mHL
LDAL
SET5A
BIT2L
LDHH
RES2A
LDEmHL
ORC
LDmHLB
LDmHLA
RRCA
LDCn
f3
SET7H
XORn
bc
LDDL
RES1A
LDDB
ORD
LDmHLE
LDDL
SRLB
LDBB
RES3C
ORn
e5
SLAL
BIT7L
SET3D
BIT7D
RES4D
LDBCnn
d8
4f
RLCA
SRAA
RLCA
RES7B
LDAE
LDLH
SLAH
RRmHL
RRCA
ORD
RES5H
ORmHL
SET1mHL
RRB
SRLD
SWAPC
CCF
LDEB
ANDmHL
LDmHLC
SET0B
LDLA
SWAPA
BIT6C
RES3B
SET0mHL
ANDn
dc
RRA
RES3A
LDHA
SLAH
LDBD
SET5mHL
XORn
ec
XORD
ANDn
68
LDDD
RRL
RES6L
DECD
LDDE
LDLA
LDmHLH
LDEn
b5
SET4D
LDHD
ORH
LDDH
SET6L
BIT1C
BIT5A
SET7C
LDCL
RES2L
LDLC
RLL
BIT7H
BIT7A
INCH
SET5D
RLD
BIT0mHL
INCA
RES2C
ORn
4a
SET7D
RES3B
SET3mHL
ANDH
XORL
NOT
BIT4E
INCA
ANDE
LDHD
SRLD
LDmHLL
ADDAn
9e
ORE
SRLD
ORB
SET3A
LDCD
RLCB
SET2D
XORD
BIT7L
XORB
LDAn
b2
RLCE
LDHn
e8
LDBL
BIT1L
ANDmHL
RLmHL
LDmHLH
LDCE
RRA
RRmHL
RRCL
LDHA
RES1A
SET0mHL
SRAA
BIT4D
INCB
RLE
ADDAmHL
BIT3E
LDAL
SET3mHL
SET0E
BIT0C
NOT
SRAD
SET1B
LDAmBC
BIT1H
RES1H
LDBn
e4
RES6H
RES4H
SET1C
SLAmHL
ADDAC
RES1mHL
RES3L
LDLL
BIT4mHL
INCA
LDAL
LDHL
LDAH
RES6mHL
ORC
ADDAC
LDDmHL
BIT1L
LDAmDE
BIT5C
LDDEnn
7a
59
SRLL
XORA
RES7L
ADCAL
BIT3E
ORD
LDDn
b
INCD
BIT0H
DECL
LDAA
NOP
LDCC
INCC
RES4B
INCH
RES5D
SET7C
LDDL
LDHLnn
a8
53
RLL
BIT6A
LDHE
LDAH
LDCL
RES6C
XORn
26
BIT5A
SLAC
BIT2C
XORA
SLAH
DECH
LDBn
99
RES7mHL
LDHC
RLmHL
ADCAB
LDmHLB
LDCB
BIT3A
LDCD
SLAB
LDDL
BIT2C
SET2L
INCA
BIT6A
LDDn
73
SET3D
DECC
SET6H
LDBn
7d
INCD
LDLmHL
BIT7C
ORH
SRAH
DECA
LDmHLC
ANDA
RES6C
RES6L
SRAE
INCA
DECC
LDAmHL
ORH
ADCAA
ADDAA
SET4D
SLAC
RES0L
RLCmHL
LDDB
LDDA
DECC
XORE
RES6mHL
SCF
RES2B
ADDAE
XORD
BIT2C
ADDAmHL
RRC
LDEB
RES2H
LDAA
RES1B
XORL
LDmHLL
ADDAE
LDAC
LDAn
39
LDBD
INCC
NOT
RRCB
ORE
BIT6A
LDCC
SET6E
SRLL
RES7E
RES5L
SET5L
BIT4D
LDAC
SET1B
LDCB
LDBn
3a
RES0H
LDAmBC
RLCH
ORH
ADDAn
dd
LDCn
c3
BIT3L
LDDL
RRCC
CCF
SCF
RLE
BIT1A
LDDB
RES0A
LDCD
LDDH
SRAE
RRCA
SRAL
LDLC
INCE
BIT7mHL
BIT3E
RRL
RES3C
BIT0D
RLCH
BIT2B
SET6H
RES7C
ORE
SRLB
SET0B
RRA
SWAPmHL
SLAmHL
RES2H
DECB
RES0D
LDCn
a9
LDLn
af
RES6E
INCA
RRA
LDED
SLAE
BIT2C
BIT7mHL
RLD
RES5E
XORB
LDCmHL
LDEA
XORC
ORmHL
SET7C
LDLmHL
BIT2A
NOP
SLAA
RRCB
SET6H
BIT6D
BIT2A
DECL
RES2B
SET2D
LDED
SET6H
LDCC
RES3B
BIT3L
RLCL
ADCAmHL
ADDAC
LDDD
ADCAH
BIT6E
SRLA
SET4L
LDDL
LDLmHL
RES0mHL
LDBD
BIT6B
RLCmHL
BIT4L
ADCAL
DECC
LDDmHL
LDDC
LDmHLL
ADCAA
BIT3D
ADDAB
LDED
LDBE
LDEmHL
LDAmDE
ADDAC
LDHC
LDCA
RES4B
BIT1mHL
INCE
LDAmHL
LDDA
BIT6H
INCD
LDmBCA
XORB
RES1mHL
RES3E
DECC
BIT5mHL
SET1mHL
ORmHL
SET1L
INCB
LDCA
SRLH
SET7B
ANDC
LDDA
BIT1H
ADDAE
DECL
BIT7L
LDAn
7a
SET0B
LDHH
ADDAE
RES0mHL
LDEA
SWAPH
LDCB
SET4E
SET2mHL
SRLH
LDBCnn
8e
d6
RLCE
XORH
LDEmHL
BIT0B
BIT4mHL
RLCD
SET1mHL
BIT5A
LDED
BIT7mHL
ADCAL
ADCAmHL
SRAmHL
ADDAmHL
ADCAC
LDBH
DECA
SET3B
LDAE
LDBC
ANDH
RRA
DECB
LDLE
LDAA
RES5D
DECH
RRA
ADDAB
SET2D
LDBL
RLCA
BIT1B
LDED
LDLH
XORD
SET6mHL
LDDC
XORL
BIT5A
BIT4D
LDAC
LDBB
ORC
SET5D
LDmHLD
INCL
ORn
3d
LDLE
RES5H
ANDE
RRmHL
RRmHL
BIT3L
RRD
LDLn
5f
ADCAB
RES7B
SET7C
SET4C
RES5mHL
RLCmHL
SET2mHL
RES7B
RLD
ADCAH
LDCmHL
BIT5H
RES2B
ANDA
ANDA
SET5A
ANDB
BIT1mHL
LDHmHL
SRLL
BIT3mHL
RES0L
ANDD
LDCn
b4
SET5H
SET1mHL
BIT4L
LDmHLH
SET3D
BIT5H
BIT0H
SET7B
LDHmHL
ORE
BIT1B
SRAC
RES5D
RES2H
LDmDEA
SWAPmHL
ADDAn
70
LDHB
RES3E
NOT
CCF
LDmHLC
RES1C
BIT3H
ADCAA
LDBCnn
f6
9
BIT5D
BIT3C
ORA
SET2mHL
ANDn
2d
SRAH
SWAPD
SRAE
RES0mHL
ANDL
BIT0H
RES3B
XORH
SET2mHL
LDCH
RES3E
BIT0A
RES3C
ORH
RRE
LDAmBC
SRAmHL
SWAPA
RES4D
RES5E
LDEmHL
RES1B
INCA
RRCH
SET6C
ADCAH
LDmHLD
SET3H
SRLA
INCL
INCL
DECA
SET2L
XORC
BIT5E
SWAPH
ORA
BIT0L
RES4D
RES5E
ADDAA
ADDAA
SET0mHL
RES1E
LDLH
LDDEnn
ac
57
ADCAE
RES2mHL
BIT6L
RES6E
SRLB
ADCAn
30
RLCA
LDHC
SLAmHL
XORH
SET5L
LDBn
80
SWAPL
LDDC
CCF
RRL
RLA
RES2mHL
SET6D
DECC
ADDAL
LDLn
e7
SET5L
ORL
BIT6mHL
RLCB
LDCmHL
RES2D
BIT4C
RES1H
RES5C
ADDAA
LDCD
LDHA
INCL
SET3L
SET0A
LDEL
SRAmHL
LDBD
SWAPL
RES0B
BIT6H
LDBL
ADCAmHL
RLCB
LDCmHL
LDBCnn
ad
14
INCD
SLAH
NOP
RES6L
LDEA
LDBL
RRL
ANDB
RES2B
RLB
BIT3D
LDmHLC
SET6L
BIT5C
LDHmHL
RLCE
LDCE
ADCAE
LDmHLB
LDAn
76
RES5mHL
ADCAH
ADDAE
RES7A
LDDEnn
82
61
LDHL
SET2H
SET5A
LDEA
ANDH
BIT7L
XORL
ORL
RES5E
LDLC
SLAC
SET2D
LDBL
BIT3B
LDHn
59
SET3L
RLA
ORC
SET1D
LDDmHL
SET5C
SET7C
CCF
BIT1E
BIT2H
XORH
SET4B
LDDEnn
42
79
SET0L
RES0C
LDHH
LDHn
18
LDCB
LDEH
INCE
LDEn
44
LDHC
RES1B
LDEmHL
ADCAmHL
BIT7B
LDDL
RES5D
SET0A
BIT1mHL
SLAL
SET7H
RES7D
BIT3mHL
BIT7D
LDCmHL
BIT2L
LDDB
INCD
BIT6D
ORB
LDCC
LDDH
RES3L
BIT1mHL
SET4A
SET2mHL
ORmHL
ORD
LDEn
d
SET3B
XORB
DECC
RES1C
SWAPE
RES6L
LDmHLD
BIT1D
LDAB
RES2E
ORA
LDCC
ANDD
LDBB
ANDA
ADDAmHL
ORH
BIT0B
RES2H
LDAC
DECE
LDDmHL
ANDC
SRAD
LDmBCA
ADCAH
RRB
DECE
BIT0B
LDCA
SET4D
LDmDEA
SET4A
RES3D
SLAE
RES7E
XORH
BIT0H
LDAE
SET4L
SET7D
LDAD
RES7H
BIT5D
SLAL
ADDAn
28
RES3L
SET1B
LDAD
BIT4H
ADCAA
LDDn
e7
ORA
BIT7H
RES4mHL
NOP
LDBL
ADCAD
SET3H
RRH
LDBB
RES5E
LDEB
ADDAB
SET7H
RES3A
RLCE
RES7E
ANDE
LDEH
SET5A
RES0L
LDEL
LDDA
RLCE
LDEE
ADDAL
RRCB
SET1D
SRAL
LDEE
RRC
RLCB
LDLC
RES5E
LDEn
c7
ADDAH
ORn
6
LDED
LDAD
SET4A
ORC
SET3mHL
LDmHLL
SET1D
SET0L
RES4A
LDLD
BIT0D
ANDC
BIT4mHL
LDDC
LDBD
RES0C
ADDAA
RRH
BIT5B
ADDAE
RES0C
RLCE
ADDAE
LDHD
DECE
RRCH
BIT2D
SET0L
LDBH
RES0E
SLAB
DECB
RES0C
SET6mHL
RES4E
LDLE
LDBD
LDCC
LDEn
82
RES5L
BIT7mHL
LDBB
RES2C
ORE
LDCB
LDDA
LDCA
SET6mHL
LDCH
BIT7L
LDCn
f6
BIT2D
ORE
BIT0A
SET2B
LDBL
ADCAB
BIT0E
XORE
ADCAn
e0
LDDEnn
90
24
LDCn
b6
LDLn
7a
DECE
LDCL
LDLmHL
BIT1L
SWAPH
ANDD
BIT5C
SET2B
SET6L
BIT6A
LDmBCA
BIT3A
BIT1H
LDLL
XORA
BIT0L
SET3E
SRLB
RES3H
RES2B
LDCL
LDCB
RES5B
BIT2H
XORA
ANDB
SWAPmHL
RES6mHL
LDAD
ADDAH
SRAA
LDBA
ORC
INCH
ADCAA
BIT5B
LDHE
ADCAmHL
BIT2L
SET2mHL
DECB
ADCAmHL
LDAC
LDHB
SET1E
LDLC
BIT2C
ADCAC
RLCE
LDLmHL
SET5L
LDHn
6a
LDBA
RLA
LDEn
65
SET4A
RES3mHL
RLCA
RLB
LDEA
SET2B
BIT7E
RES6A
LDBmHL
SLAmHL
LDmBCA
RES4E
BIT5C
BIT0H
BIT2B
DECL
ADDAA
SET0D
ADDAB
XORC
RRE
XORA
LDHC
LDHL
SET6A
SET0L
LDBB
INCH
BIT0C
RES6H
BIT0H
ADDAD
LDBL
INCE
RRD
ANDL
RES6D
BIT3A
LDDn
4d
BIT1mHL
RES5H
SET0A
RRC
ORL
RES0B
SET4A
ANDL
RLD
BIT6E
LDCL
DECE
ADCAB
NOT
SET0L
SET1C
ORE
ADCAD
BIT6C
LDLmHL
ADCAB
RES4E
LDLn
dc
RLH
LDBD
ANDL
LDCE
RRCB
ANDD
SET6E
BIT6mHL
RRCD
RRC
SET2L
BIT2D
SRLD
RES7E
RES0B
INCL
BIT3A
ORmHL
LDHA
BIT2mHL
ADDAD
SET4B
ORB
RRCC
LDDH
XORB
LDDL
RRCL
LDBH
BIT6A
ANDL
ORmHL
RLCE
ORD
SET6D
BIT6mHL
LDBn
d5
LDBCnn
5b
95
ORA
SLAA
LDEmHL
ADDAn
3c
SET0C
BIT3A
SET6mHL
BIT5C
SWAPB
SET5C
RRCC
RRA
LDBE
BIT0C
LDAmDE
LDLmHL
LDHE
BIT0L
RES4H
BIT2A
BIT2A
RES2B
ADCAH
SLAD
RES2B
LDAmDE
SET3H
LDAC
LDAE
LDHH
RES1E
LDBB
SWAPmHL
BIT5H
SWAPE
INCL
LDLmHL
SET4D
BIT1C
RLCE
LDEH
LDLE
RES1H
ADCAA
SRAD
ADCAC
ADDAC
SET6D
BIT1L
SRAE
LDAL
RLCA
RRE
LDDE
RES6E
RES4B
BIT4D
LDLB
RES6E
RLCA
ORA
SRLB
XORL
LDmBCA
ORL
LDBCnn
13
eb
RRH
SET6D
BIT2A
LDBE
SET0mHL
LDDD
SET4mHL
XORL
SET6E
INCH
LDLH
LDDE
LDAH
LDmHLD
ADCAmHL
RES0mHL
ORn
fb
LDEB
RES2D
ORB
ADCAH
BIT4A
DECE
BIT1E
DECC
SET4C
BIT0mHL
SET1H
RES3mHL
RES7A
LDmHLL
ADDAA
RES5B
RES2mHL
BIT4L
LDmHLD
RES1D
LDLn
a3
LDEC
SET4D
LDAE
XORE
INCC
LDAmDE
NOP
SWAPA
BIT4H
ORn
d2
ORC
SET1D
INCE
LDmHLC
SET5A
SET2B
LDBB
SLAC
RES0L
LDLA
BIT6L
INCA
RES2D
ORH
LDDC
XORD
LDBmHL
LDDB
RES1H
BIT1C
ADCAC
SET2H
XORmHL
RES4D
SET2L
BIT7E
ADDAD
BIT7H
XORn
1a
LDBmHL
ADCAA
RRA
RLCE
LDAE
NOP
LDLD
LDAn
cf
DECB
LDBCnn
61
cc
LDmDEA
LDHn
b5
RLCD
RES1L
SET0B
LDDn
4d
RES1A
LDBE
LDDB
LDDmHL
ADCAD
RLCB
LDHn
8d
RLCA
LDCE
ANDE
SET5C
SET7L
SET5E
BIT7H
LDBmHL
BIT3D
LDAD
RES3D
LDCL
LDLH
ADCAH
BIT1B
LDBL
ADCAC
RES0C
SWAPB
RES2B
RLL
LDDD
LDEC
RRCL
INCC
LDHLnn
49
1e
LDDL
RRmHL
SET1D
LDEH
BIT5C
RES0C
SWAPmHL
LDmHLH
LDEn
4f
RES3C
BIT2L
LDAn
6a
LDHE
LDHLnn
80
83
LDAC
DECD
SRLB
LDmHLB
SRAmHL
RES0C
ADDAL
ADDAE
SET7C
LDCD
RLCH
SRAA
SET2C
RES0H
RLCE
RRCE
ADDAE
LDLL
RRA
LDEL
RES4H
ADCAH
SRAmHL
RES4L
RRH
SET6E
LDCL
LDHB
RES2C
BIT5mHL
RES3L
BIT3C
ADDAn
14
LDLD
RRA
LDDL
LDED
SET2E
SRLmHL
BIT0C
RES2B
ANDL
LDmHLD
SET5H
SET0H
SRLB
LDHn
78
SRLA
RRCH
BIT2D
ANDL
BIT4A
INCH
RES7mHL
SET3D
RLA
LDHH
SRAmHL
ADCAC
ORE
SWAPD
RES4A
BIT0B
ADDAB
XORn
59
LDBD
ADDAB
LDBH
SET3C
RES3E
LDDn
26
BIT6mHL
SWAPC
STOP | low | 0.527459 | 110 |
#!/bin/bash
#
# Author: Constantin MASSON
#
# Start the space invaders program
# create a folder build with .class, delete old if exists
#
# EXECUTE
# Just set the execut right and execute this script
# With j param, a jar will be created as well
#
declare param_j # Used for jar creation
# *****************************************************************************
# General program functions
# *****************************************************************************
#
# Function to process parameters
#
function process_parameters(){
while getopts "xj" optname; do
case "$optname" in
"j") param_j=1 ;;
"?") echo "Error"; exit 0;;
":") echo "Error"; exit 0;;
*) echo "Error"; exit 0;;
esac
done
return $OPTIND
}
#
# Launch program (javac + java)
# Call jar creation if required
#
function main(){
process_parameters "$@"
create_build_folder
javac -d build -sourcepath src src/com/spaceinvaders/main/Main.java
java -cp build com.spaceinvaders.main.Main &
# If jar required, create it
if [[ ! -z $param_j ]];then
create_jar
fi
}
# *****************************************************************************
# Function for folders management
# *****************************************************************************
#
# Create the jar file
# In order to do that, manifest file will be created as well
#
function create_jar(){
# First, create the manifest file
echo "Manifest-Version: 1.0" > "build/manifest.mf"
echo "Main-Class: com.spaceinvaders.main.Main" >> "build/manifest.mf"
echo -e "\n\n\n" >> "build/manifest.mf"
# Then, create the jar file
cd build #place in build for jar creation
jar -cfm spaceinvaders.jar manifest.mf com/* sounds/*
cd .. #go back
cp build/spaceinvaders.jar . #copy root directory
# Note: img/* is not required since the img are recovered from data/img folder
}
# *****************************************************************************
# Function for folders management
# *****************************************************************************
# Create the build folder
function create_build_folder(){
if [[ -e "build" ]];then
rm -rf build
fi
mkdir build
cp -r data/sounds build/ #copy sounds
cp -r data/img build/ #copy images
}
main "$@" # START PRORAM
| high | 0.273032 | 111 |
<!-- Generated by pkgdown: do not edit by hand -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Method dispatch page for component_width — component_width-dispatch • ComplexHeatmap</title>
<!-- jquery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha256-916EbMg70RQy9LHiGkXzG8hSg9EdNy97GazNG/aiY1w=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha256-U5ZEeKfGNOja007MMD3YBI0A3OSZOQbeG6z2f2Y0hu8=" crossorigin="anonymous"></script>
<!-- Font Awesome icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.1/css/all.min.css" integrity="sha256-nAmazAk6vS34Xqo0BSrTb+abbtFlgsFK7NKSi6o7Y78=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.1/css/v4-shims.min.css" integrity="sha256-6qHlizsOWFskGlwVOKuns+D1nB6ssZrHQrNj1wGplHc=" crossorigin="anonymous" />
<!-- clipboard.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.4/clipboard.min.js" integrity="sha256-FiZwavyI2V6+EXO1U+xzLG3IKldpiTFf3153ea9zikQ=" crossorigin="anonymous"></script>
<!-- headroom.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/headroom/0.9.4/headroom.min.js" integrity="sha256-DJFC1kqIhelURkuza0AvYal5RxMtpzLjFhsnVIeuk+U=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/headroom/0.9.4/jQuery.headroom.min.js" integrity="sha256-ZX/yNShbjqsohH1k95liqY9Gd8uOiE1S4vZc+9KQ1K4=" crossorigin="anonymous"></script>
<!-- pkgdown -->
<link href="../pkgdown.css" rel="stylesheet">
<script src="../pkgdown.js"></script>
<meta property="og:title" content="Method dispatch page for component_width — component_width-dispatch" />
<meta property="og:description" content="Method dispatch page for component_width." />
<meta name="twitter:card" content="summary" />
<!-- mathjax -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js" integrity="sha256-nvJJv9wWKEm88qvoQl9ekL2J+k/RWIsaSScxxlsrv8k=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/config/TeX-AMS-MML_HTMLorMML.js" integrity="sha256-84DKXVJXs0/F8OTMzX4UR909+jtl4G7SPypPavF+GfA=" crossorigin="anonymous"></script>
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container template-reference-topic">
<header>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<span class="navbar-brand">
<a class="navbar-link" href="../index.html">ComplexHeatmap</a>
<span class="version label label-default" data-toggle="tooltip" data-placement="bottom" title="Released version">2.1.0</span>
</span>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="../index.html">
<span class="fas fa fas fa-home fa-lg"></span>
</a>
</li>
<li>
<a href="../reference/index.html">Reference</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Articles
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="../articles/complex_heatmap.html">UNKNOWN TITLE</a>
</li>
<li>
<a href="../articles/most_probably_asked_questions.html">UNKNOWN TITLE</a>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="https://github.com/jokergoo/ComplexHeatmap">
<span class="fab fa fab fa-github fa-lg"></span>
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
</header>
<div class="row">
<div class="col-md-9 contents">
<div class="page-header">
<h1>Method dispatch page for component_width</h1>
<div class="hidden name"><code>component_width-dispatch.rd</code></div>
</div>
<div class="ref-description">
<p>Method dispatch page for <code>component_width</code>.</p>
</div>
<h2 class="hasAnchor" id="dispatch"><a class="anchor" href="#dispatch"></a>Dispatch</h2>
<p><code>component_width</code> can be dispatched on following classes:</p>
<ul>
<li><p><code><a href='component_width-HeatmapList-method.rd.html'>component_width,HeatmapList-method</a></code>, <code><a href='HeatmapList-class.rd.html'>HeatmapList-class</a></code> class method</p></li>
<li><p><code><a href='component_width-Heatmap-method.rd.html'>component_width,Heatmap-method</a></code>, <code><a href='Heatmap-class.rd.html'>Heatmap-class</a></code> class method</p></li>
</ul>
<h2 class="hasAnchor" id="examples"><a class="anchor" href="#examples"></a>Examples</h2>
<pre class="examples"><div class='input'><span class='co'># no example</span>
<span class='kw'>NULL</span></div><div class='output co'>#> NULL</div><div class='input'>
</div></pre>
</div>
<div class="col-md-3 hidden-xs hidden-sm" id="sidebar">
<h2>Contents</h2>
<ul class="nav nav-pills nav-stacked">
<li><a href="#dispatch">Dispatch</a></li>
<li><a href="#examples">Examples</a></li>
</ul>
</div>
</div>
<footer>
<div class="copyright">
<p>Developed by Zuguang Gu.</p>
</div>
<div class="pkgdown">
<p>Site built with <a href="https://pkgdown.r-lib.org/">pkgdown</a> 1.4.1.</p>
</div>
</footer>
</div>
</body>
</html>
| low | 0.681218 | 112 |
[CmdletBinding()]
param (
[Parameter(ParameterSetName="Publish")]
[switch]
$Publish,
[Parameter(ParameterSetName="Publish")]
[string]
$NuGetApiKey
)
$ErrorActionPreference = 'Stop'
$manifest = Invoke-Expression (Get-Content $PSScriptRoot\src\Pscx\Pscx.psd1 -Raw)
$version = $manifest.ModuleVersion
"Version is: $version, prerelease is: $($manifest.PrivateData.PSData.Prerelease)"
$modulePath = Join-Path (Split-Path $profile.CurrentUserAllHosts -Parent) Modules\Pscx\$version
if (Test-Path -LiteralPath $modulePath) {
"Removing dir: $modulePath"
Remove-Item $modulePath -Recurse -Force
}
$outPath = Join-Path $PSScriptRoot src\Pscx\bin\Release -Resolve
& {
$VerbosePreference = 'Continue'
"Copying output from $outPath to $modulePath"
Copy-Item $outPath $modulePath -Recurse
Remove-Item $modulePath\*.pdb
Remove-Item $modulePath\PowerCollections.xml
Remove-Item $modulePath\Trinet.Core.IO.Ntfs.xml
Remove-Item $modulePath\x86 -Recurse -Force -ErrorAction Ignore
Remove-Item $modulePath\x64 -Recurse -Force -ErrorAction Ignore
}
if ($Publish) {
Publish-Module -Name Pscx -AllowPrerelease -NuGetApiKey $NuGetApiKey
}
| high | 0.561445 | 113 |
deprecated
username
self greaseDeprecatedApi: 'WAUrl>>#username'
details: 'Use WAUrl>>#user.'.
^ self user | low | 0.840648 | 114 |
;;;
;;; Copyright (c) 2006-2008 uim Project http://code.google.com/p/uim/
;;;
;;; All rights reserved.
;;;
;;; 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 authors nor the names of its contributors
;;; may be used to endorse or promote products derived from this software
;;; without specific prior written permission.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND
;;; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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.
;;;;
(require "util.scm")
(require-custom "chewing-custom.scm")
(require-custom "chewing-key-custom.scm")
;; widgets and actions
;; widgets
(define chewing-widgets '(widget_chewing_input_mode
widget_chewing_shape_mode))
;; default activity for each widgets
(define default-widget_chewing_input_mode 'action_chewing_off)
(define default-widget_chewing_shape_mode 'action_chewing_halfshape)
;; actions of widget_chewing_input_mode
(define chewing-input-mode-actions
'(action_chewing_off
action_chewing_on))
;; actions of widget_chewing_shape_mode
(define chewing-shape-mode-actions
'(action_chewing_halfshape
action_chewing_fullshape))
;;; implementations
(define chewing-halfshape-mode 0)
(define chewing-fullshape-mode 1)
(define chewing-kbd-layout-alist
'((chewing-kbd-default . 0)
(chewing-kbd-hsu . 1)
(chewing-kbd-ibm . 2)
(chewing-kbd-gin-yieh . 3)
(chewing-kbd-et . 4)
(chewing-kbd-et26 . 5)
(chewing-kbd-dvorak . 6)
(chewing-kbd-dvorak-hsu . 7)
(chewing-kbd-dachen-cp26 . 8)
(chewing-kbd-hanyu-pinyin . 9)))
(define chewing-lib-initialized? #f)
(register-action 'action_chewing_off
(lambda (mc)
(list
'off
"-"
(N_ "off")
(N_ "Direct Input Mode")))
(lambda (mc)
(not (chewing-context-on mc)))
(lambda (mc)
(chewing-context-set-on! mc #f)))
(register-action 'action_chewing_on
(lambda (mc)
(let* ((im (chewing-context-im mc))
(name (symbol->string (im-name im))))
(list
'on
"O"
(N_ "on")
(string-append name (N_ " Mode")))))
(lambda (mc)
(chewing-context-on mc))
(lambda (mc)
(chewing-context-set-on! mc #t)))
(register-action 'action_chewing_halfshape
(lambda (mc)
(list
'zh-half-shape
"H"
(N_ "Half shape")
(N_ "Half Shape Mode")))
(lambda (mc)
(let ((mode (chewing-lib-get-shape-mode
(chewing-context-mc-id mc))))
(if (or (not mode)
(= mode 0))
#t
#f)))
(lambda (mc)
(chewing-lib-set-shape-mode (chewing-context-mc-id mc)
chewing-halfshape-mode)))
(register-action 'action_chewing_fullshape
(lambda (mc)
(list
'zh-full-shape
"F"
(N_ "Full shape")
(N_ " Full Shape Mode")))
(lambda (mc)
(let ((mode (chewing-lib-get-shape-mode
(chewing-context-mc-id mc))))
(if (and
mode
(= mode 1))
#t
#f)))
(lambda (mc)
(chewing-lib-set-shape-mode (chewing-context-mc-id mc)
chewing-fullshape-mode)))
;; Update widget definitions based on action configurations. The
;; procedure is needed for on-the-fly reconfiguration involving the
;; custom API
(define chewing-configure-widgets
(lambda ()
(register-widget 'widget_chewing_input_mode
(activity-indicator-new chewing-input-mode-actions)
(actions-new chewing-input-mode-actions))
(register-widget 'widget_chewing_shape_mode
(activity-indicator-new chewing-shape-mode-actions)
(actions-new chewing-shape-mode-actions))))
(define chewing-context-rec-spec
(append
context-rec-spec
'((mc-id #f)
(on #f)
(showing-candidate #f)
(commit-raw #f))))
(define chewing-context-alist '())
(define-record 'chewing-context chewing-context-rec-spec)
(define chewing-context-new-internal chewing-context-new)
(define chewing-context-new
(lambda (id im name)
(let ((mc (chewing-context-new-internal id im)))
(if (symbol-bound? 'chewing-lib-init)
(set! chewing-lib-initialized? (chewing-lib-init)))
(if chewing-lib-initialized?
(begin
(chewing-context-set-mc-id! mc (chewing-lib-alloc-context))
(set! chewing-context-alist
(alist-replace
(list (chewing-context-mc-id mc) mc) chewing-context-alist))))
(chewing-context-set-widgets! mc chewing-widgets)
mc)))
(define chewing-find-mc
(lambda (mc-id)
(car (cdr (assoc mc-id chewing-context-alist)))))
(define chewing-update-preedit
(lambda (mc)
(if (chewing-context-commit-raw mc)
(chewing-context-set-commit-raw! mc #f)
(im-update-preedit mc))))
(define chewing-proc-direct-state
(lambda (mc key key-state)
(if (chewing-on-key? key key-state)
(chewing-context-set-on! mc #t)
(chewing-commit-raw mc))))
(define chewing-activate-candidate-selector
(lambda (mc-id nr nr-per-page)
(let ((mc (chewing-find-mc mc-id)))
(im-activate-candidate-selector mc nr nr-per-page))))
(define chewing-deactivate-candidate-selector
(lambda (mc-id)
(let ((mc (chewing-find-mc mc-id)))
(im-deactivate-candidate-selector mc))))
(define chewing-shift-page-candidate
(lambda (mc-id dir)
(let ((mc (chewing-find-mc mc-id)))
(im-shift-page-candidate mc dir))))
(define chewing-pushback-preedit
(lambda (mc-id attr str)
(let ((mc (chewing-find-mc mc-id)))
(im-pushback-preedit mc attr str))))
(define chewing-clear-preedit
(lambda (mc-id)
(let ((mc (chewing-find-mc mc-id)))
(im-clear-preedit mc))))
(define chewing-commit
(lambda (mc-id str)
(let ((mc (chewing-find-mc mc-id)))
(im-clear-preedit mc)
(im-commit mc str))))
(define chewing-get-kbd-layout
(lambda ()
(cdr (assq chewing-kbd-layout chewing-kbd-layout-alist))))
(define chewing-commit-raw
(lambda (mc)
(im-commit-raw mc)
(chewing-context-set-commit-raw! mc #t)))
(define chewing-press-key
(lambda (mc key key-state pressed)
(let ((mid (chewing-context-mc-id mc))
(ukey (if (symbol? key)
(chewing-lib-keysym-to-ukey key)
key)))
(chewing-lib-press-key mid ukey key-state pressed))))
(define chewing-init-handler
(lambda (id im arg)
(chewing-context-new id im arg)))
(define chewing-release-handler
(lambda (mc)
(let ((mc-id (chewing-context-mc-id mc)))
(if (number? mc-id)
(begin
(chewing-lib-free-context mc-id)
(set! chewing-context-alist
(alist-delete mc-id chewing-context-alist =)))))))
(define chewing-press-key-handler
(lambda (mc key key-state)
(if (chewing-context-on mc)
(if (chewing-press-key mc key key-state #t)
#f
(if (chewing-off-key? key key-state)
(let ((mid (chewing-context-mc-id mc)))
(chewing-lib-flush mid)
(chewing-reset-handler mc)
(im-clear-preedit mc)
(im-deactivate-candidate-selector mc)
(chewing-context-set-on! mc #f))
(im-commit-raw mc)))
(chewing-proc-direct-state mc key key-state))
(chewing-update-preedit mc)))
(define chewing-release-key-handler
(lambda (mc key key-state)
(if (or
(ichar-control? key)
(not (chewing-context-on mc)))
(chewing-commit-raw mc))))
(define chewing-reset-handler
(lambda (mc)
(let ((mid (chewing-context-mc-id mc)))
(chewing-lib-reset-context mid))))
(define chewing-focus-in-handler
(lambda (mc)
(let ((mid (chewing-context-mc-id mc)))
(if (chewing-context-on mc)
(begin
(chewing-lib-focus-in-context mid)
(im-update-preedit mc))))))
(define chewing-focus-out-handler
(lambda (mc)
(let ((mid (chewing-context-mc-id mc)))
(if (chewing-context-on mc)
(begin
(chewing-lib-focus-out-context mid)
(im-update-preedit mc))))))
(define chewing-heading-label-char-list
(lambda (style)
(cond
((eq? style 'chewing-cand-selection-asdfghjkl)
'("A" "S" "D" "F" "G" "H" "J" "K" "L" ";"))
(else
'("1" "2" "3" "4" "5" "6" "7" "8" "9" "0")))))
(define chewing-get-candidate-handler
(lambda (mc idx accel-enum-hint)
(let* ((mid (chewing-context-mc-id mc))
(cand (chewing-lib-get-nth-candidate mid idx))
(page-idx (remainder idx
(chewing-lib-get-nr-candidates-per-page mid)))
(char-list (chewing-heading-label-char-list
chewing-candidate-selection-style))
(label (if (< page-idx (length char-list))
(nth page-idx char-list)
"")))
(list cand label ""))))
(define chewing-set-candidate-index-handler
(lambda (mc idx)
#f))
(register-im
'chewing
"zh_TW:zh_HK:zh_SG"
"UTF-8"
chewing-im-name-label
chewing-im-short-desc
#f
chewing-init-handler
chewing-release-handler
context-mode-handler
chewing-press-key-handler
chewing-release-key-handler
chewing-reset-handler
chewing-get-candidate-handler
chewing-set-candidate-index-handler
context-prop-activate-handler
#f
chewing-focus-in-handler
chewing-focus-out-handler
#f
#f
)
(chewing-configure-widgets)
| high | 0.664246 | 115 |
grammar Rust;
@header {
package rustless.ast;
import rustless.*;
import rustless.command.*;
import java.util.Map;
import java.util.Arrays;
}
repl returns [Command cmd]
: 'quit' EOF { System.exit(0); }
| statement EOF { $cmd=$statement.cmd; }
;
module returns [List<Command> cmds]
: { $cmds=new ArrayList(); } (statement ';'? { $cmds.add($statement.cmd); })* EOF
;
function: 'fn' ID '(' argumentDeclarationList ')' block (';'|) ;
block returns [Command cmd] locals[List<Command> cmds]
: '{' { $cmds=new ArrayList(); } (statement ';'? { $cmds.add($statement.cmd); } )* '}' {
$cmd=new Block($cmds); }
;
statement returns [Command cmd]
: declaration { $cmd=$declaration.cmd; }
| ID '=' expr { $cmd=new Assign($ID.text, $expr.cmd); }
| expr { $cmd=$expr.cmd; }
;
declaration returns [Command cmd] locals [boolean mut, Command value]
: 'let' ('mut' {$mut=true;})? ID ( '=' a=expr { $value=$a.cmd; })?
{ $cmd=new Declare($ID.text,$mut,null,$value); }
;
functionCall returns [Command cmd]
: ID '(' argumentList ')' { $cmd=new Call($ID.text,$argumentList.arg); }
;
macroCall returns [Command cmd]
: ID '!' '(' argumentList ')' { throw new ParseCancellationException("Macros are not implemented"); }
;
argumentList returns [List<Command> arg]
: { $arg=new ArrayList(); } a=argument { $arg.add($a.cmd); } ( ',' b=argument { $arg.add($b.cmd); } )*
;
argument returns [Command cmd]: expr { $cmd=$expr.cmd; } ;
argumentDeclarationList
:
| arg+=argumentDeclaration ( ',' arg+=argumentDeclaration )*
;
argumentDeclaration: ID ;
condition returns [Command cmd] locals [Command negative]
: 'if' c=expr p=block ('else' n=block { $negative=$n.cmd; })? { $cmd=new Condition($c.cmd,$p.cmd,$negative); }
;
expr returns [Command cmd]
: ID { $cmd=new Access($ID.text); }
| literal { $cmd=$literal.cmd; }
| '(' expr ')' { $cmd=$expr.cmd; }
| functionCall { $cmd=$functionCall.cmd; }
| macroCall { $cmd=$macroCall.cmd; }
| block { $cmd=$block.cmd; }
| condition { $cmd=$condition.cmd; }
| op=('-'|'!') a=expr { $cmd=new Call($op.text,$a.cmd); }
| a=expr op=('*'|'/'|'%') b=expr { $cmd=new Call($op.text,$a.cmd,$b.cmd); }
| a=expr op=('+'|'-') b=expr { $cmd=new Call($op.text,$a.cmd,$b.cmd); }
| a=expr op=('<<'|'>>') b=expr { $cmd=new Call($op.text,$a.cmd,$b.cmd); }
| a=expr op='&' b=expr { $cmd=new Call($op.text,$a.cmd,$b.cmd); }
| a=expr op='^' b=expr { $cmd=new Call($op.text,$a.cmd,$b.cmd); }
| a=expr op='|' b=expr { $cmd=new Call($op.text,$a.cmd,$b.cmd); }
| a=expr op=('<'|'>'|'>='|'<='|'=='|'!=') b=expr { $cmd=new Call($op.text,$a.cmd,$b.cmd); }
| a=expr op='&&' b=expr { $cmd=new Call($op.text,$a.cmd,$b.cmd); }
| a=expr op='||' b=expr { $cmd=new Call($op.text,$a.cmd,$b.cmd); }
;
literal returns [Command cmd]
: FLOAT { $cmd=new Literal(new Value(Double.parseDouble($text))); }
| INT { $cmd=new Literal(new Value(Integer.parseInt($text))); }
| STRING { $cmd=new Literal(new Value($text)); }
| TRUE { $cmd=new Literal(new Value(true)); }
| FALSE { $cmd=new Literal(new Value(false)); }
;
TRUE: 'true' ;
FALSE: 'false' ;
ID : [a-zA-Z][a-zA-Z0-9]* ;
fragment NEWLINE : [\r]?[\n] ;
INT : [0-9]+ ;
FLOAT : [0-9]+([.][0-9]+)?([Ee][-]?[0-9]+)? ;
STRING : '"' ( ESC | ~[\\"] )* '"';
fragment ESC : '\\"' | '\\\\' ;
WS : [ \n\r\t]+ -> channel(HIDDEN);
ErrorTocken : . ; | high | 0.741751 | 117 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.lookup.rest
class SchemaUtil {
static final String SIMPLE = SchemaUtil.class.getResourceAsStream("/simple.avsc").text
static final String COMPLEX = SchemaUtil.class.getResourceAsStream("/complex.avsc").text
}
| high | 0.663525 | 118 |
"
Root folder explorer.
Allows to explore the root folder of a model (left panel) and shows the entities contained in each file (right panel).
- Follow: Receives a MooseModel that has a root folder
- Highlight: <TODO>
Entities if present and visible.
Could highlight the file owning a received entity.
- Propagate: <TODO>
"
Class {
#name : #MiFilesBrowser,
#superclass : #MiAbstractFamixBrowser,
#instVars : [
'tree',
'treeEntity'
],
#category : #'MooseIDE-Famix-FilesBrowser'
}
{ #category : #specs }
MiFilesBrowser class >> defaultSpec [
^ super defaultSpec
add:
(SpBoxLayout newHorizontal
add: #tree;
add: #treeEntity;
yourself);
yourself
]
{ #category : #'world menu' }
MiFilesBrowser class >> menuCommandOn: aBuilder [
<worldMenu>
<miBrowsers>
(aBuilder item: #FilesBrowser)
parent: (self toolbarFamixName);
label: (self title);
icon: (self iconNamed: #mooseFolder);
help: (self helpMessage);
order: 3;
action: [ self open ]
]
{ #category : #'instance creation' }
MiFilesBrowser class >> newModel [
^ MiFilesModel new
]
{ #category : #'instance creation' }
MiFilesBrowser class >> open [
<script>
^ super open
]
{ #category : #specs }
MiFilesBrowser class >> title [
^ 'Files'
]
{ #category : #testing }
MiFilesBrowser >> canFollowEntity: anObject [
^ anObject isMooseObject and: [
anObject isMooseModel and: [
anObject rootFolder isNotNil and: [
anObject rootFolder asFileReference exists ] ] ]
]
{ #category : #initialization }
MiFilesBrowser >> computeItemsInFileReference: aFileReference [
"isChildOf: can bug see issue https://github.com/pharo-project/pharo/issues/5720"
^ (self model mooseModel allUsing: FamixTFileAnchor)
select: [ :anchor | anchor element isClass and: [ anchor element isAnonymousClass not and: [ anchor fileReference canonicalize isChildOf: self model fileReference ] ] ]
thenCollect: [ :anchor | anchor element ]
]
{ #category : #initialization }
MiFilesBrowser >> connectPresenters [
super connectPresenters.
tree whenSelectionChangedDo: [ :selected |
( selected selectedItem isNotNil and:
[ selected selectedItem hasChildren] )
ifTrue: [
self selectFileReference: selected selectedItem.
treeEntity roots: (self computeItemsInFileReference: self model fileReference) ] ]
]
{ #category : #actions }
MiFilesBrowser >> followEntity: anEntity [
self model mooseModel: anEntity.
self selectFileReference: anEntity rootFolder asFileReference.
self updateWindowTitle
]
{ #category : #initialization }
MiFilesBrowser >> initializePresenters [
self initializeTreeTable.
treeEntity := self newTreeTable.
treeEntity
addColumn: (SpCompositeTableColumn new
addColumn: ((SpImageTableColumn evaluated: #midasIcon)
width: 20;
yourself);
addColumn: (SpStringTableColumn evaluated: #name);
yourself);
children: [ :aClass | aClass children asOrderedCollection ];
beMultipleSelection;
beResizable.
treeEntity whenSelectionChangedDo: [ :selected |
selected selectedItems ifNotEmpty: [
self freezeDuring: [
selected selectedItems size = 1
ifTrue: [
self buses do: [ :bus |
bus globallySelect: selected selectedItem ] ]
ifFalse: [
| mooseGroup |
mooseGroup := MooseGroup withAll: selected selectedItems.
self buses do: [ :bus | bus globallySelect: mooseGroup ] ] ] ] ]
]
{ #category : #initialization }
MiFilesBrowser >> initializeTreeTable [
tree := self newTable.
tree
addColumn:
(SpCompositeTableColumn new
addColumn:
(SpStringTableColumn evaluated: [ :fileRef |
(fileRef isChildOf: self model fileReference)
ifTrue: [ fileRef basename ] ifFalse: [ '..' ] ]);
yourself);
beResizable
]
{ #category : #accessing }
MiFilesBrowser >> miSelectedItem [
^ model mooseModel
]
{ #category : #refreshing }
MiFilesBrowser >> refresh [
tree items: { self model fileReference parent }
, self model fileReference directories
, self model fileReference files
]
{ #category : #actions }
MiFilesBrowser >> selectFileReference: aFileReference [
self model fileReference: aFileReference.
self refresh
]
{ #category : #refreshing }
MiFilesBrowser >> updateWindowTitle [
self
withWindowDo: [ :window |
window
title: self class title , ' of ' , self model mooseModel name , ' model' ]
]
| medium | 0.60437 | 119 |
// Copyright (c) 2015-2020 Vladimir Schneider <vladimir.schneider@gmail.com> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.language.folding
import com.intellij.lang.folding.FoldingDescriptor
import com.intellij.openapi.editor.Document
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.vladsch.md.nav.language.api.MdFoldingBuilderProvider
import com.vladsch.md.nav.language.api.MdFoldingVisitorHandler
import com.vladsch.md.nav.psi.element.*
import com.vladsch.md.nav.psi.util.MdNodeVisitor
import com.vladsch.md.nav.psi.util.MdPsiImplUtil
import com.vladsch.md.nav.psi.util.MdVisitHandler
import com.vladsch.md.nav.psi.util.MdVisitor
import com.vladsch.md.nav.util.*
import com.vladsch.md.nav.vcs.GitHubLinkResolver
import com.vladsch.plugin.util.image.ImageUtils
import com.vladsch.plugin.util.maxLimit
import java.util.*
class MdFoldingVisitor(
private val root: PsiElement,
document: Document,
private val descriptors: ArrayList<FoldingDescriptor>,
quick: Boolean,
private val defaultPlaceHolderText: String
) : MdFoldingVisitorHandler {
private val myResolver = GitHubLinkResolver(root)
private val myHeadingRanges = HashMap<MdHeaderElement, TextRange>()
private val myOpenHeadingRanges = Array<TextRange?>(6) { null }
private val myOpenHeadings = Array<MdHeaderElement?>(6) { null }
private val myRootText = document.charsSequence
private val myVisitor: MdNodeVisitor = MdNodeVisitor()
init {
addHandlers(
// // does not do anything in basic
// MdVisitHandler(MdSimToc::class.java, this::fold),
MdVisitHandler(MdJekyllFrontMatterBlock::class.java, this::fold),
MdVisitHandler(MdUnorderedListItem::class.java, this::fold),
MdVisitHandler(MdOrderedListItem::class.java, this::fold),
MdVisitHandler(MdAtxHeader::class.java, this::fold),
MdVisitHandler(MdSetextHeader::class.java, this::fold),
MdVisitHandler(MdBlockComment::class.java, this::fold),
MdVisitHandler(MdInlineComment::class.java, this::fold),
MdVisitHandler(MdVerbatim::class.java, this::fold)
)
if (!quick) {
addHandlers(
MdVisitHandler(MdAutoLinkRef::class.java, this::fold),
MdVisitHandler(MdImageLinkRef::class.java, this::fold),
MdVisitHandler(MdJekyllIncludeLinkRef::class.java, this::fold),
MdVisitHandler(MdLinkRef::class.java, this::fold),
MdVisitHandler(MdReferenceLinkRef::class.java, this::fold),
MdVisitHandler(MdWikiLinkRef::class.java, this::fold)
)
}
// allow extensions to add theirs
MdFoldingBuilderProvider.EXTENSIONS.value.forEach { it.extendFoldingHandler(this, quick) }
}
override fun addHandlers(handlers: MutableCollection<MdVisitHandler<PsiElement>>): MdNodeVisitor = myVisitor.addHandlers(handlers)
override fun addHandlers(vararg handlers: MdVisitHandler<*>): MdNodeVisitor = myVisitor.addHandlers(handlers)
override fun addHandlers(vararg handlers: Array<out MdVisitHandler<PsiElement>>): MdNodeVisitor = myVisitor.addHandlers(*handlers)
override fun addHandler(handler: MdVisitHandler<*>): MdNodeVisitor = myVisitor.addHandler(handler)
override fun visitNodeOnly(element: PsiElement): Unit = myVisitor.visitNodeOnly(element)
override fun visit(element: PsiElement): Unit = myVisitor.visit(element)
override fun visitChildren(element: PsiElement): Unit = myVisitor.visitChildren(element)
override fun getRootText(): CharSequence = myRootText
override fun getDefaultPlaceHolderText(): String = defaultPlaceHolderText
override fun addDescriptor(descriptor: FoldingDescriptor): Boolean = descriptors.add(descriptor)
override fun getFoldingHandler(klass: Class<out PsiElement>): MdVisitor<PsiElement>? = myVisitor.getAction(klass)
override fun <T : PsiElement> delegateFoldingHandler(forClass: Class<T>, toClass: Class<out T>): Boolean {
val handler = myVisitor.getAction(forClass) ?: return false
myVisitor.addHandler(MdVisitHandler(toClass) { handler.visit(it) })
return true
}
fun buildFoldingRegions(root: PsiElement) {
myVisitor.visit(root)
// close any open headings at end of file
closeOpenHeadings()
}
private fun fold(element: MdVerbatim) {
val content = element.contentElement ?: return
val range = content.textRange
if (!range.isEmpty) {
addDescriptor(object : FoldingDescriptor(element.node, TextRange(if (range.startOffset > 0) range.startOffset - 1 else range.startOffset, range.endOffset), null) {
override fun getPlaceholderText(): String? {
return null
}
})
}
}
private fun fold(element: MdLinkRefElement) {
if (!element.textRange.isEmpty) {
val linkRef = MdPsiImplUtil.getLinkRef(element.parent)
if (linkRef != null) {
val filePath = linkRef.filePath
if (ImageUtils.isPossiblyEncodedImage(filePath)) {
val collapsedText = "data:image/$defaultPlaceHolderText"
addDescriptor(object : FoldingDescriptor(element, element.textRange) {
override fun getPlaceholderText(): String? {
return collapsedText
}
})
} else {
if ((linkRef.isURL || linkRef.isFileURI) && !myResolver.isExternalUnchecked(linkRef)) {
val reference = element.reference
if (reference != null) {
val targetElement = reference.resolve()
if (targetElement != null) {
// get the repo relative if available, if not then page relative
var collapsedForm = myResolver.resolve(linkRef, Want.invoke(Local.ABS, Remote.ABS, Links.NONE), null)
if (collapsedForm == null) {
collapsedForm = myResolver.resolve(linkRef, Want.invoke(Local.REL, Remote.REL, Links.NONE), null)
}
if (collapsedForm != null && collapsedForm is LinkRef) {
val collapsedText = collapsedForm.filePath
addDescriptor(object : FoldingDescriptor(element, element.textRange) {
override fun getPlaceholderText(): String? {
return collapsedText
}
})
}
}
}
}
}
}
visitChildren(element)
}
}
private fun trimLastBlankLine(text: CharSequence, range: TextRange): TextRange {
if (range.endOffset > 1 && range.endOffset <= text.length && text[range.endOffset - 1] == '\n') {
val lastEOL = range.endOffset - 1
val prevEOL = text.lastIndexOf('\n', lastEOL - 1)
if (prevEOL >= range.startOffset && prevEOL < lastEOL) {
if (text.subSequence(prevEOL + 1, lastEOL).isBlank()) {
return TextRange(range.startOffset, prevEOL)
}
}
}
return range
}
private fun fold(element: MdHeaderElement) {
val headingRange = element.textRange
val headingIndex = element.headerLevel - 1
// extend range of all headings with lower level and close all equal or lower levels
for (i in 0 until 6) {
val openHeadingRange = myOpenHeadingRanges[i]
val openHeading = myOpenHeadings[i]
if (i < headingIndex) {
// extend its range to include this heading
if (openHeadingRange != null && openHeading != null) {
val textRange = openHeadingRange.union(headingRange)
myOpenHeadingRanges[i] = textRange
}
} else {
// end it before our start
if (openHeadingRange != null && openHeading != null) {
updateHeadingRanges(openHeading, openHeadingRange, headingRange.startOffset)
}
// close this level
myOpenHeadingRanges[i] = null
myOpenHeadings[i] = null
if (i == headingIndex) {
// this is now this heading's spot
myOpenHeadings[i] = element
myOpenHeadingRanges[i] = headingRange
if (element is MdSetextHeader) {
// need to use the end of text node
val headingTextRange = element.headerTextElement?.textRange
if (headingTextRange != null) {
myOpenHeadingRanges[headingIndex] = headingTextRange
}
} else {
myOpenHeadingRanges[headingIndex] = TextRange(headingRange.endOffset - 1, headingRange.endOffset - 1)
}
}
}
}
visitChildren(element)
}
private fun updateHeadingRanges(openHeading: MdHeaderElement, openHeadingRange: TextRange, endOffset: Int) {
val finalOpenHeadingRange = trimLastBlankLine(myRootText, TextRange(openHeadingRange.startOffset, endOffset))
if (!finalOpenHeadingRange.isEmpty && myRootText.subSequence(finalOpenHeadingRange.startOffset, finalOpenHeadingRange.endOffset).contains('\n')) {
myHeadingRanges[openHeading] = finalOpenHeadingRange
}
}
private fun closeOpenHeadings() {
val endOffset = root.textRange.endOffset
for (i in 0 until 6) {
val openHeadingRange = myOpenHeadingRanges[i]
val openHeading = myOpenHeadings[i]
if (openHeadingRange != null && openHeading != null) {
// diagnostic/4985
updateHeadingRanges(openHeading, openHeadingRange, endOffset.maxLimit(myRootText.length))
}
}
for (heading in myHeadingRanges.keys) {
val range = myHeadingRanges[heading]
if (range != null && !range.isEmpty) {
addDescriptor(object : FoldingDescriptor(heading.node, range, null) {
override fun getPlaceholderText(): String? {
return defaultPlaceHolderText
}
})
}
}
}
private fun fold(element: MdJekyllFrontMatterBlock) {
val range = element.textRange
if (!range.isEmpty && range.startOffset + 3 < range.endOffset) {
val text = element.text
val lastEOL = (text as String).lastIndexOf("\n", text.length - 1) + 1
addDescriptor(object : FoldingDescriptor(element.node, TextRange(range.startOffset + 3, range.startOffset + lastEOL), null) {
override fun getPlaceholderText(): String? {
return defaultPlaceHolderText
}
})
visitChildren(element)
}
}
private fun fold(element: MdListItem) {
val firstLineEnd = element.text.indexOf("\n")
if (firstLineEnd >= 0) {
val textRange = element.textRange
val range = TextRange.create(textRange.startOffset + firstLineEnd, textRange.endOffset - 1)
if (!range.isEmpty) {
addDescriptor(object : FoldingDescriptor(element.node, TextRange(range.startOffset, range.endOffset), null) {
override fun getPlaceholderText(): String? {
return defaultPlaceHolderText
}
})
}
}
visitChildren(element)
}
private fun fold(comment: MdComment) {
val commentText = comment.commentTextNode ?: return
var text = commentText.text
val pos = text.indexOf('\n')
if (pos > 0) {
text = text.substring(0, pos).trim() + defaultPlaceHolderText
addDescriptor(object : FoldingDescriptor(comment.node, comment.node.textRange, null) {
override fun getPlaceholderText(): String? {
return text
}
})
}
}
}
| high | 0.770679 | 120 |
// (c) Copyright 1995-2016 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
// DO NOT MODIFY THIS FILE.
// IP VLNV: digilentinc.com:IP:PWM:1.0
// IP Revision: 5
// The following must be inserted into your Verilog file for this
// core to be instantiated. Change the instance name and port connections
// (in parentheses) to your own signal names.
//----------- Begin Cut here for INSTANTIATION Template ---// INST_TAG
PmodAMP2_PWM_0_0 your_instance_name (
.pwm(pwm), // output wire pwm
.interrupt(interrupt), // output wire interrupt
.pwm_axi_awaddr(pwm_axi_awaddr), // input wire [3 : 0] pwm_axi_awaddr
.pwm_axi_awprot(pwm_axi_awprot), // input wire [2 : 0] pwm_axi_awprot
.pwm_axi_awvalid(pwm_axi_awvalid), // input wire pwm_axi_awvalid
.pwm_axi_awready(pwm_axi_awready), // output wire pwm_axi_awready
.pwm_axi_wdata(pwm_axi_wdata), // input wire [31 : 0] pwm_axi_wdata
.pwm_axi_wstrb(pwm_axi_wstrb), // input wire [3 : 0] pwm_axi_wstrb
.pwm_axi_wvalid(pwm_axi_wvalid), // input wire pwm_axi_wvalid
.pwm_axi_wready(pwm_axi_wready), // output wire pwm_axi_wready
.pwm_axi_bresp(pwm_axi_bresp), // output wire [1 : 0] pwm_axi_bresp
.pwm_axi_bvalid(pwm_axi_bvalid), // output wire pwm_axi_bvalid
.pwm_axi_bready(pwm_axi_bready), // input wire pwm_axi_bready
.pwm_axi_araddr(pwm_axi_araddr), // input wire [3 : 0] pwm_axi_araddr
.pwm_axi_arprot(pwm_axi_arprot), // input wire [2 : 0] pwm_axi_arprot
.pwm_axi_arvalid(pwm_axi_arvalid), // input wire pwm_axi_arvalid
.pwm_axi_arready(pwm_axi_arready), // output wire pwm_axi_arready
.pwm_axi_rdata(pwm_axi_rdata), // output wire [31 : 0] pwm_axi_rdata
.pwm_axi_rresp(pwm_axi_rresp), // output wire [1 : 0] pwm_axi_rresp
.pwm_axi_rvalid(pwm_axi_rvalid), // output wire pwm_axi_rvalid
.pwm_axi_rready(pwm_axi_rready), // input wire pwm_axi_rready
.pwm_axi_aclk(pwm_axi_aclk), // input wire pwm_axi_aclk
.pwm_axi_aresetn(pwm_axi_aresetn) // input wire pwm_axi_aresetn
);
// INST_TAG_END ------ End INSTANTIATION Template ---------
| low | 0.43558 | 121 |
package com.kchmielewski.sda.concurrency.task04;
import java.util.ArrayList;
import java.util.List;
public class TestMe {
public List<Integer> changeMe(List<Integer> integers) {
List<Integer> firstHalf = integers.subList(0, integers.size() / 2);
List<Integer> secondHalf = integers.subList(integers.size() / 2, integers.size());
Thread firstThread = new Thread(() -> {
for (int i = 0; i < firstHalf.size(); i++) {
firstHalf.set(i, firstHalf.get(i) * firstHalf.get(i));
}
});
Thread secondThread = new Thread(() -> {
for (int i = 0; i < secondHalf.size(); i++) {
secondHalf.set(i, secondHalf.get(i) * -secondHalf.get(i));
}
});
firstThread.start();
secondThread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
List<Integer> result = new ArrayList<>(firstHalf);
result.addAll(secondHalf);
return result;
}
}
| high | 0.36191 | 122 |
#!/bin/csh -f
source config/experiment.csh
#
# static job submission settings
# =============================================
## *AccountNumber
# OPTIONS: NMMM0015, NMMM0043
setenv StandardAccountNumber NMMM0043
setenv CYAccountNumber ${StandardAccountNumber}
setenv VFAccountNumber ${StandardAccountNumber}
## *QueueName
# OPTIONS: economy, regular, premium
setenv CYQueueName regular
setenv VFQueueName economy
if ($ABEInflation == True) then
setenv EnsMeanBGQueueName ${CYQueueName}
setenv EnsMeanBGAccountNumber ${CYAccountNumber}
else
setenv EnsMeanBGQueueName ${VFQueueName}
setenv EnsMeanBGAccountNumber ${VFAccountNumber}
endif
setenv InitializationRetry '2*PT30S'
setenv VariationalRetry '2*PT30S'
setenv EnsOfVariationalRetry '1*PT30S'
setenv CyclingFCRetry '2*PT30S'
setenv RTPPInflationRetry '2*PT30S'
setenv HofXRetry '2*PT30S'
#setenv VerifyObsRetry '1*PT30S'
#setenv VerifyModelRetry '1*PT30S'
| low | 0.23599 | 123 |
-- From @joehendrix
-- The imul doesn't type check as Lean won't try to coerce from a reg (bv 64) to a expr (bv ?u)
inductive MCType
| bv : Nat → MCType
open MCType
inductive Reg : MCType → Type
| rax : Reg (bv 64)
inductive Expr : MCType → Type
| r : ∀{tp:MCType}, Reg tp → Expr tp
| sextC {s:Nat} (x : Expr (bv s)) (t:Nat) : Expr (bv t)
instance reg_is_expr {tp:MCType} : HasCoe (Reg tp) (Expr tp) := ⟨Expr.r⟩
def bvmul {w:Nat} (x y : Expr (bv w)) : Expr (bv w) := x
def sext {s:Nat} (x : Expr (bv s)) (t:Nat) : Expr (bv t) := Expr.sextC x t
def imul {u:Nat} (e:Expr (bv 64)) : Expr (bv 128) :=
bvmul (sext Reg.rax 128) (sext e _)
| high | 0.477576 | 124 |
lexer grammar XPathLexer;
@header {
using System;
}
tokens { TokenRef, RuleRef }
/*
path : separator? word (separator word)* EOF ;
separator
: '/' '!'
| '//' '!'
| '/'
| '//'
;
word: TokenRef
| RuleRef
| String
| '*'
;
*/
Anywhere : '//' ;
Root : '/' ;
Wildcard : '*' ;
Bang : '!' ;
ID : NameStartChar NameChar*
{
String text = Text;
if ( Char.IsUpper(text[0]) )
Type = TokenRef;
else
Type = RuleRef;
}
;
fragment
NameChar : NameStartChar
| '0'..'9'
| '_'
| '\u00B7'
| '\u0300'..'\u036F'
| '\u203F'..'\u2040'
;
fragment
NameStartChar
: 'A'..'Z' | 'a'..'z'
| '\u00C0'..'\u00D6'
| '\u00D8'..'\u00F6'
| '\u00F8'..'\u02FF'
| '\u0370'..'\u037D'
| '\u037F'..'\u1FFF'
| '\u200C'..'\u200D'
| '\u2070'..'\u218F'
| '\u2C00'..'\u2FEF'
| '\u3001'..'\uD7FF'
| '\uF900'..'\uFDCF'
| '\uFDF0'..'\uFFFD'
; // ignores | ['\u10000-'\uEFFFF] ;
String : '\'' .*? '\'' ;
//Ws : [ \t\r\n]+ -> skip ;
| high | 0.329804 | 125 |
option optimize_for = LITE_RUNTIME;
package HostBuffers;
message HostMessage {
repeated Instruction instruction = 1;
}
message Instruction {
extensions 2 to max;
}
message HostBytes {
optional bytes hoststring = 4;
}
message ResizeMessage {
optional int32 width = 5;
optional int32 height = 6;
}
message EchoAck {
optional uint64 echo_ack_num = 8;
}
extend Instruction {
optional HostBytes hostbytes = 2;
optional ResizeMessage resize = 3;
optional EchoAck echoack = 7;
}
| high | 0.519942 | 126 |
"
""soy un dado""
Please comment me using the following template inspired by Class Responsibility Collaborator (CRC) design:
For the Class part: State a one line summary. For example, ""I represent a paragraph of text"".
For the Responsibility part: Three sentences about my main responsibilities - what I do, what I know.
For the Collaborators Part: State my main collaborators and one line about how I interact with them.
Public API and Key Messages
- message one
- message two
- (for bonus points) how to create instances.
One simple example is simply gorgeous.
Internal Representation and Key Implementation Points.
Instance Variables
numberOfFaces: <Object>
random: <Object>
Implementation Points
"
Class {
#name : #Dice,
#superclass : #Object,
#instVars : [
'numberOfFaces',
'random'
],
#category : #EnunciadoParte1
}
{ #category : #creation }
Dice class >> assertValidFaces: aNumberOfFaces [
aNumberOfFaces > 3
ifFalse: [ self error: 'Number of faces must be 4 or greater' ]
]
{ #category : #creation }
Dice class >> withFaces: aNumberOfFaces [
self assertValidFaces: aNumberOfFaces.
^ self new
initializeWithFaces: aNumberOfFaces;
yourself
]
{ #category : #initialize }
Dice >> initializeWithFaces: aNumberOfFaces [
numberOfFaces := aNumberOfFaces.
random := Random new
]
{ #category : #actions }
Dice >> numberOfFaces [
^ numberOfFaces
]
{ #category : #actions }
Dice >> roll [
^ (random next * numberOfFaces) floor + 1
]
| high | 0.524343 | 127 |
/* Régression linéaire sans modèle pour la corrélation intra-groupe
la méthode d'ajustement par défaut est reml, utiliser method=ml
pour maximum de vraisemblance
*/
proc mixed data=modstat.vengeance method=reml;
model vengeance = sexe age vc wom t / solution;
run;
| low | 0.373868 | 128 |
import Algebra.FunctionProperties using (LeftZero; RightZero; _DistributesOverˡ_;_DistributesOverʳ_; Idempotent)
import Function using (_on_)
import Level
import Relation.Binary.EqReasoning as EqReasoning
import Relation.Binary.On using (isEquivalence)
import Algebra.Structures using (module IsCommutativeMonoid; IsCommutativeMonoid)
open import Relation.Binary using (module IsEquivalence; IsEquivalence; _Preserves₂_⟶_⟶_ ; Setoid)
open import Data.Product renaming (_,_ to _,,_) -- just to avoid clash with other commas
open import Preliminaries using (Rel; UniqueSolution; LowerBound)
module SemiNearRingRecords where
record SemiNearRing : Set₁ where -- \structure{1}{|SemiNearRing|}
field -- \structure{1.1}{Carriers, operators}
s : Set
_≃s_ : s → s → Set
zers : s
_+s_ : s → s → s
_*s_ : s → s → s
open Algebra.Structures using (IsCommutativeMonoid)
open Algebra.FunctionProperties _≃s_ using (LeftZero; RightZero)
field -- \structure{1.2}{Commutative monoid |(+,0)|}
isCommMon : IsCommutativeMonoid _≃s_ _+s_ zers
zeroˡ : LeftZero zers _*s_ -- expands to |∀ x → (zers *s x) ≃s zers|
zeroʳ : RightZero zers _*s_ -- expands to |∀ x → (x *s zers) ≃s zers|
_<*>_ : ∀ {x y u v} → (x ≃s y) → (u ≃s v) → (x *s u ≃s y *s v)
open Algebra.FunctionProperties _≃s_
using (Idempotent; _DistributesOverˡ_; _DistributesOverʳ_)
field -- \structure{1.3}{Distributive, idempotent, \ldots}
idem : Idempotent _+s_
distl : _*s_ DistributesOverˡ _+s_
distr : _*s_ DistributesOverʳ _+s_
-- expands to |∀ a b c → (a +s b) *s c ≃s (a *s c) +s (b *s c)|
infix 4 _≤s_
_≤s_ : s -> s -> Set
x ≤s y = x +s y ≃s y
infix 4 _≃s_; infixl 6 _+s_; infixl 7 _*s_
-- \structure{1.4}{Exporting commutative monoid operations}
open Algebra.Structures.IsCommutativeMonoid isCommMon public
hiding (refl)
renaming
( isEquivalence to isEquivs
; assoc to assocs
; comm to comms
; ∙-cong to _<+>_
; identityˡ to identityˡs
)
identityʳs = proj₂ identity
sSetoid : Setoid Level.zero Level.zero -- \structure{1.5}{Setoid, \ldots}
sSetoid = record { Carrier = s;
_≈_ = _≃s_;
isEquivalence = isEquivs }
open IsEquivalence isEquivs public
hiding (reflexive) renaming (refl to refls ; sym to syms ; trans to transs)
LowerBounds = LowerBound _≤s_ -- \structure{1.6}{Lower bounds}
record SemiNearRing2 : Set₁ where -- \structure{2}{|SemiNearRing2|}
field
snr : SemiNearRing
open SemiNearRing snr public -- public = export the "local" names from |SemiNearRing|
field -- \structure{2.1}{Plus and times for |u|, \ldots}
u : Set
_+u_ : u → u → u
_*u_ : u → u → u
u2s : u → s
_≃u_ : u → u → Set
_≃u_ = _≃s_ Function.on u2s
_u*s_ : u → s → s
_u*s_ u s = u2s u *s s
_s*u_ : s → u → s
_s*u_ s u = s *s u2s u
infix 4 _≃u_; infixl 6 _+u_; infixl 7 _*u_ _u*s_ _s*u_
uSetoid : Setoid Level.zero Level.zero
uSetoid = record { isEquivalence = Relation.Binary.On.isEquivalence u2s isEquivs }
_≤u_ : u → u → Set
_≤u_ = _≤s_ Function.on u2s
L : u → s → u → s → Set -- \structure{2.2}{Linear equation |L|}
L a y b x = y +s (a u*s x +s x s*u b) ≃s x
-- \structure{2.3}{Properties of |L|}
UniqueL = ∀ {a y b} → UniqueSolution _≃s_ (L a y b)
CongL = ∀ {a x b} -> ∀ {y y'} -> y ≃s y' -> L a y b x -> L a y' b x
| high | 0.515014 | 129 |
package Paws::CognitoIdp::SetUserMFAPreference;
use Moose;
has AccessToken => (is => 'ro', isa => 'Str', required => 1);
has SMSMfaSettings => (is => 'ro', isa => 'Paws::CognitoIdp::SMSMfaSettingsType');
has SoftwareTokenMfaSettings => (is => 'ro', isa => 'Paws::CognitoIdp::SoftwareTokenMfaSettingsType');
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'SetUserMFAPreference');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::CognitoIdp::SetUserMFAPreferenceResponse');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::CognitoIdp::SetUserMFAPreference - Arguments for method SetUserMFAPreference on L<Paws::CognitoIdp>
=head1 DESCRIPTION
This class represents the parameters used for calling the method SetUserMFAPreference on the
L<Amazon Cognito Identity Provider|Paws::CognitoIdp> service. Use the attributes of this class
as arguments to method SetUserMFAPreference.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to SetUserMFAPreference.
=head1 SYNOPSIS
my $cognito-idp = Paws->service('CognitoIdp');
my $SetUserMFAPreferenceResponse = $cognito -idp->SetUserMFAPreference(
AccessToken => 'MyTokenModelType',
SMSMfaSettings => {
Enabled => 1, # OPTIONAL
PreferredMfa => 1, # OPTIONAL
}, # OPTIONAL
SoftwareTokenMfaSettings => {
Enabled => 1, # OPTIONAL
PreferredMfa => 1, # OPTIONAL
}, # OPTIONAL
);
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
For the AWS API documentation, see L<https://docs.aws.amazon.com/goto/WebAPI/cognito-idp/SetUserMFAPreference>
=head1 ATTRIBUTES
=head2 B<REQUIRED> AccessToken => Str
The access token.
=head2 SMSMfaSettings => L<Paws::CognitoIdp::SMSMfaSettingsType>
The SMS text message multi-factor authentication (MFA) settings.
=head2 SoftwareTokenMfaSettings => L<Paws::CognitoIdp::SoftwareTokenMfaSettingsType>
The time-based one-time password software token MFA settings.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method SetUserMFAPreference in L<Paws::CognitoIdp>
=head1 BUGS and CONTRIBUTIONS
The source code is located here: L<https://github.com/pplu/aws-sdk-perl>
Please report bugs to: L<https://github.com/pplu/aws-sdk-perl/issues>
=cut
| high | 0.59075 | 130 |
using Test
using ParallelStencil
import ParallelStencil: @reset_parallel_stencil, @is_initialized, @get_package, @get_numbertype, @get_ndims, SUPPORTED_PACKAGES, PKG_CUDA, PKG_NONE, NUMBERTYPE_NONE, NDIMS_NONE
import ParallelStencil: @require, @symbols, longnameof
TEST_PACKAGES = SUPPORTED_PACKAGES
@static if PKG_CUDA in TEST_PACKAGES
import CUDA
if !CUDA.functional() TEST_PACKAGES = filter!(x->x≠PKG_CUDA, TEST_PACKAGES) end
end
@static for package in TEST_PACKAGES eval(:(
@testset "$(basename(@__FILE__)) (package: $(nameof($package)))" begin
@testset "1. Reset of ParallelStencil" begin
@testset "Reset if not initialized" begin
@require !@is_initialized()
@reset_parallel_stencil()
@test !@is_initialized()
@test @get_package() == $PKG_NONE
@test @get_numbertype() == $NUMBERTYPE_NONE
@test @get_ndims() == $NDIMS_NONE
end;
@testset "Reset if initialized" begin
@require !@is_initialized()
@init_parallel_stencil($package, Float64, 3)
@require @is_initialized() && @get_package() == $package
@reset_parallel_stencil()
@test length(@symbols($(@__MODULE__), Data)) == 1
@test !@is_initialized()
@test @get_package() == $PKG_NONE
@test @get_numbertype() == $NUMBERTYPE_NONE
@test @get_ndims() == $NDIMS_NONE
end;
end;
end;
)) end == nothing || true;
| high | 0.738366 | 131 |
const std = @import("std");
const Type = @import("typeset.zig").Type;
const TypeSet = @import("typeset.zig").TypeSet;
/// A scope structure that can be used to manage variable
/// allocation with different scopes (global, local).
pub const Scope = struct {
const Self = @This();
const Variable = struct {
/// This is the offset of the variables
name: []const u8,
storage_slot: u16,
type: enum { local, global },
possible_types: TypeSet = TypeSet.any,
is_const: bool,
};
arena: std.heap.ArenaAllocator,
local_variables: std.ArrayList(Variable),
global_variables: std.ArrayList(Variable),
return_point: std.ArrayList(usize),
/// When this is true, the scope will declare
/// top-level variables as `global`, otherwise as `local`.
is_global: bool,
/// When this is non-null, the scope will use this as a fallback
/// in `get` and will pass the query to this value.
/// Note: It is not allowed that `global_scope` will return a `local` variable then!
global_scope: ?*Self,
/// The highest number of local variables that were declared at a point in this scope.
max_locals: usize = 0,
/// Creates a new scope.
/// `global_scope` is a reference towards a scope that will provide references to a encasing scope.
/// This scope must only provide `global` variables.
pub fn init(allocator: *std.mem.Allocator, global_scope: ?*Self, is_global: bool) Self {
return Self{
.arena = std.heap.ArenaAllocator.init(allocator),
.local_variables = std.ArrayList(Variable).init(allocator),
.global_variables = std.ArrayList(Variable).init(allocator),
.return_point = std.ArrayList(usize).init(allocator),
.is_global = is_global,
.global_scope = global_scope,
};
}
pub fn deinit(self: *Self) void {
self.local_variables.deinit();
self.global_variables.deinit();
self.return_point.deinit();
self.arena.deinit();
self.* = undefined;
}
/// Enters a sub-scope. This is usually called at the start of a block.
/// Sub-scopes are a set of variables that are only valid in a smaller
/// portion of the code.
/// This will push a return point to which later must be returned by
/// calling `leave`.
pub fn enter(self: *Self) !void {
try self.return_point.append(self.local_variables.items.len);
}
/// Leaves a sub-scope. This is usually called at the end of a block.
pub fn leave(self: *Self) !void {
self.local_variables.shrink(self.return_point.pop());
}
/// Declares are new variable.
pub fn declare(self: *Self, name: []const u8, is_const: bool) !void {
if (self.is_global and (self.return_point.items.len == 0)) {
// a variable is only global when the scope is a global scope and
// we don't have any sub-scopes open (which would create temporary variables)
for (self.global_variables.items) |variable| {
if (std.mem.eql(u8, variable.name, name)) {
// Global variables are not allowed to
return error.AlreadyDeclared;
}
}
if (self.global_variables.items.len == std.math.maxInt(u16))
return error.TooManyVariables;
try self.global_variables.append(Variable{
.storage_slot = @intCast(u16, self.global_variables.items.len),
.name = try self.arena.allocator.dupe(u8, name),
.type = .global,
.is_const = is_const,
});
} else {
if (self.local_variables.items.len == std.math.maxInt(u16))
return error.TooManyVariables;
try self.local_variables.append(Variable{
.storage_slot = @intCast(u16, self.local_variables.items.len),
.name = try self.arena.allocator.dupe(u8, name),
.type = .local,
.is_const = is_const,
});
self.max_locals = std.math.max(self.max_locals, self.local_variables.items.len);
}
}
/// Tries to return a variable named `name`. This will first search in the
/// local variables, then in the global ones.
/// Will return `null` when a variable is not found.
pub fn get(self: Self, name: []const u8) ?*Variable {
var i: usize = undefined;
// First, search all local variables back-to-front:
// This allows trivial shadowing as variables will be searched
// in reverse declaration order.
i = self.local_variables.items.len;
while (i > 0) {
i -= 1;
const variable = &self.local_variables.items[i];
if (std.mem.eql(u8, variable.name, name))
return variable;
}
if (self.is_global) {
// The same goes for global variables
i = self.global_variables.items.len;
while (i > 0) {
i -= 1;
const variable = &self.global_variables.items[i];
if (std.mem.eql(u8, variable.name, name))
return variable;
}
}
if (self.global_scope) |globals| {
const global = globals.get(name);
// The global scope is not allowed to supply local variables to us. If this happens,
// a programming error was done.
std.debug.assert(global == null or global.?.type != .local);
return global;
}
return null;
}
};
test "scope init/deinit" {
var scope = Scope.init(std.testing.allocator, null, false);
defer scope.deinit();
}
test "scope declare/get" {
var scope = Scope.init(std.testing.allocator, null, true);
defer scope.deinit();
try scope.declare("foo", true);
std.testing.expectError(error.AlreadyDeclared, scope.declare("foo", true));
try scope.enter();
try scope.declare("bar", true);
std.testing.expect(scope.get("foo").?.type == .global);
std.testing.expect(scope.get("bar").?.type == .local);
std.testing.expect(scope.get("bam") == null);
try scope.leave();
std.testing.expect(scope.get("foo").?.type == .global);
std.testing.expect(scope.get("bar") == null);
std.testing.expect(scope.get("bam") == null);
}
test "variable allocation" {
var scope = Scope.init(std.testing.allocator, null, true);
defer scope.deinit();
try scope.declare("foo", true);
try scope.declare("bar", true);
try scope.declare("bam", true);
std.testing.expect(scope.get("foo").?.storage_slot == 0);
std.testing.expect(scope.get("bar").?.storage_slot == 1);
std.testing.expect(scope.get("bam").?.storage_slot == 2);
try scope.enter();
try scope.declare("foo", true);
try scope.enter();
try scope.declare("bar", true);
try scope.declare("bam", true);
std.testing.expect(scope.get("foo").?.storage_slot == 0);
std.testing.expect(scope.get("bar").?.storage_slot == 1);
std.testing.expect(scope.get("bam").?.storage_slot == 2);
std.testing.expect(scope.get("foo").?.type == .local);
std.testing.expect(scope.get("bar").?.type == .local);
std.testing.expect(scope.get("bam").?.type == .local);
try scope.leave();
std.testing.expect(scope.get("foo").?.type == .local);
std.testing.expect(scope.get("bar").?.type == .global);
std.testing.expect(scope.get("bam").?.type == .global);
try scope.leave();
std.testing.expect(scope.get("foo").?.type == .global);
std.testing.expect(scope.get("bar").?.type == .global);
std.testing.expect(scope.get("bam").?.type == .global);
}
| high | 0.826012 | 132 |
<!DOCTYPE html>
<html lang="{{ .Site.Language }}" dir="{{ .Language.LanguageDirection | default "auto" }}">
<head>
{{- partial "head.html" . }}
</head>
<body class="
{{- if (or (ne .Kind `page` ) (eq .Layout `archives`) (eq .Layout `search`)) -}}
{{- print "list" -}}
{{- end -}}
{{- if eq $.Site.Params.defaultTheme `dark` -}}
{{- print " dark" }}
{{- end -}}
" id="top">
{{- partialCached "header.html" . .Page -}}
<main class="main">
{{- block "main" . }}{{ end }}
</main>
{{ partialCached "footer.html" . .Layout .Kind -}}
</body>
</html>
| low | 0.364609 | 133 |
(cl:in-package #:common-lisp-user)
(defpackage #:cleavir-bir-transformations
(:use #:cl)
(:local-nicknames (#:bir #:cleavir-bir)
(#:set #:cleavir-set)
(#:ctype #:cleavir-ctype)
(#:attributes #:cleavir-attributes))
(:export #:module-eliminate-come-froms #:eliminate-come-froms)
(:export #:module-optimize-variables #:function-optimize-variables)
(:export #:simple-unwinding-p #:simple-dynenv-p)
(:export #:find-module-local-calls #:maybe-interpolate)
(:export #:determine-function-environments)
(:export #:determine-closure-extents)
(:export #:determine-variable-extents)
(:export #:meta-evaluate-module
#:generate-type-check-function
#:transform-call #:fold-call #:derive-return-type)
(:export #:module-generate-type-checks))
| high | 0.517725 | 134 |
(when (cdr command-line-args)
(setcdr command-line-args (cons "--no-splash" (cdr command-line-args))))
| low | 0.415774 | 135 |
TYPE=VIEW
query=select if(isnull(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`USER`),\'background\',`performance_schema`.`events_statements_summary_by_user_by_event_name`.`USER`) AS `user`,sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`COUNT_STAR`) AS `total`,sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`SUM_TIMER_WAIT`) AS `total_latency`,sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`MAX_TIMER_WAIT`) AS `max_latency`,sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`SUM_LOCK_TIME`) AS `lock_latency`,sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`SUM_ROWS_SENT`) AS `rows_sent`,sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`SUM_ROWS_EXAMINED`) AS `rows_examined`,sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`SUM_ROWS_AFFECTED`) AS `rows_affected`,(sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`SUM_NO_INDEX_USED`) + sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`SUM_NO_GOOD_INDEX_USED`)) AS `full_scans` from `performance_schema`.`events_statements_summary_by_user_by_event_name` group by if(isnull(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`USER`),\'background\',`performance_schema`.`events_statements_summary_by_user_by_event_name`.`USER`) order by sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`SUM_TIMER_WAIT`) desc
md5=dbfce7fc47556cfedc1a1ec2c2e6081c
updatable=0
algorithm=1
definer_user=mysql.sys
definer_host=localhost
suid=0
with_check_option=0
timestamp=2021-11-01 06:46:14
create-version=1
source=SELECT IF(user IS NULL, \'background\', user) AS user, SUM(count_star) AS total, SUM(sum_timer_wait) AS total_latency, SUM(max_timer_wait) AS max_latency, SUM(sum_lock_time) AS lock_latency, SUM(sum_rows_sent) AS rows_sent, SUM(sum_rows_examined) AS rows_examined, SUM(sum_rows_affected) AS rows_affected, SUM(sum_no_index_used) + SUM(sum_no_good_index_used) AS full_scans FROM performance_schema.events_statements_summary_by_user_by_event_name GROUP BY IF(user IS NULL, \'background\', user) ORDER BY SUM(sum_timer_wait) DESC
client_cs_name=utf8
connection_cl_name=utf8_general_ci
view_body_utf8=select if(isnull(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`USER`),\'background\',`performance_schema`.`events_statements_summary_by_user_by_event_name`.`USER`) AS `user`,sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`COUNT_STAR`) AS `total`,sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`SUM_TIMER_WAIT`) AS `total_latency`,sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`MAX_TIMER_WAIT`) AS `max_latency`,sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`SUM_LOCK_TIME`) AS `lock_latency`,sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`SUM_ROWS_SENT`) AS `rows_sent`,sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`SUM_ROWS_EXAMINED`) AS `rows_examined`,sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`SUM_ROWS_AFFECTED`) AS `rows_affected`,(sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`SUM_NO_INDEX_USED`) + sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`SUM_NO_GOOD_INDEX_USED`)) AS `full_scans` from `performance_schema`.`events_statements_summary_by_user_by_event_name` group by if(isnull(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`USER`),\'background\',`performance_schema`.`events_statements_summary_by_user_by_event_name`.`USER`) order by sum(`performance_schema`.`events_statements_summary_by_user_by_event_name`.`SUM_TIMER_WAIT`) desc
| high | 0.605705 | 136 |
package tech.mlsql.dsl.adaptor
import streaming.dsl.parser.DSLSQLParser.SqlContext
import streaming.dsl.{IncludeAdaptor, ScriptSQLExecListener}
import streaming.parser.lisener.BaseParseListenerextends
import scala.collection.mutable.ArrayBuffer
/**
* 2019-04-11 WilliamZhu(allwefantasy@gmail.com)
*/
class PreProcessIncludeListener(val scriptSQLExecListener: ScriptSQLExecListener) extends BaseParseListenerextends {
private val _statements = new ArrayBuffer[StatementChunk]()
def toScript = {
val stringBuffer = new StringBuffer()
_statements.foreach { f =>
f.st match {
case SCType.Normal =>
stringBuffer.append(f.content + ";")
case SCType.Include =>
stringBuffer.append(f.content)
}
}
stringBuffer.toString
}
def addStatement(v: String, scType: SCType.Value) = {
_statements += StatementChunk(v, scType)
this
}
override def exitSql(ctx: SqlContext): Unit = {
ctx.getChild(0).getText.toLowerCase() match {
case "include" =>
new IncludeAdaptor(this).parse(ctx)
case _ => new StatementForIncludeAdaptor(this).parse(ctx)
}
}
}
case class StatementChunk(content: String, st: SCType.Value)
object SCType extends Enumeration {
val Include, Normal = Value
}
| high | 0.432095 | 137 |
(*
Copyright (C) 2017 M.A.L. Marques
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*)
(* type: gga_exc *)
(* prefix:
gga_x_optx_params *params;
assert(p->params != NULL);
params = (gga_x_optx_params * )(p->params);
*)
optx_f := x-> params_a_a + params_a_b*(params_a_gamma*x^2/(1 + params_a_gamma*x^2))^2:
f := (rs, z, xt, xs0, xs1) -> gga_exchange(optx_f, rs, z, xs0, xs1):
| medium | 0.394376 | 138 |
__precompile__()
module GggenomeSearch
export
getResponse,
generateGggenomeUrl,
extractTopResultFromResponse,
showGggenomeTopHit
using Requests
function getResponse(url::String)
res = get(url)
return(String(res.data))
end
function generateGggenomeUrl(seq::AbstractString, db::String, format::String)
return(@sprintf "https://gggenome.dbcls.jp/%s/%s%s" db seq format)
end
function extractTopResultFromResponse(res_str::String)
topResult = "No hit"
for ln in split(chomp(res_str), "\n")
if ln[1] == '#'
continue
else
topResult = split(chomp(ln), "\t")[1]
break
end
end
return(topResult)
end
function showGggenomeTopHit(seq::AbstractString, db::String)
url = generateGggenomeUrl(seq, db, ".txt")
res_str = getResponse(url)
return(extractTopResultFromResponse(res_str))
end
end # module
| high | 0.298002 | 139 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# OS : GNU/Linux Ubuntu 16.04 or 18.04
# LANGUAGE : Python 3.5.2 or later
# AUTHOR : Klim V. O.
# DATE : 14.10.2019
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
from setuptools import setup, find_packages
from typing import List
__version__ = 1.1
def readme() -> List[str]:
with open('README.md', 'r', encoding='utf-8') as f_readme:
return f_readme.read()
def requirements() -> List[str]:
with open('requirements.txt', 'r', encoding='utf-8') as f_requirements:
return f_requirements.read()
setup(
name='rnnoise-wrapper',
packages=find_packages(),
include_package_data=True,
entry_points={
'console_scripts':
['rnnoise_wrapper = rnnoise_wrapper.cli:denoise']
},
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Topic :: Software Development :: Libraries',
],
version=__version__,
install_requires=requirements(),
description='RNNoise_Wrapper is a simple wrapper to audio noise reduction RNNoise',
long_description=readme(),
long_description_content_type='text/markdown',
author='Vlad Klim',
author_email='valdsklim@gmail.com',
license='Apache 2.0',
url='https://github.com/Desklop/RNNoise_Wrapper',
keywords='noise noise-reduction noise-suppression denoiser denoise rnnoise rnn nn rtc dsp audio audio-processing wav nlp',
project_urls={
'Source': 'https://github.com/Desklop/RNNoise_Wrapper',
}
)
print('\nRNNoise_Wrapper is ready for work and defense!')
print('All information about this package is available at https://github.com/Desklop/RNNoise_Wrapper')
# To build package run: python3 setup.py sdist bdist_wheel
| high | 0.830631 | 140 |
module P2P.Neighbours where
import P2P.Chan
import P2P.JSONUtils
import P2P.SendMessage
import P2P.SockAddr
import Test.QuickCheck.Gen
updateNeighbours :: AddrChan -> SockAddr -> IO ()
updateNeighbours chan addr = do
addresses <- readEverything chan
neighbours <- gen minNumOfNeighbours addresses
notify neighbours addr
gen :: (Eq a) => Int -> [a] -> IO [a]
gen n xs =
if length xs < n
then pure xs
else genMore n xs []
genMore :: (Eq a) => Int -> [a] -> [a] -> IO [a]
genMore 0 _ xs = pure xs
genMore n list xs = do
x <- generate $ elements list
if x `elem` xs
then genMore n list xs
else genMore (n - 1) list (x : xs)
notify :: [SockAddr] -> SockAddr -> IO ()
notify addresses addr = do
mapM_ (sendMessage (encode addr)) addresses
flip sendMessage addr $ encode addresses
minNumOfNeighbours :: Int
minNumOfNeighbours = 5
| high | 0.309505 | 141 |
(*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open Core
open Pyre
open Ast
open Analysis
open Expression
module DefinitionsCache (Type : sig
type t
end) =
struct
let cache : Type.t Reference.Table.t = Reference.Table.create ()
let set key value = Hashtbl.set cache ~key ~data:value
let get = Hashtbl.find cache
let invalidate () = Hashtbl.clear cache
end
module ClassDefinitionsCache = DefinitionsCache (struct
type t = Statement.Class.t Node.t list option
end)
let containing_source ~resolution reference =
let global_resolution = Resolution.global_resolution resolution in
let ast_environment = GlobalResolution.ast_environment global_resolution in
let rec qualifier ~lead ~tail =
match tail with
| head :: (_ :: _ as tail) ->
let new_lead = Reference.create ~prefix:lead head in
if not (GlobalResolution.module_exists global_resolution new_lead) then
lead
else
qualifier ~lead:new_lead ~tail
| _ -> lead
in
qualifier ~lead:Reference.empty ~tail:(Reference.as_list reference)
|> AstEnvironment.ReadOnly.get_processed_source ast_environment
let class_summaries ~resolution reference =
match ClassDefinitionsCache.get reference with
| Some result -> result
| None ->
let open Option in
let result =
containing_source ~resolution reference
>>| Preprocessing.classes
>>| List.filter ~f:(fun { Node.value = { Statement.Class.name; _ }; _ } ->
Reference.equal reference name)
(* Prefer earlier definitions. *)
>>| List.rev
in
ClassDefinitionsCache.set reference result;
result
(* Find a method definition matching the given predicate. *)
let find_method_definitions ~resolution ?(predicate = fun _ -> true) name =
let open Statement in
let get_matching_define = function
| {
Node.value =
Statement.Define ({ signature = { name = define_name; _ } as signature; _ } as define);
_;
} ->
if Reference.equal define_name name && predicate define then
let global_resolution = Resolution.global_resolution resolution in
let parser = GlobalResolution.annotation_parser global_resolution in
let variables = GlobalResolution.variables global_resolution in
Annotated.Define.Callable.create_overload_without_applying_decorators
~parser
~variables
signature
|> Option.some
else
None
| _ -> None
in
Reference.prefix name
>>= class_summaries ~resolution
>>= List.hd
>>| (fun definition -> definition.Node.value.Class.body)
>>| List.filter_map ~f:get_matching_define
|> Option.value ~default:[]
module Global = struct
type t =
| Class
| Module
| Attribute of Type.t
[@@deriving show]
end
(* Resolve global symbols, ignoring decorators. *)
let resolve_global ~resolution name =
let global_resolution = Resolution.global_resolution resolution in
(* Resolve undecorated functions. *)
match GlobalResolution.global global_resolution name with
| Some { AttributeResolution.Global.undecorated_signature = Some signature; _ } ->
Some (Global.Attribute (Type.Callable signature))
| _ -> (
(* Resolve undecorated methods. *)
match find_method_definitions ~resolution name with
| [callable] -> Some (Global.Attribute (Type.Callable.create_from_implementation callable))
| first :: _ :: _ as overloads ->
(* Note that we use the first overload as the base implementation, which might be unsound. *)
Some
(Global.Attribute
(Type.Callable.create
~overloads
~parameters:first.parameters
~annotation:first.annotation
()))
| [] -> (
(* Fall back for anything else. *)
let annotation =
from_reference name ~location:Location.any
|> Resolution.resolve_expression_to_annotation resolution
in
match Annotation.annotation annotation with
| Type.Parametric { name = "type"; _ }
when GlobalResolution.class_exists global_resolution (Reference.show name) ->
Some Global.Class
| Type.Top when GlobalResolution.module_exists global_resolution name ->
Some Global.Module
| Type.Top when not (Annotation.is_immutable annotation) ->
(* FIXME: We are relying on the fact that nonexistent functions & attributes resolve
to mutable annotation, while existing ones resolve to immutable annotation. This is
fragile! *)
None
| annotation -> Some (Global.Attribute annotation)))
type parameter_requirements = {
anonymous_parameters_positions: Int.Set.t;
parameter_set: String.Set.t;
has_star_parameter: bool;
has_star_star_parameter: bool;
}
let create_parameters_requirements ~type_parameters =
let get_parameters_requirements requirements type_parameter =
let open Type.Callable.RecordParameter in
match type_parameter with
| PositionalOnly { index; _ } ->
{
requirements with
anonymous_parameters_positions =
Int.Set.add requirements.anonymous_parameters_positions index;
}
| Named { name; _ }
| KeywordOnly { name; _ } ->
let name = Identifier.sanitized name in
{ requirements with parameter_set = String.Set.add requirements.parameter_set name }
| Variable _ -> { requirements with has_star_parameter = true }
| Keywords _ -> { requirements with has_star_star_parameter = true }
in
let init =
{
anonymous_parameters_positions = Int.Set.empty;
parameter_set = String.Set.empty;
has_star_parameter = false;
has_star_star_parameter = false;
}
in
List.fold_left type_parameters ~f:get_parameters_requirements ~init
let demangle_class_attribute name =
if String.is_substring ~substring:"__class__" name then
String.split name ~on:'.'
|> List.rev
|> function
| attribute :: "__class__" :: rest -> List.rev (attribute :: rest) |> String.concat ~sep:"."
| _ -> name
else
name
let model_verification_error ~path ~location kind = { ModelVerificationError.kind; path; location }
let verify_model_syntax ~path ~location ~callable_name ~normalized_model_parameters =
(* Ensure that the parameter's default value is either not present or `...` to catch common errors
when declaring models. *)
let check_default_value (_, _, original) =
match Node.value original with
| { Parameter.value = None; _ }
| { Parameter.value = Some { Node.value = Expression.Constant Constant.Ellipsis; _ }; _ } ->
None
| { Parameter.value = Some expression; name; _ } ->
Some
(model_verification_error
~path
~location
(InvalidDefaultValue { callable_name = Reference.show callable_name; name; expression }))
in
List.find_map normalized_model_parameters ~f:check_default_value
|> function
| Some error -> Error error
| None -> Ok ()
let verify_imported_model ~path ~location ~callable_name ~callable_annotation =
match callable_annotation with
| Some { Type.Callable.kind = Type.Callable.Named actual_name; _ }
when not (Reference.equal callable_name actual_name) ->
Error
(model_verification_error
~path
~location
(ImportedFunctionModel { name = callable_name; actual_name }))
| _ -> Ok ()
let model_compatible_errors ~callable_overload ~normalized_model_parameters =
let open ModelVerificationError in
(* Once a requirement has been satisfied, it is removed from requirement object. At the end, we
check whether there remains unsatisfied requirements. *)
let validate_model_parameter position (errors, requirements) (model_parameter, _, _) =
match model_parameter with
| AccessPath.Root.LocalResult
| AccessPath.Root.Variable _ ->
failwith
("LocalResult|Variable won't be generated by AccessPath.Root.normalize_parameters, "
^ "and they cannot be compared with type_parameters.")
| AccessPath.Root.PositionalParameter { name; positional_only = true; _ } ->
if Int.Set.mem requirements.anonymous_parameters_positions position then
errors, requirements
else
( IncompatibleModelError.UnexpectedPositionalOnlyParameter
{
name;
position;
valid_positions = Int.Set.elements requirements.anonymous_parameters_positions;
}
:: errors,
requirements )
| AccessPath.Root.PositionalParameter { name; positional_only = false; _ }
| AccessPath.Root.NamedParameter { name } ->
let name = Identifier.sanitized name in
if String.is_prefix name ~prefix:"__" then (* It is an positional only parameter. *)
if Int.Set.mem requirements.anonymous_parameters_positions position then
errors, requirements
else if requirements.has_star_parameter then
(* If all positional only parameter quota is used, it might be covered by a `*args` *)
errors, requirements
else
( IncompatibleModelError.UnexpectedPositionalOnlyParameter
{
name;
position;
valid_positions = Int.Set.elements requirements.anonymous_parameters_positions;
}
:: errors,
requirements )
else
let { parameter_set; has_star_parameter; has_star_star_parameter; _ } = requirements in
(* Consume an required or optional named parameter. *)
if String.Set.mem parameter_set name then
let parameter_set = String.Set.remove parameter_set name in
errors, { requirements with parameter_set }
else if has_star_star_parameter then
(* If the name is not found in the set, it is covered by `**kwargs` *)
errors, requirements
else if has_star_parameter then (* positional parameters can be covered by `*args` *)
match model_parameter with
| PositionalParameter _ -> errors, requirements
| _ -> UnexpectedNamedParameter name :: errors, requirements
else
IncompatibleModelError.UnexpectedNamedParameter name :: errors, requirements
| AccessPath.Root.StarParameter _ ->
if requirements.has_star_parameter then
errors, requirements
else
IncompatibleModelError.UnexpectedStarredParameter :: errors, requirements
| AccessPath.Root.StarStarParameter _ ->
if requirements.has_star_star_parameter then
errors, requirements
else
IncompatibleModelError.UnexpectedDoubleStarredParameter :: errors, requirements
in
match callable_overload with
| { Type.Callable.parameters = Type.Callable.Defined type_parameters; _ } ->
let parameter_requirements = create_parameters_requirements ~type_parameters in
let errors, _ =
List.foldi
normalized_model_parameters
~f:validate_model_parameter
~init:([], parameter_requirements)
in
List.map
~f:(fun reason -> { IncompatibleModelError.reason; overload = Some callable_overload })
errors
| _ -> []
let verify_signature
~path
~location
~normalized_model_parameters
~name:callable_name
callable_annotation
=
let open Result in
verify_model_syntax ~path ~location ~callable_name ~normalized_model_parameters
>>= fun () ->
verify_imported_model ~path ~location ~callable_name ~callable_annotation
>>= fun () ->
match callable_annotation with
| Some ({ Type.Callable.implementation; overloads; _ } as callable) ->
let errors =
model_compatible_errors ~callable_overload:implementation ~normalized_model_parameters
in
let errors =
if (not (List.is_empty errors)) && not (List.is_empty overloads) then
(* We might be refering to a parameter defined in an overload. *)
let errors_in_overloads =
List.map overloads ~f:(fun callable_overload ->
model_compatible_errors ~callable_overload ~normalized_model_parameters)
in
if List.find ~f:List.is_empty errors_in_overloads |> Option.is_some then
[]
else
errors @ List.concat errors_in_overloads
else
List.map ~f:ModelVerificationError.IncompatibleModelError.strip_overload errors
in
if not (List.is_empty errors) then
Error
(model_verification_error
~path
~location
(IncompatibleModelError
{ name = Reference.show callable_name; callable_type = callable; errors }))
else
Ok ()
| _ -> Ok ()
let verify_global ~path ~location ~resolution ~name =
let name = demangle_class_attribute (Reference.show name) |> Reference.create in
let global = resolve_global ~resolution name in
match global with
| Some Global.Class ->
Error
(model_verification_error ~path ~location (ModelingClassAsAttribute (Reference.show name)))
| Some Global.Module ->
Error
(model_verification_error ~path ~location (ModelingModuleAsAttribute (Reference.show name)))
| Some (Global.Attribute (Type.Callable _))
| Some
(Global.Attribute
(Type.Parametric
{ name = "BoundMethod"; parameters = [Type.Parameter.Single (Type.Callable _); _] })) ->
Error
(model_verification_error
~path
~location
(ModelingCallableAsAttribute (Reference.show name)))
| Some (Global.Attribute _)
| None -> (
let global_resolution = Resolution.global_resolution resolution in
let class_summary =
Reference.prefix name
>>| Reference.show
>>| (fun class_name -> Type.Primitive class_name)
>>= GlobalResolution.class_summary global_resolution
>>| Node.value
in
match class_summary, global with
| Some ({ name = class_name; _ } as class_summary), _ ->
let attributes =
ClassSummary.attributes ~include_generated_attributes:false class_summary
in
let constructor_attributes = ClassSummary.constructor_attributes class_summary in
let attribute_name = Reference.last name in
if
Identifier.SerializableMap.mem attribute_name attributes
|| Identifier.SerializableMap.mem attribute_name constructor_attributes
then
Ok ()
else
Error
(model_verification_error
~path
~location
(MissingAttribute
{ class_name = Reference.show class_name; attribute_name = Reference.last name }))
| None, Some _ -> Ok ()
| None, None -> (
let module_name = Reference.first name in
let module_resolved = resolve_global ~resolution (Reference.create module_name) in
match module_resolved with
| Some _ ->
Error
(model_verification_error
~path
~location
(MissingSymbol { module_name; symbol_name = Reference.show name }))
| None ->
Error
(model_verification_error
~path
~location
(NotInEnvironment { module_name; name = Reference.show name }))))
| high | 0.646313 | 142 |
(*---------------------------------------------------------------------------
Copyright (c) 2018 The brzo programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
(** Opam b0 helpers. *)
open B00_std
open B00
val tool : Tool.t
(** [tool] is the [opam] tool. *)
val exists : Memo.t -> bool Fut.t
val if_exists : Memo.t -> (unit -> 'a Fut.t) -> 'a option Fut.t
val lib_dir : Memo.t -> ?switch:string -> unit -> Fpath.t Fut.t
val list :
Memo.t -> ?switch:string -> [ `Available | `Installed ] -> unit ->
string list Fut.t
type pkg = string * string option
val pkg_list : ?switch:string -> unit -> (pkg list, string) result
(*---------------------------------------------------------------------------
Copyright (c) 2018 The brzo programmers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
| medium | 0.405022 | 143 |
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@include file="/commons/taglibs.jsp"%>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>资源管理平台</title>
</head>
<%@include file="/new_page/top.jsp"%>
<body class="bjs">
<!-- 题库内容 -->
<form action="${ctx}/userManage/getUsers.do?method=search" method="post" name="searchFrm" id="searchFrm">
<div class="center">
<div class="tk_center01" style="min-height:120px;">
<div class="tk_zuo">
<div class="tik_xuanze">
<div class="mt10 fl tk_tixing">
<em class="fl">姓名:</em>
<input type="text" name="realName" class="fl tik_select" value="${realName}"/>
</div>
<%-- <div class="mt10 ml5 fl tk_tixing">
<span class="fl">用户类型:</span>
<div class="fl tik_select" >
<div class="tik_position_2">
<b class="ml5" id="sel_userType">${userType}</b>
<input type="hidden" name="userType" id="userType" value=""/>
<p class="tik_position01"><i class="tk_bjt10"></i></p>
</div>
<ul class="fl tk_list_1 tk_list" style="display:none;">
<select name="rolesId" id = "rolesId" style="display:none;">
<option value="0">请选择</option>
<c:forEach items="${roles}" var="role">
<option value="${role.id}"<c:if test="${role.id==info.id}"> selected</c:if>>${role.nameDesc}</option>
</c:forEach>
</select>
<li>请选择</li>
<c:forEach items="${roles}" var="role">
<li>${role.nameDesc}</li>
</c:forEach>
</ul>
</div>
</div> --%>
<div class="mt10 ml5 fl tk_tixing">
<p class="fl"><span class="fr">用户类型:</span></p>
<div id="searchRoleNames" name="searchRoleNames" readonly class="fl tik_select01 searchRoles">${userType}</div>
<input type = "hidden" id = "serchRoleIds" name = "serchRoleIds" >
<input type="hidden" name="userType" id="userType" value=""/>
</div>
<div class="mt10 ml5 fl tk_tixing">
<span class="fl">性别:</span>
<div class="fl tik_select" >
<div class="tik_position_2">
<b class="ml5" id="sel_sex"><c:if test="${sex == 1}">男</c:if><c:if test="${sex == 2}">女</c:if></b>
<input type="hidden" id="userSex" name="sex" value="${sex}"/>
<p class="tik_position01"><i class="tk_bjt10"></i></p>
</div>
<ul class="fl tk_list_1 tk_list" style="display:none;">
<li>请选择</li>
<li>男</li>
<li>女</li>
</ul>
</div>
</div>
<div class="mt10 ml10 fl tk_tixing">
<span class="fl">单位:</span>
<input type="text" name="workUnit" class="fl tik_select" value="${workUnit}"/>
</div>
</div>
<div class="clear"></div>
<div class="tik_xuanze">
<div class="mt10 fl tk_tixing">
<em class="fl">状态:</em>
<div class="fl tik_select" >
<div class="tik_position_2">
<b class="ml5" id="sel_status"><c:if test="${status == 1}">启用</c:if><c:if test="${status == 2}">禁用</c:if></b>
<input type="hidden" id="userStatus" name="status" value="${status}"/>
<p class="tik_position01"><i class="tk_bjt10"></i></p>
</div>
<ul class="fl tk_list_1 tk_list" style="display:none;">
<li>请选择</li>
<li>启用</li>
<li>禁用</li>
</ul>
</div>
</div>
<div class="mt10 ml5 fl tk_tixing">
<span class="fl">账号:</span>
<input type="text" name="loginName" class="fl tik_select" value="${loginName}"/>
</div>
<div class="mt10 fl tk_tixing">
<span class="fl ml5">学科:</span>
<div id="groupNames" class="fl tik_select01 searchProp" >${deptNames}</div>
<input type="hidden" name="groupIds" id="groupIds" value=""/>
<input type = "hidden" name = "deptNames" id = "deptNames" value = "">
</div>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="mt20 tk_you shiti" style="">
<a href="javascript:searchSysUserInf();" class="fl tk_chaxun">查询</a>
<a href="javascript:void(0);" class="fl ml30 tk_chaxun01">清空</a>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
</form>
<div class="tkbjs"></div>
<!-- -->
<div class="center none" style="">
<div class="tk_center01">
<div class="mt10 kit1_tiaojia">
<div class="fr cas_anniu">
<a href="javascript:addSysUser();" class="fl exp1_tianjia01" style="width:95px;margin-right:15px;">添加用户</a><a href="${ctx}/new_page/systemUser/systemUserDownLoad.jsp" class="fl" style="width:95px;">批量导入</a>
</div>
</div>
<div class="clear"></div>
<form id="listfm" name="listfm" method="post" action="${ctx}/userManage/getUsers.do" sort="list" defaultsort="1">
<display:table id="systemUser" cellpadding="0" cellspacing="0" partialList="true" requestURI="${ctx}/userManage/getUsers.do"
size="${page.fullListSize}" pagesize="${page.objectsPerPage}" list="${page}"
style="font-size:12px;width:100%;" class="mt10 cas_table"
decorator="com.hys.exam.displaytag.TableOverOutWrapper" >
<display:column
title="<input type='checkbox' id='chkall' value='' class='chkall'>"
style="width:3%;text-align:center">
<input type="checkbox" class="chk" name="ids" value="${systemUser.id}" id="qcid" />
</display:column>
<display:column title="序号" class="td_mat1" style="width:3%">
${systemUser_rowNum}
</display:column>
<display:column title="账号" sortable="true" class="td_mat1" style="width:16%" sortProperty="u.LOGIN_NAME">
${systemUser.loginName}
<em class="fr exp1_xiugai action" onclick = "javascript:editPass(${systemUser.id});" style="">修改密码</em>
</display:column>
<display:column title="用户姓名" sortable="true" property="realName" sortProperty="u.realName" style="width:7%;text-align:center" />
<display:column title="性别" sortable="true" sortProperty="d.sex" style="width:7%;text-align:center">
<c:if test="${systemUser.sex==1}">男</c:if>
<c:if test="${systemUser.sex==2}">女</c:if>
</display:column>
<display:column title="学科" property="deptName" style="width:10%;text-align:center" />
<display:column title="用户类型" property="roleName" style="width:7%;text-align:center">
</display:column>
<display:column title="单位" sortable="true" property="workUnit" sortProperty="d.work_unit" style="width:10%;text-align:center">
</display:column>
<display:column title="手机号码" sortable="true" property="phoneNumber" sortProperty="d.phone_Number" style="width:12%;text-align:center">
</display:column>
<display:column title="状态" style="width:7%;text-align:center">
<c:if test="${systemUser.enable == 1}">启用</c:if>
<c:if test="${systemUser.enable == 2}">禁用</c:if>
</display:column>
<display:column title="操作" style="width:14%;text-align:center">
<a href="javascript:sysUserModify('${systemUser.id}','${systemUser.loginName}','${systemUser.realName}','${systemUser.workUnit}','${systemUser.enable}',
'${systemUser.roleName}','${systemUser.sex}','${systemUser.phoneNumber}','${systemUser.deptName}','${systemUser.roleIds}');" class="exp1_tianjia01">修改</a>
<a href="javascript:offLine(${systemUser.id},${systemUser.enable});">
<c:if test="${systemUser.enable == 2}">启用</c:if>
<c:if test="${systemUser.enable == 1}">禁用</c:if>
</a>
</display:column>
</display:table>
<input type="hidden" name="org.apache.struts.taglib.html.TOKEN" value="${sessionScope['org.apache.struts.action.TOKEN']}" />
</form>
<div class="clear"></div>
<!-- 分页 -->
</div>
</div>
<!-- 试题内容(结束) -->
<div class="clear"></div>
<!-- 添加用户 -->
<div class="toumingdu exp_tang03" style="display:none;">
<form action="${ctx}/userManage/updateUser.do" method="post" name="editFrm" id="editFrm">
<div class="exper_tangkuang01" style="height:400px;margin:160px auto;border-radius:8px;-moz-border-radius:8px;-webkit-border-radius:8px;-khtml-border-radius:8px;background:#fff;width:700px;">
<div class="exr_mingchengz">
<div class="thi_shitineirong" style="width:700px;padding-top:50px;">
<ul>
<li class="mt15">
<div class="fl shitin_xinzeng04">
<p class="fl"><span class="fr">账号:</span><i style="color:red;"><em>*</em></i></p>
<input type="hidden" id="sysId" name="id"/>
<input type="hidden" id="roleIds" name="roleIds"/>
<input class="fl tki_bianji011" id="userId" name="userId" maxlength = "20"/>
</div>
<div class="fl ml10 shitin_xinzeng4">
<p class="fl"><span class="fr">用户类型:</span><i style="color:red;"><em>*</em></i></p>
<textarea cols="" placeholder="" rows="" id="curRolesNames" name="curRolesNames" readonly class="fl tki_bianji011 takuang_xk editRole"></textarea>
<input type = "hidden" id = "curRolesIds" name = "curRolesIds" >
</div>
<div class="clear"></div>
</li>
<li class="mt15">
<div class="fl shitin_xinzeng04">
<p class="fl"><span class="fr">姓名:</span><i style="color:red;"><em>*</em></i></p>
<input class="fl tki_bianji011" id="realName" name="realName" maxlength = "50"/>
</div>
<div class="fl ml10 shitin_xinzeng4">
<p class="fl"><span class="fr">性别:</span><i style="color:red;"><em>*</em></i></p>
<select class="fl tki_list01" id="sex" name="sex">
<option value="-1">---请选择---</option>
<option value="1">男</option>
<option value="2">女</option>
</select>
</div>
<div class="clear"></div>
</li>
<li class="mt15">
<div class="fl shitin_xinzeng04">
<p class="fl"><span class="fr">单位:</span></p>
<input class="fl tki_bianji011" id="workUnit" name="workUnit"/>
</div>
<div class="fl ml10 shitin_xinzeng4">
<p class="fl"><span class="fr">手机号:</span></p>
<input class="fl tki_bianji011" id="mobilPhone" name="mobilPhone"/>
</div>
<div class="clear"></div>
</li>
<li class="mt15">
<div class="fl shitin_xinzeng04">
<p class="fl"><span class="fr">状态:</span><i style="color:red;"><em>*</em></i></p>
<select class="fl tki_list01" style="width:202px;" id="curStatus" name="curStatus">
<option value="-1">---请选择---</option>
<option value="1">启用</option>
<option value="2">禁用</option>
</select>
</div>
<div class="fl ml10 shitin_xinzeng4">
<p class="fl"><span class="fr">学科:</span></p>
<textarea cols="" placeholder="" rows="" id="curPropNames" name="curPropNames" readonly class="fl tki_bianji011 takuang_xk editProp"></textarea>
<input type = "hidden" id = "curPropIds" name = "curPropIds" >
</div>
<div class="clear"></div>
</li>
<li>
<div class="ca1_anniu" style="width:200px;">
<a href="javascript:modifySysUser();" class="fl hide" style="margin-right:30px">保存</a>
<a href="javascript:void(0);" class="fl hide01" >返回</a>
</div>
<div class="clear"></div>
</li>
</ul>
<div class="clear"></div>
</div>
</div>
</div>
</form>
</div>
<!-- Add Window -->
<div class="toumingdu exp_tang04" style="display:none;">
<form action="${ctx}/userManage/addUsers.do" method="post" name="addFrm" id="addFrm">
<div class="exper_tangkuang01" style="height:400px;margin:160px auto;border-radius:8px;-moz-border-radius:8px;-webkit-border-radius:8px;-khtml-border-radius:8px;background:#fff;width:700px;">
<div class="exr_mingchengz">
<div class="thi_shitineirong" style="width:700px;padding-top:50px;">
<ul>
<li class="mt15">
<div class="fl shitin_xinzeng04">
<p class="fl"><span class="fr"><i style="color:red;"><em>*</em></i>账号:</span></p>
<input class="fl tki_bianji011" id="newuserId" name="loginName"/>
</div>
<div class="fl shitin_xinzeng04">
<p class="fl ml10"><span class="fr">用户类型:</span><i style="color:red;"><em>*</em></i></p>
<textarea cols="" placeholder="" rows="" id="newRoleNames" name="newRoleNames" readonly class="fl tki_bianji011 addRoles"></textarea>
<input type = "hidden" id = "newRoleIds" name = "newRoleIds" >
</div>
<div class="clear"></div>
</li>
<li class="mt15">
<div class="fl shitin_xinzeng04">
<p class="fl"><span class="fr"><i style="color:red;"><em>*</em></i>姓名:</span></p>
<input class="fl tki_bianji011" id="newrealName" name="realName"/>
</div>
<div class="fl ml10 shitin_xinzeng4">
<p class="fl"><span class="fr">性别:</span><i style="color:red;"><em>*</em></i></p>
<select class="fl tki_list01" name="sex" id = "addUserSex">
<option value="-1">---请选择---</option>
<option value="1">男</option>
<option value="2">女</option>
</select>
</div>
<div class="clear"></div>
</li>
<li class="mt15">
<div class="fl shitin_xinzeng04">
<p class="fl"><span class="fr">单位:</span></p>
<input class="fl tki_bianji011" name="addworkUnit" id = "addworkUnit"/>
</div>
<div class="fl ml10 shitin_xinzeng4">
<p class="fl"><span class="fr">手机号:</span></p>
<input class="fl tki_bianji011" name="addmobilPhone" id = "addmobilPhone"/>
</div>
<div class="clear"></div>
</li>
<li class="mt15">
<div class="fl shitin_xinzeng04">
<p class="fl"><span class="fr">状态:</span><i style="color:red;"><em>*</em></i></p>
<select class="fl tki_list01" style="width:202px;" name="status" id = "addStatus">
<option value="-1">---请选择---</option>
<option value="1">启用</option>
<option value="2">禁用</option>
</select>
</div>
<div class="fl ml10 shitin_xinzeng4">
<p class="fl"><span class="fr">学科:</span></p>
<textarea cols="" placeholder="" rows="" id="newgroupNames" name="newPropName" readonly class="fl tki_bianji011 takuang_xk addProp"></textarea>
<input type = "hidden" id = "newgroupIds" name = "newPropIds" >
</div>
<div class="clear"></div>
</li>
<li>
<div class="ca1_anniu" style="width:200px;">
<a href="javascript:addSysUserInf();" class="fl hide" style="margin-right:30px">保存</a>
<a href="javascript:void(0);" class="fl hide01" >返回</a>
</div>
<div class="clear"></div>
</li>
</ul>
<div class="clear"></div>
</div>
</div>
</div>
</form>
</div>
<!-- 新学科弹出框-一级 -->
<!-- 修改密码 -->
<form method = "post" name = "passFrm" id = "passFrm" action = "${ctx}/userManage/getUsers.do?method=setPass">
<div class="toumingdu exp_tang02" style="display:none;">
<div class="exper_tangkuang01" style="width:450px;height:300px;margin:200px auto;background:#fff;border:1px solid #dddddd;border-radius:5px;-moz-border-radius:5px;-webkit-border-radius:5px;-khtml-border-radius:5px;">
<div class="exr_mingchengz">
<div class="thi_shitineirong" style="padding-top:50px;padding-left:50px;">
<ul>
<li class="mt15">
<div class="fl shitin_xinzeng04">
<p class="fl"><span class="fr">新密码:</span></p>
<input class="fl tki_bianji011 newPassPanel" id = "newPassPanel" style = "width:200px;"/>
</div>
<div class="clear"></div>
</li>
<li class="mt15">
<div class="fl shitin_xinzeng04">
<p class="fl"><span class="fr">确认密码:</span></p>
<input class="fl tki_bianji011 conPassPanel" id = "conPassPanel" style = "width:200px;"/>
</div>
<div class="clear"></div>
</li>
<li class="mt30">
<div class="cas_cha" style="margin-left:70px;">
<p class="fl ml30" style="margin-left:10px;"><a href="javascript:setPass();" >保存</a></p>
<p class="fl ml30"><a href="javascript:void(0);" class="hide01" >返回</a></p>
</div>
<div class="clear"></div>
</li>
</ul>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<input type = "hidden" id = "userId" name = "userId" value = "0">
</form>
<script type="text/javascript">
$(function(){
//select menu
var CDCode = window.localStorage.getItem("CDCode");
var code = CDCode.split("-");
var menuindex = code[0];
var submenuindex = code[1];
var submenu = "mar_left0" + menuindex;
$('.tk_mainmenu>ul').find('li').eq(menuindex-1).addClass("action");
$('.'+submenu+'').show();
$('.'+submenu+'>a').eq(submenuindex-1).addClass("action");
//下拉框
$('.tik_select').click(function(){
$(".tk_list").css("display","none");
$(this).find('ul').show();
});
$('.tk_list li').click(function(){
var str=$(this).text();
$(this).parent().parent().find('div').find('b').text(str);
$('.tk_list').slideUp(50);
});
$('.tik_select').click(function(e){
return false
});
$(document).click(function(){
$('.tk_list').hide('fast');
});
//清空
$('.tk_chaxun01').click(function(){
$('#searchFrm').find('input').val('');
$('#searchFrm').find('select').val('');
//$('.tik_select').find('b').text("请选择");
$('#searchFrm').find('textarea').val('');
//$('#searchRoleNames').val("");
$('#groupNames').text("");
});
$('.cas_anniu_4,.bjt_kt,.make02').click(function(){
$('.att_make02').hide();
});
$('.hide01').click(function(){
$('.exp_tang02').hide();
$('.exp_tang03').hide();
$('.exp_tang04').hide();
});
$('.chkall').click(function(){
if ($(this).attr('checked') == true)
{
$('.chk').attr('checked' , 'true');
}
else
$('.chk').removeAttr('checked');
});
$('.exp1_xiugai').click(function(){
$('.exp_tang02').show();
});
});
//if ($('#sel_userType').text() == '') $('#sel_userType').text("请选择");
if ($('#sel_sex').text() == '') $('#sel_sex').text("请选择");
if ($('#sel_status').text() == '') $('#sel_status').text("请选择");
function searchSysUserInf(){
var selUserType = $('#searchRoleNames').val();
var selSex = $('#sel_sex').text();
var selStatus = $('#sel_status').text();
var selUserId;
var selSexId;
var selStatusId;
if (selSex == "男") selSexId = 1;
else if (selSex == "女") selSexId = 2;
if (selStatus == "启用") selStatusId = 1;
else if (selStatus == "禁用") selStatusId = 2;
$('#serchRoleIds').val(selUserType);
$('#userSex').val(selSexId);
$('#userStatus').val(selStatusId);
$('#deptNames').val($('#groupNames').text());
$('#searchFrm').submit();
}
function setPass() {
var newPass = $('#newPassPanel').val();
var conPass = $('#conPassPanel').val();
if (newPass == ""){
alert("请输入新密码!");
return;
}
if (conPass == ""){
alert("请确认新密码!");
return;
}
if (newPass != conPass){
alert("输入密码错误!");
return;
}
var url = "${ctx}/userManage/getUsers.do?method=setPass&newPass=" + newPass +"&userId="+ $('#userId').val();
$.ajax({
type: 'POST',
url: url,
dataType: 'text',
success : function (b){
if(b == "success")
{
$('.exp_tang02').hide();
alert('添加成功!');
}
else{
alert('添加失败!');
}
},
});
}
function sysUserModify(userId,loginName,realName,workUnit,status,roleName,sex,mobilPhone,deptName,roleIds){
if(status == 2) {
alert("禁用的用户不能修改!");
return false;
}
$('#sysId').val(userId);
$('#userId').val(loginName);
$('#realName').val(realName);
$('#workUnit').val(workUnit);
$('#curStatus').val(status);
$('#curRolesNames').text(roleName);
$('#sex').val(sex);
$('#mobilPhone').val(mobilPhone);
$('#curRolesIds').val(roleIds);
$('#curPropNames').text(deptName);
$('.exp_tang03').show();
}
function modifySysUser(){
var userid = $('#userId').val();
var realName = $('#realName').val();
var newRoleNames = $('#curRolesNames').val();
var sex = $('#sex').val();
var curStatus = $('#curStatus').val();
if(userid == ""){
alert ("帐号不能为空!");
return false;
}else if(realName == ""){
alert ("姓名不能为空!");
return false;
}else if(curRolesNames == ""){
alert ("用户类型不能为空!");
return false;
}else if(sex == ""){
alert ("性别不能为空!");
return false;
}else if(curStatus == ""){
alert ("状态不能为空!");
return false;
}
/* else if($('#workUnit').val() == ""){
alert ("单位不能为空!");
return false;
} */
$('#editFrm').submit();
$('.exp_tang03').hide();
}
function addSysUser(){
$('.exp_tang04').show();
}
function addSysUserInf(){
var userid = $('#newuserId').val();
var realName = $('#newrealName').val();
var addworkUnit = $('#addworkUnit').val();
var newRoleNames=$('#newRoleNames').val();
var addUserSex=$('#addUserSex').val();
var addStatus=$('#addStatus').val();
if(userid == ""){
alert ("帐号不能为空!");
return false;
}else if(realName == ""){
alert ("姓名不能为空!");
return false;
}else if(newRoleNames == ""){
alert("用户类型不能为空!");
return false;
}else if(addUserSex == "-1"){
alert("请选择性别!");
return false;
}else if(addStatus == "-1"){
alert("请选择状态!");
return false;
}
var url ="${ctx}/userManage/addUsers.do";
var params = "loginName=" + userid;
params += "&newRolesIds="+ $('#newRoleIds').val();
params += "&realName="+ $('#newrealName').val();
params += "&deptName="+ $('#newgroupNames').val();
params += "&sex=" + $('#addUserSex').val();
params += "&workUnit="+ $('#addworkUnit').val();
params += "&mobilPhone="+ $('#addmobilPhone').val();
params += "&status="+ $('#addStatus').val();
$.ajax({
type: 'POST',
url: url,
data : params,
dataType: 'text',
success : function (b){
if(b == "success")
{
alert('添加成功!');
document.location.href = document.location.href.split("#")[0];
}
else{
alert('账号不能重复!');
}
},
error: function(){
alert('添加失败');
}
});
$('.exp_tang04').hide();
}
function goBack() {
window.history.back();
}
//下拉框
function selectInit(){
$('.tik1_select').click(function(){
$(".tk1_list").css("display","none");
$(this).find('ul').show();
return false;
});
$('.tk1_list li').click(function(){
var str=$(this).text();
$(this).parent().parent().find('div').find('b').text(str);
$(this).parent().find('option').prop('selected', '');
$(this).parent().find('option').eq($(this).index()-1).prop('selected', 'selected');
$('.tk1_list').slideUp(50);
});
$('.tk1_list option:selected').each(function(){
var str=$(this).text();
$(this).parent().parent().parent().find('b').text(str);
});
}
function selSubRoles(id){
var rolesName = '';
var rolesIds = '';
$("input[name='rolesunit']").each(function () {
if ($(this).is(':checked')) {
if (rolesIds == '') rolesIds += this.value;
else rolesIds += ',' + this.value;
if (rolesName == '') rolesName += this.title;
else rolesName += ', ' + this.title;
}
});
$('#rolesNamePanel').text(rolesName);
}
function offLine(selId,state) {
if(state == 1)
{
if(!confirm("您确定要禁用此用户吗?"))
{
return false;
}
}
else
{
if(!confirm("您确定要启用此用户吗?"))
{
return false;
}
}
var url = "${ctx}/userManage/deleteUser.do";
var params = "id=" + selId;
$.ajax({
type: 'POST',
url: url,
data : params,
dataType: 'text',
success : function (b){
alert('添加成功!');
searchSysUserInf();
},
error: function(){
alert('添加失败');
}
});
}
function editPass(selId){
$('#userId').val(selId);
}
$('.searchProp').click(function(){
initPropList("学科", "${ctx}/propManage/getPropListAjax.do", 1, 0, 5, 3, $('#groupIds'), $('#groupNames'));
$('.att_make01').show();
});
$('.editProp').click(function(){
initPropList("学科", "${ctx}/propManage/getPropListAjax.do", 1, 0, 5, 3, $('#curPropIds'), $('#curPropNames'));
$('.att_make01').show();
});
$('.addProp').click(function(){
initPropList("学科", "${ctx}/propManage/getPropListAjax.do", 1, 0, 5, 3, $('#newgroupIds'), $('#newgroupNames'));
$('.att_make01').show();
});
$('.editRole').click(function(){
initPropList("用户类型", "${ctx}/userManage/getUserRoles.do", 1, 0, 2, 1, $('#curRolesIds'), $('#curRolesNames'));
$('.att_make01').show();
});
$('.addRoles').click(function(){
initPropList("用户类型", "${ctx}/userManage/getUserRoles.do", 1, 0, 2, 1, $('#newRoleIds'), $('#newRoleNames'));
$('.att_make01').show();
});
$('.searchRoles').click(function(){
initPropList("用户类型", "${ctx}/userManage/getUserRoles.do", 1, 0, 2, 1, $('#serchRoleIds'), $('#searchRoleNames'));
$('.att_make01').show();
});
</script>
</body>
</html>
| low | 0.786866 | 144 |
type foo
logical, allocatable :: bar[:]
end type
contains
subroutine foobar(this)
class(foo), intent(out) :: this
end subroutine
end
| low | 0.212605 | 145 |
use std::fmt;
use crate::AvailableDevice;
use crate::protos::MessageType;
mod error;
pub use error::*;
mod protocol;
pub use protocol::*;
pub mod usb;
use usb::*;
pub mod udp;
use udp::*;
pub const DEV_TREZOR_ONE: (u16, u16) = (0x534C, 0x0001);
pub const DEV_TREZOR_T: (u16, u16) = (0x1209, 0x53C1);
// pub const DEV_TREZOR2_BL: (u16, u16) = (0x1209, 0x53C0);
/// An available transport for a Trezor device, containing any of the
/// different supported transports.
#[derive(Debug)]
pub enum AvailableDeviceTransport {
// Hid(hid::AvailableHidTransport),
Usb(AvailableUsbTransport),
Udp(AvailableUdpTransport),
}
impl fmt::Display for AvailableDeviceTransport {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Usb(ref t) => write!(f, "{}", t),
Self::Udp(ref t) => write!(f, "{}", t),
}
}
}
/// A protobuf message accompanied by the message type. This type is used to pass messages over the
/// transport and used to contain messages received from the transport.
pub struct ProtoMessage(pub MessageType, pub Vec<u8>);
impl ProtoMessage {
pub fn new(mt: MessageType, payload: Vec<u8>) -> ProtoMessage {
ProtoMessage(mt, payload)
}
pub fn message_type(&self) -> MessageType {
self.0
}
pub fn payload(&self) -> &[u8] {
&self.1
}
pub fn into_payload(self) -> Vec<u8> {
self.1
}
/// Take the payload from the ProtoMessage and parse it to a protobuf message.
pub fn into_message<M: protobuf::Message>(self) -> Result<M, protobuf::error::ProtobufError> {
Ok(protobuf::Message::parse_from_bytes(&self.into_payload())?)
}
}
/// The transport interface that is implemented by the different ways to communicate with a Trezor
/// device.
pub trait Transport {
fn session_begin(&mut self) -> Result<(), error::Error>;
fn session_end(&mut self) -> Result<(), error::Error>;
fn write_message(&mut self, message: ProtoMessage) -> Result<(), error::Error>;
fn read_message(&mut self) -> Result<ProtoMessage, error::Error>;
}
pub fn connect(device: &AvailableDevice) -> Result<Box<dyn Transport>, Error> {
match &device.transport {
AvailableDeviceTransport::Usb(_) => UsbTransport::connect(device),
AvailableDeviceTransport::Udp(_) => UdpTransport::connect(device),
}
}
| high | 0.579677 | 146 |
; A215602: a(n) = L(n)*L(n+1), where L = A000032 (Lucas numbers).
; 2,3,12,28,77,198,522,1363,3572,9348,24477,64078,167762,439203,1149852,3010348,7881197,20633238,54018522,141422323,370248452,969323028,2537720637,6643838878,17393796002,45537549123,119218851372,312119004988,817138163597,2139295485798,5600748293802,14662949395603,38388099893012,100501350283428,263115950957277,688846502588398,1803423556807922,4721424167835363,12360848946698172,32361122672259148,84722519070079277,221806434537978678,580696784543856762,1520283919093591603,3980154972736918052,10420180999117162548,27280388024614569597,71420983074726546238,186982561199565069122,489526700523968661123,1281597540372340914252,3355265920593054081628,8784200221406821330637,22997334743627409910278,60207804009475408400202,157626077284798815290323,412670427844921037470772,1080385206249964297121988,2828485190904971853895197,7405070366464951264563598,19386725908489881939795602,50755107359004694554823203,132878596168524201724674012,347880681146567910619198828,910763447271179530132922477,2384409660666970679779568598,6242465534729732509205783322,16342986943522226847837781363,42786495295836948034307560772,112016498943988617255084900948,293263001536128903730947142077,767772505664398093937756525278,2010054515457065378082322433762,5262391040706798040309210776003,13777118606663328742845309894252,36068964779283188188226718906748,94429775731186235821834846825997,247220362414275519277277821571238,647231311511640322009998617887722,1694473572120645446752718032091923,4436189404850296018248155478388052,11614094642430242607991748403072228,30406094522440431805727089730828637,79604188924891052809189520789413678,208406472252232726621841472637412402,545615227831807127056334897122823523
seq $0,2878 ; Bisection of Lucas sequence: a(n) = L(2*n+1).
mov $1,$0
sub $0,1
sub $1,2
lpb $1
sub $1,2
mod $1,5
sub $1,2
add $0,$1
trn $1,1
lpe
add $0,2
| low | 0.770605 | 147 |
/*
* Copyright © 2014, David Tesler (https://github.com/protobufel)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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.
*/
/**
* A complete .proto format grammar.
* This grammar is used for the direct construction of a protobuf
* FileDescriptorProto object.
*
*/
grammar Proto;
import ProtoLiterals;
// all collections must have unique respective names
//proto : (fileOption | publicImport | regularImport | SEMI)* packageStatement?
// (fileOption | message | extend | enumStatement | service | SEMI )* EOF ;
// lax mix as in protoc
proto : topRepeatedStatement* packageStatement? topRepeatedStatement* EOF ;
topRepeatedStatement
: publicImport
| regularImport
| fileOption
| message
| extend
| enumStatement
| service
| SEMI ;
publicImport : 'import' 'public' importPath SEMI ;
regularImport : 'import' importPath SEMI ;
packageStatement : 'package' packageName SEMI ;
// Options stuff
fileOption : 'option' ( standardFileOption | customFileOption ) SEMI ;
customFileOption : customOption ;
standardFileOption
: 'java_package' '=' StringLiteral # standardFileOptionJavaPackage
| 'java_outer_classname' '=' StringLiteral # standardFileOptionJavaOuterClassname
| 'java_multiple_files' '=' BooleanLiteral # standardFileOptionJavaMultipleFiles
| 'java_generate_equals_and_hash' '=' BooleanLiteral # standardFileOptionJavaGenerateEqualsAndHash
| 'optimize_for' '=' optimizeMode # standardFileOptionOptimizeFor
| 'go_package' '=' StringLiteral # standardFileOptionGoPackage
| 'cc_generic_services' '=' BooleanLiteral # standardFileOptionCcGenericServices
| 'java_generic_services' '=' BooleanLiteral # standardFileOptionJavaGenericServices
| 'py_generic_services' '=' BooleanLiteral # standardFileOptionPyGenericServices
| 'java_string_check_utf8' '=' BooleanLiteral # standardFileOptionJavaStringCheckUtf8
| 'deprecated' '=' BooleanLiteral # standardFileOptionDeprecated
;
optimizeMode
: 'SPEED'
| 'CODE_SIZE'
| 'LITE_RUNTIME'
;
customOption: customOptionName '=' customOptionValue ;
customOptionName
: 'default' {notifyErrorListeners("cannot use default option here");}
| customOptionNamePart ( '.' customOptionNamePart )* ;
customOptionNamePart : '(' customOptionNamePartId ')' | identifier ;
customOptionNamePartId : extendedId ;
//TODO: should this also include list values?
customOptionValue: optionScalarValue | optionAggregateValue ;
optionAggregateValue: '{' optionAggregateValueField* RBRACE ;
optionAggregateValueField : aggregateCustomOptionName
(
':' (optionScalarValue | optionScalarListValue | optionAggregateListValue)
| optionAggregateValue
)
;
// we don't enforce List's element types; it should be done during actual TextFormat parsing!
optionAggregateListValue: '[' (optionAggregateValue (',' optionAggregateValue)*)? ']' ;
optionScalarListValue: '[' (optionScalarValue (',' optionScalarValue)*)? ']' ;
aggregateCustomOptionName
: ( aggregateCustomOptionNamePart | identifier )
( '.' ( aggregateCustomOptionNamePart | identifier ) )* ;
aggregateCustomOptionNamePart : '[' extendedId ']' ;
service: 'service' identifier '{' ( methodStatement | serviceOption | SEMI )* RBRACE ;
serviceOption: 'option' ( standardServiceOption | customOption ) SEMI ;
standardServiceOption
: 'deprecated' '=' BooleanLiteral # standardServiceOptionDeprecated
;
methodStatement: 'rpc' identifier '(' extendedId ')' 'returns' '(' extendedId ')' (SEMI | '{' methodOption* RBRACE) ;
methodOption: 'option' ( standardMethodOption | customOption ) SEMI ;
standardMethodOption
: 'deprecated' '=' BooleanLiteral # standardMethodOptionDeprecated
;
message : 'message' identifier '{' messageStatements? RBRACE ;
messageStatements : (messageOption | groupOrFieldOrExtend | message | extensions
| enumStatement | oneofStatement | SEMI)+ ;
oneofStatement: 'oneof' identifier '{' oneofGroupOrField+ RBRACE ;
oneofGroupOrField : oneofGroup | oneofField ;
oneofField:
( optionalScalarField |
enumDefaultField |
( scalarType | extendedId ) identifier '=' fieldNumber fieldOptions?
)
SEMI
;
oneofGroup : 'group' groupIdentifier '=' fieldNumber '{' messageStatements RBRACE ;
groupOrFieldOrExtend: group | field | extend ;
messageOption : 'option' ( standardMessageOption | customOption ) SEMI ;
standardMessageOption
: 'message_set_wire_format' '=' BooleanLiteral # standardMessageOptionMessageSetWireFormat
| 'no_standard_descriptor_accessor' '=' BooleanLiteral # standardMessageOptionNoStandardDescriptorAccessor
| 'deprecated' '=' BooleanLiteral # standardMessageOptionDeprecated
;
extensions: 'extensions' fieldNumber extensionRangeEnd? SEMI ;
extensionRangeEnd: 'to' (fieldNumber | 'max') ;
extend : 'extend' extendedId '{' groupOrField+ RBRACE ;
groupOrField : group | field ;
group : label 'group' groupIdentifier '=' fieldNumber '{' messageStatements RBRACE ;
//enumStatement : 'enum' identifier '{' ( enumOption | enumField | SEMI )* RBRACE ;
enumStatement : 'enum' identifier '{' ( enumOption | SEMI )? enumField (enumOption | SEMI | enumField)* RBRACE ;
enumOption: 'option' ( standardEnumOption | customOption ) SEMI ;
standardEnumOption
: 'allow_alias' '=' BooleanLiteral # standardEnumOptionAllowAlias
| 'deprecated' '=' BooleanLiteral # standardEnumOptionDeprecated
;
enumField : identifier '=' enumValue enumValueOptions? SEMI ;
enumValue : NegativeIntegerLiteral | IntegerLiteral ;
enumValueOptions: '[' (standardEnumValueOption | customOption) (',' customOption)* ']' ;
standardEnumValueOption
: 'deprecated' '=' BooleanLiteral # standardEnumValueOptionDeprecated
;
field :
( 'optional' optionalScalarField |
'optional' enumDefaultField |
label ( scalarType | extendedId ) identifier '=' fieldNumber fieldOptions?
)
SEMI
;
enumDefaultField: extendedId identifier '=' fieldNumber
'[' (fieldOption ',')* enumDefaultFieldOption ( ',' fieldOption )* ']' ;
enumDefaultFieldOption: 'default' '=' identifier ;
optionalScalarField
: doubleField
| floatField
| int32Field
| int64Field
| uint32Field
| uint64Field
| sint32Field
| sint64Field
| fixed32Field
| fixed64Field
| sfixed32Field
| sfixed64Field
| boolField
| bytesField
| stringField
;
doubleField : 'double' identifier '=' fieldNumber ('[' doubleFieldOption ( ',' doubleFieldOption )* ']')? ;
floatField : 'float' identifier '=' fieldNumber ('[' floatFieldOption ( ',' floatFieldOption )* ']')? ;
int32Field : 'int32' identifier '=' fieldNumber ('[' int32FieldOption ( ',' int32FieldOption )* ']')? ;
int64Field : 'int64' identifier '=' fieldNumber ('[' int64FieldOption ( ',' int64FieldOption )* ']')? ;
uint32Field : 'uint32' identifier '=' fieldNumber ('[' uint32FieldOption ( ',' uint32FieldOption )* ']')? ;
uint64Field : 'uint64' identifier '=' fieldNumber ('[' uint64FieldOption ( ',' uint64FieldOption )* ']')? ;
sint32Field : 'sint32' identifier '=' fieldNumber ('[' sint32FieldOption ( ',' sint32FieldOption )* ']')? ;
sint64Field : 'sint64' identifier '=' fieldNumber ('[' sint64FieldOption ( ',' sint64FieldOption )* ']')? ;
fixed32Field : 'fixed32' identifier '=' fieldNumber ('[' fixed32FieldOption ( ',' fixed32FieldOption )* ']')? ;
fixed64Field : 'fixed64' identifier '=' fieldNumber ('[' fixed64FieldOption ( ',' fixed64FieldOption )* ']')? ;
sfixed32Field : 'sfixed32' identifier '=' fieldNumber ('[' sfixed32FieldOption ( ',' sfixed32FieldOption )* ']')? ;
sfixed64Field : 'sfixed64' identifier '=' fieldNumber ('[' sfixed64FieldOption ( ',' sfixed64FieldOption )* ']')? ;
boolField : 'bool' identifier '=' fieldNumber ('[' boolFieldOption ( ',' boolFieldOption )* ']')? ;
stringField : 'string' identifier '=' fieldNumber ('[' stringFieldOption ( ',' stringFieldOption )* ']')? ;
bytesField : 'bytes' identifier '=' fieldNumber ('[' bytesFieldOption ( ',' bytesFieldOption )* ']')? ;
doubleFieldOption : 'default' '=' doubleValue | fieldOption ;
floatFieldOption : 'default' '=' floatValue | fieldOption ;
int32FieldOption : 'default' '=' int32Value | fieldOption ;
int64FieldOption : 'default' '=' int64Value | fieldOption ;
uint32FieldOption : 'default' '=' uint32Value | fieldOption ;
uint64FieldOption : 'default' '=' uint64Value | fieldOption ;
sint32FieldOption : 'default' '=' sint32Value | fieldOption ;
sint64FieldOption : 'default' '=' sint64Value | fieldOption ;
fixed32FieldOption : 'default' '=' fixed32Value | fieldOption ;
fixed64FieldOption : 'default' '=' fixed64Value | fieldOption ;
sfixed32FieldOption : 'default' '=' sfixed32Value | fieldOption ;
sfixed64FieldOption : 'default' '=' sfixed64Value | fieldOption ;
boolFieldOption : 'default' '=' boolValue | fieldOption ;
stringFieldOption : 'default' '=' stringValue | fieldOption ;
bytesFieldOption : 'default' '=' bytesValue | fieldOption ;
fieldOptions : '[' fieldOption (',' fieldOption)* ']' ;
fieldOption : standardFieldOption | customOption ;
standardFieldOption
: 'ctype' '=' cType # standardFieldOptionCTypeOption
| 'packed' '=' BooleanLiteral # standardFieldOptionPacked
| 'lazy' '=' BooleanLiteral # standardFieldOptionLazy
| 'deprecated' '=' BooleanLiteral # standardFieldOptionDeprecated
// Experimental
| 'experimental_map_key' '=' StringLiteral # standardFieldOptionExperimentalMapKey
// Google-internal
| 'weak' '=' BooleanLiteral # standardFieldOptionWeak
;
cType
: 'STRING'
| 'CORD'
| 'STRING_PIECE'
;
packageName : identifier ('.' identifier)* ;
fieldNumber : IntegerLiteral ;
importPath : StringLiteral ;
label : 'optional' | 'repeated' | 'required' ;
optionScalarValue
: (NegativeIntegerLiteral
| IntegerLiteral)
| doubleValue
| (StringLiteral
| BooleanLiteral)
| identifier
;
literal
: numberLiteral
| ( StringLiteral | BooleanLiteral )
;
numberLiteral
: NegativeIntegerLiteral
| NegativeFloatingPointLiteral
| IntegerLiteral
| FloatingPointLiteral
;
unsignedNumberLiteral
: IntegerLiteral
| FloatingPointLiteral
;
intLiteral
: NegativeIntegerLiteral
| IntegerLiteral
;
doubleValue : NegativeIntegerLiteral | IntegerLiteral | NegativeFloatingPointLiteral | FloatingPointLiteral ;
floatValue : NegativeIntegerLiteral | IntegerLiteral | NegativeFloatingPointLiteral | FloatingPointLiteral ;
int32Value : NegativeIntegerLiteral | IntegerLiteral ;
int64Value : NegativeIntegerLiteral | IntegerLiteral ;
uint32Value : IntegerLiteral ;
uint64Value : IntegerLiteral ;
sint32Value : NegativeIntegerLiteral | IntegerLiteral ;
sint64Value : NegativeIntegerLiteral | IntegerLiteral ;
fixed32Value : NegativeIntegerLiteral | IntegerLiteral ;
fixed64Value : NegativeIntegerLiteral | IntegerLiteral ;
sfixed32Value : NegativeIntegerLiteral | IntegerLiteral ;
sfixed64Value : NegativeIntegerLiteral | IntegerLiteral ;
boolValue : BooleanLiteral;
bytesValue : StringLiteral | ByteStringLiteral;
stringValue : StringLiteral;
groupIdentifier
: 'Import'
| 'Go_package'
| 'Java_generic_services'
| 'Repeated'
| 'CODE_SIZE'
| 'String'
| 'Ctype'
| 'Bool'
| 'Public'
| 'To'
| 'Service'
| 'LITE_RUNTIME'
| 'Allow_alias'
| 'Packed'
| 'Option'
| 'Weak'
| 'Message_set_wire_format'
| 'Deprecated'
| 'Double'
| 'Sint64'
| 'Bytes'
| 'Sint32'
| 'Optional'
| 'Enum'
| 'Max'
| 'No_standard_descriptor_accessor'
| 'Extensions'
| 'Extend'
| 'Group'
| 'Lazy'
| 'Int64'
| 'Cc_generic_services'
| 'Int32'
| 'Java_generate_equals_and_hash'
| 'Message'
| 'Fixed64'
| 'Experimental_map_key'
| 'Returns'
| 'Fixed32'
| 'Rpc'
| 'Optimize_for'
| 'Py_generic_services'
| 'STRING'
| 'CORD'
| 'Required'
| 'Package'
| 'STRING_PIECE'
| 'Java_package'
| 'Java_multiple_files'
| 'Uint32'
| 'Java_outer_classname'
| 'Float'
| 'Sfixed64'
| 'Sfixed32'
| 'SPEED'
| 'Default'
| 'Uint64'
| 'oneof'
| 'deprecated'
| 'java_string_check_utf8'
// all Java built-in
| 'Override'
| 'Deprecated'
| 'SuppressWarnings'
| 'SafeVarargs'
| 'FunctionalInterface'
| 'Retention'
| 'Documented'
| 'Target'
| 'Inherited'
| 'Repeatable'
| 'String'
| 'Boolean'
| 'Byte'
| 'Character'
| 'Short'
| 'Integer'
| 'Long'
| 'Float'
| 'Double'
| 'Class'
| 'Object'
| UpperIdentifier ;
identifier
: 'import'
| 'go_package'
| 'java_generic_services'
| 'repeated'
| 'CODE_SIZE'
| 'string'
| 'ctype'
| 'bool'
| 'public'
| 'to'
| 'service'
| 'LITE_RUNTIME'
| 'allow_alias'
| 'packed'
| 'option'
| 'weak'
| 'message_set_wire_format'
| 'deprecated'
| 'double'
| 'sint64'
| 'bytes'
| 'sint32'
| 'optional'
| 'enum'
| 'max'
| 'no_standard_descriptor_accessor'
| 'extensions'
| 'extend'
| 'group'
| 'lazy'
| 'int64'
| 'cc_generic_services'
| 'int32'
| 'java_generate_equals_and_hash'
| 'message'
| 'fixed64'
| 'experimental_map_key'
| 'returns'
| 'fixed32'
| 'rpc'
| 'optimize_for'
| 'py_generic_services'
| 'STRING'
| 'CORD'
| 'required'
| 'package'
| 'STRING_PIECE'
| 'java_package'
| 'java_multiple_files'
| 'uint32'
| 'java_outer_classname'
| 'float'
| 'sfixed64'
| 'sfixed32'
| 'SPEED'
| 'default'
| 'uint64'
| 'oneof'
| 'deprecated'
| 'java_string_check_utf8'
// all Java reserved and built-in
| 'abstract'
| 'assert'
| 'boolean'
| 'break'
| 'byte'
| 'case'
| 'catch'
| 'char'
| 'class'
| 'const'
| 'continue'
| 'default'
| 'do'
| 'double'
| 'else'
| 'enum'
| 'extends'
| 'final'
| 'finally'
| 'float'
| 'for'
| 'if'
| 'goto'
| 'implements'
| 'import'
| 'instanceof'
| 'int'
| 'interface'
| 'long'
| 'native'
| 'new'
| 'package'
| 'private'
| 'protected'
| 'public'
| 'return'
| 'short'
| 'static'
| 'strictfp'
| 'super'
| 'switch'
| 'synchronized'
| 'this'
| 'throw'
| 'throws'
| 'transient'
| 'try'
| 'void'
| 'volatile'
| 'while'
| 'Override'
| 'Deprecated'
| 'SuppressWarnings'
| 'SafeVarargs'
| 'FunctionalInterface'
| 'Retention'
| 'Documented'
| 'Target'
| 'Inherited'
| 'Repeatable'
| 'String'
| 'Boolean'
| 'Byte'
| 'Character'
| 'Short'
| 'Integer'
| 'Long'
| 'Float'
| 'Double'
| 'Class'
| 'Object'
| UpperIdentifier
| LowerIdentifier ;
extendedId : '.'? identifier ('.' identifier)* ;
// Lexer rules
//
// Keywords, sort of
scalarType :
'double' |
'float' |
'int32' |
'int64' |
'uint32' |
'uint64' |
'sint32' |
'sint64' |
'fixed32' |
'fixed64' |
'sfixed32' |
'sfixed64' |
'bool' |
'string' |
'bytes' ;
// ProtoLiterals lexer
| high | 0.366622 | 148 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Pos.Logic.Full
( LogicWorkMode
, logicFull
) where
import Universum hiding (id)
import Control.Lens (at, to)
import Data.Conduit (ConduitT)
import qualified Data.HashMap.Strict as HM
import Data.Tagged (Tagged (..), tagWith)
import Formatting (build, sformat, (%))
import System.Wlog (WithLogger, logDebug)
import Pos.Chain.Block (Block, BlockHeader, HasBlockConfiguration,
HeaderHash)
import Pos.Chain.Security (SecurityParams, shouldIgnorePkAddress)
import Pos.Chain.Ssc (MCCommitment (..), MCOpening (..),
MCShares (..), MCVssCertificate (..), SscTag (..),
TossModifier, ldModifier, sscRunLocalQuery,
tmCertificates, tmCommitments, tmOpenings, tmShares)
import Pos.Chain.Txp (MemPool (..), TxpConfiguration)
import Pos.Communication (NodeId)
import Pos.Core (HasConfiguration, StakeholderId, addressHash)
import Pos.Core.Chrono (NE, NewestFirst, OldestFirst)
import Pos.Core.Delegation (ProxySKHeavy)
import Pos.Core.Ssc (getCertId, getCommitmentsMap, lookupVss)
import Pos.Core.Txp (TxAux (..), TxMsgContents (..))
import Pos.Core.Update (BlockVersionData, UpdateProposal (..),
UpdateVote (..))
import Pos.Crypto (ProtocolMagic, hash)
import qualified Pos.DB.Block as Block
import qualified Pos.DB.Block as DB (getTipBlock)
import qualified Pos.DB.BlockIndex as DB (getHeader, getTipHeader)
import Pos.DB.Class (MonadBlockDBRead, MonadDBRead, MonadGState (..),
SerializedBlock)
import qualified Pos.DB.Class as DB (MonadDBRead (dbGetSerBlock))
import Pos.DB.Ssc (sscIsDataUseful, sscProcessCertificate,
sscProcessCommitment, sscProcessOpening, sscProcessShares)
import Pos.DB.Txp.MemState (getMemPool, withTxpLocalData)
import Pos.DB.Update (getLocalProposalNVotes, getLocalVote,
isProposalNeeded, isVoteNeeded)
import Pos.Infra.Recovery.Types (RecoveryHeader, RecoveryHeaderTag)
import Pos.Infra.Slotting (MonadSlots)
import Pos.Infra.Util.JsonLog.Events (JLEvent)
import Pos.Listener.Delegation (DlgListenerConstraint)
import qualified Pos.Listener.Delegation as Delegation (handlePsk)
import Pos.Listener.Txp (TxpMode)
import qualified Pos.Listener.Txp as Txp (handleTxDo)
import Pos.Listener.Update (UpdateMode, handleProposal, handleVote)
import Pos.Logic.Types (KeyVal (..), Logic (..))
import qualified Pos.Network.Block.Logic as Block
import Pos.Network.Block.WorkMode (BlockWorkMode)
import Pos.Recovery (MonadRecoveryInfo)
import qualified Pos.Recovery as Recovery
import Pos.Util.Util (HasLens (..))
-- The full logic layer uses existing pieces from the former monolithic
-- approach, in which there was no distinction between networking and
-- blockchain logic (any piece could use the network via some class constraint
-- on the monad). The class-based approach is not problematic for
-- integration with a diffusion layer, because in practice the concrete
-- monad which satisfies these constraints is a reader form over IO, so we
-- always have
--
-- runIO :: m x -> IO x
-- liftIO :: IO x -> m x
--
-- thus a diffusion layer which is in IO can be made to work with a logic
-- layer which uses the more complicated monad, and vice-versa.
type LogicWorkMode ctx m =
( HasConfiguration
, HasBlockConfiguration
, WithLogger m
, MonadReader ctx m
, MonadMask m
, MonadBlockDBRead m
, MonadDBRead m
, MonadGState m
, MonadRecoveryInfo ctx m
, MonadSlots ctx m
, HasLens RecoveryHeaderTag ctx RecoveryHeader
, BlockWorkMode ctx m
, DlgListenerConstraint ctx m
, TxpMode ctx m
, UpdateMode ctx m
)
-- | A stop-gap full logic layer based on the RealMode. It just uses the
-- monadX constraints to do most of its work.
logicFull
:: forall ctx m .
( LogicWorkMode ctx m )
=> ProtocolMagic
-> TxpConfiguration
-> StakeholderId
-> SecurityParams
-> (JLEvent -> m ()) -- ^ JSON log callback. FIXME replace by structured logging solution
-> Logic m
logicFull pm txpConfig ourStakeholderId securityParams jsonLogTx =
let
getSerializedBlock :: HeaderHash -> m (Maybe SerializedBlock)
getSerializedBlock = DB.dbGetSerBlock
streamBlocks :: HeaderHash -> ConduitT () SerializedBlock m ()
streamBlocks = Block.streamBlocks DB.dbGetSerBlock Block.resolveForwardLink
getTip :: m Block
getTip = DB.getTipBlock
getTipHeader :: m BlockHeader
getTipHeader = DB.getTipHeader
getAdoptedBVData :: m BlockVersionData
getAdoptedBVData = gsAdoptedBVData
recoveryInProgress :: m Bool
recoveryInProgress = Recovery.recoveryInProgress
getBlockHeader :: HeaderHash -> m (Maybe BlockHeader)
getBlockHeader = DB.getHeader
getHashesRange
:: Maybe Word -- ^ Optional limit on how many to pull in.
-> HeaderHash
-> HeaderHash
-> m (Either Block.GetHashesRangeError (OldestFirst NE HeaderHash))
getHashesRange = Block.getHashesRange
getBlockHeaders
:: Maybe Word -- ^ Optional limit on how many to pull in.
-> NonEmpty HeaderHash
-> Maybe HeaderHash
-> m (Either Block.GetHeadersFromManyToError (NewestFirst NE BlockHeader))
getBlockHeaders = Block.getHeadersFromManyTo
getLcaMainChain
:: OldestFirst [] HeaderHash
-> m (NewestFirst [] HeaderHash, OldestFirst [] HeaderHash)
getLcaMainChain = Block.lcaWithMainChainSuffix
postBlockHeader :: BlockHeader -> NodeId -> m ()
postBlockHeader = Block.handleUnsolicitedHeader pm
postPskHeavy :: ProxySKHeavy -> m Bool
postPskHeavy = Delegation.handlePsk pm
postTx = KeyVal
{ toKey = pure . Tagged . hash . taTx . getTxMsgContents
, handleInv = \(Tagged txId) -> not . HM.member txId . _mpLocalTxs <$> withTxpLocalData getMemPool
, handleReq = \(Tagged txId) -> fmap TxMsgContents . HM.lookup txId . _mpLocalTxs <$> withTxpLocalData getMemPool
, handleData = \(TxMsgContents txAux) -> Txp.handleTxDo pm txpConfig jsonLogTx txAux
}
postUpdate = KeyVal
{ toKey = \(up, _) -> pure . tag $ hash up
, handleInv = isProposalNeeded . unTagged
, handleReq = getLocalProposalNVotes . unTagged
, handleData = handleProposal pm
}
where
tag = tagWith (Proxy :: Proxy (UpdateProposal, [UpdateVote]))
postVote = KeyVal
{ toKey = \UnsafeUpdateVote{..} -> pure $ tag (uvProposalId, uvKey, uvDecision)
, handleInv = \(Tagged (id, pk, dec)) -> isVoteNeeded id pk dec
, handleReq = \(Tagged (id, pk, dec)) -> getLocalVote id pk dec
, handleData = handleVote pm
}
where
tag = tagWith (Proxy :: Proxy UpdateVote)
postSscCommitment = postSscCommon
CommitmentMsg
(\(MCCommitment (pk, _, _)) -> addressHash pk)
(\id tm -> MCCommitment <$> tm ^. tmCommitments . to getCommitmentsMap . at id)
(\(MCCommitment comm) -> sscProcessCommitment pm comm)
postSscOpening = postSscCommon
OpeningMsg
(\(MCOpening key _) -> key)
(\id tm -> MCOpening id <$> tm ^. tmOpenings . at id)
(\(MCOpening key open) -> sscProcessOpening pm key open)
postSscShares = postSscCommon
SharesMsg
(\(MCShares key _) -> key)
(\id tm -> MCShares id <$> tm ^. tmShares . at id)
(\(MCShares key shares) -> sscProcessShares pm key shares)
postSscVssCert = postSscCommon
VssCertificateMsg
(\(MCVssCertificate vc) -> getCertId vc)
(\id tm -> MCVssCertificate <$> lookupVss id (tm ^. tmCertificates))
(\(MCVssCertificate cert) -> sscProcessCertificate pm cert)
postSscCommon
:: ( Buildable err, Buildable contents )
=> SscTag
-> (contents -> StakeholderId)
-> (StakeholderId -> TossModifier -> Maybe contents)
-> (contents -> m (Either err ()))
-> KeyVal (Tagged contents StakeholderId) contents m
postSscCommon sscTag contentsToKey toContents processData = KeyVal
{ toKey = pure . tagWith contentsProxy . contentsToKey
, handleInv = sscIsDataUseful sscTag . unTagged
, handleReq = \(Tagged addr) -> toContents addr . view ldModifier <$> sscRunLocalQuery ask
, handleData = \dat -> do
let addr = contentsToKey dat
-- [CSL-685] TODO: Add here malicious emulation for network
-- addresses when TW will support getting peer address
-- properly
-- Stale comment?
handleDataDo dat addr =<< shouldIgnorePkAddress addr
}
where
contentsProxy = (const Proxy :: (contents -> k) -> Proxy contents) contentsToKey
ignoreFmt =
"Malicious emulation: data "%build%" for id "%build%" is ignored"
handleDataDo dat id shouldIgnore
| shouldIgnore = False <$ logDebug (sformat ignoreFmt id dat)
| otherwise = sscProcessMessage processData dat
sscProcessMessage sscProcessMessageDo dat =
sscProcessMessageDo dat >>= \case
Left err -> False <$ logDebug (sformat ("Data is rejected, reason: "%build) err)
Right () -> return True
in Logic {..}
| high | 0.89278 | 149 |
<?xml version="1.0"?>
<!--
platform-xidl.xsl:
XSLT stylesheet that generates a platform-specific
VirtualBox.xidl from ../idl/VirtualBox.xidl, which
is identical to the original except that all <if...>
sections are resolved (for easier processing).
Copyright (C) 2006-2012 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute it and/or modify it under the terms of the GNU
General Public License (GPL) as published by the Free Software
Foundation, in version 2 as it comes in the "COPYING" file of the
VirtualBox OSE distribution. VirtualBox OSE is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
-->
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output
method="xml"
version="1.0"
encoding="utf-8"
indent="yes"/>
<xsl:strip-space
elements="*" />
<!--
template for "idl" match; this emits the header of the target file
and recurses into the libraries with interfaces (which are matched below)
-->
<xsl:template match="/idl">
<xsl:comment>
DO NOT EDIT! This is a generated file.
Generated from: src/VBox/Main/idl/VirtualBox.xidl (VirtualBox's interface definitions in XML)
Generator: src/VBox/Main/webservice/platform-xidl.xsl
</xsl:comment>
<idl>
<xsl:apply-templates />
</idl>
</xsl:template>
<!--
template for "if" match: ignore all ifs except those for wsdl
-->
<xsl:template match="if">
<xsl:if test="@target='wsdl'">
<xsl:apply-templates/>
</xsl:if>
</xsl:template>
<!--
ignore everything we don't need
-->
<xsl:template match="cpp|class|enumerator">
</xsl:template>
<!--
and keep the rest intact (including all attributes)
NOTE: this drops class and everything in it, which I left unchanged
since the other xslt scripts blow up badly.
-->
<xsl:template match="library|module|enum|const|interface|attribute|collection|method|param|result">
<xsl:copy><xsl:copy-of select="@*"/><xsl:apply-templates/></xsl:copy>
</xsl:template>
<!--
keep those completely unchanged, including child nodes (including all
attributes)
-->
<xsl:template match="descGroup|desc|note">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
| low | 0.569624 | 150 |
Mit dieser Datei schalten wir die Vektor-Implementierungen um.
\begin{code}
{-# OPTIONS -fno-monomorphism-restriction #-}
module MathObj.Vector.Vector (length, concat, transpose, (@+), (@-), (@*), (@/), ($/), ($*), (!!), splitAt, filter, fromList, toList, (++))
where
\end{code}
Die Moeglichkleiten sind:
* "normale" Listen
* Listen mit Laenge
* chunked Listen mit Laenge (TODO)
ggf. werden Hinzugefuegt:
* Arrays
Die Implementierung wird hier included. Diese Zeile wird geaendert, wen wir auf die andere Implementierung schalten!
\begin{code}
import qualified Prelude -- hide standard implementations
import MathObj.Vector.Indexed
-- (length, concat, transpose, add, substr, mult, divide, divideSkalar, multSkalar, (!!), splitAt, filter, fromList, toList, (++))
\end{code}
Alle diese Strukturen muessen die Funktionen an der rechten Seite implementieren:
\begin{code}
(@+) = add
(@-) = substr
(@*) = mult
(@/) = divide
($/) = divideSkalar
($*) = multSkalar
\end{code}
| high | 0.240502 | 151 |
{
"id": "bcd1774a-005a-440c-b96a-c4e8d29065bc",
"modelName": "GMScript",
"mvc": "1.0",
"name": "dialog_create_commit_switches_resize",
"IsCompatibility": false,
"IsDnD": false
} | low | 0.595424 | 152 |
\begin{titlepage} % Suppresses headers and footers on the title page
\raggedleft % Right align everything
\vspace*{\baselineskip} % Whitespace at the top of the page
\vspace*{0.1\textheight} % Whitespace before the title
% \textbf{\LARGE Language and Toponymy in Alaska and Beyond}\\[\baselineskip]
\textbf{\Huge Language and Toponymy in Alaska and Beyond}\\[\baselineskip]
\textbf{\LARGE Papers in Honor of James Kari}
\vspace*{0.15\textheight}
{\large \textit{edited by}}\\[\baselineskip]
{\Large
Gary Holton\\[2pt]
Thomas Thornton\\[2pt]
}
\vfill % Whitespace between the titles and the publisher
{\large Language Documentation \& Conservation Special Publication No. 16}
\vspace*{3\baselineskip} % Whitespace at the bottom of the page
\end{titlepage}
| low | 0.401846 | 153 |
# -*- coding: utf-8 -*-
from ._autoscaling import Autoscaling
| low | 0.601114 | 154 |
(*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
type chain = [
| `Main
| `Test
| `Hash of Chain_id.t
]
type chain_prefix = unit * chain
val chain_path: (unit, chain_prefix) RPC_path.t
val parse_chain: string -> (chain, string) result
val chain_to_string: chain -> string
val chain_arg: chain RPC_arg.t
type block = [
| `Genesis
| `Head of int
| `Hash of Block_hash.t * int
| `Level of Int32.t
]
val parse_block: string -> (block, string) result
val to_string: block -> string
type prefix = (unit * chain) * block
val dir_path: (chain_prefix, chain_prefix) RPC_path.t
val path: (chain_prefix, chain_prefix * block) RPC_path.t
val mempool_path : ('a, 'b) RPC_path.t -> ('a, 'b) RPC_path.t
val live_blocks_path : ('a, 'b) RPC_path.t -> ('a, 'b) RPC_path.t
type operation_list_quota = {
max_size: int ;
max_op: int option ;
}
type raw_context =
| Key of MBytes.t
| Dir of (string * raw_context) list
| Cut
val pp_raw_context: Format.formatter -> raw_context -> unit
type error +=
| Invalid_depth_arg of int
module type PROTO = sig
val hash: Protocol_hash.t
type block_header_data
val block_header_data_encoding: block_header_data Data_encoding.t
type block_header_metadata
val block_header_metadata_encoding:
block_header_metadata Data_encoding.t
type operation_data
type operation_receipt
type operation = {
shell: Operation.shell_header ;
protocol_data: operation_data ;
}
val operation_data_encoding: operation_data Data_encoding.t
val operation_receipt_encoding: operation_receipt Data_encoding.t
val operation_data_and_receipt_encoding:
(operation_data * operation_receipt) Data_encoding.t
end
module Make(Proto : PROTO)(Next_proto : PROTO) : sig
val path: (unit, chain_prefix * block) RPC_path.t
type raw_block_header = {
shell: Block_header.shell_header ;
protocol_data: Proto.block_header_data ;
}
type block_header = {
chain_id: Chain_id.t ;
hash: Block_hash.t ;
shell: Block_header.shell_header ;
protocol_data: Proto.block_header_data ;
}
type block_metadata = {
protocol_data: Proto.block_header_metadata ;
test_chain_status: Test_chain_status.t ;
max_operations_ttl: int ;
max_operation_data_length: int ;
max_block_header_length: int ;
operation_list_quota: operation_list_quota list ;
}
type operation = {
chain_id: Chain_id.t ;
hash: Operation_hash.t ;
shell: Operation.shell_header ;
protocol_data: Proto.operation_data ;
receipt: Proto.operation_receipt ;
}
type block_info = {
chain_id: Chain_id.t ;
hash: Block_hash.t ;
header: raw_block_header ;
metadata: block_metadata ;
operations: operation list list ;
}
open RPC_context
val info:
#simple -> ?chain:chain -> ?block:block ->
unit -> block_info tzresult Lwt.t
val hash:
#simple -> ?chain:chain -> ?block:block ->
unit -> Block_hash.t tzresult Lwt.t
val raw_header:
#simple -> ?chain:chain -> ?block:block ->
unit -> MBytes.t tzresult Lwt.t
val header:
#simple -> ?chain:chain -> ?block:block ->
unit -> block_header tzresult Lwt.t
val metadata:
#simple -> ?chain:chain -> ?block:block ->
unit -> block_metadata tzresult Lwt.t
module Header : sig
val shell_header:
#simple -> ?chain:chain -> ?block:block ->
unit -> Block_header.shell_header tzresult Lwt.t
val protocol_data:
#simple -> ?chain:chain -> ?block:block ->
unit -> Proto.block_header_data tzresult Lwt.t
val raw_protocol_data:
#simple -> ?chain:chain -> ?block:block ->
unit -> MBytes.t tzresult Lwt.t
end
module Operations : sig
val operations:
#simple -> ?chain:chain -> ?block:block ->
unit -> operation list list tzresult Lwt.t
val operations_in_pass:
#simple -> ?chain:chain -> ?block:block ->
int -> operation list tzresult Lwt.t
val operation:
#simple -> ?chain:chain -> ?block:block ->
int -> int -> operation tzresult Lwt.t
end
module Operation_hashes : sig
val operation_hashes:
#simple -> ?chain:chain -> ?block:block ->
unit -> Operation_hash.t list list tzresult Lwt.t
val operation_hashes_in_pass:
#simple -> ?chain:chain -> ?block:block ->
int -> Operation_hash.t list tzresult Lwt.t
val operation_hash:
#simple -> ?chain:chain -> ?block:block ->
int -> int -> Operation_hash.t tzresult Lwt.t
end
module Context : sig
val read:
#simple -> ?chain:chain -> ?block:block ->
?depth: int ->
string list -> raw_context tzresult Lwt.t
end
module Helpers : sig
module Forge : sig
val block_header:
#RPC_context.simple ->
?chain:chain ->
?block:block ->
Block_header.t ->
MBytes.t tzresult Lwt.t
end
module Preapply : sig
val block:
#simple -> ?chain:chain -> ?block:block ->
?sort:bool ->
?timestamp:Time.Protocol.t ->
protocol_data:Next_proto.block_header_data ->
Next_proto.operation list list ->
(Block_header.shell_header * error Preapply_result.t list) tzresult Lwt.t
val operations:
#simple -> ?chain:chain -> ?block:block ->
Next_proto.operation list ->
(Next_proto.operation_data * Next_proto.operation_receipt) list tzresult Lwt.t
end
val complete:
#simple -> ?chain:chain -> ?block:block ->
string -> string list tzresult Lwt.t
end
module Mempool : sig
type t = {
applied: (Operation_hash.t * Next_proto.operation) list ;
refused: (Next_proto.operation * error list) Operation_hash.Map.t ;
branch_refused: (Next_proto.operation * error list) Operation_hash.Map.t ;
branch_delayed: (Next_proto.operation * error list) Operation_hash.Map.t ;
unprocessed: Next_proto.operation Operation_hash.Map.t ;
}
val pending_operations:
#simple ->
?chain:chain ->
unit -> t tzresult Lwt.t
val monitor_operations:
#streamed ->
?chain:chain ->
?applied:bool ->
?branch_delayed:bool ->
?branch_refused:bool ->
?refused:bool ->
unit -> (Next_proto.operation list Lwt_stream.t * stopper) tzresult Lwt.t
val request_operations:
#simple ->
?chain:chain ->
unit -> unit tzresult Lwt.t
end
val live_blocks:
#simple ->
?chain:chain ->
?block:block ->
unit -> Block_hash.Set.t tzresult Lwt.t
module S : sig
val hash:
([ `GET ], prefix,
prefix, unit, unit,
Block_hash.t) RPC_service.t
val info:
([ `GET ], prefix,
prefix, unit, unit,
block_info) RPC_service.t
val header:
([ `GET ], prefix,
prefix, unit, unit,
block_header) RPC_service.t
val raw_header:
([ `GET ], prefix,
prefix, unit, unit,
MBytes.t) RPC_service.t
val metadata:
([ `GET ], prefix,
prefix, unit, unit,
block_metadata) RPC_service.t
module Header : sig
val shell_header:
([ `GET ], prefix,
prefix, unit, unit,
Block_header.shell_header) RPC_service.t
val protocol_data:
([ `GET ], prefix,
prefix, unit, unit,
Proto.block_header_data) RPC_service.t
val raw_protocol_data:
([ `GET ], prefix,
prefix, unit, unit,
MBytes.t) RPC_service.t
end
module Operations : sig
val operations:
([ `GET ], prefix,
prefix, unit, unit,
operation list list) RPC_service.t
val operations_in_pass:
([ `GET ], prefix,
prefix * int, unit, unit,
operation list) RPC_service.t
val operation:
([ `GET ], prefix,
(prefix * int) * int, unit, unit,
operation) RPC_service.t
end
module Operation_hashes : sig
val operation_hashes:
([ `GET ], prefix,
prefix, unit, unit,
Tezos_crypto.Operation_hash.t list list) RPC_service.t
val operation_hashes_in_pass:
([ `GET ], prefix,
prefix * int, unit, unit,
Tezos_crypto.Operation_hash.t list) RPC_service.t
val operation_hash:
([ `GET ], prefix,
(prefix * int) * int, unit, unit,
Tezos_crypto.Operation_hash.t) RPC_service.t
end
module Context : sig
val read:
([ `GET ], prefix,
prefix * string list, < depth : int option >, unit,
raw_context) RPC_service.t
end
module Helpers : sig
module Forge : sig
val block_header:
([ `POST ], prefix,
prefix, unit, Block_header.t, MBytes.t) RPC_service.service
end
module Preapply : sig
type block_param = {
protocol_data: Next_proto.block_header_data ;
operations: Next_proto.operation list list ;
}
val block:
([ `POST ], prefix,
prefix, < sort_operations : bool;
timestamp : Time.Protocol.t option >, block_param,
Block_header.shell_header * error Preapply_result.t list) RPC_service.t
val operations:
([ `POST ], prefix,
prefix, unit, Next_proto.operation list,
(Next_proto.operation_data * Next_proto.operation_receipt) list) RPC_service.t
end
val complete:
([ `GET ], prefix,
prefix * string, unit, unit,
string list) RPC_service.t
end
module Mempool : sig
val encoding: Mempool.t Data_encoding.t
val pending_operations:
('a, 'b) RPC_path.t ->
([ `GET ], 'a,
'b , unit, unit,
Mempool.t) RPC_service.t
val monitor_operations:
('a, 'b) RPC_path.t ->
([ `GET ], 'a, 'b,
< applied : bool ; branch_delayed : bool ;
branch_refused : bool ; refused : bool ; >,
unit,
Next_proto.operation list) RPC_service.t
val request_operations :
('a, 'b) RPC_path.t ->
([ `POST ], 'a,
'b , unit, unit, unit) RPC_service.t
end
val live_blocks:
([ `GET ], prefix,
prefix, unit, unit,
Block_hash.Set.t) RPC_service.t
end
end
module Fake_protocol : PROTO
module Empty : (module type of Make(Fake_protocol)(Fake_protocol))
type protocols = {
current_protocol: Protocol_hash.t ;
next_protocol: Protocol_hash.t ;
}
val protocols:
#RPC_context.simple -> ?chain:chain -> ?block:block ->
unit -> protocols tzresult Lwt.t
| high | 0.838543 | 155 |
#
# Module manifest for module 'Microsoft.Azure.Commands.Management.CognitiveServices'
#
# Generated by: Microsoft Corporation
#
# Generated on: 5/13/2016
#
@{
# Version number of this module.
ModuleVersion = '0.1.0'
# ID used to uniquely identify this module
GUID = '8fc0b7d4-715d-4027-9e8b-9880ec56ef35'
# Author of this module
Author = 'Microsoft Corporation'
# Company or vendor of this module
CompanyName = 'Microsoft Corporation'
# Copyright statement for this module
Copyright = 'Microsoft Corporation. All rights reserved.'
# Description of the functionality provided by this module
Description = 'Microsoft Azure PowerShell - Cognitive Services management cmdlets for Azure Resource Manager. Creates and manages cognitive services accounts in Azure Resource Manager.'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '3.0'
# Name of the Windows PowerShell host required by this module
PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
PowerShellHostVersion = ''
# Minimum version of the .NET Framework required by this module
DotNetFrameworkVersion = '4.0'
# Minimum version of the common language runtime (CLR) required by this module
CLRVersion='4.0'
# Processor architecture (None, X86, Amd64, IA64) required by this module
ProcessorArchitecture = 'None'
# Modules that must be imported into the global environment prior to importing this module
#RequiredModules = @( @{ ModuleName = 'AzureRM.Profile'; ModuleVersion = '1.0.9'})
# Assemblies that must be loaded prior to importing this module
RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module
ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = @()
# Modules to import as nested modules of the module specified in ModuleToProcess
NestedModules = @(
'..\..\..\Package\Debug\ResourceManager\AzureResourceManager\AzureRM.CognitiveServices\Microsoft.Azure.Commands.Management.CognitiveServices.dll'
)
# Functions to export from this module
FunctionsToExport = '*'
# Cmdlets to export from this module
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module
AliasesToExport = @()
# List of all modules packaged with this module
ModuleList = @()
# List of all files packaged with this module
FileList = @()
# Private data to pass to the module specified in ModuleToProcess
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
LicenseUri = 'https://raw.githubusercontent.com/Azure/azure-powershell/dev/LICENSE.txt'
# A URL to the main website for this project.
ProjectUri = 'https://github.com/Azure/azure-powershell'
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
ReleaseNotes = 'https://github.com/Azure/azure-powershell/blob/dev/ChangeLog.md'
} # End of PSData hashtable
} # End of PrivateData hashtable
}
| low | 0.532528 | 156 |
package mesosphere.marathon
package raml
import java.time.OffsetDateTime
import mesosphere.marathon.state.{ AppDefinition, FetchUri, PathId, Residency }
trait AppConversion extends ConstraintConversion with EnvVarConversion with SecretConversion
with NetworkConversion with ReadinessConversions with HealthCheckConversion with UnreachableStrategyConversion {
implicit val pathIdWrites: Writes[PathId, String] = Writes { _.toString }
implicit val artifactWrites: Writes[FetchUri, Artifact] = Writes { fetch =>
Artifact(fetch.uri, Some(fetch.extract), Some(fetch.executable), Some(fetch.cache))
}
implicit val upgradeStrategyWrites: Writes[state.UpgradeStrategy, UpgradeStrategy] = Writes { strategy =>
UpgradeStrategy(strategy.maximumOverCapacity, strategy.minimumHealthCapacity)
}
implicit val appResidencyWrites: Writes[Residency, AppResidency] = Writes { residency =>
AppResidency(residency.relaunchEscalationTimeoutSeconds.toInt, residency.taskLostBehavior.toRaml)
}
implicit val versionInfoWrites: Writes[state.VersionInfo, VersionInfo] = Writes {
case state.VersionInfo.FullVersionInfo(_, scale, config) => VersionInfo(scale.toOffsetDateTime, config.toOffsetDateTime)
case state.VersionInfo.OnlyVersion(version) => VersionInfo(version.toOffsetDateTime, version.toOffsetDateTime)
case state.VersionInfo.NoVersion => VersionInfo(OffsetDateTime.now(), OffsetDateTime.now())
}
implicit val parameterWrites: Writes[state.Parameter, DockerParameter] = Writes { param =>
DockerParameter(param.key, param.value)
}
implicit val appWriter: Writes[AppDefinition, App] = Writes { app =>
App(
id = app.id.toString,
acceptedResourceRoles = if (app.acceptedResourceRoles.nonEmpty) Some(app.acceptedResourceRoles.to[Seq]) else None,
args = app.args,
backoffFactor = app.backoffStrategy.factor,
backoffSeconds = app.backoffStrategy.backoff.toSeconds.toInt,
cmd = app.cmd,
constraints = app.constraints.toRaml[Seq[Seq[String]]],
container = app.container.toRaml,
cpus = app.resources.cpus,
dependencies = app.dependencies.toRaml,
disk = app.resources.disk,
env = app.env.toRaml,
executor = app.executor,
fetch = app.fetch.toRaml,
healthChecks = app.healthChecks.toRaml,
instances = app.instances,
labels = app.labels,
maxLaunchDelaySeconds = app.backoffStrategy.maxLaunchDelay.toSeconds.toInt,
mem = app.resources.mem,
gpus = app.resources.gpus,
ipAddress = app.ipAddress.toRaml,
ports = app.portDefinitions.map(_.port),
portDefinitions = app.portDefinitions.toRaml,
readinessChecks = app.readinessChecks.toRaml,
residency = app.residency.toRaml,
requirePorts = Some(app.requirePorts),
secrets = app.secrets.toRaml,
storeUrls = app.storeUrls,
taskKillGracePeriodSeconds = app.taskKillGracePeriod.map(_.toSeconds.toInt),
upgradeStrategy = Some(app.upgradeStrategy.toRaml),
uris = app.fetch.map(_.uri),
user = app.user,
version = Some(app.versionInfo.version.toOffsetDateTime),
versionInfo = Some(app.versionInfo.toRaml),
unreachableStrategy = Some(app.unreachableStrategy.toRaml)
)
}
}
| high | 0.937985 | 157 |
import {
ChangeDetectionStrategy,
Component,
EventEmitter,
Inject,
Input,
OnChanges,
OnInit,
Output,
SimpleChanges
} from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { validateMultipleUrls } from '@forgerock/openbanking-ngx-common/utils';
export interface DialogData {
animal: string;
name: string;
}
@Component({
selector: 'app-application-list-application-form',
templateUrl: './application-form.component.html',
styleUrls: ['./application-form.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ApplicationListFormComponent implements OnInit, OnChanges {
@Input() isLoading = false;
@Input() isSuccess = false;
@Output() submit = new EventEmitter<void>();
@Input() directoryId: string;
formGroup: FormGroup;
constructor(
public dialogRef: MatDialogRef<ApplicationListFormComponent>,
@Inject(MAT_DIALOG_DATA) public data: DialogData
) {}
ngOnInit() {
this.formGroup = new FormGroup({
applicationName: new FormControl('', [Validators.minLength(4), Validators.required]),
applicationDescription: new FormControl(''),
redirectUris: new FormControl('', [Validators.required, validateMultipleUrls]),
softwareStatementAssertion: new FormControl(''),
qsealPem: new FormControl('')
});
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.isSuccess && changes.isSuccess.currentValue && changes.isLoading.previousValue) {
// https://github.com/angular/angular/issues/17572
// not sure if that the best but for now it works
setTimeout(() => this.dialogRef.close());
}
}
onSubmit() {
const value = {
...this.formGroup.value,
qsealPem: this.formGroup.value.qsealPem.trim(),
softwareStatementAssertion: this.formGroup.value.softwareStatementAssertion.trim(),
redirectUris: this.formGroup.value.redirectUris.split(',').map(url => url.trim())
};
this.submit.emit(value);
}
}
| high | 0.46708 | 158 |
// Copyright 2021 Google LLC
//
// 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.
syntax = "proto3";
package google.ads.googleads.v9.common;
import "google/ads/googleads/v9/enums/age_range_type.proto";
import "google/ads/googleads/v9/enums/app_payment_model_type.proto";
import "google/ads/googleads/v9/enums/content_label_type.proto";
import "google/ads/googleads/v9/enums/day_of_week.proto";
import "google/ads/googleads/v9/enums/device.proto";
import "google/ads/googleads/v9/enums/gender_type.proto";
import "google/ads/googleads/v9/enums/hotel_date_selection_type.proto";
import "google/ads/googleads/v9/enums/income_range_type.proto";
import "google/ads/googleads/v9/enums/interaction_type.proto";
import "google/ads/googleads/v9/enums/keyword_match_type.proto";
import "google/ads/googleads/v9/enums/listing_group_type.proto";
import "google/ads/googleads/v9/enums/location_group_radius_units.proto";
import "google/ads/googleads/v9/enums/minute_of_hour.proto";
import "google/ads/googleads/v9/enums/parental_status_type.proto";
import "google/ads/googleads/v9/enums/preferred_content_type.proto";
import "google/ads/googleads/v9/enums/product_bidding_category_level.proto";
import "google/ads/googleads/v9/enums/product_channel.proto";
import "google/ads/googleads/v9/enums/product_channel_exclusivity.proto";
import "google/ads/googleads/v9/enums/product_condition.proto";
import "google/ads/googleads/v9/enums/product_custom_attribute_index.proto";
import "google/ads/googleads/v9/enums/product_type_level.proto";
import "google/ads/googleads/v9/enums/proximity_radius_units.proto";
import "google/ads/googleads/v9/enums/webpage_condition_operand.proto";
import "google/ads/googleads/v9/enums/webpage_condition_operator.proto";
import "google/api/annotations.proto";
option csharp_namespace = "Google.Ads.GoogleAds.V9.Common";
option go_package = "google.golang.org/genproto/googleapis/ads/googleads/v9/common;common";
option java_multiple_files = true;
option java_outer_classname = "CriteriaProto";
option java_package = "com.google.ads.googleads.v9.common";
option objc_class_prefix = "GAA";
option php_namespace = "Google\\Ads\\GoogleAds\\V9\\Common";
option ruby_package = "Google::Ads::GoogleAds::V9::Common";
// Proto file describing criteria types.
// A keyword criterion.
message KeywordInfo {
// The text of the keyword (at most 80 characters and 10 words).
optional string text = 3;
// The match type of the keyword.
google.ads.googleads.v9.enums.KeywordMatchTypeEnum.KeywordMatchType match_type = 2;
}
// A placement criterion. This can be used to modify bids for sites when
// targeting the content network.
message PlacementInfo {
// URL of the placement.
//
// For example, "http://www.domain.com".
optional string url = 2;
}
// A mobile app category criterion.
message MobileAppCategoryInfo {
// The mobile app category constant resource name.
optional string mobile_app_category_constant = 2;
}
// A mobile application criterion.
message MobileApplicationInfo {
// A string that uniquely identifies a mobile application to Google Ads API.
// The format of this string is "{platform}-{platform_native_id}", where
// platform is "1" for iOS apps and "2" for Android apps, and where
// platform_native_id is the mobile application identifier native to the
// corresponding platform.
// For iOS, this native identifier is the 9 digit string that appears at the
// end of an App Store URL (e.g., "476943146" for "Flood-It! 2" whose App
// Store link is "http://itunes.apple.com/us/app/flood-it!-2/id476943146").
// For Android, this native identifier is the application's package name
// (e.g., "com.labpixies.colordrips" for "Color Drips" given Google Play link
// "https://play.google.com/store/apps/details?id=com.labpixies.colordrips").
// A well formed app id for Google Ads API would thus be "1-476943146" for iOS
// and "2-com.labpixies.colordrips" for Android.
// This field is required and must be set in CREATE operations.
optional string app_id = 4;
// Name of this mobile application.
optional string name = 5;
}
// A location criterion.
message LocationInfo {
// The geo target constant resource name.
optional string geo_target_constant = 2;
}
// A device criterion.
message DeviceInfo {
// Type of the device.
google.ads.googleads.v9.enums.DeviceEnum.Device type = 1;
}
// A preferred content criterion.
message PreferredContentInfo {
// Type of the preferred content.
google.ads.googleads.v9.enums.PreferredContentTypeEnum.PreferredContentType type = 2;
}
// A listing group criterion.
message ListingGroupInfo {
// Type of the listing group.
google.ads.googleads.v9.enums.ListingGroupTypeEnum.ListingGroupType type = 1;
// Dimension value with which this listing group is refining its parent.
// Undefined for the root group.
ListingDimensionInfo case_value = 2;
// Resource name of ad group criterion which is the parent listing group
// subdivision. Null for the root group.
optional string parent_ad_group_criterion = 4;
}
// A listing scope criterion.
message ListingScopeInfo {
// Scope of the campaign criterion.
repeated ListingDimensionInfo dimensions = 2;
}
// Listing dimensions for listing group criterion.
message ListingDimensionInfo {
// Dimension of one of the types below is always present.
oneof dimension {
// Advertiser-specific hotel ID.
HotelIdInfo hotel_id = 2;
// Class of the hotel as a number of stars 1 to 5.
HotelClassInfo hotel_class = 3;
// Country or Region the hotel is located in.
HotelCountryRegionInfo hotel_country_region = 4;
// State the hotel is located in.
HotelStateInfo hotel_state = 5;
// City the hotel is located in.
HotelCityInfo hotel_city = 6;
// Bidding category of a product offer.
ProductBiddingCategoryInfo product_bidding_category = 13;
// Brand of a product offer.
ProductBrandInfo product_brand = 15;
// Locality of a product offer.
ProductChannelInfo product_channel = 8;
// Availability of a product offer.
ProductChannelExclusivityInfo product_channel_exclusivity = 9;
// Condition of a product offer.
ProductConditionInfo product_condition = 10;
// Custom attribute of a product offer.
ProductCustomAttributeInfo product_custom_attribute = 16;
// Item id of a product offer.
ProductItemIdInfo product_item_id = 11;
// Type of a product offer.
ProductTypeInfo product_type = 12;
// Unknown dimension. Set when no other listing dimension is set.
UnknownListingDimensionInfo unknown_listing_dimension = 14;
}
}
// Advertiser-specific hotel ID.
message HotelIdInfo {
// String value of the hotel ID.
optional string value = 2;
}
// Class of the hotel as a number of stars 1 to 5.
message HotelClassInfo {
// Long value of the hotel class.
optional int64 value = 2;
}
// Country or Region the hotel is located in.
message HotelCountryRegionInfo {
// The Geo Target Constant resource name.
optional string country_region_criterion = 2;
}
// State the hotel is located in.
message HotelStateInfo {
// The Geo Target Constant resource name.
optional string state_criterion = 2;
}
// City the hotel is located in.
message HotelCityInfo {
// The Geo Target Constant resource name.
optional string city_criterion = 2;
}
// Bidding category of a product offer.
message ProductBiddingCategoryInfo {
// ID of the product bidding category.
//
// This ID is equivalent to the google_product_category ID as described in
// this article: https://support.google.com/merchants/answer/6324436
optional int64 id = 4;
// Two-letter upper-case country code of the product bidding category. It must
// match the campaign.shopping_setting.sales_country field.
optional string country_code = 5;
// Level of the product bidding category.
google.ads.googleads.v9.enums.ProductBiddingCategoryLevelEnum.ProductBiddingCategoryLevel level = 3;
}
// Brand of the product.
message ProductBrandInfo {
// String value of the product brand.
optional string value = 2;
}
// Locality of a product offer.
message ProductChannelInfo {
// Value of the locality.
google.ads.googleads.v9.enums.ProductChannelEnum.ProductChannel channel = 1;
}
// Availability of a product offer.
message ProductChannelExclusivityInfo {
// Value of the availability.
google.ads.googleads.v9.enums.ProductChannelExclusivityEnum.ProductChannelExclusivity channel_exclusivity = 1;
}
// Condition of a product offer.
message ProductConditionInfo {
// Value of the condition.
google.ads.googleads.v9.enums.ProductConditionEnum.ProductCondition condition = 1;
}
// Custom attribute of a product offer.
message ProductCustomAttributeInfo {
// String value of the product custom attribute.
optional string value = 3;
// Indicates the index of the custom attribute.
google.ads.googleads.v9.enums.ProductCustomAttributeIndexEnum.ProductCustomAttributeIndex index = 2;
}
// Item id of a product offer.
message ProductItemIdInfo {
// Value of the id.
optional string value = 2;
}
// Type of a product offer.
message ProductTypeInfo {
// Value of the type.
optional string value = 3;
// Level of the type.
google.ads.googleads.v9.enums.ProductTypeLevelEnum.ProductTypeLevel level = 2;
}
// Unknown listing dimension.
message UnknownListingDimensionInfo {
}
// Criterion for hotel date selection (default dates vs. user selected).
message HotelDateSelectionTypeInfo {
// Type of the hotel date selection
google.ads.googleads.v9.enums.HotelDateSelectionTypeEnum.HotelDateSelectionType type = 1;
}
// Criterion for number of days prior to the stay the booking is being made.
message HotelAdvanceBookingWindowInfo {
// Low end of the number of days prior to the stay.
optional int64 min_days = 3;
// High end of the number of days prior to the stay.
optional int64 max_days = 4;
}
// Criterion for length of hotel stay in nights.
message HotelLengthOfStayInfo {
// Low end of the number of nights in the stay.
optional int64 min_nights = 3;
// High end of the number of nights in the stay.
optional int64 max_nights = 4;
}
// Criterion for a check-in date range.
message HotelCheckInDateRangeInfo {
// Start date in the YYYY-MM-DD format.
string start_date = 1;
// End date in the YYYY-MM-DD format.
string end_date = 2;
}
// Criterion for day of the week the booking is for.
message HotelCheckInDayInfo {
// The day of the week.
google.ads.googleads.v9.enums.DayOfWeekEnum.DayOfWeek day_of_week = 1;
}
// Criterion for Interaction Type.
message InteractionTypeInfo {
// The interaction type.
google.ads.googleads.v9.enums.InteractionTypeEnum.InteractionType type = 1;
}
// Represents an AdSchedule criterion.
//
// AdSchedule is specified as the day of the week and a time interval
// within which ads will be shown.
//
// No more than six AdSchedules can be added for the same day.
message AdScheduleInfo {
// Minutes after the start hour at which this schedule starts.
//
// This field is required for CREATE operations and is prohibited on UPDATE
// operations.
google.ads.googleads.v9.enums.MinuteOfHourEnum.MinuteOfHour start_minute = 1;
// Minutes after the end hour at which this schedule ends. The schedule is
// exclusive of the end minute.
//
// This field is required for CREATE operations and is prohibited on UPDATE
// operations.
google.ads.googleads.v9.enums.MinuteOfHourEnum.MinuteOfHour end_minute = 2;
// Starting hour in 24 hour time.
// This field must be between 0 and 23, inclusive.
//
// This field is required for CREATE operations and is prohibited on UPDATE
// operations.
optional int32 start_hour = 6;
// Ending hour in 24 hour time; 24 signifies end of the day.
// This field must be between 0 and 24, inclusive.
//
// This field is required for CREATE operations and is prohibited on UPDATE
// operations.
optional int32 end_hour = 7;
// Day of the week the schedule applies to.
//
// This field is required for CREATE operations and is prohibited on UPDATE
// operations.
google.ads.googleads.v9.enums.DayOfWeekEnum.DayOfWeek day_of_week = 5;
}
// An age range criterion.
message AgeRangeInfo {
// Type of the age range.
google.ads.googleads.v9.enums.AgeRangeTypeEnum.AgeRangeType type = 1;
}
// A gender criterion.
message GenderInfo {
// Type of the gender.
google.ads.googleads.v9.enums.GenderTypeEnum.GenderType type = 1;
}
// An income range criterion.
message IncomeRangeInfo {
// Type of the income range.
google.ads.googleads.v9.enums.IncomeRangeTypeEnum.IncomeRangeType type = 1;
}
// A parental status criterion.
message ParentalStatusInfo {
// Type of the parental status.
google.ads.googleads.v9.enums.ParentalStatusTypeEnum.ParentalStatusType type = 1;
}
// A YouTube Video criterion.
message YouTubeVideoInfo {
// YouTube video id as it appears on the YouTube watch page.
optional string video_id = 2;
}
// A YouTube Channel criterion.
message YouTubeChannelInfo {
// The YouTube uploader channel id or the channel code of a YouTube channel.
optional string channel_id = 2;
}
// A User List criterion. Represents a user list that is defined by the
// advertiser to be targeted.
message UserListInfo {
// The User List resource name.
optional string user_list = 2;
}
// A Proximity criterion. The geo point and radius determine what geographical
// area is included. The address is a description of the geo point that does
// not affect ad serving.
//
// There are two ways to create a proximity. First, by setting an address
// and radius. The geo point will be automatically computed. Second, by
// setting a geo point and radius. The address is an optional label that won't
// be validated.
message ProximityInfo {
// Latitude and longitude.
GeoPointInfo geo_point = 1;
// The radius of the proximity.
optional double radius = 5;
// The unit of measurement of the radius. Default is KILOMETERS.
google.ads.googleads.v9.enums.ProximityRadiusUnitsEnum.ProximityRadiusUnits radius_units = 3;
// Full address.
AddressInfo address = 4;
}
// Geo point for proximity criterion.
message GeoPointInfo {
// Micro degrees for the longitude.
optional int32 longitude_in_micro_degrees = 3;
// Micro degrees for the latitude.
optional int32 latitude_in_micro_degrees = 4;
}
// Address for proximity criterion.
message AddressInfo {
// Postal code.
optional string postal_code = 8;
// Province or state code.
optional string province_code = 9;
// Country code.
optional string country_code = 10;
// Province or state name.
optional string province_name = 11;
// Street address line 1.
optional string street_address = 12;
// Street address line 2. This field is write-only. It is only used for
// calculating the longitude and latitude of an address when geo_point is
// empty.
optional string street_address2 = 13;
// Name of the city.
optional string city_name = 14;
}
// A topic criterion. Use topics to target or exclude placements in the
// Google Display Network based on the category into which the placement falls
// (for example, "Pets & Animals/Pets/Dogs").
message TopicInfo {
// The Topic Constant resource name.
optional string topic_constant = 3;
// The category to target or exclude. Each subsequent element in the array
// describes a more specific sub-category. For example,
// "Pets & Animals", "Pets", "Dogs" represents the "Pets & Animals/Pets/Dogs"
// category.
repeated string path = 4;
}
// A language criterion.
message LanguageInfo {
// The language constant resource name.
optional string language_constant = 2;
}
// An IpBlock criterion used for IP exclusions. We allow:
// - IPv4 and IPv6 addresses
// - individual addresses (192.168.0.1)
// - masks for individual addresses (192.168.0.1/32)
// - masks for Class C networks (192.168.0.1/24)
message IpBlockInfo {
// The IP address of this IP block.
optional string ip_address = 2;
}
// Content Label for category exclusion.
message ContentLabelInfo {
// Content label type, required for CREATE operations.
google.ads.googleads.v9.enums.ContentLabelTypeEnum.ContentLabelType type = 1;
}
// Represents a Carrier Criterion.
message CarrierInfo {
// The Carrier constant resource name.
optional string carrier_constant = 2;
}
// Represents a particular interest-based topic to be targeted.
message UserInterestInfo {
// The UserInterest resource name.
optional string user_interest_category = 2;
}
// Represents a criterion for targeting webpages of an advertiser's website.
message WebpageInfo {
// The name of the criterion that is defined by this parameter. The name value
// will be used for identifying, sorting and filtering criteria with this type
// of parameters.
//
// This field is required for CREATE operations and is prohibited on UPDATE
// operations.
optional string criterion_name = 3;
// Conditions, or logical expressions, for webpage targeting. The list of
// webpage targeting conditions are and-ed together when evaluated
// for targeting.
//
// This field is required for CREATE operations and is prohibited on UPDATE
// operations.
repeated WebpageConditionInfo conditions = 2;
// Website criteria coverage percentage. This is the computed percentage
// of website coverage based on the website target, negative website target
// and negative keywords in the ad group and campaign. For instance, when
// coverage returns as 1, it indicates it has 100% coverage. This field is
// read-only.
double coverage_percentage = 4;
// List of sample urls that match the website target. This field is read-only.
WebpageSampleInfo sample = 5;
}
// Logical expression for targeting webpages of an advertiser's website.
message WebpageConditionInfo {
// Operand of webpage targeting condition.
google.ads.googleads.v9.enums.WebpageConditionOperandEnum.WebpageConditionOperand operand = 1;
// Operator of webpage targeting condition.
google.ads.googleads.v9.enums.WebpageConditionOperatorEnum.WebpageConditionOperator operator = 2;
// Argument of webpage targeting condition.
optional string argument = 4;
}
// List of sample urls that match the website target
message WebpageSampleInfo {
// Webpage sample urls
repeated string sample_urls = 1;
}
// Represents an operating system version to be targeted.
message OperatingSystemVersionInfo {
// The operating system version constant resource name.
optional string operating_system_version_constant = 2;
}
// An app payment model criterion.
message AppPaymentModelInfo {
// Type of the app payment model.
google.ads.googleads.v9.enums.AppPaymentModelTypeEnum.AppPaymentModelType type = 1;
}
// A mobile device criterion.
message MobileDeviceInfo {
// The mobile device constant resource name.
optional string mobile_device_constant = 2;
}
// A custom affinity criterion.
// A criterion of this type is only targetable.
message CustomAffinityInfo {
// The CustomInterest resource name.
optional string custom_affinity = 2;
}
// A custom intent criterion.
// A criterion of this type is only targetable.
message CustomIntentInfo {
// The CustomInterest resource name.
optional string custom_intent = 2;
}
// A radius around a list of locations specified via a feed.
message LocationGroupInfo {
// Feed specifying locations for targeting.
// This is required and must be set in CREATE operations.
optional string feed = 5;
// Geo target constant(s) restricting the scope of the geographic area within
// the feed. Currently only one geo target constant is allowed.
repeated string geo_target_constants = 6;
// Distance in units specifying the radius around targeted locations.
// This is required and must be set in CREATE operations.
optional int64 radius = 7;
// Unit of the radius. Miles and meters are supported for geo target
// constants. Milli miles and meters are supported for feed item sets.
// This is required and must be set in CREATE operations.
google.ads.googleads.v9.enums.LocationGroupRadiusUnitsEnum.LocationGroupRadiusUnits radius_units = 4;
// FeedItemSets whose FeedItems are targeted. If multiple IDs are specified,
// then all items that appear in at least one set are targeted. This field
// cannot be used with geo_target_constants. This is optional and can only be
// set in CREATE operations.
repeated string feed_item_sets = 8;
}
// A custom audience criterion.
message CustomAudienceInfo {
// The CustomAudience resource name.
string custom_audience = 1;
}
// A combined audience criterion.
message CombinedAudienceInfo {
// The CombinedAudience resource name.
string combined_audience = 1;
}
// A Smart Campaign keyword theme.
message KeywordThemeInfo {
// Either a predefined keyword theme constant or free-form text may be
// specified.
oneof keyword_theme {
// The resource name of a Smart Campaign keyword theme constant.
// `keywordThemeConstants/{keyword_theme_id}~{sub_keyword_theme_id}`
string keyword_theme_constant = 1;
// Free-form text to be matched to a Smart Campaign keyword theme constant
// on a best-effort basis.
string free_form_keyword_theme = 2;
}
}
| high | 0.849442 | 159 |
package ucesoft.cbm.peripheral.sid
import ucesoft.cbm.cpu.RAMComponent
trait SIDDevice extends RAMComponent {
def start : Unit
def stop : Unit
def setFullSpeed(full:Boolean) : Unit
def getDriver : AudioDriverDevice
def clock : Unit
def setCycleExact(ce:Boolean): Unit
} | high | 0.598624 | 160 |
# AUTOGENERATED FILE
FROM balenalib/raspberrypi400-64-debian:bookworm-run
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates \
curl \
\
# .NET Core dependencies
libc6 \
libgcc1 \
libgssapi-krb5-2 \
libicu67 \
libssl1.1 \
libstdc++6 \
zlib1g \
&& rm -rf /var/lib/apt/lists/*
# Configure web servers to bind to port 80 when present
ENV ASPNETCORE_URLS=http://+:80 \
# Enable detection of running in a container
DOTNET_RUNNING_IN_CONTAINER=true
# Install .NET Core
ENV DOTNET_VERSION 5.0.12
RUN curl -SL --output dotnet.tar.gz "https://dotnetcli.blob.core.windows.net/dotnet/Runtime/$DOTNET_VERSION/dotnet-runtime-$DOTNET_VERSION-linux-arm64.tar.gz" \
&& dotnet_sha512='a8089fad8d21a4b582aa6c3d7162d56a21fee697fd400f050a772f67c2ace5e4196d1c4261d3e861d6dc2e5439666f112c406104d6271e5ab60cda80ef2ffc64' \
&& echo "$dotnet_sha512 dotnet.tar.gz" | sha512sum -c - \
&& mkdir -p /usr/share/dotnet \
&& tar -zxf dotnet.tar.gz -C /usr/share/dotnet \
&& rm dotnet.tar.gz \
&& ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/44e597e40f2010cdde15b3ba1e397aea3a5c5271/scripts/assets/tests/test-stack@dotnet.sh" \
&& echo "Running test-stack@dotnet" \
&& chmod +x test-stack@dotnet.sh \
&& bash test-stack@dotnet.sh \
&& rm -rf test-stack@dotnet.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Bookworm \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \ndotnet 5.0-runtime \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | high | 0.569648 | 161 |
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head>
<title>Accommodation Report</title>
</head>
<body>
<div>
<h1>Programme Report</h1>
<div>
<h2>Programme List</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Programme Code</th>
<th>Programme Name</th>
<th>Programme Description</th>
<th>Duration(Year of Study)</th>
<th>Level of Study</th>
<th>Faculty</th>
<th>Branch Offered</th>
</tr>
<xsl:for-each select="programs/program">
<xsl:sort select="programCode" order="ascending"/>
<tr>
<td><xsl:value-of select="programCode"/></td>
<td><xsl:value-of select="programName"/></td>
<td><xsl:value-of select="programDesc"/></td>
<td><xsl:value-of select="programDuration"/></td>
<td><xsl:value-of select="programLevel"/></td>
<td><xsl:value-of select="facultyCode"/></td>
<td><xsl:value-of select="branchName"/></td>
</tr>
</xsl:for-each>
</table>
</div>
<div>
<h2>Programme Type</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Programme Code</th>
<th>Programme Name</th>
<th>Programme Description</th>
<th>Duration(Year of Study)</th>
<th>Level of Study</th>
<th>Faculty</th>
<th>Branch Offered</th>
</tr>
<xsl:for-each select="programs/program">
<xsl:sort select="programCode" order="ascending"/>
<tr>
<xsl:choose>
<xsl:when test="@programDuration='4'">
<td bgcolor="#ff00ff"><xsl:value-of select="programCode"/></td>
<td bgcolor="#ff00ff"><xsl:value-of select="programName"/></td>
<td bgcolor="#ff00ff"><xsl:value-of select="programDesc"/></td>
<td bgcolor="#ff00ff"><xsl:value-of select="programDuration"/></td>
<td bgcolor="#ff00ff"><xsl:value-of select="programLevel"/></td>
<td bgcolor="#ff00ff"><xsl:value-of select="facultyCode"/></td>
<td bgcolor="#ff00ff"><xsl:value-of select="branchName"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="programCode"/></td>
<td><xsl:value-of select="programName"/></td>
<td><xsl:value-of select="programDesc"/></td>
<td><xsl:value-of select="programDuration"/></td>
<td><xsl:value-of select="programLevel"/></td>
<td><xsl:value-of select="facultyCode"/></td>
<td><xsl:value-of select="branchName"/></td>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>
</table>
</div>
<div>
<h2>Total Programme List</h2>
<p>
Total Programmes: <xsl:value-of select="count(//programme)"/> in the accommodation list.
</p>
</div>
</div>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
| high | 0.406666 | 162 |
#pragma once
#ifndef SegmentationStats_H
#define SegmentationStats_H
#include <limits>
#include <cmath>
#include <deque>
#include <set>
#include "constants.h"
#include "tools.h"
#include "Coordinate.h"
#include "EUVImage.h"
#include "ColorMap.h"
#include "FitsFile.h"
//! Class to obtain information about the statistics of a class
/*!
This class gives statistics information about Segmentation classes such as area, filling factor
and common statistics mesure on the intensities of the class like mean, variance, etc.
*/
class SegmentationStats
{
private :
//! Class id
unsigned id;
//! Observation Time for the stats
time_t observationTime;
//! Total number of pixels in the class
unsigned numberPixels;
//! Moments
mutable Real m2, m3, m4;
Real minIntensity, maxIntensity, totalIntensity, area_Raw, area_AtDiskCenter, fillingFactor;
mutable std::deque<EUVPixelType> intensities;
private :
//! Routine to compute the moments from the pixel intensities vector
void computeMoments();
public :
//! Constructor
SegmentationStats(const time_t& observationTime, const unsigned id = 0);
//! Accessor to retrieve the id
unsigned Id() const;
//! Accessor to set the id
void setId(const unsigned& id);
//! Accessor to retrieve the observation time
time_t ObservationTime() const;
//! Accessor to retrieve the observation time as a string
std::string ObservationDate() const;
//! Accessor to retrieve the number of pixels
unsigned NumberPixels() const;
//! Mean of the intensities the class
Real Mean() const;
//! Median of the intensities the class
Real Median() const;
//! Variance of the intensities the class
Real Variance() const;
//! Low quartile (25 percentile) of the intensities the class
Real LowerQuartile() const;
//! High quartile (75 percentile) of the intensities the class
Real UpperQuartile() const;
//! Skewness of the intensities the class
Real Skewness() const;
//! Kurtosis of the intensities the class
Real Kurtosis() const;
//! Minimum intensity of the class
Real MinIntensity() const;
//! Maximum intensity of the class
Real MaxIntensity() const;
//! Total intensity of the class
Real TotalIntensity() const;
//! Area of the class as seen on the image (Mm²)
Real Area_Raw() const;
//! Area of the class as it would be if the class was centered on the disk (Mm²)
Real Area_AtDiskCenter() const;
//! Filling factor of the class
Real FillingFactor() const;
//! Output a class as a string
std::string toString(const std::string& separator, bool header = false) const;
//! Routine to update a class with a new pixel
void add(const PixLoc& coordinate, const EUVPixelType& pixelIntensity, const RealPixLoc& sunCenter, const Real& R);
// We must make the getSTAFFStats functions as friends so they can correct the filling factor
friend std::vector<SegmentationStats*> getSegmentationStats(const ColorMap*, const EUVImage*);
friend std::vector<SegmentationStats*> getSegmentationStats(const ColorMap*, const EUVImage*, const std::set<ColorType>&);
};
//! Compute all statistics of an image using a ColorMap as a cache
/*
@param map A segmentation map, each class must have a different color
@param image The image to compute the intensities statistics.
*/
std::vector<SegmentationStats*> getSegmentationStats(const ColorMap* coloredMap, const EUVImage* image);
//! Compute the statistics of the classes using a ColorMap as a cache
/*
@param map A segmentation map, each class must have a different color
@param image The image to compute the intensities statistics.
@param classes The classes for wich to compute the stats
*/
std::vector<SegmentationStats*> getSegmentationStats(const ColorMap* coloredMap, const EUVImage* image, const std::set<ColorType>& classes);
//! Write the classes into a fits file as column into the current table
FitsFile& writeRegions(FitsFile& file, const std::vector<SegmentationStats*>& segmentation_stats);
#endif
| high | 0.774882 | 163 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>reduction-effects: 12 s</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.12.1 / reduction-effects - 0.1.2</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
reduction-effects
<small>
0.1.2
<span class="label label-success">12 s</span>
</small>
</h1>
<p><em><script>document.write(moment("2021-07-24 17:42:16 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-07-24 17:42:16 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.12.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.06.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1 Official 4.06.1 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
synopsis: "A Coq plugin to add reduction side effects to some Coq reduction strategies"
maintainer: "Yishuai Li <yishuai@cis.upenn.edu>"
authors: "Hugo Herbelin <Hugo.Herbelin@inria.fr>"
license: "LGPL-2.1"
homepage: "https://github.com/coq-community/reduction-effects"
bug-reports: "https://github.com/coq-community/reduction-effects/issues"
depends: [
"coq" { >= "8.10" }
]
build: [make "-j%{jobs}%"]
install: [make "-j%{jobs}%" "install"]
run-test:[make "-j%{jobs}%" "test"]
dev-repo: "git+https://github.com/coq-community/reduction-effects"
url {
src: "https://github.com/coq-community/reduction-effects/archive/v0.1.2.tar.gz"
checksum: "md5=c371e8adeb7d749035a2dd55ede49eb4"
}
tags: [
"logpath:ReductionEffect"
]
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-reduction-effects.0.1.2 coq.8.12.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-reduction-effects.0.1.2 coq.8.12.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>7 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-reduction-effects.0.1.2 coq.8.12.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>12 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 50 K</p>
<ul>
<li>31 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ReductionEffect/redeffect_plugin.cmxs</code></li>
<li>5 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ReductionEffect/redeffect_plugin.cmx</code></li>
<li>5 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ReductionEffect/redeffect_plugin.cmi</code></li>
<li>5 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ReductionEffect/redeffect_plugin.cmxa</code></li>
<li>3 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ReductionEffect/PrintingEffect.vo</code></li>
<li>1 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ReductionEffect/PrintingEffect.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ReductionEffect/PrintingEffect.glob</code></li>
</ul>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-reduction-effects.0.1.2</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| low | 0.878802 | 164 |
defmodule ChromicPdf.MixProject do
use Mix.Project
@source_url "https://github.com/bitcrowd/chromic_pdf"
@version "1.1.2"
def project do
[
app: :chromic_pdf,
version: @version,
elixir: "~> 1.10",
start_permanent: Mix.env() == :prod,
dialyzer: [plt_file: {:no_warn, ".plts/dialyzer.plt"}],
elixirc_paths: elixirc_paths(Mix.env()),
deps: deps(),
aliases: aliases(),
# ExUnit
test_paths: test_paths(Mix.env()),
# hex.pm
package: package(),
# hexdocs.pm
name: "ChromicPDF",
source_url: @source_url,
homepage_url: @source_url,
docs: [
extras: [
"CHANGELOG.md": [title: "Changelog"],
LICENSE: [title: "License"],
"README.md": [title: "Overview"]
],
main: "readme",
source_url: @source_url,
source_ref: "v#{@version}",
formatters: ["html"],
assets: "assets"
]
]
end
def application do
[
extra_applications: [:eex, :logger]
]
end
defp package do
[
description: "Fast HTML-2-PDF/A renderer based on Chrome & Ghostscript",
maintainers: ["@bitcrowd"],
licenses: ["Apache-2.0"],
links: %{
Changelog: "https://hexdocs.pm/chromic_pdf/changelog.html",
GitHub: @source_url
}
]
end
defp elixirc_paths(:dev), do: ["examples", "lib"]
defp elixirc_paths(:integration), do: ["examples", "lib", "test/integration/support"]
defp elixirc_paths(:test), do: ["lib", "test/unit/support"]
defp elixirc_paths(_env), do: ["lib"]
defp test_paths(:test), do: ["test/unit"]
defp test_paths(:integration), do: ["test/integration"]
defp test_paths(_env), do: []
defp deps do
[
{:jason, "~> 1.1"},
{:nimble_pool, "~> 0.2.3"},
{:telemetry, "~> 0.4 or ~> 1.0"},
{:dialyxir, "~> 1.1", only: [:dev, :test], runtime: false},
{:credo, "~> 1.5", only: [:dev, :test], runtime: false},
{:ex_doc, ">= 0.0.0", only: [:test, :dev], runtime: false},
{:junit_formatter, "~> 3.1", only: [:test, :integration]},
{:mox, "~> 1.0", only: [:test]},
{:phoenix, "~> 1.5", only: [:dev, :integration]},
{:phoenix_html, "~> 2.14", only: [:dev, :integration]},
{:plug, "~> 1.11", only: [:dev, :integration]},
{:plug_cowboy, "~> 2.4", only: [:integration]}
]
end
defp aliases do
[
lint: [
"format --check-formatted",
"credo --strict",
"dialyzer --format dialyxir"
]
]
end
end
| high | 0.832756 | 165 |
syntax = "proto2";
package main;
message Command {
enum IpVersion {
IPv4 = 4;
IPv6 = 6;
}
message Ping {
optional string address = 1 [default = "dragonsector.pl"];
optional uint64 count = 2 [default = 1];
optional IpVersion ip_version = 3 [default = IPv4];
}
message Traceroute {
optional string address = 1 [default = "dragonsector.pl"];
optional IpVersion ip_version = 2 [default = IPv4];
}
oneof command {
Ping ping_command = 1;
Traceroute traceroute_command = 2;
}
}
message ExecutionResult {
message Success {
optional bytes output = 1;
}
message Error {
optional string error = 1;
}
oneof result {
Success success = 1;
Error error = 2;
}
}
| low | 0.370916 | 166 |
const std = @import("std");
const ascii = std.ascii;
const base64 = std.base64;
const c = std.c;
const debug = std.debug;
const fs = std.fs;
const heap = std.heap;
const io = std.io;
const math = std.math;
const mem = std.mem;
const os = std.os;
const unicode = std.unicode;
const Rune = u32;
const ATTR_NULL = 0;
const ATTR_BOLD = 1 << 0;
const ATTR_FAINT = 1 << 1;
const ATTR_ITALIC = 1 << 2;
const ATTR_UNDERLINE = 1 << 3;
const ATTR_BLINK = 1 << 4;
const ATTR_REVERSE = 1 << 5;
const ATTR_INVISIBLE = 1 << 6;
const ATTR_STRUCK = 1 << 7;
const ATTR_WRAP = 1 << 8;
const ATTR_WIDE = 1 << 9;
const ATTR_WDUMMY = 1 << 10;
const ATTR_BOLD_FAINT = ATTR_BOLD | ATTR_FAINT;
const MODE_WRAP = 1 << 0;
const MODE_INSERT = 1 << 1;
const MODE_ALTSCREEN = 1 << 2;
const MODE_CRLF = 1 << 3;
const MODE_ECHO = 1 << 4;
const MODE_PRINT = 1 << 5;
const MODE_UTF8 = 1 << 6;
const SEL_IDLE = 0;
const SEL_EMPTY = 1;
const SEL_READY = 2;
const SEL_REGULAR = 1;
const SEL_RECTANGULAR = 2;
const SNAP_WORD = 1;
const SNAP_LINE = 2;
const CURSOR_DEFAULT: u8 = 0;
const CURSOR_WRAPNEXT: u8 = 1;
const CURSOR_ORIGIN: u8 = 2;
const CURSOR_SAVE = 0;
const CURSOR_LOAD = 1;
const Selection = extern struct {
mode: c_int = SEL_IDLE,
type: c_int = 0,
snap: c_int = 0,
nb: Var = Var{},
ne: Var = Var{},
ob: Var = Var{ .x = -1 },
oe: Var = Var{},
alt: c_int = 0,
const Var = extern struct { x: c_int = 0, y: c_int = 0 };
};
const Line = [*]Glyph;
const Glyph = extern struct {
u: Rune = 0,
mode: c_ushort = 0,
fg: u32 = 0,
bg: u32 = 0,
};
const TCursor = extern struct {
attr: Glyph = Glyph{},
x: c_int = 0,
y: c_int = 0,
state: u8 = 0,
};
const histsize = 2000;
const Term = extern struct {
row: c_int = 0,
col: c_int = 0,
line: [*]Line = undefined,
alt: [*]Line = undefined,
hist: [histsize]Line = undefined,
histi: c_int = 0,
scr: c_int = 0,
dirty: [*]c_int = undefined,
c: TCursor = TCursor{},
ocx: c_int = 0,
ocy: c_int = 0,
top: c_int = 0,
bot: c_int = 0,
mode: c_int = 0,
esc: c_int = 0,
trantbl: [4]u8 = [_]u8{0} ** 4,
charset: c_int = 0,
icharset: c_int = 0,
tabs: [*]c_int = undefined,
lastc: Rune = 0,
};
export var term: Term = Term{};
export var sel: Selection = Selection{};
export var cmdfd: os.fd_t = 0;
export var iofd: os.fd_t = 1;
export var pid: os.pid_t = 0;
export fn xwrite(fd: os.fd_t, str: [*]const u8, len: usize) isize {
const file = fs.File{ .handle = fd, .io_mode = io.mode };
file.writeAll(str[0..len]) catch return -1;
return @intCast(isize, len);
}
export fn xstrdup(s: [*:0]u8) [*:0]u8 {
const len = mem.lenZ(s);
const res = heap.c_allocator.allocSentinel(u8, len, 0) catch std.debug.panic("strdup failed", .{});
mem.copy(u8, res, s[0..len]);
return res.ptr;
}
export fn utf8decode(bytes: [*]const u8, u: *u32, clen: usize) usize {
const slice = bytes[0..clen];
u.* = 0xFFFD;
if (slice.len == 0)
return 0;
const len = unicode.utf8ByteSequenceLength(slice[0]) catch return 0;
if (clen < len)
return 0;
u.* = unicode.utf8Decode(slice[0..len]) catch return 0;
return len;
}
export fn utf8encode(u: u32, out: [*]u8) usize {
const codepoint = math.cast(u21, u) catch return 0;
return unicode.utf8Encode(codepoint, out[0..4]) catch return 0;
}
export fn base64dec(src: [*:0]const u8) [*:0]u8 {
const len = mem.lenZ(src);
const size = base64.standard_decoder.calcSize(src[0..len]) catch unreachable;
const res = heap.c_allocator.allocSentinel(u8, size, 0) catch std.debug.panic("strdup failed", .{});
base64.standard_decoder.decode(res, src[0..len]) catch unreachable;
return res.ptr;
}
fn tline(y: c_int) Line {
if (y < term.scr)
return term.hist[@intCast(usize, @mod(y + term.histi - term.scr + histsize + 1, histsize))];
return term.line[@intCast(usize, y - term.scr)];
}
export fn tlinelen(y: c_int) c_int {
var i = @intCast(usize, term.col);
if (tline(y)[i - 1].mode & ATTR_WRAP != 0)
return @intCast(c_int, i);
while (i > 0 and tline(y)[i - 1].u == ' ')
i -= 1;
return @intCast(c_int, i);
}
export fn tmoveto(x: c_int, y: c_int) void {
const miny = if (term.c.state & CURSOR_ORIGIN != 0) term.top else 0;
const maxy = if (term.c.state & CURSOR_ORIGIN != 0) term.bot else term.row - 1;
term.c.state &= ~CURSOR_WRAPNEXT;
term.c.x = math.clamp(x, 0, term.col - 1);
term.c.y = math.clamp(y, miny, maxy);
}
export fn tmoveato(x: c_int, y: c_int) void {
tmoveto(x, y + if (term.c.state & CURSOR_ORIGIN != 0) term.top else 0);
}
export fn tsetdirt(_top: c_int, _bot: c_int) void {
const top = math.clamp(_top, 0, term.row - 1);
const bot = math.clamp(_bot, 0, term.row - 1);
var i = @intCast(usize, top);
while (i <= bot) : (i += 1)
term.dirty[i] = 1;
}
export fn tprinter(s: [*]const u8, len: usize) void {
if (iofd == 0)
return;
const file = fs.File{ .handle = iofd, .io_mode = io.mode };
file.writeAll(s[0..len]) catch |err| {
debug.warn("Error writing to output file {}\n", .{err});
file.close();
iofd = 0;
};
}
export fn selclear() void {
if (sel.ob.x == -1)
return;
sel.mode = SEL_IDLE;
sel.ob.x = -1;
tsetdirt(sel.nb.y, sel.ne.y);
}
const word_delimiters = [_]u32{' '};
fn isdelim(u: u32) bool {
return mem.indexOfScalar(u32, &word_delimiters, u) != null;
}
fn between(x: var, a: var, b: var) bool {
return a <= x and x <= b;
}
export fn selsnap(x: *c_int, y: *c_int, direction: c_int) void {
switch (sel.snap) {
// Snap around if the word wraps around at the end or
// beginning of a line.
SNAP_WORD => {
var prevgb = tline(y.*)[@intCast(usize, x.*)];
var prevdelim = isdelim(prevgb.u);
while (true) {
var newx = x.* + direction;
var newy = y.*;
if (!between(newx, 0, term.col - 1)) {
newy += direction;
newx = @mod(newx + term.col, term.col);
if (!between(newy, 0, term.row - 1))
break;
const yt = if (direction > 0) y.* else newy;
const xt = if (direction > 0) x.* else newx;
if (tline(yt)[@intCast(usize, xt)].mode & ATTR_WRAP == 0)
break;
}
if (newx >= tlinelen(newy))
break;
const gb = tline(newy)[@intCast(usize, newx)];
const delim = isdelim(gb.u);
if (gb.mode & ATTR_WDUMMY == 0 and (delim != prevdelim or
(delim and gb.u != prevgb.u)))
{
break;
}
x.* = newx;
y.* = newy;
prevgb = gb;
prevdelim = delim;
}
},
// Snap around if the the previous line or the current one
// has set ATTR_WRAP at its end. Then the whole next or
// previous line will be selected.
SNAP_LINE => {
x.* = if (direction < 0) 0 else term.col - 1;
if (direction < 0) {
while (y.* > 0) : (y.* += direction) {
if (tline(y.* - 1)[@intCast(usize, term.col - 1)].mode & ATTR_WRAP == 0)
break;
}
} else if (direction > 0) {
while (y.* < term.row - 1) : (y.* += direction) {
if (tline(y.*)[@intCast(usize, term.col - 1)].mode & ATTR_WRAP == 0)
break;
}
}
},
else => {},
}
}
export fn selnormalize() void {
if (sel.type == SEL_REGULAR and sel.ob.y != sel.oe.y) {
sel.nb.x = if (sel.ob.y < sel.oe.y) sel.ob.x else sel.oe.x;
sel.ne.x = if (sel.ob.y < sel.oe.y) sel.oe.x else sel.ob.x;
} else {
sel.nb.x = math.min(sel.ob.x, sel.oe.x);
sel.ne.x = math.max(sel.ob.x, sel.oe.x);
}
sel.nb.y = math.min(sel.ob.y, sel.oe.y);
sel.ne.y = math.max(sel.ob.y, sel.oe.y);
selsnap(&sel.nb.x, &sel.nb.y, -1);
selsnap(&sel.ne.x, &sel.ne.y, 1);
// expand selection over line breaks
if (sel.type == SEL_RECTANGULAR)
return;
const i = tlinelen(sel.nb.y);
if (i < sel.nb.x)
sel.nb.x = i;
if (tlinelen(sel.ne.y) <= sel.ne.x)
sel.ne.x = term.col - 1;
}
export fn selscroll(orig: c_int, n: c_int) void {
if (sel.ob.x == -1)
return;
if (between(sel.nb.y, orig, term.bot) != between(sel.ne.y, orig, term.bot)) {
selclear();
} else if (between(sel.nb.y, orig, term.bot)) {
sel.ob.y += n;
sel.oe.y += n;
if (sel.ob.y < term.top or sel.ob.y > term.bot or
sel.oe.y < term.top or sel.oe.y > term.bot)
{
selclear();
} else {
selnormalize();
}
}
}
fn is_set(flag: var) bool {
return term.mode & flag != 0;
}
export fn selstart(col: c_int, row: c_int, snap: c_int) void {
selclear();
sel.mode = SEL_EMPTY;
sel.type = SEL_REGULAR;
sel.alt = @boolToInt(is_set(MODE_ALTSCREEN));
sel.snap = snap;
sel.oe.x = col;
sel.ob.x = col;
sel.oe.y = row;
sel.ob.y = row;
selnormalize();
if (sel.snap != 0)
sel.mode = SEL_READY;
tsetdirt(sel.nb.y, sel.ne.y);
}
export fn selextend(col: c_int, row: c_int, _type: c_int, done: c_int) void {
if (sel.mode == SEL_IDLE)
return;
if (done != 0 and sel.mode == SEL_EMPTY) {
selclear();
return;
}
const oldey = sel.oe.y;
const oldex = sel.oe.x;
const oldsby = sel.nb.y;
const oldsey = sel.ne.y;
const oldtype = sel.type;
sel.oe.x = col;
sel.oe.y = row;
selnormalize();
sel.type = _type;
if (oldey != sel.oe.y or oldex != sel.oe.x or oldtype != sel.type or sel.mode == SEL_EMPTY)
tsetdirt(math.min(sel.nb.y, oldsby), math.max(sel.ne.y, oldsey));
sel.mode = if (done != 0) SEL_IDLE else SEL_READY;
}
export fn selected(x: c_int, y: c_int) c_int {
if (sel.mode == SEL_EMPTY or sel.ob.x == -1 or
sel.alt != @boolToInt(is_set(MODE_ALTSCREEN)))
return 0;
if (sel.type == SEL_RECTANGULAR)
return @boolToInt(between(y, sel.nb.y, sel.ne.y) and
between(x, sel.nb.x, sel.ne.x));
return @boolToInt(between(y, sel.nb.y, sel.ne.y) and
(y != sel.nb.y or x >= sel.nb.x) and
(y != sel.ne.y or x <= sel.ne.x));
}
export fn tputtab(_n: c_int) void {
var n = _n;
var x: usize = @intCast(usize, term.c.x);
if (n > 0) {
while (x < term.col and n != 0) : (n -= 1) {
x += 1;
while (x < term.col and term.tabs[x] == 0) : (x += 1) {}
}
} else if (n < 0) {
while (x > 0 and n != 0) : (n += 1) {
x -= 1;
while (x > 0 and term.tabs[x] == 0) : (x -= 1) {}
}
}
term.c.x = math.clamp(@intCast(c_int, x), 0, term.col - 1);
}
export fn tclearregion(_x1: c_int, _y1: c_int, _x2: c_int, _y2: c_int) void {
const x1 = math.clamp(math.min(_x1, _x2), 0, term.col - 1);
const x2 = math.clamp(math.max(_x1, _x2), 0, term.col - 1);
const y1 = math.clamp(math.min(_y1, _y2), 0, term.row - 1);
const y2 = math.clamp(math.max(_y1, _y2), 0, term.row - 1);
var y = @intCast(usize, y1);
while (y <= @intCast(usize, y2)) : (y += 1) {
term.dirty[y] = 1;
var x = @intCast(usize, x1);
while (x <= @intCast(usize, x2)) : (x += 1) {
const gp = &term.line[y][x];
if (selected(@intCast(c_int, x), @intCast(c_int, y)) != 0)
selclear();
gp.fg = term.c.attr.fg;
gp.bg = term.c.attr.bg;
gp.mode = 0;
gp.u = ' ';
}
}
}
export fn tscrolldown(orig: c_int, _n: c_int, copyhist: c_int) void {
const n = math.clamp(_n, 0, term.bot - orig + 1);
if (copyhist != 0) {
term.histi = @mod(term.histi - 1 + histsize, histsize);
mem.swap(
Line,
&term.hist[@intCast(usize, term.histi)],
&term.line[@intCast(usize, term.bot)],
);
}
tsetdirt(orig, term.bot - n);
tclearregion(0, term.bot - n + 1, term.col - 1, term.bot);
var i = term.bot;
while (i >= orig + n) : (i -= 1) {
mem.swap(
Line,
&term.line[@intCast(usize, i)],
&term.line[@intCast(usize, i - n)],
);
}
if (term.scr == 0)
selscroll(orig, n);
}
export fn tscrollup(orig: c_int, _n: c_int, copyhist: c_int) void {
const n = math.clamp(_n, 0, term.bot - orig + 1);
if (copyhist != 0) {
term.histi = @mod(term.histi + 1, histsize);
mem.swap(
Line,
&term.hist[@intCast(usize, term.histi)],
&term.line[@intCast(usize, orig)],
);
}
if (term.scr > 0 and term.scr < histsize)
term.scr = math.min(term.scr + n, histsize - 1);
tclearregion(0, orig, term.col - 1, orig + n - 1);
tsetdirt(orig + n, term.bot);
var i = orig;
while (i <= term.bot - n) : (i += 1) {
mem.swap(
Line,
&term.line[@intCast(usize, i)],
&term.line[@intCast(usize, i + n)],
);
}
if (term.scr == 0)
selscroll(orig, -n);
}
export fn tattrset(attr: c_int) c_int {
var i: usize = 0;
while (i < term.row - 1) : (i += 1) {
var j: usize = 0;
while (j < term.col - 1) : (j += 1) {
if (term.line[i][j].mode & @intCast(c_ushort, attr) != 0)
return 1;
}
}
return 0;
}
export fn tsetdirtattr(attr: c_int) void {
var i: usize = 0;
while (i < term.row - 1) : (i += 1) {
var j: usize = 0;
while (j < term.col - 1) : (j += 1) {
if (term.line[i][j].mode & @intCast(c_ushort, attr) != 0) {
tsetdirt(@intCast(c_int, i), @intCast(c_int, i));
break;
}
}
}
}
export fn tcursor(mode: c_int) void {
const Static = struct {
var cur: [2]TCursor = undefined;
};
const alt = @boolToInt(is_set(MODE_ALTSCREEN));
if (mode == CURSOR_SAVE) {
Static.cur[alt] = term.c;
} else if (mode == CURSOR_LOAD) {
term.c = Static.cur[alt];
tmoveto(Static.cur[alt].x, Static.cur[alt].y);
}
}
export fn ttyhangup() void {
// Send SIGHUP to shell
os.kill(pid, os.SIGHUP) catch unreachable;
}
export fn tfulldirt() void {
tsetdirt(0, term.row - 1);
}
export fn tisaltscr() c_int {
return @boolToInt(is_set(MODE_ALTSCREEN));
}
export fn tswapscreen() void {
mem.swap([*]Line, &term.line, &term.alt);
term.mode ^= MODE_ALTSCREEN;
tfulldirt();
}
export fn tnewline(first_col: c_int) void {
var y = term.c.y;
if (y == term.bot) {
tscrollup(term.top, 1, 1);
} else {
y += 1;
}
tmoveto(if (first_col != 0) 0 else term.c.x, y);
}
export fn tdeletechar(_n: c_int) void {
const n = math.clamp(_n, 0, term.col - term.c.x);
const dst = @intCast(usize, term.c.x);
const src = @intCast(usize, term.c.x + n);
const size = @intCast(usize, term.col) - src;
const line = term.line[@intCast(usize, term.c.y)];
mem.copy(Glyph, (line + dst)[0..size], (line + src)[0..size]);
tclearregion(term.col - n, term.c.y, term.col - 1, term.c.y);
}
export fn tinsertblank(_n: c_int) void {
const n = math.clamp(_n, 0, term.col - term.c.x);
const dst = @intCast(usize, term.c.x + n);
const src = @intCast(usize, term.c.x);
const size = @intCast(usize, term.col) - dst;
const line = term.line[@intCast(usize, term.c.y)];
mem.copyBackwards(Glyph, (line + dst)[0..size], (line + src)[0..size]);
tclearregion(@intCast(c_int, src), term.c.y, @intCast(c_int, dst - 1), term.c.y);
}
export fn tinsertblankline(n: c_int) void {
if (between(term.c.y, term.top, term.bot))
tscrolldown(term.c.y, n, 0);
}
export fn tdeleteline(n: c_int) void {
if (between(term.c.y, term.top, term.bot))
tscrollup(term.c.y, n, 0);
}
| high | 0.487266 | 167 |
-module(maislurp-client-erlang_bounced_email_dto).
-export([encode/1]).
-export_type([maislurp-client-erlang_bounced_email_dto/0]).
-type maislurp-client-erlang_bounced_email_dto() ::
#{ 'id' => maislurp-client-erlang_u_uid:maislurp-client-erlang_u_uid(),
'userId' := maislurp-client-erlang_u_uid:maislurp-client-erlang_u_uid(),
'notificationType' := binary(),
'sentToRecipients' => list(),
'sender' := binary(),
'bounceMta' => binary(),
'bounceType' => binary(),
'bounceRecipients' => list(),
'bounceSubType' => binary(),
'createdAt' := maislurp-client-erlang_date_time:maislurp-client-erlang_date_time()
}.
encode(#{ 'id' := Id,
'userId' := UserId,
'notificationType' := NotificationType,
'sentToRecipients' := SentToRecipients,
'sender' := Sender,
'bounceMta' := BounceMta,
'bounceType' := BounceType,
'bounceRecipients' := BounceRecipients,
'bounceSubType' := BounceSubType,
'createdAt' := CreatedAt
}) ->
#{ 'id' => Id,
'userId' => UserId,
'notificationType' => NotificationType,
'sentToRecipients' => SentToRecipients,
'sender' => Sender,
'bounceMta' => BounceMta,
'bounceType' => BounceType,
'bounceRecipients' => BounceRecipients,
'bounceSubType' => BounceSubType,
'createdAt' => CreatedAt
}.
| medium | 0.408746 | 168 |
import Controller from '@ember/controller';
import { action } from '@ember/object';
export default class extends Controller {
@action
updateSettings() {
this.set('isLoading', true);
let settings = this.model;
settings.save()
.then(() => {
this.notify.success(this.l10n.t('Settings have been saved successfully.'),
{
id: 'setting_analytic_save'
});
})
.catch(e => {
console.error('Error while saving analytics settings', e);
this.notify.error(this.l10n.t('An unexpected error has occurred. Settings not saved.'),
{
id: 'setting_analytic_error'
});
})
.finally(() => {
this.set('isLoading', false);
});
}
}
| medium | 0.353201 | 169 |
module Page.Login exposing (Model, Msg, init, subscriptions, toSession, update, view)
import Browser.Navigation as Navigation exposing (load)
import Helper exposing (Response, decodeResponse, endPoint, informHttpError)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput)
import Http
import Json.Encode as Encode
import Route exposing (Route)
import Session exposing (Session)
import Url.Builder as Builder
import User exposing (Profile)
init : Session -> ( Model, Cmd Msg )
init session =
let
cmd =
case Session.cred session of
Just cred ->
Route.replaceUrl (Session.navKey session) Route.Home
Nothing ->
Cmd.none
in
( { session = session
, problems = []
, form =
{ email = ""
, password = ""
}
}
, cmd
)
type alias Model =
{ session : Session
, form : Form
, problems : List Problem
}
type Problem
= InvalidEntry ValidatedField String
| ServerError String
-- VIEW
view : Model -> { title : String, content : Html Msg }
view model =
{ title = "Eat Right - Login"
, content = loginView model
}
type alias Form =
{ email : String
, password : String
}
loginView : Model -> Html Msg
loginView model =
div [ class "container" ]
[ div [ class "card .login-card" ]
[ div [ class "card-body" ]
[ p [ class "validation-problem" ]
(List.map (\str -> viewServerError str) model.problems)
, loginForm model
]
]
]
loginForm : Model -> Html Msg
loginForm model =
div [ class "login-form" ]
[ h3 [ class "card-title" ] [ text "Login" ]
, div []
[ div [ class "form-group" ]
[ div [] [ viewInput model Email "Email" "text" "johndoe@example.com" ]
, div [] [ viewInput model Password "Password" "password" "*******" ]
, div []
[ button [ class "btn btn-primary", onClick SubmittedDetails ] [ text "LOGIN" ] ]
]
]
]
viewServerError : Problem -> Html Msg
viewServerError problem =
case problem of
ServerError str ->
text str
_ ->
text ""
viewProblem : Model -> ValidatedField -> Problem -> Html msg
viewProblem model formfield problem =
let
errorMsg =
case problem of
InvalidEntry f str ->
if f == formfield then
str
else
""
ServerError _ ->
""
in
if String.length errorMsg > 1 then
p [ class "validation-problem" ] [ text errorMsg ]
else
text ""
setErrors : List Problem -> Model -> Model
setErrors problems model =
{ model | problems = problems }
setField : ValidatedField -> String -> Model -> Model
setField field value model =
case field of
Email ->
updateForm (\form -> { form | email = value }) model
Password ->
updateForm (\form -> { form | password = value }) model
viewInput : Model -> ValidatedField -> String -> String -> String -> Html Msg
viewInput model formField labelName inputType inputName =
let
what =
case formField of
Email ->
model.form.email
Password ->
model.form.password
lis =
List.map (\err -> viewProblem model formField err) model.problems
in
label
[ class "" ]
[ text labelName
, input
[ type_ inputType
, placeholder inputName
, onInput <| SetField formField
, value what
, class "form-control"
]
[]
, ul [] lis
]
type Msg
= SubmittedDetails
| SetField ValidatedField String
| GotResponse (Result Http.Error Response)
| GotSession Session
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
let
problemList =
validate model.form
in
case msg of
SubmittedDetails ->
case problemList of
[] ->
-- send data to the server
-- receive server response
-- trigger command to handle or consume response
( { model | problems = [] }
, login model
)
problems ->
( { model | problems = problems }
, Cmd.none
)
SetField field value ->
( model
|> setField field value
|> setErrors problemList
, Cmd.none
)
GotResponse resp ->
case resp of
Ok successData ->
( model
, Cmd.batch [ Session.login successData, Route.loadPage Route.Home ]
)
Err err ->
let
errorMsg =
informHttpError err
in
( { model | problems = [ ServerError errorMsg ] }
, Cmd.none
)
GotSession session ->
( { model | session = session }
, Navigation.load "/home"
)
-- tiny helper function to update the form in the session
updateForm : (Form -> Form) -> Model -> Model
updateForm transform model =
{ model | form = transform model.form }
-- Subscriptions
subscriptions : Model -> Sub Msg
subscriptions model =
Session.changes GotSession (Session.navKey model.session)
-- Handle the Form
type ValidatedField
= Email
| Password
-- To ensure we only trim the form when the user is done
type TrimmedForm
= Trimmed Form
fieldsToValidate : List ValidatedField
fieldsToValidate =
[ Email
, Password
]
-- trim and validate form
validate : Form -> List Problem
validate form =
let
trimmedForm =
trimFields form
in
case List.concatMap (validateField trimmedForm) fieldsToValidate of
[] ->
[]
problems ->
problems
-- validateField
validateField : TrimmedForm -> ValidatedField -> List Problem
validateField (Trimmed form) field =
List.map (InvalidEntry field) <|
case field of
Email ->
if String.isEmpty form.email then
[ "email can't be blank." ]
else
[]
Password ->
if String.isEmpty form.password then
[ "password can't be blank." ]
else if String.length form.password < 8 then
[ "password should be at least 8 characters long." ]
else
[]
-- trimFields on demand
trimFields : Form -> TrimmedForm
trimFields form =
Trimmed
{ email = String.trim form.email
, password = String.trim form.password
}
-- Exported Session Builder
toSession : Model -> Session
toSession model =
model.session
-- http
login : Model -> Cmd Msg
login model =
Http.request
{ url = endPoint [ "auth", "login" ]
, headers = [ Http.header "Origin" "http://localhost:5000" ]
, body = Http.jsonBody (encodeLogin model)
, expect = Http.expectJson GotResponse decodeResponse
, method = "POST"
, timeout = Nothing
, tracker = Nothing
}
encodeLogin : Model -> Encode.Value
encodeLogin { form } =
Encode.object
[ ( "email", Encode.string form.email )
, ( "password", Encode.string form.password )
]
| high | 0.656175 | 170 |
require 'nn'
local utils = paths.dofile'./utils.lua'
local model = nn.Sequential()
local fSize = {2, 96, 192, 256, 256, 1}
model:add(nn.SpatialConvolution(fSize[1], fSize[2], 7, 7, 3, 3))
model:add(nn.ReLU())
model:add(nn.SpatialMaxPooling(2,2,2,2))
model:add(nn.SpatialConvolution(fSize[2], fSize[3], 5, 5))
model:add(nn.ReLU())
model:add(nn.SpatialMaxPooling(2,2,2,2))
model:add(nn.SpatialConvolution(fSize[3], fSize[4], 3, 3))
model:add(nn.ReLU())
model:add(nn.View(-1):setNumInputDims(3))
model:add(nn.Linear(fSize[4], fSize[5]))
model:add(nn.ReLU())
model:add(nn.Linear(fSize[5], fSize[6]))
utils.MSRinit(model)
utils.testModel(model)
return model
| high | 0.435976 | 171 |
python setup.py sdist bdist_wheel
twine check dist/*
twine upload --skip-existing dist/*
| low | 0.472487 | 172 |
model: {
second: {
voxel_generator {
point_cloud_range : [0, -39.68, -3, 69.12, 39.68, 1]
#voxel_size : [1280, 384, 1]
#voxel_size : [640, 192, 8]
voxel_size : [512, 128, 7]
max_number_of_points_per_voxel : 100
}
num_class: 1
voxel_feature_extractor: {
module_class_name: "FrontViewFeatureNet"
num_filters: [64]
with_distance: false
}
middle_feature_extractor: {
module_class_name: "FrontViewScatter"
}
rpn: {
module_class_name: "RPN"
layer_nums: [3, 5, 5]
layer_strides: [2, 2, 2]
num_filters: [64, 128, 256]
upsample_strides: [1, 2, 4]
num_upsample_filters: [128, 128, 128]
use_groupnorm: false
num_groups: 32
}
loss: {
classification_loss: {
weighted_sigmoid_focal: {
alpha: 0.25
gamma: 2.0
anchorwise_output: true
}
}
localization_loss: {
weighted_smooth_l1: {
sigma: 3.0
code_weight: [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
}
}
classification_weight: 1.0
localization_weight: 2.0
}
# Outputs
use_sigmoid_score: true
encode_background_as_zeros: true
encode_rad_error_by_sin: true
use_direction_classifier: true
direction_loss_weight: 0.2
use_aux_classifier: false
# Loss
pos_class_weight: 1.0
neg_class_weight: 1.0
loss_norm_type: NormByNumPositives
# Postprocess
post_center_limit_range: [0, -39.68, -5, 69.12, 39.68, 5]
use_rotate_nms: false
use_multi_class_nms: false
nms_pre_max_size: 1000
nms_post_max_size: 300
nms_score_threshold: 0.05
nms_iou_threshold: 0.5
use_bev: false
num_point_features: 4
without_reflectivity: false
box_coder: {
ground_box3d_coder: {
linear_dim: false
encode_angle_vector: false
}
}
target_assigner: {
anchor_generators: {
anchor_generator_stride: {
sizes: [1.6, 3.9, 1.56] # wlh
strides: [0.32, 0.32, 0.0] # if generate only 1 z_center, z_stride will be ignored
offsets: [0.16, -39.52, -1.78] # origin_offset + strides / 2
rotations: [0, 1.57] # 0, pi/2
matched_threshold : 0.6
unmatched_threshold : 0.45
}
}
sample_positive_fraction : -1
sample_size : 512
region_similarity_calculator: {
nearest_iou_similarity: {
}
}
}
}
}
train_input_reader: {
record_file_path: "/home/js/data/KITTI/object/kitti_train.tfrecord"
class_names: ["Car"]
max_num_epochs : 160
batch_size: 2
prefetch_size : 25
max_number_of_voxels: 20000
shuffle_points: true
num_workers: 2
groundtruth_localization_noise_std: [0.25, 0.25, 0.25]
groundtruth_rotation_uniform_noise: [-0.15707963267, 0.15707963267]
global_rotation_uniform_noise: [-0.78539816, 0.78539816]
global_scaling_uniform_noise: [0.95, 1.05]
global_random_rotation_range_per_object: [0, 0]
anchor_area_threshold: 1
remove_points_after_sample: true
groundtruth_points_drop_percentage: 0.0
groundtruth_drop_max_keep_points: 15
database_sampler {
#database_info_path: "/home/js/data/KITTI/object/kitti_dbinfos_train.pkl"
database_info_path: "/home/js/data/KITTI/object/kitti_dbinfos_train_RGB.pkl"
sample_groups {
name_to_max_num {
key: "Car"
value: 15
}
}
database_prep_steps {
filter_by_min_num_points {
min_num_point_pairs {
key: "Car"
value: 5
}
}
}
database_prep_steps {
filter_by_difficulty {
removed_difficulties: [-1]
}
}
global_random_rotation_range_per_object: [0, 0]
rate: 1.0
}
remove_unknown_examples: false
remove_environment: false
kitti_info_path: "/home/js/data/KITTI/object/kitti_infos_train.pkl"
kitti_root_path: "/home/js/data/KITTI/object"
}
train_config: {
optimizer: {
adam_optimizer: {
learning_rate: {
exponential_decay_learning_rate: {
initial_learning_rate: 0.0002
decay_steps: 27840 # 6960 # 27840 # 1856 steps per epoch * 15 epochs
decay_factor: 0.8
staircase: true
}
}
weight_decay: 0.0001
}
use_moving_average: false
}
inter_op_parallelism_threads: 4
intra_op_parallelism_threads: 4
steps: 296960 # 74240 # 296960 # 1856 steps per epoch * 160 epochs
steps_per_eval: 9280 # 2320 # 9280 # 1856 steps per epoch * 5 epochs
save_checkpoints_secs : 3600 # half hour
save_summary_steps : 10
enable_mixed_precision: false
loss_scale_factor : 512.0
clear_metrics_every_epoch: false
}
eval_input_reader: {
record_file_path: "/home/js/data/KITTI/object/kitti_val.tfrecord"
class_names: ["Car"]
batch_size: 2
max_num_epochs : 160
prefetch_size : 25
max_number_of_voxels: 20000
shuffle_points: false
num_workers: 2
anchor_area_threshold: 1
remove_environment: false
kitti_info_path: "/home/js/data/KITTI/object/kitti_infos_val.pkl"
kitti_root_path: "/home/js/data/KITTI/object"
}
| low | 0.50533 | 173 |
module Task.Utils where
{-| Helper functions for working with Tasks
# The missing functions
@docs fold, bimap
-}
import Task exposing (Task, succeed, onError, map, mapError)
{-| Catamorphism. If the task is a failure, apply the first function to a; if it is successful, apply the second function to b.
-}
fold : (a -> c) -> (b -> c) -> Task a b -> Task y c
fold f1 f2 t =
map f2 t `onError` (\x -> succeed(f1 x))
{-| Binary functor map on a Task
-}
bimap : (a1 -> a2) -> (b1 -> b2) -> Task a1 b1 -> Task a2 b2
bimap f1 f2 t =
Task.mapError f1 t
|> Task.map f2
| high | 0.606317 | 174 |
module Shrink.Testing.Tactics (
shrinkingTactics,
testTacticOn,
run,
prettyPrintTerm,
Similar ((~=)),
(~/=),
) where
import Shrink (defaultShrinkParams, size)
import Shrink.Names (dTermToN)
import Shrink.Testing.Gen (genUplc)
import Shrink.Types (NTerm, SafeTactic, Tactic, safeTactics, tactics)
import Data.Function (on)
import Hedgehog (MonadTest, annotate, assert, failure, forAll, property, success)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.Hedgehog (testProperty)
import Plutus.V1.Ledger.Scripts (Script (Script))
import PlutusCore.Default (DefaultFun, DefaultUni)
import PlutusCore.Evaluation.Machine.ExBudget (
ExBudget (ExBudget, exBudgetCPU, exBudgetMemory),
ExRestrictingBudget (ExRestrictingBudget, unExRestrictingBudget),
)
import PlutusCore.Evaluation.Machine.ExMemory (ExCPU (), ExMemory ())
import PlutusCore.Name (Name)
import UntypedPlutusCore.Evaluation.Machine.Cek (CekEvaluationException, RestrictingSt (RestrictingSt), restricting, runCekNoEmit)
import PlutusCore qualified as PLC
import UntypedPlutusCore.Core.Type qualified as UPLC
type Result =
Either
(CekEvaluationException DefaultUni DefaultFun)
(UPLC.Term Name DefaultUni DefaultFun ())
class Similar a where
(~=) :: a -> a -> Bool
instance Similar (Result, RestrictingSt) where
(lres, lcost) ~= (rres, rcost) = lres ~= rres && getCpu lcost ~= getCpu rcost && getMem lcost ~= getMem rcost
where
getCpu (RestrictingSt budget) = exBudgetCPU . unExRestrictingBudget $ budget
getMem (RestrictingSt budget) = exBudgetMemory . unExRestrictingBudget $ budget
-- For now I test that cpu and memory changes are not too signifigant
instance Similar ExCPU where
a ~= b = 5 * abs (a - b) < abs a + abs b
instance Similar ExMemory where
a ~= b = 5 * abs (a - b) < abs a + abs b
instance Similar Result where
(~=) = curry $ \case
(Left _, Left _) -> True
(Right lValue, Right rValue) -> lValue ~= rValue
_ -> False
instance Similar (UPLC.Term Name DefaultUni DefaultFun ()) where
(~=) = curry $ \case
(UPLC.Var () _, UPLC.Var () _) -> True
-- I don't love this clause but there are
-- equivelent terms where this seems to be the best
-- you can reasonably do
-- !((\x -> #()) ()) == ()
-- !(!(#(#()))) == ()
-- !() == Error
-- nearly anything in a force can be nearly anthing
(UPLC.Force {}, _) -> True
(_, UPLC.Force {}) -> True
(UPLC.Delay () a, UPLC.Delay () b) -> a ~= b
(UPLC.Apply () _ _, _) -> True
(_, UPLC.Apply () _ _) -> True
(UPLC.LamAbs () _ _, UPLC.LamAbs () _ _) -> True
(UPLC.Builtin () a, UPLC.Builtin () b) -> a == b
(UPLC.Constant () a, UPLC.Constant () b) -> a == b
(UPLC.Error (), UPLC.Error ()) -> True
_ -> False
instance Similar (UPLC.Term PLC.DeBruijn DefaultUni DefaultFun ()) where
(~=) = (~=) `on` dTermToN
instance Similar (UPLC.Program PLC.DeBruijn DefaultUni DefaultFun ()) where
(UPLC.Program () vl tl) ~= (UPLC.Program () vr tr) = vl == vr && tl ~= tr
instance Similar Script where
(Script pl) ~= (Script pr) = pl ~= pr
(~/=) :: Similar a => a -> a -> Bool
a ~/= b = not $ a ~= b
shrinkingTactics :: TestTree
shrinkingTactics =
testGroup
"shrinking tactics"
( [ testGroup tactName [testSafeTactic tactName tact, testSafeTacticShrinks tact]
| (tactName, tact) <- safeTactics defaultShrinkParams
]
++ [ testGroup tactName [testTactic tactName tact]
| (tactName, tact) <- tactics defaultShrinkParams
]
)
testSafeTactic :: String -> SafeTactic -> TestTree
testSafeTactic tactName safeTactic = testTactic tactName (return . safeTactic)
testSafeTacticShrinks :: SafeTactic -> TestTree
testSafeTacticShrinks st = testProperty "Safe tactic doesn't grow code" . property $ do
uplc <- dTermToN <$> forAll genUplc
assert $ size uplc >= size (st uplc)
testTactic :: String -> Tactic -> TestTree
testTactic tactName tactic = testProperty "Tactic doesn't break code" . property $ do
uplc <- forAll genUplc
testTacticOn tactName tactic (dTermToN uplc)
testTacticOn :: MonadTest m => String -> Tactic -> NTerm -> m ()
testTacticOn tactName tact uplc = do
let res = run uplc
let fails =
[ uplc' | uplc' <- tact uplc, uplc' /= uplc, run uplc' ~/= res
]
case fails of
[] -> success
(bad : _) -> do
annotate $ prettyPrintTerm uplc
annotate $ "produced: " ++ show res
annotate $ "Shrank by " ++ tactName ++ " to"
annotate $ prettyPrintTerm bad
annotate $ "produced: " ++ show (run bad)
failure
run :: NTerm -> (Result, RestrictingSt)
run =
runCekNoEmit
PLC.defaultCekParameters
( restricting . ExRestrictingBudget $
ExBudget
{ exBudgetCPU = 1_000_000_000 :: ExCPU
, exBudgetMemory = 1_000_000 :: ExMemory
}
)
prettyPrintTerm :: NTerm -> String
prettyPrintTerm =
let showName n = "V-" ++ show (PLC.unUnique (PLC.nameUnique n))
in \case
UPLC.Var () name -> showName name
UPLC.LamAbs () name term -> "(\\" ++ showName name ++ "->" ++ prettyPrintTerm term ++ ")"
UPLC.Apply () f@UPLC.LamAbs {} x -> prettyPrintTerm f ++ " (" ++ prettyPrintTerm x ++ ")"
UPLC.Apply () f x -> "(" ++ prettyPrintTerm f ++ ") (" ++ prettyPrintTerm x ++ ")"
UPLC.Force () term -> "!(" ++ prettyPrintTerm term ++ ")"
UPLC.Delay () term -> "#(" ++ prettyPrintTerm term ++ ")"
UPLC.Constant () (PLC.Some (PLC.ValueOf ty con)) -> case (ty, con) of
(PLC.DefaultUniInteger, i) -> show i
(PLC.DefaultUniByteString, bs) -> show bs
(PLC.DefaultUniString, txt) -> show txt
(PLC.DefaultUniUnit, ()) -> "()"
(PLC.DefaultUniBool, b) -> show b
(PLC.DefaultUniData, dat) -> show dat
_ -> "Exotic constant"
UPLC.Builtin () f -> show f
UPLC.Error () -> "Error"
| high | 0.787926 | 175 |
FROM node:10.13-alpine
ARG COMMIT_HASH
RUN test -n "$COMMIT_HASH"
RUN apk add curl git nginx
# Set up deploy user and working directory
RUN adduser -D -g '' deploy
RUN mkdir -p /app
RUN chown deploy:deploy /app
# Set up dumb-init
ADD https://github.com/Yelp/dumb-init/releases/download/v1.2.2/dumb-init_1.2.2_amd64 /usr/local/bin/dumb-init
RUN chown deploy:deploy /usr/local/bin/dumb-init
RUN chmod +x /usr/local/bin/dumb-init
# Setup nginx
RUN rm -v /etc/nginx/nginx.conf
RUN rm -v /etc/nginx/conf.d/default.conf
ADD conf/nginx.conf /etc/nginx/
ADD conf/positron-backend.conf /etc/nginx/conf.d/
RUN touch /var/run/nginx.pid && \
chown -R deploy:deploy /var/run/nginx.pid && \
chown -R deploy:deploy /etc/nginx && \
chown -R deploy:deploy /var/lib/nginx && \
chown -R deploy:deploy /var/tmp/nginx
# Symlink nginx logs to stderr / stdout
RUN ln -sf /dev/stdout /var/log/nginx/access.log \
&& ln -sf /dev/stderr /var/log/nginx/error.log
RUN npm install -g yarn@1.9.4
# Switch to deploy user
USER deploy
ENV USER deploy
ENV HOME /home/deploy
# Set up node_modules
WORKDIR /app
ADD package.json /app
ADD yarn.lock /app
RUN yarn install && yarn cache clean
# Add the codebase
ADD --chown=deploy:deploy . /app
# Echo commit hash
RUN echo $COMMIT_HASH > COMMIT_HASH.txt
ENV PORT 3005
EXPOSE 3005
ENTRYPOINT ["/usr/local/bin/dumb-init", "--"]
CMD ["yarn", "start"]
| low | 0.538846 | 176 |
file(REMOVE_RECURSE
"CMakeFiles/crypto.test_suite_hmac_drbg.pr.dir/test_suite_hmac_drbg.pr.c.o"
"CMakeFiles/crypto.test_suite_hmac_drbg.pr.dir/test_suite_hmac_drbg.pr.c.o.d"
"crypto.test_suite_hmac_drbg.pr"
"crypto.test_suite_hmac_drbg.pr.pdb"
"test_suite_hmac_drbg.pr.c"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/crypto.test_suite_hmac_drbg.pr.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
| low | 0.913025 | 177 |
* Command to send messages to slack
*! Version 1.3.3 14may2020
* Contact jesse.wursten@kuleuven.be for bug reports/inquiries.
* Changelog
** 14may20: Fixed default URL again (Slack decided to kill the previous one)
** 05nov18: Default url updated (see item below)
** 29oct18: Help file updated (someone removed the existing webhook)
** 26jun18: Cosmetic changes and better integration with other commands
** 01dec17: Improved functionality of saving the url
** 16nov17: Text is now formatted in bold
** 04sep17: You can now store URLs in profile.do using the build option and added extra examples
** 01sep17: The command is born.
program define sendtoslack
version 8.0
syntax, [Url(string) Message(string) method(string) saveurlas(string) col(integer 0)]
* Save Url (default or named)
if "`saveurlas'" != "" {
sts_Saveurl, urltosave(`url') name(`saveurlas')
if `"`message'"' == "" local message "Testing whether saveurlas worked correctly."
di "We will now send a text message to the saved url."
local url "`saveurlas'"
}
* Send message
sts_Send, url(`url') message(`message') method(`method') col(`col')
end
program define sts_Send
syntax, [url(string) message(string) method(string) col(integer 0)]
** Parse col (mainly used for integration with other commands that use sendtoslack)
if `col' == 0 local preCol ""
if `col' != 0 local preCol "_col(`col')"
** Parse url
*** (saved) Name
if "${sts_`url'}" != "" & "sts_`url'" != "sts_default" {
di `preCol' as text "Sending message to url saved as `url': " as result "${sts_`url'}"
local url "${sts_`url'}"
}
*** Empty
**** Default specified
if ("`url'" == "" | "`url'" == "default") & "$sts_default" != "" {
di `preCol' as text "Sending message to " as result "default" as text " url: " as result "$sts_default"
local url "${sts_default}"
}
*** Default not specified
if "`url'" == "" & "$sts_default" == "" {
di as text "No url provided and no url saved. Sending test message to the stataMessage workspace."
di as text "Accessible at: " as result "https://statamessage.slack.com/messages/C6WSHNXM1/"
local url "https://hooks.slack.com/services/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"
}
** Fill in empty message
if `"`message'"' == "" {
local message "`c(hostname)': Stata has done something you wanted to know about!"
}
** Filter out apostrophes and quotes
local message = subinstr(`"`message'"', `"""', "", .)
local message = subinstr(`"`message'"', `"'"', "", .)
** Curl
if "`method'" == "curl" {
! curl -X POST --data-urlencode "payload={'username': 'statamessage', 'text': '`message'', 'icon_emoji': ':bell:'}" `url'
}
** Powershell
else {
! powershell -Command "Invoke-WebRequest -Body(ConvertTo-Json -Compress -InputObject @{'username'='statamessage'; 'text'='`message''; 'icon_emoji' = ':bell:'}) -Method Post -Uri `url'"
}
di `preCol' as text "Message sent: " as result `"`message'"'
end
program define sts_Saveurl
syntax, name(string) urltosave(string)
* Determine whether profile.do exists
cap findfile profile.do
** If profile.do does not exist yet
** Create profile.do (asking permission)
if _rc == 601 {
di "Profile.do does not exist yet."
di "Do you want to allow this program to create one for you? y: yes, n: no" _newline "(enter below)" _request(_createPermission)
if "`createPermission'" == "y" {
di "Creating profile.do as `c(sysdir_oldplace)'profile.do"
tempname createdProfileDo
file open `createdProfileDo' using `"`c(sysdir_oldplace)'profile.do"', write
file close `createdProfileDo'
}
if "`createPermission'" != "y" {
di "User did not give permission to create profile.do, aborting program."
exit
}
}
* Write in global for url
** Verify if global is already defined (if so, give warning)
*** Find location of profile.do
qui findfile profile.do
local profileDofilePath "`r(fn)'"
*** Open
tempname profileDofile
file open `profileDofile' using "`profileDofilePath'", read text
file read `profileDofile' line
*** Loop over profile.do until ...
*** you reached the end
*** found the global we want to define
local keepGoing = 1
while `keepGoing' == 1 {
if strpos(`"`macval(line)'"', "sts_`name'") > 0 {
di as error "Global was already defined in profile.do"
di as result"The program will add the new definition at the bottom."
di "You might want to open profile.do and remove the old entry."
di "This is not required, but prevents clogging your profile.do."
di "To do so, type: " as txt "doed `profileDofilePath'" _newline
local keepGoing = 0
}
file read `profileDofile' line
if r(eof) == 1 local keepGoing = 0
}
file close `profileDofile'
** Write in the global
file open `profileDofile' using "`profileDofilePath'", write text append
file write `profileDofile' _newline `"global sts_`name' "`urltosave'""'
file close `profileDofile'
** Define it now too, as profile.do changes only take place once it has ran
global sts_`name' "`urltosave'"
* Report back to user
di as result "Added a url entitled, (sts_)`name' to " as txt "`profileDofilePath'"
if "`name'" == "default" di as result "On this PC, this url will be used if no url option was specified." _newline
if "`name'" != "default" di as result "On this PC, you can now specify url(name) to use this link." _newline
end
| medium | 0.407054 | 178 |
library(devtools)
library(parallel)
devtools::load_all()
RNGkind("L'Ecuyer-CMRG")
s_seed <- 999983 + 4000
s_k <- 1000
s_n <- 500
s_m <- 7
v_seed <- c(s_seed, s_seed + s_k)
center_5007_3 <- mclapply(v_seed, seed_loop <- function(seed) {
type_1(seed, s_k / 2, s_n, s_m, L = 1000,
fast.tn = T, semi.iter = F, center.bs = T, no.pen = T)
}, mc.cores = 2)
save(center_5007_3, file = "center_5007_3.RData") | low | 0.442697 | 179 |
<!-- START Top Navbar-->
<nav class="navbar topnavbar" role="navigation">
<!-- START navbar header-->
<div class="navbar-header">
<a class="navbar-brand" href="#/">
<div class="brand-logo">
<img class="img-responsive" src="assets/img/logo.png" alt="App Logo" />
</div>
<div class="brand-logo-collapsed">
<img class="img-responsive" src="assets/img/logo-single.png" alt="App Logo" />
</div>
</a>
</div>
<!-- END navbar header-->
<!-- START Nav wrapper-->
<div class="nav-wrapper">
<!-- START Left navbar-->
<ul class="nav navbar-nav">
<li>
<!-- Button used to collapse the left sidebar. Only visible on tablet and desktops-->
<a class="hidden-xs" trigger-resize="" (click)="toggleCollapsedSideabar()" *ngIf="!isCollapsedText()">
<em class="fa fa-navicon"></em>
</a>
<!-- Button to show/hide the sidebar on mobile. Visible on mobile only.-->
<a class="visible-xs sidebar-toggle" (click)="settings.layout.asideToggled =! settings.layout.asideToggled">
<em class="fa fa-navicon"></em>
</a>
</li>
</ul>
<!-- END Left navbar-->
<!-- START Right Navbar-->
<ul class="nav navbar-nav navbar-right">
<!-- START Alert menu-->
<li class="dropdown dropdown-list" dropdown>
<a dropdownToggle>
<em class="icon-user"></em>
</a>
<!-- START Dropdown menu-->
<ul dropdownMenu class="dropdown-menu animated flipInY">
<li>
<!-- START list group-->
<div class="list-group">
<!-- list item-->
<a class="list-group-item">
<div class="media-box">
<div class="pull-left">
<img src="assets/img/user/01.png" height="40px" width="40px"/>
</div>
<div class="media-box-body clearfix">
<p class="m0">{{userMe?.name}}</p>
<p class="m0 text-muted">@{{userMe?.twitterUsername}}</p>
</div>
</div>
</a>
<!-- last list item-->
<a class="list-group-item" (click)="logoutClicked()">
<span>{{"topbar.LOGOUT" | translate}}</span>
<em class="fa fa-power-off icon-red pull-right"></em>
</a>
</div>
<!-- END list group-->
</li>
</ul>
<!-- END Dropdown menu-->
</li>
<!-- END Alert menu-->
</ul>
<!-- END Right Navbar-->
</div>
<!-- END Nav wrapper-->
</nav>
<!-- END Top Navbar-->
| high | 0.578625 | 180 |
# Copyright 2020 Google LLC
#
# 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.
# Exit the script with an error status if any files had bad guards.
BEGIN {
found_bad_include_guards = 0;
}
END {
if (found_bad_include_guards) {
exit 1;
}
}
# Reset the state at the beginning of each file.
BEGINFILE {
# The guard must begin with the name of the project.
guard_prefix="GOOGLE_CLOUD_CPP_"
# The guard name is the filename (including path from the root of the
# project), with "/" and "." characters replaced with "_", and all
# characters converted to uppercase:
guard_body=toupper(FILENAME)
gsub("[/\\.]", "_", guard_body)
guard=toupper(guard_prefix guard_body)
matches=0
}
# By the end of the file we expect to find 3 matches for the include guards.
ENDFILE {
if (matches != 3) {
printf("%s has invalid include guards\n", FILENAME);
found_bad_include_guards = 1;
}
}
# Check only lines that start with #ifndef, #define, or #endif.
/^#ifndef / {
# Ignore lines that do not look like guards at all.
if ($0 !~ "_H$") { next; }
if (index($0, guard) == 9) {
matches++;
} else {
printf("%s:\n", FILENAME)
printf("expected: #ifndef %s\n", guard)
printf(" found: %s\n", $0);
}
}
/^#define / {
# Ignore lines that do not look like guards at all.
if ($0 !~ "_H$") { next; }
if (index($0, guard) == 9) {
matches++;
} else {
printf("%s:\n", FILENAME)
printf("expected: #define %s\n", guard)
printf(" found: %s\n", $0);
}
}
/^#endif / {
# Ignore lines that do not look like guards at all.
if ($0 !~ "_H$") { next; }
if (index($0, "// " guard) == 9) {
matches++;
} else {
printf("%s:\n", FILENAME)
printf("expected: #endif // %s\n", guard)
printf(" found: %s\n", $0);
}
}
| high | 0.347409 | 181 |
/**
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.services.datamodeller.core;
import java.util.List;
public interface HasInterfaces {
public List<String> getInterfaces();
void addInterface( String interfaceDefinition );
}
| high | 0.61168 | 182 |
# This file must be used with "source bin/activate.csh" *from csh*.
# You cannot run it directly.
# Created by Davide Di Blasi <davidedb@gmail.com>.
# Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; test "\!:*" != "nondestructive" && unalias deactivate'
# Unset irrelevant variables.
deactivate nondestructive
setenv VIRTUAL_ENV "/Users/joelleo/Desktop/Work/ICC:Computing/Projects:Events/CT-Quest/ct-quest/ct-quest"
set _OLD_VIRTUAL_PATH="$PATH"
setenv PATH "$VIRTUAL_ENV/bin:$PATH"
set _OLD_VIRTUAL_PROMPT="$prompt"
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
if ("ct-quest" != "") then
set env_name = "ct-quest"
else
if (`basename "VIRTUAL_ENV"` == "__") then
# special case for Aspen magic directories
# see https://aspen.io/
set env_name = `basename \`dirname "$VIRTUAL_ENV"\``
else
set env_name = `basename "$VIRTUAL_ENV"`
endif
endif
set prompt = "[$env_name] $prompt"
unset env_name
endif
alias pydoc python -m pydoc
rehash
| low | 1 | 183 |
# Welcome to om_midi
欢迎阅读 om_midi.jsx 的中文文档。
[![Index](/gallery/index1.webp)](/gallery/index1.webp)
!!! danger "暂停更新"
> _[再次对om_midi脚本进行修改](https://www.bilibili.com/read/cv1217487)_
NGDXW 改了一个更NBA的版本
om_midi 事一个能够自动将 MIDI 文件转换为 After Effects 中关键帧的脚本。它的诞生使得用AE***一键PV***成为可能。与原版相比,[NGDXW](https://space.bilibili.com/40208180)先辈 修改的版本可以输出更多、更实用的关键帧类型。希望在 om_midi 的帮助下,可以把人们从枯燥繁重的音画对齐中解救出来,把更多的精力投入到更有创造性的工作中。
!!! important "为何这里看起来如此简陋?"
文档正在施工中,任何内容都不准确且可能遭到大幅更改。
页面右上角有指向对应 Github页面的链接,非常欢迎您的贡献!
## 支持的AE版本
理论上支持 `CS5` 及以后的版本 | low | 0.47679 | 184 |
// (C) 2001-2017 Intel Corporation. All rights reserved.
// Your use of Intel Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Intel Program License Subscription
// Agreement, Intel MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Intel and sold by
// Intel or its authorized distributors. Please refer to the applicable
// agreement for further details.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
// $Id: //acds/rel/16.1/ip/merlin/altera_merlin_router/altera_merlin_router.sv.terp#1 $
// $Revision: #1 $
// $Date: 2016/08/07 $
// $Author: swbranch $
// -------------------------------------------------------
// Merlin Router
//
// Asserts the appropriate one-hot encoded channel based on
// either (a) the address or (b) the dest id. The DECODER_TYPE
// parameter controls this behaviour. 0 means address decoder,
// 1 means dest id decoder.
//
// In the case of (a), it also sets the destination id.
// -------------------------------------------------------
`timescale 1 ns / 1 ns
module olive_std_core_mm_interconnect_0_router_default_decode
#(
parameter DEFAULT_CHANNEL = 1,
DEFAULT_WR_CHANNEL = -1,
DEFAULT_RD_CHANNEL = -1,
DEFAULT_DESTID = 3
)
(output [92 - 91 : 0] default_destination_id,
output [4-1 : 0] default_wr_channel,
output [4-1 : 0] default_rd_channel,
output [4-1 : 0] default_src_channel
);
assign default_destination_id =
DEFAULT_DESTID[92 - 91 : 0];
generate
if (DEFAULT_CHANNEL == -1) begin : no_default_channel_assignment
assign default_src_channel = '0;
end
else begin : default_channel_assignment
assign default_src_channel = 4'b1 << DEFAULT_CHANNEL;
end
endgenerate
generate
if (DEFAULT_RD_CHANNEL == -1) begin : no_default_rw_channel_assignment
assign default_wr_channel = '0;
assign default_rd_channel = '0;
end
else begin : default_rw_channel_assignment
assign default_wr_channel = 4'b1 << DEFAULT_WR_CHANNEL;
assign default_rd_channel = 4'b1 << DEFAULT_RD_CHANNEL;
end
endgenerate
endmodule
module olive_std_core_mm_interconnect_0_router
(
// -------------------
// Clock & Reset
// -------------------
input clk,
input reset,
// -------------------
// Command Sink (Input)
// -------------------
input sink_valid,
input [106-1 : 0] sink_data,
input sink_startofpacket,
input sink_endofpacket,
output sink_ready,
// -------------------
// Command Source (Output)
// -------------------
output src_valid,
output reg [106-1 : 0] src_data,
output reg [4-1 : 0] src_channel,
output src_startofpacket,
output src_endofpacket,
input src_ready
);
// -------------------------------------------------------
// Local parameters and variables
// -------------------------------------------------------
localparam PKT_ADDR_H = 67;
localparam PKT_ADDR_L = 36;
localparam PKT_DEST_ID_H = 92;
localparam PKT_DEST_ID_L = 91;
localparam PKT_PROTECTION_H = 96;
localparam PKT_PROTECTION_L = 94;
localparam ST_DATA_W = 106;
localparam ST_CHANNEL_W = 4;
localparam DECODER_TYPE = 0;
localparam PKT_TRANS_WRITE = 70;
localparam PKT_TRANS_READ = 71;
localparam PKT_ADDR_W = PKT_ADDR_H-PKT_ADDR_L + 1;
localparam PKT_DEST_ID_W = PKT_DEST_ID_H-PKT_DEST_ID_L + 1;
// -------------------------------------------------------
// Figure out the number of bits to mask off for each slave span
// during address decoding
// -------------------------------------------------------
localparam PAD0 = log2ceil(64'h800000 - 64'h0);
localparam PAD1 = log2ceil(64'hf000800 - 64'hf000000);
localparam PAD2 = log2ceil(64'h10000200 - 64'h10000000);
// -------------------------------------------------------
// Work out which address bits are significant based on the
// address range of the slaves. If the required width is too
// large or too small, we use the address field width instead.
// -------------------------------------------------------
localparam ADDR_RANGE = 64'h10000200;
localparam RANGE_ADDR_WIDTH = log2ceil(ADDR_RANGE);
localparam OPTIMIZED_ADDR_H = (RANGE_ADDR_WIDTH > PKT_ADDR_W) ||
(RANGE_ADDR_WIDTH == 0) ?
PKT_ADDR_H :
PKT_ADDR_L + RANGE_ADDR_WIDTH - 1;
localparam RG = RANGE_ADDR_WIDTH-1;
localparam REAL_ADDRESS_RANGE = OPTIMIZED_ADDR_H - PKT_ADDR_L;
reg [PKT_ADDR_W-1 : 0] address;
always @* begin
address = {PKT_ADDR_W{1'b0}};
address [REAL_ADDRESS_RANGE:0] = sink_data[OPTIMIZED_ADDR_H : PKT_ADDR_L];
end
// -------------------------------------------------------
// Pass almost everything through, untouched
// -------------------------------------------------------
assign sink_ready = src_ready;
assign src_valid = sink_valid;
assign src_startofpacket = sink_startofpacket;
assign src_endofpacket = sink_endofpacket;
wire [PKT_DEST_ID_W-1:0] default_destid;
wire [4-1 : 0] default_src_channel;
olive_std_core_mm_interconnect_0_router_default_decode the_default_decode(
.default_destination_id (default_destid),
.default_wr_channel (),
.default_rd_channel (),
.default_src_channel (default_src_channel)
);
always @* begin
src_data = sink_data;
src_channel = default_src_channel;
src_data[PKT_DEST_ID_H:PKT_DEST_ID_L] = default_destid;
// --------------------------------------------------
// Address Decoder
// Sets the channel and destination ID based on the address
// --------------------------------------------------
// ( 0x0 .. 0x800000 )
if ( {address[RG:PAD0],{PAD0{1'b0}}} == 29'h0 ) begin
src_channel = 4'b010;
src_data[PKT_DEST_ID_H:PKT_DEST_ID_L] = 3;
end
// ( 0xf000000 .. 0xf000800 )
if ( {address[RG:PAD1],{PAD1{1'b0}}} == 29'hf000000 ) begin
src_channel = 4'b100;
src_data[PKT_DEST_ID_H:PKT_DEST_ID_L] = 0;
end
// ( 0x10000000 .. 0x10000200 )
if ( {address[RG:PAD2],{PAD2{1'b0}}} == 29'h10000000 ) begin
src_channel = 4'b001;
src_data[PKT_DEST_ID_H:PKT_DEST_ID_L] = 2;
end
end
// --------------------------------------------------
// Ceil(log2()) function
// --------------------------------------------------
function integer log2ceil;
input reg[65:0] val;
reg [65:0] i;
begin
i = 1;
log2ceil = 0;
while (i < val) begin
log2ceil = log2ceil + 1;
i = i << 1;
end
end
endfunction
endmodule
| high | 0.713748 | 185 |
(* Title: HOL/Auth/n_german_lemma_inv__19_on_rules.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_german Protocol Case Study*}
theory n_german_lemma_inv__19_on_rules imports n_german_lemma_on_inv__19
begin
section{*All lemmas on causal relation between inv__19*}
lemma lemma_inv__19_on_rules:
assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__19 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
proof -
have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
apply (cut_tac b1, auto) done
moreover {
assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_StoreVsinv__19) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqSVsinv__19) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqE__part__0Vsinv__19) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqE__part__1Vsinv__19) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqSVsinv__19) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqEVsinv__19) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__19) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__19) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInvAckVsinv__19) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__19) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntSVsinv__19) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntEVsinv__19) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntSVsinv__19) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntEVsinv__19) done
}
ultimately show "invHoldForRule s f r (invariants N)"
by satx
qed
end
| high | 0.559768 | 186 |
####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() #######
####### Any changes to this file will be overwritten by the next CMake run ####
####### The input file was glog-config.cmake.in ########
get_filename_component(PACKAGE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/../../../" ABSOLUTE)
macro(set_and_check _var _file)
set(${_var} "${_file}")
if(NOT EXISTS "${_file}")
message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist !")
endif()
endmacro()
####################################################################################
include (CMakeFindDependencyMacro)
include ("${CMAKE_CURRENT_LIST_DIR}/glog-targets.cmake")
| low | 0.859339 | 187 |
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! A networking stack.
// In case we roll the toolchain and something we're using as a feature has been
// stabilized.
#![allow(stable_features)]
#![feature(specialization)]
#![deny(missing_docs, unreachable_patterns)]
// This is a hack until we migrate to a different benchmarking framework. To run
// benchmarks, edit your Cargo.toml file to add a "benchmark" feature, and then
// run with that feature enabled.
#![cfg_attr(feature = "benchmark", feature(test))]
// TODO Follow 2018 idioms
#![allow(elided_lifetimes_in_paths)]
#![cfg_attr(not(test), no_std)]
// TODO(https://github.com/rust-lang-nursery/portability-wg/issues/11): remove this module.
extern crate fakealloc as alloc;
// TODO(https://github.com/dtolnay/thiserror/pull/64): remove this module.
#[cfg(not(test))]
extern crate fakestd as std;
#[cfg(all(test, feature = "benchmark"))]
extern crate test;
#[macro_use]
mod macros;
mod algorithm;
#[cfg(test)]
mod benchmarks;
mod context;
mod data_structures;
mod device;
pub mod error;
mod ip;
#[cfg(test)]
mod testutil;
mod transport;
mod wire;
use log::trace;
pub use crate::data_structures::{IdMap, IdMapCollection, IdMapCollectionKey};
pub use crate::device::ndp::NdpConfigurations;
pub use crate::device::{
get_assigned_ip_addr_subnets, initialize_device, receive_frame, remove_device, DeviceId,
DeviceLayerEventDispatcher,
};
pub use crate::error::{LocalAddressError, NetstackError, RemoteAddressError, SocketError};
pub use crate::ip::{
icmp, EntryDest, EntryDestEither, EntryEither, IpLayerEventDispatcher, Ipv4StateBuilder,
Ipv6StateBuilder,
};
pub use crate::transport::udp::{
connect_udp, get_udp_conn_info, get_udp_listener_info, listen_udp, remove_udp_conn,
remove_udp_listener, send_udp, send_udp_conn, send_udp_listener, SendError as UdpSendError,
UdpConnId, UdpEventDispatcher, UdpListenerId,
};
pub use crate::transport::TransportLayerEventDispatcher;
use alloc::vec::Vec;
use core::fmt::Debug;
use core::time;
use net_types::ethernet::Mac;
use net_types::ip::{AddrSubnetEither, IpAddr, Ipv4, Ipv4Addr, Ipv6, Ipv6Addr, SubnetEither};
use net_types::SpecifiedAddr;
use packet::{Buf, BufferMut, EmptyBuf};
use rand::{CryptoRng, RngCore};
use crate::context::TimerContext;
use crate::device::{DeviceLayerState, DeviceLayerTimerId, DeviceStateBuilder};
use crate::ip::{IpLayerTimerId, Ipv4State, Ipv6State};
use crate::transport::{TransportLayerState, TransportLayerTimerId};
/// Map an expression over either version of one or more addresses.
///
/// `map_addr_version!` when given a value of a type which is an enum with two
/// variants - `V4` and `V6` - matches on the variants, and for both variants,
/// invokes an expression on the inner contents. `$addr` is both the name of the
/// variable to match on, and the name that the address will be bound to for the
/// scope of the expression.
///
/// `map_addr_version!` when given a list of values and their types (all enums
/// with variants `V4` and `V6`), matches on the tuple of values and invokes the
/// `$match` expression when all values are of the same variant. Otherwise the
/// `$mismatch` expression is invoked.
///
/// To make it concrete, the expression `map_addr_version!(bar: Foo; blah(bar))`
/// desugars to:
///
/// ```rust,ignore
/// match bar {
/// Foo::V4(bar) => blah(bar),
/// Foo::V6(bar) => blah(bar),
/// }
/// ```
///
/// Also,
/// `map_addr_version!((foo: Foo, bar: Bar); blah(foo, bar), unreachable!())`
/// desugars to:
///
/// ```rust,ignore
/// match (foo, bar) {
/// (Foo::V4(foo), Bar::V4(bar)) => blah(foo, bar),
/// (Foo::V6(foo), Bar::V6(bar)) => blah(foo, bar),
/// _ => unreachable!(),
/// }
/// ```
#[macro_export]
macro_rules! map_addr_version {
($addr:ident: $ty:tt; $expr:expr) => {
match $addr {
$ty::V4($addr) => $expr,
$ty::V6($addr) => $expr,
}
};
(( $( $addr:ident : $ty:tt ),+ ); $match:expr, $mismatch:expr) => {
match ( $( $addr ),+ ) {
( $( $ty::V4( $addr ) ),+ ) => $match,
( $( $ty::V6( $addr ) ),+ ) => $match,
_ => $mismatch,
}
};
(( $( $addr:ident : $ty:tt ),+ ); $match:expr, $mismatch:expr,) => {
map_addr_version!(($( $addr: $ty ),+); $match, $mismatch)
};
}
/// A builder for [`StackState`].
#[derive(Default, Clone)]
pub struct StackStateBuilder {
ipv4: Ipv4StateBuilder,
ipv6: Ipv6StateBuilder,
device: DeviceStateBuilder,
}
impl StackStateBuilder {
/// Get the builder for the IPv4 state.
pub fn ipv4_builder(&mut self) -> &mut Ipv4StateBuilder {
&mut self.ipv4
}
/// Get the builder for the IPv6 state.
pub fn ipv6_builder(&mut self) -> &mut Ipv6StateBuilder {
&mut self.ipv6
}
/// Get the builder for the device state.
pub fn device_builder(&mut self) -> &mut DeviceStateBuilder {
&mut self.device
}
/// Consume this builder and produce a `StackState`.
pub fn build<D: EventDispatcher>(self) -> StackState<D> {
StackState {
transport: TransportLayerState::default(),
ipv4: self.ipv4.build(),
ipv6: self.ipv6.build(),
device: self.device.build(),
#[cfg(test)]
test_counters: testutil::TestCounters::default(),
}
}
}
/// The state associated with the network stack.
pub struct StackState<D: EventDispatcher> {
transport: TransportLayerState,
ipv4: Ipv4State<D::Instant, DeviceId>,
ipv6: Ipv6State<D::Instant, DeviceId>,
device: DeviceLayerState<D::Instant>,
#[cfg(test)]
test_counters: testutil::TestCounters,
}
impl<D: EventDispatcher> StackState<D> {
/// Add a new ethernet device to the device layer.
///
/// `add_ethernet_device` only makes the netstack aware of the device. The device still needs to
/// be initialized. A device MUST NOT be used until it has been initialized. The netstack
/// promises not to generate any outbound traffic on the device until [`initialize_device`] has
/// been called.
///
/// See [`initialize_device`] for more information.
///
/// [`initialize_device`]: crate::device::initialize_device
pub fn add_ethernet_device(&mut self, mac: Mac, mtu: u32) -> DeviceId {
self.device.add_ethernet_device(mac, mtu)
}
}
impl<D: EventDispatcher> Default for StackState<D> {
fn default() -> StackState<D> {
StackStateBuilder::default().build()
}
}
/// Context available during the execution of the netstack.
///
/// `Context` provides access to the state of the netstack and to an event
/// dispatcher which can be used to emit events and schedule timeouts. A mutable
/// reference to a `Context` is passed to every function in the netstack.
#[derive(Default)]
pub struct Context<D: EventDispatcher> {
state: StackState<D>,
dispatcher: D,
}
impl<D: EventDispatcher> Context<D> {
/// Construct a new `Context`.
pub fn new(state: StackState<D>, dispatcher: D) -> Context<D> {
Context { state, dispatcher }
}
/// Construct a new `Context` using the default `StackState`.
pub fn with_default_state(dispatcher: D) -> Context<D> {
Context { state: StackState::default(), dispatcher }
}
/// Get the stack state immutably.
pub fn state(&self) -> &StackState<D> {
&self.state
}
/// Get the stack state mutably.
pub fn state_mut(&mut self) -> &mut StackState<D> {
&mut self.state
}
/// Get the dispatcher immutably.
pub fn dispatcher(&self) -> &D {
&self.dispatcher
}
/// Get the dispatcher mutably.
pub fn dispatcher_mut(&mut self) -> &mut D {
&mut self.dispatcher
}
/// Get the stack state and the dispatcher.
///
/// This is useful when a mutable reference to both are required at the same
/// time, which isn't possible when using the `state` or `dispatcher`
/// methods.
pub fn state_and_dispatcher(&mut self) -> (&mut StackState<D>, &mut D) {
(&mut self.state, &mut self.dispatcher)
}
}
impl<D: EventDispatcher + Default> Context<D> {
/// Construct a new `Context` using the default dispatcher.
pub fn with_default_dispatcher(state: StackState<D>) -> Context<D> {
Context { state, dispatcher: D::default() }
}
}
/// The identifier for any timer event.
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
pub struct TimerId(TimerIdInner);
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
enum TimerIdInner {
/// A timer event in the device layer.
DeviceLayer(DeviceLayerTimerId),
/// A timer event in the transport layer.
_TransportLayer(TransportLayerTimerId),
/// A timer event in the IP layer.
IpLayer(IpLayerTimerId),
/// A no-op timer event (used for tests)
#[cfg(test)]
Nop(usize),
}
impl From<DeviceLayerTimerId> for TimerId {
fn from(id: DeviceLayerTimerId) -> TimerId {
TimerId(TimerIdInner::DeviceLayer(id))
}
}
impl_timer_context!(TimerId, DeviceLayerTimerId, TimerId(TimerIdInner::DeviceLayer(id)), id);
/// Handle a generic timer event.
pub fn handle_timeout<D: EventDispatcher>(ctx: &mut Context<D>, id: TimerId) {
trace!("handle_timeout: dispatching timerid: {:?}", id);
match id {
TimerId(TimerIdInner::DeviceLayer(x)) => {
device::handle_timeout(ctx, x);
}
TimerId(TimerIdInner::_TransportLayer(x)) => {
transport::handle_timeout(ctx, x);
}
TimerId(TimerIdInner::IpLayer(x)) => {
ip::handle_timeout(ctx, x);
}
#[cfg(test)]
TimerId(TimerIdInner::Nop(_)) => {
increment_counter!(ctx, "timer::nop");
}
}
}
/// A type representing an instant in time.
///
/// `Instant` can be implemented by any type which represents an instant in
/// time. This can include any sort of real-world clock time (e.g.,
/// [`std::time::Instant`]) or fake time such as in testing.
pub trait Instant: Sized + Ord + Copy + Clone + Debug + Send + Sync {
/// Returns the amount of time elapsed from another instant to this one.
///
/// # Panics
///
/// This function will panic if `earlier` is later than `self`.
fn duration_since(&self, earlier: Self) -> time::Duration;
/// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be
/// represented as `Instant` (which means it's inside the bounds of the
/// underlying data structure), `None` otherwise.
fn checked_add(&self, duration: time::Duration) -> Option<Self>;
/// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be
/// represented as `Instant` (which means it's inside the bounds of the
/// underlying data structure), `None` otherwise.
fn checked_sub(&self, duration: time::Duration) -> Option<Self>;
}
/// An `EventDispatcher` which supports sending buffers of a given type.
///
/// `D: BufferDispatcher<B>` is shorthand for `D: EventDispatcher +
/// DeviceLayerEventDispatcher<B>`.
pub trait BufferDispatcher<B: BufferMut>:
EventDispatcher + DeviceLayerEventDispatcher<B> + IpLayerEventDispatcher<B>
{
}
impl<
B: BufferMut,
D: EventDispatcher + DeviceLayerEventDispatcher<B> + IpLayerEventDispatcher<B>,
> BufferDispatcher<B> for D
{
}
// TODO(joshlf): Should we add a `for<'a> DeviceLayerEventDispatcher<&'a mut
// [u8]>` bound? Would anything get more efficient if we were able to stack
// allocate internally-generated buffers?
/// An object which can dispatch events to a real system.
///
/// An `EventDispatcher` provides access to a real system. It provides the
/// ability to emit events and schedule timeouts. Each layer of the stack
/// provides its own event dispatcher trait which specifies the types of actions
/// that must be supported in order to support that layer of the stack. The
/// `EventDispatcher` trait is a sub-trait of all of these traits.
pub trait EventDispatcher:
DeviceLayerEventDispatcher<Buf<Vec<u8>>>
+ DeviceLayerEventDispatcher<EmptyBuf>
+ IpLayerEventDispatcher<Buf<Vec<u8>>>
+ IpLayerEventDispatcher<EmptyBuf>
+ TransportLayerEventDispatcher<Ipv4>
+ TransportLayerEventDispatcher<Ipv6>
{
/// The type of an instant in time.
///
/// All time is measured using `Instant`s, including scheduling timeouts.
/// This type may represent some sort of real-world time (e.g.,
/// [`std::time::Instant`]), or may be mocked in testing using a fake clock.
type Instant: Instant;
/// Returns the current instant.
///
/// `now` guarantees that two subsequent calls to `now` will return monotonically
/// non-decreasing values.
fn now(&self) -> Self::Instant;
/// Schedule a callback to be invoked after a timeout.
///
/// `schedule_timeout` schedules `f` to be invoked after `duration` has
/// elapsed, overwriting any previous timeout with the same ID.
///
/// If there was previously a timer with that ID, return the time at which
/// is was scheduled to fire.
///
/// # Panics
///
/// `schedule_timeout` may panic if `duration` is large enough that
/// `self.now() + duration` overflows.
fn schedule_timeout(&mut self, duration: time::Duration, id: TimerId) -> Option<Self::Instant> {
self.schedule_timeout_instant(self.now().checked_add(duration).unwrap(), id)
}
/// Schedule a callback to be invoked at a specific time.
///
/// `schedule_timeout_instant` schedules `f` to be invoked at `time`,
/// overwriting any previous timeout with the same ID.
///
/// If there was previously a timer with that ID, return the time at which
/// is was scheduled to fire.
fn schedule_timeout_instant(
&mut self,
time: Self::Instant,
id: TimerId,
) -> Option<Self::Instant>;
/// Cancel a timeout.
///
/// Returns true if the timeout was cancelled, false if there was no timeout
/// for the given ID.
fn cancel_timeout(&mut self, id: TimerId) -> Option<Self::Instant>;
/// Cancel all timeouts which satisfy a predicate.
///
/// `cancel_timeouts_with` calls `f` on each scheduled timer, and cancels
/// any timeout for which `f` returns true.
fn cancel_timeouts_with<F: FnMut(&TimerId) -> bool>(&mut self, f: F);
/// Get the instant a timer will fire, if one is scheduled.
///
/// Returns the [`Instant`] a timer with ID `id` will be invoked. If no timer
/// with the given ID exists, `scheduled_instant` will return `None`.
fn scheduled_instant(&self, id: TimerId) -> Option<Self::Instant>;
// TODO(joshlf): If the CSPRNG requirement becomes a performance problem,
// introduce a second, non-cryptographically secure, RNG.
/// The random number generator (RNG) provided by this `EventDispatcher`.
///
/// Code in the core is required to only obtain random values through this
/// RNG. This allows a deterministic RNG to be provided when useful (for
/// example, in tests).
///
/// The provided RNG must be cryptographically secure in order to ensure
/// that random values produced within the network stack are not predictable
/// by outside observers. This helps to prevent certain kinds of
/// fingerprinting and denial of service attacks.
type Rng: RngCore + CryptoRng;
/// Get the random number generator (RNG).
///
/// Code in the core is required to only obtain random values through this
/// RNG. This allows a deterministic RNG to be provided when useful (for
/// example, in tests).
fn rng(&mut self) -> &mut Self::Rng;
}
impl<D: EventDispatcher> TimerContext<TimerId> for Context<D> {
fn schedule_timer_instant(
&mut self,
time: Self::Instant,
id: TimerId,
) -> Option<Self::Instant> {
self.dispatcher_mut().schedule_timeout_instant(time, id)
}
fn cancel_timer(&mut self, id: TimerId) -> Option<Self::Instant> {
self.dispatcher_mut().cancel_timeout(id)
}
fn cancel_timers_with<F: FnMut(&TimerId) -> bool>(&mut self, f: F) {
self.dispatcher_mut().cancel_timeouts_with(f)
}
fn scheduled_instant(&self, id: TimerId) -> Option<Self::Instant> {
self.dispatcher().scheduled_instant(id)
}
}
/// Get all IPv4 and IPv6 address/subnet pairs configured on a device
pub fn get_all_ip_addr_subnets<'a, D: EventDispatcher>(
ctx: &'a Context<D>,
device: DeviceId,
) -> impl 'a + Iterator<Item = AddrSubnetEither> {
let addr_v4 = crate::device::get_assigned_ip_addr_subnets::<_, Ipv4Addr>(ctx, device)
.map(|a| AddrSubnetEither::V4(a));
let addr_v6 = crate::device::get_assigned_ip_addr_subnets::<_, Ipv6Addr>(ctx, device)
.map(|a| AddrSubnetEither::V6(a));
addr_v4.chain(addr_v6)
}
/// Set the IP address and subnet for a device.
pub fn add_ip_addr_subnet<D: EventDispatcher>(
ctx: &mut Context<D>,
device: DeviceId,
addr_sub: AddrSubnetEither,
) -> error::Result<()> {
map_addr_version!(
addr_sub: AddrSubnetEither;
crate::device::add_ip_addr_subnet(ctx, device, addr_sub)
)
.map_err(From::from)
}
/// Delete an IP address on a device.
pub fn del_ip_addr<D: EventDispatcher>(
ctx: &mut Context<D>,
device: DeviceId,
addr: IpAddr<SpecifiedAddr<Ipv4Addr>, SpecifiedAddr<Ipv6Addr>>,
) -> error::Result<()> {
map_addr_version!(
addr: IpAddr;
crate::device::del_ip_addr(ctx, device, &addr)
)
.map_err(From::from)
}
/// Adds a route to the forwarding table.
pub fn add_route<D: EventDispatcher>(
ctx: &mut Context<D>,
entry: EntryEither<DeviceId>,
) -> Result<(), error::NetstackError> {
let (subnet, dest) = entry.into_subnet_dest();
match dest {
EntryDest::Local { device } => map_addr_version!(
subnet: SubnetEither;
crate::ip::add_device_route(ctx, subnet, device)
)
.map_err(From::from),
EntryDest::Remote { next_hop } => {
let next_hop = next_hop.into();
map_addr_version!(
(subnet: SubnetEither, next_hop: IpAddr);
crate::ip::add_route(ctx, subnet, next_hop),
unreachable!(),
)
.map_err(From::from)
}
}
}
/// Delete a route from the forwarding table, returning `Err` if no
/// route was found to be deleted.
pub fn del_device_route<D: EventDispatcher>(
ctx: &mut Context<D>,
subnet: SubnetEither,
) -> error::Result<()> {
map_addr_version!(subnet: SubnetEither; crate::ip::del_device_route(ctx, subnet))
.map_err(From::from)
}
/// Get all the routes.
pub fn get_all_routes<'a, D: EventDispatcher>(
ctx: &'a Context<D>,
) -> impl 'a + Iterator<Item = EntryEither<DeviceId>> {
let v4_routes = ip::iter_all_routes::<_, Ipv4Addr>(ctx);
let v6_routes = ip::iter_all_routes::<_, Ipv6Addr>(ctx);
v4_routes.cloned().map(From::from).chain(v6_routes.cloned().map(From::from))
}
#[cfg(test)]
mod test {
use super::*;
use crate::testutil::{
get_dummy_config, get_other_ip_address, DummyEventDispatcher, DummyEventDispatcherBuilder,
};
use net_types::ip::{Ip, Ipv4, Ipv6};
use net_types::Witness;
fn test_add_remove_ip_addresses<I: Ip>() {
let config = get_dummy_config::<I::Addr>();
let mut ctx = DummyEventDispatcherBuilder::default().build::<DummyEventDispatcher>();
let device = ctx.state_mut().add_ethernet_device(config.local_mac, crate::ip::IPV6_MIN_MTU);
crate::device::initialize_device(&mut ctx, device);
let ip: IpAddr = get_other_ip_address::<I::Addr>(1).get().into();
let prefix = config.subnet.prefix();
let addr_subnet = AddrSubnetEither::new(ip, prefix).unwrap();
// ip doesn't exist initially
assert!(get_all_ip_addr_subnets(&ctx, device).find(|&a| a == addr_subnet).is_none());
// Add ip (ok)
let () = add_ip_addr_subnet(&mut ctx, device, addr_subnet).unwrap();
assert!(get_all_ip_addr_subnets(&ctx, device).find(|&a| a == addr_subnet).is_some());
// Add ip again (already exists)
assert_eq!(
add_ip_addr_subnet(&mut ctx, device, addr_subnet).unwrap_err(),
NetstackError::Exists
);
assert!(get_all_ip_addr_subnets(&ctx, device).find(|&a| a == addr_subnet).is_some());
// Add ip with different subnet (already exists)
let wrong_addr_subnet = AddrSubnetEither::new(ip, prefix - 1).unwrap();
assert_eq!(
add_ip_addr_subnet(&mut ctx, device, wrong_addr_subnet).unwrap_err(),
NetstackError::Exists
);
assert!(get_all_ip_addr_subnets(&ctx, device).find(|&a| a == addr_subnet).is_some());
let ip = SpecifiedAddr::new(ip).unwrap();
// Del ip (ok)
let () = del_ip_addr(&mut ctx, device, ip.into()).unwrap();
assert!(get_all_ip_addr_subnets(&ctx, device).find(|&a| a == addr_subnet).is_none());
// Del ip again (not found)
assert_eq!(del_ip_addr(&mut ctx, device, ip.into()).unwrap_err(), NetstackError::NotFound);
assert!(get_all_ip_addr_subnets(&ctx, device).find(|&a| a == addr_subnet).is_none());
}
#[test]
fn test_add_remove_ipv4_addresses() {
test_add_remove_ip_addresses::<Ipv4>();
}
#[test]
fn test_add_remove_ipv6_addresses() {
test_add_remove_ip_addresses::<Ipv6>();
}
}
| high | 0.807084 | 188 |
functions {
real binomial_logit_lpmf_marginalise(
int[] deaths_slice,
int start,
int end,
//pars
vector p_log_avg,
// data
int[] casesL,
int[] casesU,
matrix log_choose_fct,
matrix auxCases
)
{
real lpmf = 0.0;
int N_slice = end - start + 1;
for(n_slice in 1:N_slice) {
int n = n_slice + start - 1;
int casesN_local = casesU[n]-casesL[n]+1;
vector[casesN_local] log_choose_fct_local = log_choose_fct[1:(casesU[n]-casesL[n]+1), n];
vector[casesN_local] auxCases_local = auxCases[1:(casesU[n]-casesL[n]+1), n];
lpmf += log_sum_exp( log_choose_fct_local + rep_vector(deaths_slice[n], casesN_local) .* log( exp(rep_vector(p_log_avg[n], casesN_local ))) +
(auxCases_local-rep_vector(deaths_slice[n], casesN_local)) .* log(1 - exp(rep_vector(p_log_avg[n], casesN_local))) );
}
print("lpmf", lpmf);
return( lpmf );
}
}
data {
int<lower=0> N; // number of observations
int<lower=0> N_predict; // number of predictions
int<lower=0> M; // number of studies
int deaths[N]; // number of deaths
int casesU[N]; // upper bound cases
int casesL[N]; // lower bound cases
vector<lower=0>[N_predict] age; // age
vector<lower=0>[N] age_study; // age
int lower_age_idx[N]; // lower index
int upper_age_idx[N]; // lower index
int study[N];
int max_casesN;
matrix[max_casesN, N] log_choose_fct;
matrix[max_casesN, N] auxCases;
}
parameters {
real alpha;
real beta;
real gamma[M];
real<lower=0> tau;
}
transformed parameters
{
vector[N] p_log_avg;
for(i in 1:N)
p_log_avg = alpha + beta*age_study + gamma[study[i]];
}
model
{
target += normal_lpdf( alpha | 0, 0.5);
target += normal_lpdf( beta | 0, 0.5);
target += normal_lpdf( gamma | 0, tau);
target += cauchy_lpdf( tau | 0, 1);
for(n in 1:N){
{
int casesN_local = casesU[n]-casesL[n]+1;
vector[casesN_local] log_choose_fct_local = log_choose_fct[1:(casesU[n]-casesL[n]+1), n];
vector[casesN_local] auxCases_local = auxCases[1:(casesU[n]-casesL[n]+1), n];
target += log_sum_exp( log_choose_fct_local + rep_vector(deaths[n], casesN_local) .* log( exp(rep_vector(p_log_avg[n], casesN_local )) ) +
(auxCases_local-rep_vector(deaths[n], casesN_local)) .* log(1 - exp(rep_vector(p_log_avg[n], casesN_local))) );
}
}
// rstan version
// target += binomial_logit_lpmf_marginalise(deaths, 1, N,
// // cmdstan version
// //target += reduce_sum(binomial_logit_lpmf_marginalise, deaths, 1,
// p_log_avg,
// casesL,
// casesU,
// log_choose_fct,
// auxCases
// );
}
| high | 0.488759 | 189 |
---
title: "FrameMaker Authoring Interface"
linkTitle: "2.2 FrameMaker Authoring Interface"
weight: 3
description: >
This section details the various features within Adobe FrameMaker, along with how to author using our unstructured (non-DITA/XML) template.
---
## Launching FrameMaker
To fully open a FrameMaker file, do the following:
1. Go to the desired FrameMaker file folder location.
2. Double-click the FrameMaker **.book** file. FrameMaker will open.
3. Go to the **Navigation Pane** on the left side of the FrameMaker interface.
4. Double click each of the three (3) files listed below the **.book** file (**_TitlePage.fm**, **_TOC.fm**, and **_Content.fm**). Each of the three (3) files should now be open. Your interface should look similar to the image displayed below.
![alt text](https://github.com/taddieken95/Accuray_Tech_Comm_Guide/blob/master/img/FrameMaker%20Interface%20Example.png "FrameMaker Interface Example")
## Authoring Options - Paragraph Catalog
A floating side panel featuring the **Paragraph Catalog** should be present inside the FrameMaker interface. If this is not the case, perform the following:
1. Go to the **View** dropdown at the top of the screen.
2. Go to **Pods** then select **Paragraph Catalog**.
3. The sidepanel should now appear. It is likely that additional pods (such as **Variables**, **Character Designer**, and **Cross References**) will appear as well. Ignore these tabs for now and go to the **Paragraph Catalog** tab.
The final result should appear as shown **below**:
![alt text](https://github.com/taddieken95/Accuray_Tech_Comm_Guide/blob/master/img/Paragraph%20Catalog%20Tab.png "Paragraph Catalog Tab")
These options listed in the **Paragraph Catalog** pod are the different authoring text styles that come with the Accuray Manufacturing FrameMaker template. These, of course, can be stylistically modified through the **Character Designer** tab, but for the majority of work instructions, this list should contain all of the needed elements to producing robust documentation.
## Paragraph Catalog Functionality
The following table will provide an explanation for different features of the **Paragraph Catalog**.
|Paragraph Feature | Description | Ideal Usage|
|---------------------------|-------------|------------|
|**Heading 1**| Creates a section heading along with an ordered numerical value (1.0, 2.0, etc.). This will be automatically linked to the **Table of Contents** file.| Use to provide a title for each overall section. Each FrameMaker work instruction should have a minimum of one (1) **Heading 1**.|
|**Heading 2**| Creates a heading for a subsection. Will have a numeric value in the tenth decimal place (e.g. 1.1, 1.2, etc.) Barring special circumstances, subsection headings will not be featured in a **Table of Contents**. | Use to provide a title for a subsection. Subsections should likely be created in place of sections if ordered numerical list surpasses ten (10) steps.|
|**Heading 3**| Creates a subsection for a subsection. Will have a numeric value in the hundredth decimal place (e.g. 1.1.1, 1.1.2, etc.)| Use to provide a title for a subsection of a subsection. It is recommended to create one if content within a subsection surpasses ten (10) steps.|
|**Body Text**| Think of this authoring feature as your "standard." **Body Text** authoring allows the user to create unordered blocks of text.| **Body Text** is often used in instances where step-by-step instructions are not required|
|**Step 1**| Initializes an ordered list. Further steps can be created by pressing **Enter** after Step 1 has been generated.| Use at the beginning of a section / subsection. Ordered steps will *NOT* automatically reset at 1 with each section. It must be manually entered.|
|**Steps**| Continues an ordered list.| As previously mentioned, ordered steps should be automatically entered after **Step 1** by pressing **Enter**.|
|**StepNoNum**| Creates an opportunity to produce text at the same indentation level of an ordered **Step** without continuing the ordering level| **StepNoNum** is best used with trying to separate two (2) or more sentences in a **Step** into separate lines. In this case, **StepNoNum** would be used on the second line, so that it does not separate this line into an additional **Step**.|
|**Sub Step_a**| Initializes an ordered list (level "a") within a step inside of an ordered list (substep)| Use when two (2) or more clarifying substeps are deemed necessary for a user to follow a step. |
|**Sub Steps**| Continues an ordered sublist| Use to continue a sublist after initializing it with **Sub Step_a**|
|**Bullet List**| Creates an unordered, bulleted list | Use for instances where further clarification is required, but order is not of importance. ***OR*** Use in place of steps when only an unordered list is deemed neccessary (such as an **Tools Required** list.|
|**Sq. Bullet List**| Use as an unordered sublist beneath a **Bullet List** or a **Sub Step**| Use when further clarification is required for an ordered sublist or an unordered list.|
|**FigureCaption**| Automatically creates a numerically ordered **Figure Number** along with space to create a descriptive caption of the **Figure** shown above | Use after every **Figure** added to the document. Captions are not required by FrameMaker but best practices would suggest providing a descriptive phrase to each image added. See [this section](https://github.com/taddieken95/Accuray_Tech_Comm_Guide/blob/master/Chapter%202:%20Adobe%20FrameMaker/Section%204:%20Uploading%20Images%20in%20FrameMaker.md) for more information on how to incorporate images into a work instruction.|
| high | 0.185263 | 190 |
(ns load-order.core
(:require [clojure.tools.namespace.track :as track]
[clojure.tools.namespace.dir :as dir])
(:import (java.io File)
(java.nio.file Path Paths Files)))
;; generic utilities
(def ^:private pwd (System/getProperty "user.dir"))
(defn- get-path
"Creates a Path using the segments provided."
[x & more]
(let [more-array (into-array String more)]
(Paths/get x more-array)))
;; data
(def ^:private cwd
"The JVM's user dir, as a Path object."
(get-path pwd))
(def ns-to-path
"A mapping from namespace to Path object."
(reduce
(fn [m [file ns]]
(assoc m ns (.toPath file)))
{}
(:clojure.tools.namespace.file/filemap
(dir/scan-dirs (track/tracker)))))
;; functions
(defn ns-to-relative-path-string
"The name of the relative path from which the given namespace was loaded."
[ns root-path]
(.toString
(.relativize
root-path
(ns-to-path ns))))
(defn loaded-namespaces
"The namespaces that are present, in the order they were loaded."
[]
(-> (track/tracker)
dir/scan-dirs
::track/load))
(defn print-require-all
"Generate lines to require all namespaces, in order they were loaded."
[]
(doseq [ns (loaded-namespaces)]
(printf " [%s :refer :all]%n" ns)))
(defn loaded-files
"The clojure files in the order they have been loaded."
[]
(map
#(ns-to-relative-path-string % cwd)
(loaded-namespaces)))
(defn print-loaded-files
"See namespaces, one per line, in order they were loaded."
([fmt]
(doseq [filepath (loaded-files)]
(printf fmt filepath)))
([]
(print-loaded-files " %s%n")))
| high | 0.624485 | 191 |
(define anthy-on-key '("zenkaku-hankaku" "<IgnoreShift><Control>("))
(define anthy-on-key? (make-key-predicate '("zenkaku-hankaku" "<IgnoreShift><Control>(")))
(define anthy-off-key '("zenkaku-hankaku" "<IgnoreShift><Control>("))
(define anthy-off-key? (make-key-predicate '("zenkaku-hankaku" "<IgnoreShift><Control>(")))
(define anthy-begin-conv-key '(generic-begin-conv-key))
(define anthy-begin-conv-key? (make-key-predicate '(generic-begin-conv-key?)))
(define anthy-commit-key '(generic-commit-key))
(define anthy-commit-key? (make-key-predicate '(generic-commit-key?)))
(define anthy-cancel-key '(generic-cancel-key))
(define anthy-cancel-key? (make-key-predicate '(generic-cancel-key?)))
(define anthy-next-candidate-key '(generic-next-candidate-key))
(define anthy-next-candidate-key? (make-key-predicate '(generic-next-candidate-key?)))
(define anthy-prev-candidate-key '(generic-prev-candidate-key))
(define anthy-prev-candidate-key? (make-key-predicate '(generic-prev-candidate-key?)))
(define anthy-next-page-key '(generic-next-page-key))
(define anthy-next-page-key? (make-key-predicate '(generic-next-page-key?)))
(define anthy-prev-page-key '(generic-prev-page-key))
(define anthy-prev-page-key? (make-key-predicate '(generic-prev-page-key?)))
| low | 0.57211 | 192 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 java org.apache.iotdb.service.rpc.thrift
// The return status code and message in each response.
struct TSStatusType {
1: required i32 code
2: required string message
}
// The return status of a remote request
struct TSStatus {
1: required TSStatusType statusType
2: optional list<string> infoMessages
3: optional string sqlState // as defined in the ISO/IEF CLIENT specification
}
struct TSExecuteStatementResp {
1: required TSStatus status
2: optional i64 queryId
// Column names in select statement of SQL
3: optional list<string> columns
4: optional string operationType
5: optional bool ignoreTimeStamp
// Data type list of columns in select statement of SQL
6: optional list<string> dataTypeList
7: optional TSQueryDataSet queryDataSet
}
enum TSProtocolVersion {
IOTDB_SERVICE_PROTOCOL_V1,
}
struct TSOpenSessionResp {
1: required TSStatus status
// The protocol version that the server is using.
2: required TSProtocolVersion serverProtocolVersion = TSProtocolVersion.IOTDB_SERVICE_PROTOCOL_V1
// Session id
3: optional i64 sessionId
// The configuration settings for this session.
4: optional map<string, string> configuration
}
// OpenSession()
// Open a session (connection) on the server against which operations may be executed.
struct TSOpenSessionReq {
1: required TSProtocolVersion client_protocol = TSProtocolVersion.IOTDB_SERVICE_PROTOCOL_V1
2: optional string username
3: optional string password
4: optional map<string, string> configuration
}
// CloseSession()
// Closes the specified session and frees any resources currently allocated to that session.
// Any open operations in that session will be canceled.
struct TSCloseSessionReq {
1: required i64 sessionId
}
// ExecuteStatement()
//
// Execute a statement.
// The returned OperationHandle can be used to check on the status of the statement, and to fetch results once the
// statement has finished executing.
struct TSExecuteStatementReq {
// The session to execute the statement against
1: required i64 sessionId
// The statement to be executed (DML, DDL, SET, etc)
2: required string statement
// statementId
3: required i64 statementId
4: optional i32 fetchSize
}
struct TSExecuteInsertRowInBatchResp{
1: required i64 sessionId
2: required list<TSStatus> statusList
}
struct TSExecuteBatchStatementResp{
1: required TSStatus status
// For each value in result, Statement.SUCCESS_NO_INFO represents success, Statement.EXECUTE_FAILED represents fail otherwise.
2: optional list<i32> result
}
struct TSExecuteBatchStatementReq{
// The session to execute the statement against
1: required i64 sessionId
// The statements to be executed (DML, DDL, SET, etc)
2: required list<string> statements
}
struct TSGetOperationStatusReq {
1: required i64 sessionId
// Session to run this request against
2: required i64 queryId
}
// CancelOperation()
//
// Cancels processing on the specified operation handle and frees any resources which were allocated.
struct TSCancelOperationReq {
1: required i64 sessionId
// Operation to cancel
2: required i64 queryId
}
// CloseOperation()
struct TSCloseOperationReq {
1: required i64 sessionId
2: optional i64 queryId
3: optional i64 statementId
}
struct TSFetchResultsReq{
1: required i64 sessionId
2: required string statement
3: required i32 fetchSize
4: required i64 queryId
}
struct TSFetchResultsResp{
1: required TSStatus status
2: required bool hasResultSet
3: optional TSQueryDataSet queryDataSet
}
struct TSFetchMetadataResp{
1: required TSStatus status
2: optional string metadataInJson
3: optional list<string> columnsList
4: optional string dataType
}
struct TSFetchMetadataReq{
1: required i64 sessionId
2: required string type
3: optional string columnPath
}
struct TSGetTimeZoneResp {
1: required TSStatus status
2: required string timeZone
}
struct TSSetTimeZoneReq {
1: required i64 sessionId
2: required string timeZone
}
// for session
struct TSInsertReq {
1: required i64 sessionId
2: required string deviceId
3: required list<string> measurements
4: required list<string> values
5: required i64 timestamp
}
struct TSBatchInsertionReq {
1: required i64 sessionId
2: required string deviceId
3: required list<string> measurements
4: required binary values
5: required binary timestamps
6: required list<i32> types
7: required i32 size
}
struct TSInsertInBatchReq {
1: required i64 sessionId
2: required list<string> deviceIds
3: required list<list<string>> measurementsList
4: required list<list<string>> valuesList
5: required list<i64> timestamps
}
struct TSDeleteDataReq {
1: required i64 sessionId
2: required list<string> paths
3: required i64 timestamp
}
struct TSCreateTimeseriesReq {
1: required i64 sessionId
2: required string path
3: required i32 dataType
4: required i32 encoding
5: required i32 compressor
}
struct ServerProperties {
1: required string version;
2: required list<string> supportedTimeAggregationOperations;
3: required string timestampPrecision;
}
struct TSQueryDataSet{
// ByteBuffer for time column
1: required binary time
// ByteBuffer for each column values
2: required list<binary> valueList
// Bitmap for each column to indicate whether it is a null value
3: required list<binary> bitmapList
}
service TSIService {
TSOpenSessionResp openSession(1:TSOpenSessionReq req);
TSStatus closeSession(1:TSCloseSessionReq req);
TSExecuteStatementResp executeStatement(1:TSExecuteStatementReq req);
TSExecuteBatchStatementResp executeBatchStatement(1:TSExecuteBatchStatementReq req);
TSExecuteStatementResp executeQueryStatement(1:TSExecuteStatementReq req);
TSExecuteStatementResp executeUpdateStatement(1:TSExecuteStatementReq req);
TSFetchResultsResp fetchResults(1:TSFetchResultsReq req)
TSFetchMetadataResp fetchMetadata(1:TSFetchMetadataReq req)
TSStatus cancelOperation(1:TSCancelOperationReq req);
TSStatus closeOperation(1:TSCloseOperationReq req);
TSGetTimeZoneResp getTimeZone(1:i64 sessionId);
TSStatus setTimeZone(1:TSSetTimeZoneReq req);
ServerProperties getProperties();
TSStatus setStorageGroup(1:i64 sessionId, 2:string storageGroup);
TSStatus createTimeseries(1:TSCreateTimeseriesReq req);
TSStatus deleteTimeseries(1:i64 sessionId, 2:list<string> path)
TSStatus deleteStorageGroups(1:i64 sessionId, 2:list<string> storageGroup);
TSStatus insert(1:TSInsertReq req);
TSExecuteBatchStatementResp insertBatch(1:TSBatchInsertionReq req);
TSExecuteInsertRowInBatchResp insertRowInBatch(1:TSInsertInBatchReq req);
TSExecuteBatchStatementResp testInsertBatch(1:TSBatchInsertionReq req);
TSStatus testInsertRow(1:TSInsertReq req);
TSExecuteInsertRowInBatchResp testInsertRowInBatch(1:TSInsertInBatchReq req);
TSStatus deleteData(1:TSDeleteDataReq req);
i64 requestStatementId(1:i64 sessionId);
}
| high | 0.889537 | 193 |
open Core
open Signature_lib
let validate_int16 x =
let max_port = 1 lsl 16 in
if 0 <= x && x < max_port then Ok x
else Or_error.errorf !"Port not between 0 and %d" max_port
let int16 =
Command.Arg_type.map Command.Param.int
~f:(Fn.compose Or_error.ok_exn validate_int16)
let public_key_compressed =
Command.Arg_type.create (fun s ->
try Public_key.Compressed.of_base58_check_exn s
with e ->
let random = Public_key.compress (Keypair.create ()).public_key in
eprintf
"Error parsing command line. Run with -help for usage information.\n\n\
Couldn't read public key (Invalid key format)\n\
\ %s\n\
\ - here's a sample one: %s\n"
(Error.to_string_hum (Error.of_exn e))
(Public_key.Compressed.to_base58_check random) ;
exit 1 )
(* Hack to allow us to deprecate a value without needing to add an mli
* just for this. We only want to have one "kind" of public key in the
* public-facing interface if possible *)
include (
struct
let public_key =
Command.Arg_type.map public_key_compressed ~f:(fun pk ->
match Public_key.decompress pk with
| None ->
failwith "Invalid key"
| Some pk' ->
pk' )
end :
sig
val public_key : Public_key.t Command.Arg_type.t
[@@deprecated "Use public_key_compressed in commandline args"]
end )
let token_id =
Command.Arg_type.map ~f:Coda_base.Token_id.of_string Command.Param.string
let receipt_chain_hash =
Command.Arg_type.map Command.Param.string
~f:Coda_base.Receipt.Chain_hash.of_string
let peer : Host_and_port.t Command.Arg_type.t =
Command.Arg_type.create (fun s -> Host_and_port.of_string s)
let global_slot =
Command.Arg_type.map Command.Param.int ~f:Coda_numbers.Global_slot.of_int
let txn_fee =
Command.Arg_type.map Command.Param.string ~f:Currency.Fee.of_formatted_string
let txn_amount =
Command.Arg_type.map Command.Param.string
~f:Currency.Amount.of_formatted_string
let txn_nonce =
let open Coda_base in
Command.Arg_type.map Command.Param.string ~f:Account.Nonce.of_string
let hd_index =
Command.Arg_type.map Command.Param.string ~f:Coda_numbers.Hd_index.of_string
let ip_address =
Command.Arg_type.map Command.Param.string ~f:Unix.Inet_addr.of_string
let cidr_mask =
Command.Arg_type.map Command.Param.string ~f:Unix.Cidr.of_string
let log_level =
Command.Arg_type.map Command.Param.string ~f:(fun log_level_str_with_case ->
let open Logger in
let log_level_str = String.lowercase log_level_str_with_case in
match Level.of_string log_level_str with
| Error _ ->
eprintf "Received unknown log-level %s. Expected one of: %s\n"
log_level_str
( Level.all |> List.map ~f:Level.show
|> List.map ~f:String.lowercase
|> String.concat ~sep:", " ) ;
exit 14
| Ok ll ->
ll )
let user_command =
Command.Arg_type.create (fun s ->
try Coda_base.User_command.of_base58_check_exn s
with e ->
failwithf "Couldn't decode transaction id: %s\n"
(Error.to_string_hum (Error.of_exn e))
() )
module Work_selection_method = struct
[%%versioned
module Stable = struct
module V1 = struct
type t = Sequence | Random
let to_latest = Fn.id
end
end]
end
let work_selection_method_val = function
| "seq" ->
Work_selection_method.Sequence
| "rand" ->
Random
| _ ->
failwith "Invalid work selection"
let work_selection_method =
Command.Arg_type.map Command.Param.string ~f:work_selection_method_val
let work_selection_method_to_module :
Work_selection_method.t -> (module Work_selector.Selection_method_intf) =
function
| Sequence ->
(module Work_selector.Selection_methods.Sequence)
| Random ->
(module Work_selector.Selection_methods.Random)
| high | 0.779601 | 194 |
import React from "react";
export const Loader = () => (
<div className='text-center'>
<div className='spinner-border' role='status'>
<span className='sr-only'>Loading...</span>
</div>
</div>
); | high | 0.536476 | 195 |
mongoimport:
mongoimport -d donorschoose -c projects --type csv --file /home/lserra/dashio/opendata_projects_small.csv --headerline | medium | 0.443838 | 196 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_45) on Fri Aug 28 09:51:25 EDT 2015 -->
<title>Cassandra.describe_splits_ex_result._Fields (apache-cassandra API)</title>
<meta name="date" content="2015-08-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Cassandra.describe_splits_ex_result._Fields (apache-cassandra API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":9,"i1":9,"i2":9,"i3":10,"i4":10,"i5":9,"i6":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Cassandra.describe_splits_ex_result._Fields.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result.html" title="class in org.apache.cassandra.thrift"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_result.html" title="class in org.apache.cassandra.thrift"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" target="_top">Frames</a></li>
<li><a href="Cassandra.describe_splits_ex_result._Fields.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#enum.constant.summary">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum.constant.detail">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.cassandra.thrift</div>
<h2 title="Enum Cassandra.describe_splits_ex_result._Fields" class="title">Enum Cassandra.describe_splits_ex_result._Fields</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>java.lang.Enum<<a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_splits_ex_result._Fields</a>></li>
<li>
<ul class="inheritance">
<li>org.apache.cassandra.thrift.Cassandra.describe_splits_ex_result._Fields</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable, java.lang.Comparable<<a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_splits_ex_result._Fields</a>>, org.apache.thrift.TFieldIdEnum</dd>
</dl>
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result.html" title="class in org.apache.cassandra.thrift">Cassandra.describe_splits_ex_result</a></dd>
</dl>
<hr>
<br>
<pre>public static enum <span class="typeNameLabel">Cassandra.describe_splits_ex_result._Fields</span>
extends java.lang.Enum<<a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_splits_ex_result._Fields</a>>
implements org.apache.thrift.TFieldIdEnum</pre>
<div class="block">The set of fields this struct contains, along with convenience methods for finding and manipulating them.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum.constant.summary">
<!-- -->
</a>
<h3>Enum Constant Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Constant Summary table, listing enum constants, and an explanation">
<caption><span>Enum Constants</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Enum Constant and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html#IRE">IRE</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html#SUCCESS">SUCCESS</a></span></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_splits_ex_result._Fields</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html#findByName-java.lang.String-">findByName</a></span>(java.lang.String name)</code>
<div class="block">Find the _Fields constant that matches name, or null if its not found.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_splits_ex_result._Fields</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html#findByThriftId-int-">findByThriftId</a></span>(int fieldId)</code>
<div class="block">Find the _Fields constant that matches fieldId, or null if its not found.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_splits_ex_result._Fields</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html#findByThriftIdOrThrow-int-">findByThriftIdOrThrow</a></span>(int fieldId)</code>
<div class="block">Find the _Fields constant that matches fieldId, throwing an exception
if it is not found.</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html#getFieldName--">getFieldName</a></span>()</code> </td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>short</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html#getThriftFieldId--">getThriftFieldId</a></span>()</code> </td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_splits_ex_result._Fields</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html#valueOf-java.lang.String-">valueOf</a></span>(java.lang.String name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_splits_ex_result._Fields</a>[]</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html#values--">values</a></span>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Enum">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Enum</h3>
<code>clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>getClass, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ ENUM CONSTANT DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum.constant.detail">
<!-- -->
</a>
<h3>Enum Constant Detail</h3>
<a name="SUCCESS">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>SUCCESS</h4>
<pre>public static final <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_splits_ex_result._Fields</a> SUCCESS</pre>
</li>
</ul>
<a name="IRE">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>IRE</h4>
<pre>public static final <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_splits_ex_result._Fields</a> IRE</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="values--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>values</h4>
<pre>public static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_splits_ex_result._Fields</a>[] values()</pre>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared. This method may be used to iterate
over the constants as follows:
<pre>
for (Cassandra.describe_splits_ex_result._Fields c : Cassandra.describe_splits_ex_result._Fields.values())
System.out.println(c);
</pre></div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>an array containing the constants of this enum type, in the order they are declared</dd>
</dl>
</li>
</ul>
<a name="valueOf-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>valueOf</h4>
<pre>public static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_splits_ex_result._Fields</a> valueOf(java.lang.String name)</pre>
<div class="block">Returns the enum constant of this type with the specified name.
The string must match <i>exactly</i> an identifier used to declare an
enum constant in this type. (Extraneous whitespace characters are
not permitted.)</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>name</code> - the name of the enum constant to be returned.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the enum constant with the specified name</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.lang.IllegalArgumentException</code> - if this enum type has no constant with the specified name</dd>
<dd><code>java.lang.NullPointerException</code> - if the argument is null</dd>
</dl>
</li>
</ul>
<a name="findByThriftId-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>findByThriftId</h4>
<pre>public static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_splits_ex_result._Fields</a> findByThriftId(int fieldId)</pre>
<div class="block">Find the _Fields constant that matches fieldId, or null if its not found.</div>
</li>
</ul>
<a name="findByThriftIdOrThrow-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>findByThriftIdOrThrow</h4>
<pre>public static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_splits_ex_result._Fields</a> findByThriftIdOrThrow(int fieldId)</pre>
<div class="block">Find the _Fields constant that matches fieldId, throwing an exception
if it is not found.</div>
</li>
</ul>
<a name="findByName-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>findByName</h4>
<pre>public static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_splits_ex_result._Fields</a> findByName(java.lang.String name)</pre>
<div class="block">Find the _Fields constant that matches name, or null if its not found.</div>
</li>
</ul>
<a name="getThriftFieldId--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getThriftFieldId</h4>
<pre>public short getThriftFieldId()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>getThriftFieldId</code> in interface <code>org.apache.thrift.TFieldIdEnum</code></dd>
</dl>
</li>
</ul>
<a name="getFieldName--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getFieldName</h4>
<pre>public java.lang.String getFieldName()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>getFieldName</code> in interface <code>org.apache.thrift.TFieldIdEnum</code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Cassandra.describe_splits_ex_result._Fields.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result.html" title="class in org.apache.cassandra.thrift"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_splits_result.html" title="class in org.apache.cassandra.thrift"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/thrift/Cassandra.describe_splits_ex_result._Fields.html" target="_top">Frames</a></li>
<li><a href="Cassandra.describe_splits_ex_result._Fields.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#enum.constant.summary">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum.constant.detail">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2015 The Apache Software Foundation</small></p>
</body>
</html>
| high | 0.302971 | 197 |
/*
* Copyright 2008 ZXing authors
*
* 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.
*/
using ZXing.Common.Test;
namespace ZXing.OneD.Test
{
/// <summary>
/// <author>dswitkin@google.com (Daniel Switkin)</author>
/// </summary>
public sealed class UPCABlackBox2TestCase : AbstractBlackBoxTestCase
{
public UPCABlackBox2TestCase()
: base("test/data/blackbox/upca-2", new MultiFormatReader(), BarcodeFormat.UPC_A)
{
addTest(30, 36, 0, 2, 0.0f);
addTest(31, 36, 0, 2, 180.0f);
}
}
} | high | 0.672319 | 198 |
# This file must be used with "source bin/activate.csh" *from csh*.
# You cannot run it directly.
# Created by Davide Di Blasi <davidedb@gmail.com>.
# Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; test "\!:*" != "nondestructive" && unalias deactivate'
# Unset irrelevant variables.
deactivate nondestructive
setenv VIRTUAL_ENV "/home/emmah/Desktop/moringa-school-projects/Neighborhood/virtual"
set _OLD_VIRTUAL_PATH="$PATH"
setenv PATH "$VIRTUAL_ENV/bin:$PATH"
set _OLD_VIRTUAL_PROMPT="$prompt"
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
if ("virtual" != "") then
set env_name = "virtual"
else
if (`basename "VIRTUAL_ENV"` == "__") then
# special case for Aspen magic directories
# see http://www.zetadev.com/software/aspen/
set env_name = `basename \`dirname "$VIRTUAL_ENV"\``
else
set env_name = `basename "$VIRTUAL_ENV"`
endif
endif
set prompt = "[$env_name] $prompt"
unset env_name
endif
alias pydoc python -m pydoc
rehash
| low | 1 | 199 |
{-# OPTIONS --without-K --rewriting #-}
open import lib.Basics
open import lib.NType2
open import lib.NConnected
open import lib.types.Truncation
open import lib.types.Group
module lib.types.EilenbergMacLane1.Core {i} where
module _ (G : Group i) where
private
module G = Group G
postulate -- HIT
EM₁ : Type i
embase' : EM₁
emloop' : G.El → embase' == embase'
emloop-comp' : ∀ g₁ g₂ → emloop' (G.comp g₁ g₂) == emloop' g₁ ∙ emloop' g₂
emloop-coh₁' : (g₁ g₂ g₃ : G.El)
→ emloop' (G.comp (G.comp g₁ g₂) g₃) =-= emloop' g₁ ∙ (emloop' g₂ ∙ emloop' g₃)
emloop-coh₁' g₁ g₂ g₃ =
emloop' (G.comp (G.comp g₁ g₂) g₃)
=⟪ emloop-comp' (G.comp g₁ g₂) g₃ ⟫
emloop' (G.comp g₁ g₂) ∙ emloop' g₃
=⟪ ap (λ l → l ∙ emloop' g₃) (emloop-comp' g₁ g₂) ⟫
(emloop' g₁ ∙ emloop' g₂) ∙ emloop' g₃
=⟪ ∙-assoc (emloop' g₁) (emloop' g₂) (emloop' g₃) ⟫
emloop' g₁ ∙ (emloop' g₂ ∙ emloop' g₃) ∎∎
emloop-coh₂' : (g₁ g₂ g₃ : G.El)
→ emloop' (G.comp (G.comp g₁ g₂) g₃) =-= emloop' g₁ ∙ (emloop' g₂ ∙ emloop' g₃)
emloop-coh₂' g₁ g₂ g₃ =
emloop' (G.comp (G.comp g₁ g₂) g₃)
=⟪ ap emloop' (Group.assoc G g₁ g₂ g₃) ⟫
emloop' (G.comp g₁ (G.comp g₂ g₃))
=⟪ emloop-comp' g₁ (Group.comp G g₂ g₃) ⟫
emloop' g₁ ∙ emloop' (G.comp g₂ g₃)
=⟪ ap (λ l → emloop' g₁ ∙ l) (emloop-comp' g₂ g₃) ⟫
emloop' g₁ ∙ (emloop' g₂ ∙ emloop' g₃) ∎∎
postulate
emloop-coh' : ∀ g₁ g₂ g₃ → emloop-coh₁' g₁ g₂ g₃ =ₛ emloop-coh₂' g₁ g₂ g₃
EM₁-level' : has-level 2 EM₁
⊙EM₁ : Ptd i
⊙EM₁ = ⊙[ EM₁ , embase' ]
module _ {G : Group i} where
private
module G = Group G
embase = embase' G
emloop = emloop' G
emloop-comp = emloop-comp' G
emloop-coh₁ = emloop-coh₁' G
emloop-coh₂ = emloop-coh₂' G
emloop-coh = emloop-coh' G
instance
EM₁-level : {n : ℕ₋₂} → has-level (S (S (S (S n)))) (EM₁ G)
EM₁-level {⟨-2⟩} = EM₁-level' G
EM₁-level {S n} = raise-level _ EM₁-level
abstract
-- This was in the original paper, but is actually derivable.
emloop-ident : emloop G.ident == idp
emloop-ident = ! $ anti-whisker-right (emloop G.ident) $
ap emloop (! $ G.unit-r G.ident) ∙ emloop-comp G.ident G.ident
module EM₁Elim {j} {P : EM₁ G → Type j}
{{_ : (x : EM₁ G) → has-level 2 (P x)}}
(embase* : P embase)
(emloop* : ∀ g → embase* == embase* [ P ↓ emloop g ])
(emloop-comp* : ∀ g₁ g₂ →
emloop* (G.comp g₁ g₂) == emloop* g₁ ∙ᵈ emloop* g₂
[ (λ p → embase* == embase* [ P ↓ p ]) ↓ emloop-comp g₁ g₂ ])
(emloop-coh* : ∀ g₁ g₂ g₃ →
emloop-comp* (G.comp g₁ g₂) g₃ ∙ᵈ
(emloop-comp* g₁ g₂ ∙ᵈᵣ emloop* g₃) ∙ᵈ
∙ᵈ-assoc (emloop* g₁) (emloop* g₂) (emloop* g₃)
==
↓-ap-in (λ p → embase* == embase* [ P ↓ p ]) emloop (apd emloop* (G.assoc g₁ g₂ g₃)) ∙ᵈ
emloop-comp* g₁ (G.comp g₂ g₃) ∙ᵈ
(emloop* g₁ ∙ᵈₗ emloop-comp* g₂ g₃)
[ (λ e → emloop* (G.comp (G.comp g₁ g₂) g₃) == emloop* g₁ ∙ᵈ (emloop* g₂ ∙ᵈ emloop* g₃)
[ (λ p → embase* == embase* [ P ↓ p ]) ↓ e ])
↓ =ₛ-out (emloop-coh g₁ g₂ g₃) ])
where
postulate -- HIT
f : Π (EM₁ G) P
embase-β : f embase ↦ embase*
{-# REWRITE embase-β #-}
postulate -- HIT
emloop-β : (g : G.El) → apd f (emloop g) == emloop* g
emloop-comp-path : (g₁ g₂ : G.El)
→ apd (apd f) (emloop-comp g₁ g₂) ▹
apd-∙ f (emloop g₁) (emloop g₂) ∙
ap2 _∙ᵈ_ (emloop-β g₁) (emloop-β g₂)
==
emloop-β (G.comp g₁ g₂) ◃
emloop-comp* g₁ g₂
open EM₁Elim public using () renaming (f to EM₁-elim)
module EM₁Level₁Elim {j} {P : EM₁ G → Type j}
{{is-1-type : (x : EM₁ G) → has-level 1 (P x)}}
(embase* : P embase)
(emloop* : (g : G.El) → embase* == embase* [ P ↓ emloop g ])
(emloop-comp* : (g₁ g₂ : G.El) →
emloop* (G.comp g₁ g₂) == emloop* g₁ ∙ᵈ emloop* g₂
[ (λ p → embase* == embase* [ P ↓ p ]) ↓ emloop-comp g₁ g₂ ]) where
private
module M = EM₁Elim {{λ x → raise-level 1 (is-1-type x)}}
embase* emloop* emloop-comp*
(λ g₁ g₂ g₃ → prop-has-all-paths-↓ {{↓-level (↓-level (is-1-type embase))}})
abstract
f : Π (EM₁ G) P
f = M.f
embase-β : f embase ↦ embase*
embase-β = M.embase-β
{-# REWRITE embase-β #-}
emloop-β : (g : G.El) → apd f (emloop g) == emloop* g
emloop-β = M.emloop-β
open EM₁Level₁Elim public using () renaming (f to EM₁-level₁-elim)
module EM₁SetElim {j} {P : EM₁ G → Type j}
{{is-set : (x : EM₁ G) → is-set (P x)}}
(embase* : P embase)
(emloop* : (g : G.El) → embase* == embase* [ P ↓ emloop g ]) where
private
module M = EM₁Level₁Elim {P = P} {{λ x → raise-level 0 (is-set x)}}
embase* emloop*
(λ g₁ g₂ → set-↓-has-all-paths-↓ {{is-set embase}})
open M public
open EM₁SetElim public using () renaming (f to EM₁-set-elim)
module EM₁PropElim {j} {P : EM₁ G → Type j}
{{is-prop : (x : EM₁ G) → is-prop (P x)}}
(embase* : P embase) where
module P = EM₁SetElim {{λ x → raise-level -1 (is-prop x)}}
embase*
(λ g → prop-has-all-paths-↓ {{is-prop embase}})
open P public
open EM₁PropElim public using () renaming (f to EM₁-prop-elim)
-- basic lemmas about [EM₁]
module _ {G : Group i} where
private
module G = Group G
abstract
emloop-inv : ∀ g → emloop' G (G.inv g) == ! (emloop g)
emloop-inv g = cancels-inverse _ _ lemma
where
cancels-inverse : ∀ {i} {A : Type i} {x y : A}
(p : x == y) (q : y == x) → p ∙ q == idp → p == ! q
cancels-inverse p idp r = ! (∙-unit-r p) ∙ r
lemma : emloop' G (G.inv g) ∙ emloop g == idp
lemma = ! (emloop-comp (G.inv g) g) ∙ ap emloop (G.inv-l g) ∙ emloop-ident
{- EM₁ is 0-connected -}
instance
EM₁-conn : is-connected 0 (EM₁ G)
EM₁-conn = has-level-in ([ embase ] , Trunc-elim
(EM₁-level₁-elim
{P = λ x → [ embase ] == [ x ]}
{{λ _ → raise-level _ (=-preserves-level Trunc-level)}}
idp
(λ _ → prop-has-all-paths-↓)
(λ _ _ → set-↓-has-all-paths-↓)))
| high | 0.822479 | 200 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}
-- | Functions for receive timeouts and delayed messages sending.
--
-- Based on the 'delay' function.
--
-- @since 0.12.0
module Control.Eff.Concurrent.Process.Timer
( TimerReference (),
TimerElapsed (fromTimerElapsed),
sendAfter,
startTimer,
sendAfterWithTitle,
sendAfterWithTitleAndLogMsg,
startTimerWithTitle,
cancelTimer,
selectTimerElapsed,
receiveAfter,
receiveSelectedAfter,
receiveSelectedWithMonitorAfter,
receiveAfterWithTitle,
receiveSelectedAfterWithTitle,
receiveSelectedWithMonitorAfterWithTitle,
)
where
import Control.Applicative
import Control.DeepSeq
import Control.Eff
import Control.Eff.Concurrent.Process
import Control.Eff.Log.Handler
import Control.Eff.Log.Message
import Data.Foldable
import Data.Proxy
import Data.Typeable
import GHC.Stack
-- | Wait for a message of the given type for the given time. When no message
-- arrives in time, return 'Nothing'. This is based on
-- 'receiveSelectedAfter'.
--
-- @since 0.12.0
receiveAfter ::
forall a r q.
( HasCallStack,
HasProcesses r q,
Member Logs q,
Typeable a
) =>
Timeout ->
Eff r (Maybe a)
receiveAfter t =
either (const Nothing) Just <$> receiveSelectedAfter (selectMessage @a) t
-- | Wait for a message of the given type for the given time. When no message
-- arrives in time, return 'Left' 'TimerElapsed'. This is based on
-- 'selectTimerElapsed' and 'startTimer'.
--
-- @since 0.12.0
receiveSelectedAfter ::
forall a r q.
( HasCallStack,
HasProcesses r q,
Member Logs q
) =>
MessageSelector a ->
Timeout ->
Eff r (Either TimerElapsed a)
receiveSelectedAfter sel t = do
let timerTitle = MkProcessTitle "receive-timer"
timerRef <- startTimerWithTitle timerTitle t
res <-
receiveSelectedMessage
(Left <$> selectTimerElapsed timerRef <|> Right <$> sel)
cancelTimer timerRef
return res
-- | Like 'receiveWithMonitor' combined with 'receiveSelectedAfter'.
--
-- @since 0.22.0
receiveSelectedWithMonitorAfter ::
forall a r q.
( HasCallStack,
HasProcesses r q,
Member Logs q,
Member Logs r,
ToTypeLogMsg a
) =>
ProcessId ->
MessageSelector a ->
Timeout ->
Eff r (Either (Either ProcessDown TimerElapsed) a)
receiveSelectedWithMonitorAfter pid sel t = do
fromPid <- self
let timerTitle = MkProcessTitle "receive-timeout"
initialLog =
packLogMsg "receice-timeout receiver: "
<> toLogMsg fromPid
<> packLogMsg " expected message type: "
<> toTypeLogMsg (Proxy @a)
receiveSelectedWithMonitorAfterWithTitle pid sel t timerTitle initialLog
-- | Wait for a message of the given type for the given time. When no message
-- arrives in time, return 'Nothing'. This is based on
-- 'receiveSelectedAfterWithTitle'.
--
-- @since 0.12.0
receiveAfterWithTitle ::
forall a r q.
( HasCallStack,
HasProcesses r q,
Member Logs q,
Typeable a
) =>
Timeout ->
ProcessTitle ->
Eff r (Maybe a)
receiveAfterWithTitle t timerTitle =
either (const Nothing) Just <$> receiveSelectedAfterWithTitle (selectMessage @a) t timerTitle
-- | Wait for a message of the given type for the given time. When no message
-- arrives in time, return 'Left' 'TimerElapsed'. This is based on
-- 'selectTimerElapsed' and 'startTimerWithTitle'.
--
-- @since 0.12.0
receiveSelectedAfterWithTitle ::
forall a r q.
( HasCallStack,
HasProcesses r q,
Member Logs q
) =>
MessageSelector a ->
Timeout ->
ProcessTitle ->
Eff r (Either TimerElapsed a)
receiveSelectedAfterWithTitle sel t timerTitle = do
timerRef <- startTimerWithTitle timerTitle t
res <-
receiveSelectedMessage
(Left <$> selectTimerElapsed timerRef <|> Right <$> sel)
cancelTimer timerRef
return res
-- | Like 'receiveWithMonitorWithTitle' combined with 'receiveSelectedAfterWithTitle'.
--
-- @since 0.30.0
receiveSelectedWithMonitorAfterWithTitle ::
forall a r q.
( HasCallStack,
HasProcesses r q,
Member Logs q,
Member Logs r
) =>
ProcessId ->
MessageSelector a ->
Timeout ->
ProcessTitle ->
LogMsg ->
Eff r (Either (Either ProcessDown TimerElapsed) a)
receiveSelectedWithMonitorAfterWithTitle pid sel t timerTitle initialLogMsg = do
timerRef <- startTimerWithTitle timerTitle t
logDebug (LABEL "started" timerRef)
logDebug initialLogMsg
res <- withMonitor pid $ \pidMon -> do
receiveSelectedMessage
( Left . Left <$> selectProcessDown pidMon
<|> Left . Right <$> selectTimerElapsed timerRef
<|> Right <$> sel
)
cancelTimer timerRef
return res
-- | A 'MessageSelector' matching 'TimerElapsed' messages created by
-- 'startTimer'.
--
-- @since 0.12.0
selectTimerElapsed :: TimerReference -> MessageSelector TimerElapsed
selectTimerElapsed timerRef =
filterMessage (\(TimerElapsed timerRefIn) -> timerRef == timerRefIn)
-- | The reference to a timer started by 'startTimer', required to stop
-- a timer via 'cancelTimer'.
--
-- @since 0.12.0
newtype TimerReference = TimerReference ProcessId
deriving (NFData, Ord, Eq, Num, Integral, Real, Enum, Typeable)
instance ToLogMsg TimerReference where
toLogMsg (TimerReference p) = "timer-ref" <> toLogMsg p
-- | A value to be sent when timer started with 'startTimer' has elapsed.
--
-- @since 0.12.0
newtype TimerElapsed = TimerElapsed {fromTimerElapsed :: TimerReference}
deriving (NFData, Ord, Eq, Typeable)
instance ToTypeLogMsg TimerElapsed where
toTypeLogMsg _ = "timer-elapsed"
instance ToLogMsg TimerElapsed where
toLogMsg x = packLogMsg "elapsed: " <> toLogMsg (fromTimerElapsed x)
-- | Send a message to a given process after waiting. The message is created by
-- applying the function parameter to the 'TimerReference', such that the
-- message can directly refer to the timer.
--
-- @since 0.12.0
sendAfter ::
forall r q message.
( HasCallStack,
HasProcesses r q,
Typeable message,
NFData message,
Member Logs q
) =>
ProcessId ->
Timeout ->
(TimerReference -> message) ->
Eff r TimerReference
sendAfter pid t mkMsg =
sendAfterWithTitle
(MkProcessTitle "send-after-timer")
pid
t
mkMsg
-- | Like 'sendAfter' but with a user provided name for the timer process.
--
-- @since 0.30.0
sendAfterWithTitle ::
forall r q message.
( HasCallStack,
HasProcesses r q,
Typeable message,
NFData message,
Member Logs q
) =>
ProcessTitle ->
ProcessId ->
Timeout ->
(TimerReference -> message) ->
Eff r TimerReference
sendAfterWithTitle = sendAfterWithTitleAndMaybeLogMsg Nothing
-- | Like 'sendAfterWithTitle' but with a user provided initial debug `LogMsg`.
--
-- @since 1.0.0
sendAfterWithTitleAndLogMsg ::
forall r q message.
( HasCallStack,
HasProcesses r q,
Member Logs q,
Typeable message,
NFData message
) =>
LogMsg ->
ProcessTitle ->
ProcessId ->
Timeout ->
(TimerReference -> message) ->
Eff r TimerReference
sendAfterWithTitleAndLogMsg =
sendAfterWithTitleAndMaybeLogMsg . Just
-- | Like 'sendAfterWithTitle' but with a user provided, optional initial debug `LogMsg`.
--
-- @since 1.0.0
sendAfterWithTitleAndMaybeLogMsg ::
forall r q message.
( HasCallStack,
HasProcesses r q,
Member Logs q,
Typeable message,
NFData message
) =>
Maybe LogMsg ->
ProcessTitle ->
ProcessId ->
Timeout ->
(TimerReference -> message) ->
Eff r TimerReference
sendAfterWithTitleAndMaybeLogMsg initialLogMsg title pid t mkMsg =
TimerReference
<$> ( spawn
title
( do
traverse_ logDebug initialLogMsg
me <- self
let meRef = TimerReference me
logDebug (LABEL "timer started" title) pid t meRef
delay t
logDebug (LABEL "timer elapsed" title) pid t meRef
sendMessage pid (force (mkMsg meRef))
)
)
-- | Start a new timer, after the time has elapsed, 'TimerElapsed' is sent to
-- calling process. The message also contains the 'TimerReference' returned by
-- this function. Use 'cancelTimer' to cancel the timer. Use
-- 'selectTimerElapsed' to receive the message using 'receiveSelectedMessage'.
-- To receive messages with guarded with a timeout see 'receiveAfter'.
--
-- This calls 'sendAfterWithTitle' under the hood with 'TimerElapsed' as
-- message.
--
-- @since 0.30.0
startTimerWithTitle ::
forall r q.
( HasCallStack,
Member Logs q,
HasProcesses r q
) =>
ProcessTitle ->
Timeout ->
Eff r TimerReference -- TODO add a parameter to the TimerReference
startTimerWithTitle title t = do
p <- self
sendAfterWithTitle title p t TimerElapsed
-- | Start a new timer, after the time has elapsed, 'TimerElapsed' is sent to
-- calling process. The message also contains the 'TimerReference' returned by
-- this function. Use 'cancelTimer' to cancel the timer. Use
-- 'selectTimerElapsed' to receive the message using 'receiveSelectedMessage'.
-- To receive messages with guarded with a timeout see 'receiveAfter'.
--
-- Calls 'sendAfter' under the hood.
--
-- @since 0.12.0
startTimer ::
forall r q.
( HasCallStack,
HasProcesses r q,
Member Logs q
) =>
Timeout ->
Eff r TimerReference -- TODO add a parameter to the TimerReference
startTimer t = do
p <- self
sendAfter p t TimerElapsed
-- | Cancel a timer started with 'startTimer'.
--
-- @since 0.12.0
cancelTimer ::
forall r q. HasProcesses r q => TimerReference -> Eff r ()
cancelTimer (TimerReference tr) = sendShutdown tr ExitNormally
| high | 0.924198 | 201 |
------------------------------------------------------------------------------
-- Schedule controller; implemented as a Mealy FSM
--
-- Project :
-- File : $URL: svn+ssh://plessl@yosemite.ethz.ch/home/plessl/SVN/simzippy/trunk/vhdl/schedulectrl.vhd $
-- Authors : Rolf Enzler <enzler@ife.ee.ethz.ch>
-- Christian Plessl <plessl@tik.ee.ethz.ch>
-- Company : Swiss Federal Institute of Technology (ETH) Zurich
-- Created : 2003-10-16
-- $Id: schedulectrl.vhd 242 2005-04-07 09:17:51Z plessl $
------------------------------------------------------------------------------
-- The schedule controller implements the sequencing of the contexts. The
-- sequence is specified in the context sequence program store (see Rolfs PhD
-- thesis pp 77ff).
--
-- The controller stays in idle mode, until the sequencing is
-- acitvated (StartxEI = '1'). After activation it switches to the
-- first context and executes it (run state) until the number of
-- execution cycles for this context has been reached (RunningSI =
-- '0'). If the last context has been executed (LastxSI=0) the
-- scheduler is stopped, otherwise the scheduler switches to the next
-- context as specified with the next address field in the instruction
-- word.
--
-- FIXME: Maybe the switch context state could be removed, thus the
-- context could be switched in a single cycle. While this doesn't
-- make much of a difference in performance when contexts are executed
-- for many cycles, it makes a differenece when the context has to be switched
-- every cycle, which is the case for certain virtualization modes.
--
-- FIXME: The sequencer could be extended to provide a little more microcode
-- features. E.g. the ability to run a certain schedule repeatedly.
--
-- FIXME: Rolf mentioned something about status flags, that can be polled from
-- CPUs. What flags can be polled?
-------------------------------------------------------------------------------
library ieee;
use ieee.std_logic_1164.all;
entity ScheduleCtrl is
port (
ClkxC : in std_logic;
RstxRB : in std_logic;
StartxEI : in std_logic;
RunningxSI : in std_logic;
LastxSI : in std_logic;
SwitchxEO : out std_logic; -- initiate context switch
BusyxSO : out std_logic); -- busy status flag
end ScheduleCtrl;
architecture simple of ScheduleCtrl is
type state is (idle, switch, run);
signal currstate : state;
signal nextstate : state;
begin -- simple
--
-- computation of next state and current outputs
--
process (LastxSI, RunningxSI, StartxEI, currstate)
begin -- process
-- default assignments
nextstate <= currstate;
SwitchxEO <= '0';
BusyxSO <= '0';
-- non-default transitions and current outputs
case currstate is
when idle =>
if StartxEI = '1' then
SwitchxEO <= '1';
BusyxSO <= '1';
nextstate <= switch;
end if;
when switch =>
BusyxSO <= '1';
nextstate <= run;
when run =>
BusyxSO <= '1';
if (RunningxSI = '0') and (LastxSI = '0') then
SwitchxEO <= '1';
nextstate <= switch;
elsif (RunningxSI = '0') and (LastxSI = '1') then
nextstate <= idle;
end if;
-- have all parasitic states flow into idle state
when others =>
nextstate <= idle;
end case;
end process;
--
-- updating of state
--
process (ClkxC, RstxRB)
begin -- process
if RstxRB = '0' then -- asynchronous reset (active low)
currstate <= idle;
elsif ClkxC'event and ClkxC = '1' then -- rising clock edge
currstate <= nextstate;
end if;
end process;
end simple;
| medium | 0.420512 | 202 |