content
stringlengths 10
4.9M
|
---|
/**
* record and send pcm data to mobile device
*
* @author ouyangnengjun
*/
public class RecordService extends Service {
private static final String TAG = "CarLifeVoice";
public static final int VR_STATUS_RECOGNITION = 1;
public static final int VR_STATUS_WAKEUP = 2;
private PcmRecorder mPcmRecorder = null;
@Override
public void onCreate() {
super.onCreate();
mPcmRecorder = new PcmRecorder();
mPcmRecorder.start();
}
@Override
public IBinder onBind(Intent intent) {
return new RecordServiceBinder();
}
@Override
public void onDestroy() {
LogUtil.d(TAG, "--RecordService--onDestroy----");
mPcmRecorder = null;
super.onDestroy();
}
public class RecordServiceBinder extends Binder {
public void requestAudioFocus() {
LogUtil.e(TAG, "-----requestAudioFocus-----");
VehiclePCMPlayer.getInstance().requestVRAudioFocus();
sendBroadcast(new Intent(BroadcastActionConstant.CARLIFE_RECORD_SERVICE_START));
}
public void abandonAudioFocus() {
LogUtil.e(TAG, "-----abandonAudioFocus-----");
VehiclePCMPlayer.getInstance().abandonVRAudioFocus();
sendBroadcast(new Intent(BroadcastActionConstant.CARLIFE_RECORD_SERVICE_STOP));
}
public void onRecordEnd() {
LogUtil.e(TAG, "-----MSG_CMD_MIC_RECORD_END-----");
if (mPcmRecorder != null) {
mPcmRecorder.setRecording(false);
}
}
public void onWakeUpStart() {
LogUtil.e(TAG, "-----MSG_CMD_MIC_RECORD_WAKEUP_START-----");
if (mPcmRecorder == null || !mPcmRecorder.isAlive()) {
mPcmRecorder = new PcmRecorder();
mPcmRecorder.start();
}
mPcmRecorder.setRecording(true);
// close down sample
mPcmRecorder.setDownSampleStatus(false);
}
public void onVRStart() {
LogUtil.e(TAG, "-----MSG_CMD_MIC_RECORD_RECOG_START-----");
if (mPcmRecorder == null || !mPcmRecorder.isAlive()) {
mPcmRecorder = new PcmRecorder();
mPcmRecorder.start();
}
mPcmRecorder.setRecording(true);
// close down sample
mPcmRecorder.setDownSampleStatus(false);
}
public void onUsbDisconnected() {
VehiclePCMPlayer.getInstance().abandonVRAudioFocus();
if (mPcmRecorder != null) {
mPcmRecorder.setRecording(false);
}
}
}
} |
'''1. Write a Python program to compute and print sum of two given integers (more than or equal to zero).
If given integers or the sum have more than 80 digits, print "overflow".
Input first integer:
25
Input second integer:
22
Sum of the two integers: 47'''
def sum_integers(x, y):
if x >= 10 ** 80 or y >= 10 ** 80 or x + y >= 10 ** 80:
response = "Overflow!"
else:
response = x + y
return response
print(sum_integers(25, 22))
print(sum_integers(25**80, 22)) |
import sys
import argparse
import pickle
import numpy as np
from quadtree import Quadtree
def read_data(f):
data = []
for line in f:
entries = line.rstrip().split(' ')
lat = float(entries[0])
lng = float(entries[1])
data.append((lat,lng))
return np.array(data)
p = argparse.ArgumentParser()
p.add_argument("-i", "--infile", help="input file", type=argparse.FileType('r'), required=True)
p.add_argument("-m", "--modelfile", help="model file", type=argparse.FileType('r'), required=True)
p.add_argument("-o", "--outfile", help="output file (default=STDOUT)", type=argparse.FileType('w'), nargs='?', default=sys.stdout)
args = p.parse_args()
X = read_data(args.infile)
qtree = pickle.load(args.modelfile)
X_trans = qtree.transform(X)
print '"area ID","upper left x","upper left y","lower right x","lower right y"'
for i in range(len(X_trans)):
a = qtree.leaves_[X_trans[i]]
print >>args.outfile, "%s,%s,%s,%s,%s" % (a.aid,a.x1,a.y1,a.x2,a.y2)
|
The changing picture of otitis media in childhood.
Pick any youngster in this country who is approaching his second birthday. Odds are three to one that he has had otitis media, possibly several times. Some clinicians are now suggesting that the condition and its complications warrant more attention. Three such clinicians are Jerome O. Klein, MD, Boston University School of Medicine; Charles D. Bluestone, MD, University of Pittsburgh School of Medicine; and John D. Nelson, MD, University of Texas (Dallas) Southwestern Medical School. At a recent New York City briefing for medical editors sponsored by Eli Lilly and Company, Indianapolis, this trio agreed that: Not only is otitis media a widespread problem, but heretofore largely unrecognized complications raise questions about how this infection should be managed by physicians. While the infection can be bacterial or viral, Haemophilus influenzae is the most common bacterial cause—after Streptococcus pneumoniae—of otitis media with effusion, and there is growing recognition that strains of |
/**
* Created by Administrator on 23.12.2017.
*/
public class TestRunner {
public static void main(String[] args) {
runTestsByClassName("nnglebanov.custom.testpackage.TestClass");
runTestsByPackageName("nnglebanov.custom.testpackage");
runTestsByPackageName("testtest");
}
public static void runTestsByClassName(String className) {
try {
if(!isTestClass(className)){return;}
System.out.println(className+":");
Class c = Class.forName(className);
ArrayList<Method> methodsBefore = new ArrayList<>();
ArrayList<Method> methodsTest = new ArrayList<>();
ArrayList<Method> methodsAfter = new ArrayList<>();
ArrayList<Method> methods = new ArrayList<Method>(Arrays.asList(c.getDeclaredMethods()));
for (Method a : methods) {
if (a.isAnnotationPresent(Before.class)) {
methodsBefore.add(a);
} else if (a.isAnnotationPresent(Test.class)) {
methodsTest.add(a);
} else if (a.isAnnotationPresent(After.class)) {
methodsAfter.add(a);
}
}
methodsTest.sort((Method m1, Method m2) -> m1.getName().compareTo(m2.getName()));
methodsBefore.sort((Method m1, Method m2) -> m1.getName().compareTo(m2.getName()));
methodsAfter.sort((Method m1, Method m2) -> m1.getName().compareTo(m2.getName()));
for (Method test : methodsTest) {
Object obj = c.newInstance();
for (Method before : methodsBefore) {
before.invoke(obj, null);
}
test.invoke(obj, null);
for (Method after : methodsAfter) {
after.invoke(obj, null);
}
}
} catch (ClassNotFoundException e) {
System.out.println("Класс не найден");
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
e.printStackTrace();
}
}
public static void runTestsByPackageName(String packageName) {
final ClassLoader loader = Thread.currentThread()
.getContextClassLoader();
try {
for (final ClassPath.ClassInfo info : ClassPath.from(loader)
.getTopLevelClasses()) {
if (info.getName().startsWith(packageName)) {
if(isTestClass(info.getName()))
runTestsByClassName(info.getName());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static boolean isTestClass(String className) {
try {
Class c = Class.forName(className);
ArrayList<Method> methods = new ArrayList<Method>(Arrays.asList(c.getDeclaredMethods()));
for (Method a : methods) {
if (a.isAnnotationPresent(Test.class)) {
return true;
}
}
return false;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
}
}
} |
<gh_stars>0
export default {
apiKey: "<KEY>",
authDomain: "echo-fe0b8.firebaseapp.com",
databaseURL: "https://echo-fe0b8.firebaseio.com",
projectId: "echo-fe0b8",
storageBucket: "echo-fe0b8.appspot.com",
messagingSenderId: "1073761593124",
appId: "1:1073761593124:web:56d733ad1ca6c8026c75b1",
};
export const slides = [
{
title: "Relaxed",
image:
"https://res.cloudinary.com/dqv9mfbvt/image/upload/v1596790785/marginalia-productive-work_dzm3tg.png",
subtitle: "Find your Outfits",
description:
"Confused about your outfit? Don't worry! Find the best outfits here",
color: "#a4b494",
},
{
title: "Playful",
image:
"https://res.cloudinary.com/dqv9mfbvt/image/upload/v1596282567/pixeltrue-settings-1_nmkacn.png",
subtitle: "Hear it First, Wear it First",
description:
"Hating the clothes in your website? Explore hundreds of outfit ideas",
color: "#3282b8",
},
{
title: "Excentric",
image:
"https://res.cloudinary.com/dqv9mfbvt/image/upload/v1596973769/abstract-phone-purchases_ujecdw.png",
subtitle: "Your Style, Your Way",
description:
"Create your individual & unique style and look amazing everyday",
color: "#be79df",
},
{
title: "Funky",
image:
"https://res.cloudinary.com/dqv9mfbvt/image/upload/v1597223392/pixeltrue-idea_mcxuhs.png",
subtitle: "Look Good, Feel Good",
description:
"Discover the latests trends in fashion and explore your personality ",
color: "#ff9a76",
},
];
|
<reponame>komak-nabo/backend<gh_stars>1-10
import { Injectable, Logger as NestLogger } from '@nestjs/common';
@Injectable()
export class LoggerService extends NestLogger {
public _log: (message: any, context?: string) => void;
constructor(onlyImportant = false) {
super();
if (onlyImportant) {
this.debug = () => {
// do nothing.
};
this.log = () => {
// do nothing.
};
} else {
this._log = this.log;
this.log = (value: any, context?: string) => {
if (!this.isAcceptedLog(value)) {
return;
}
this._log(value, context);
};
}
}
private isAcceptedLog(value: any) {
if (typeof value !== 'string') {
return true;
}
if (
value.includes('dependencies initialized') ||
value.includes('Nest microservice successfully started') ||
value.includes('Controller {/') ||
value.includes('Mapped {/') ||
value.includes('Nest application successfully started') ||
value.includes('Starting Nest application...')
) {
return false;
}
return true;
}
}
|
// Alert displays a desktop notification and plays a default system sound
func Alert(appName string, title string, text string, iconPath string) {
note := notification(appName, title, text, iconPath)
note.Sound = gosxnotifier.Default
if err := note.Push(); err != nil {
log.Println("ERROR:", err)
}
} |
// This example shows how to implement a command with a "catch all."
//
// This requires writing your own impl for `Decodable` because docopt's
// decoder uses `Option<T>` to mean "T may not be present" rather than
// "T may be present but incorrect."
use std::fmt;
use docopt::Docopt;
use serde::{Deserialize, de::{Deserializer, Error, Visitor}};
// Write the Docopt usage string.
const USAGE: &'static str = "
Rust's package manager
Usage:
mycli [<command>]
Options:
-h, --help Display this message
";
#[derive(Debug, Deserialize)]
struct Args {
arg_command: Command,
}
struct CommandVisitor;
impl<'de> Visitor<'de> for CommandVisitor {
type Value = Command;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a string A, B or C")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where E: Error
{
Ok(match s {
"" => Command::None,
"A" => Command::A,
"B" => Command::B,
"C" => Command::C,
s => Command::Unknown(s.to_string()),
})
}
}
impl<'de> Deserialize<'de> for Command {
fn deserialize<D>(d: D) -> Result<Command, D::Error>
where D: Deserializer<'de>
{
d.deserialize_str(CommandVisitor)
}
}
#[derive(Debug)]
enum Command {
A,
B,
C,
Unknown(String),
None,
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
println!("{:?}", args);
}
|
<reponame>miyanokomiya/gosla2
package lib
import (
"testing"
)
func TestCreatePostText(t *testing.T) {
type fromTo struct {
from EventSummary
to string
}
table := map[string]fromTo{
"case1": fromTo{
from: EventSummary{
RepositoryName: "repo",
Title: "tit",
URL: "url",
Description: "desc",
Comment: "comm",
},
to: "*[repo] tit*\nurl\n> desc\ncomm",
},
"case2": fromTo{
from: EventSummary{
RepositoryName: "repo aaaa",
Title: "tit",
URL: "url",
Description: "desc",
Comment: "comm\naaa\naaaeee",
},
to: "*[repo aaaa] tit*\nurl\n> desc\ncomm\naaa\naaaeee",
},
}
for key, fromTo := range table {
result := CreatePostText(fromTo.from)
if result != fromTo.to {
t.Fatal("failed: "+key, "expect: "+fromTo.to, "actual: "+result)
}
}
}
|
//d(n) which stores the current layer that I have visit now
void BFS(int u)
{
int ans=1;
q.push(u);
visited[u] = true;
p[u] = -1;
while (!q.empty())
{
int v = q.front();
q.pop();
for (int u : adj[v])
if (!visited[u])
{
visited[u] = true;
q.push(u);
++ans;
d[u] = d[v] + 1;
p[u] = v;
}
}
} |
<gh_stars>1-10
{-# LANGUAGE TupleSections, FlexibleContexts, PackageImports #-}
module Data.Pipe.TChan (
fromTChan, toTChan, fromTChans, toTChans, toTChansM) where
import Control.Applicative
import Control.Arrow
import "monads-tf" Control.Monad.Trans
import Control.Monad.Base
import Control.Concurrent.STM
import Data.List
import Data.Pipe
fromTChan :: (PipeClass p, MonadBase IO m,
MonadTrans (p x a), Monad (p x a m)) => TChan a -> p x a m ()
fromTChan c = lift (liftBase . atomically $ readTChan c) >>= yield >> fromTChan c
fromTChans :: (PipeClass p, MonadBase IO m,
MonadTrans (p x a), Monad (p x a m)) => [TChan a] -> p x a m ()
fromTChans cs = do
(cs', x) <- lift . liftBase . atomically $ do
readTChans cs >>= maybe retry return
yield x
fromTChans $ uncurry (flip (++)) cs'
readTChans :: [TChan a] -> STM (Maybe (([TChan a], [TChan a]), a))
readTChans [] = return Nothing
readTChans (c : cs) = do
e <- isEmptyTChan c
if e
then (first (first (c :)) <$>) <$> readTChans cs
else Just . (([c], cs) ,) <$> readTChan c
toTChan :: (PipeClass p, MonadBase IO m,
MonadTrans (p a x), Monad (p a x m)) => TChan a -> p a x m ()
toTChan c = await >>= maybe (return ())
((>> toTChan c) . lift . liftBase . atomically . writeTChan c)
toTChans :: (PipeClass p, MonadBase IO m,
MonadTrans (p (a, b) x), Monad (p (a, b) x m)) =>
[(a -> Bool, TChan b)] -> p (a, b) x m ()
toTChans cs = (await >>=) . maybe (return ()) $ \(t, x) -> (>> toTChans cs) $
case find (($ t) . fst) cs of
Just (_, c)-> lift . liftBase . atomically $ writeTChan c x
_ -> return ()
toTChansM :: (PipeClass p, MonadBase IO m,
MonadTrans (p (a, b) x), Monad (p (a, b) x m)) =>
m [(a -> Bool, TChan b)] -> p (a, b) x m ()
toTChansM mcs = (await >>=) . maybe (return ()) $ \(t, x) -> (>> toTChansM mcs) $ do
cs <- lift mcs
case find (($ t) . fst) cs of
Just (_, c)-> lift . liftBase . atomically $ writeTChan c x
_ -> return ()
|
#pragma once
#include "subsystem/entities/Object.h"
#include "subsystem/entities/Mesh.h"
// TODO: Investigate decoupling Instance from Object, separating
// transformation methods, removing superfluous class members
class Instance : public Object {
public:
~Instance();
void from(Object* reference);
void rehydrate() override {};
}; |
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
class DenoisingAutoencoder(nn.Module):
def __init__(
self,
embedding_dimension: int,
hidden_dimension: int,
activation: Optional[torch.nn.Module] = nn.ReLU(),
gain: float = nn.init.calculate_gain("relu"),
corruption: Optional[torch.nn.Module] = None,
tied: bool = False,
) -> None:
"""
Autoencoder composed of two Linear units with optional encoder activation and corruption.
:param embedding_dimension: embedding dimension, input to the encoder
:param hidden_dimension: hidden dimension, output of the encoder
:param activation: optional activation unit, defaults to nn.ReLU()
:param gain: gain for use in weight initialisation
:param corruption: optional unit to apply to corrupt input during training, defaults to None
:param tied: whether the autoencoder weights are tied, defaults to False
"""
super(DenoisingAutoencoder, self).__init__()
self.embedding_dimension = embedding_dimension
self.hidden_dimension = hidden_dimension
self.activation = activation
self.gain = gain
self.corruption = corruption
# encoder parameters
self.encoder_weight = Parameter(
torch.Tensor(hidden_dimension, embedding_dimension)
)
self.encoder_bias = Parameter(torch.Tensor(hidden_dimension))
self._initialise_weight_bias(self.encoder_weight, self.encoder_bias, self.gain)
# decoder parameters
self._decoder_weight = (
Parameter(torch.Tensor(embedding_dimension, hidden_dimension))
if not tied
else None
)
self.decoder_bias = Parameter(torch.Tensor(embedding_dimension))
self._initialise_weight_bias(self._decoder_weight, self.decoder_bias, self.gain)
@property
def decoder_weight(self):
return (
self._decoder_weight
if self._decoder_weight is not None
else self.encoder_weight.t()
)
@staticmethod
def _initialise_weight_bias(weight: torch.Tensor, bias: torch.Tensor, gain: float):
"""
Initialise the weights in a the Linear layers of the DenoisingAutoencoder.
:param weight: weight Tensor of the Linear layer
:param bias: bias Tensor of the Linear layer
:param gain: gain for use in initialiser
:return: None
"""
if weight is not None:
nn.init.xavier_uniform_(weight, gain)
nn.init.constant_(bias, 0)
def copy_weights(self, encoder: torch.nn.Linear, decoder: torch.nn.Linear) -> None:
"""
Utility method to copy the weights of self into the given encoder and decoder, where
encoder and decoder should be instances of torch.nn.Linear.
:param encoder: encoder Linear unit
:param decoder: decoder Linear unit
:return: None
"""
encoder.weight.data.copy_(self.encoder_weight)
encoder.bias.data.copy_(self.encoder_bias)
decoder.weight.data.copy_(self.decoder_weight)
decoder.bias.data.copy_(self.decoder_bias)
def encode(self, batch: torch.Tensor) -> torch.Tensor:
transformed = F.linear(batch, self.encoder_weight, self.encoder_bias)
if self.activation is not None:
transformed = self.activation(transformed)
if self.corruption is not None:
transformed = self.corruption(transformed)
return transformed
def decode(self, batch: torch.Tensor) -> torch.Tensor:
return F.linear(batch, self.decoder_weight, self.decoder_bias)
def forward(self, batch: torch.Tensor) -> torch.Tensor:
return self.decode(self.encode(batch))
|
<gh_stars>1-10
package skaro.pokeapi.resource;
import skaro.pokeapi.resource.language.Language;
import skaro.pokeapi.resource.versiongroup.VersionGroup;
public class VersionGroupFlavorText {
private String text;
private NamedApiResource<Language> language;
private NamedApiResource<VersionGroup> versionGroup;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public NamedApiResource<Language> getLanguage() {
return language;
}
public void setLanguage(NamedApiResource<Language> language) {
this.language = language;
}
public NamedApiResource<VersionGroup> getVersionGroup() {
return versionGroup;
}
public void setVersionGroup(NamedApiResource<VersionGroup> versionGroup) {
this.versionGroup = versionGroup;
}
}
|
/************************************************************
Copyright (C), 2020, DT9025A
文件名: spi.h
作者: DT9025A
版本: R1.0
日期: 20/7/8
描述: STC系列的硬件/软件SPI驱动程序
部分配置通过unsigned char变量存储, 可能占据额外空间.
若空间紧张可将其通过define替换
本驱动在 [email protected] 和 [email protected]平台试验通过
修订历史:
<作者> <时间> <版本> <描述>
DT9025A 20/4/5 A1.0 编写完成
DT9025A 20/7/8 R1.0 完善文档注释
DT9025A 20/7/9 R1.1 更改一些define为变量, 以适应STC8系列的可变端口
***********************************************************/
#ifndef _SPI_H_
#define _SPI_H_
#include <STC8F.h>
#include <intrins.h>
//判断一下新stc头文件, 这些已经在新头文件内定义
#ifndef __STC8F_H_
#define SPIF 0x80 //SPSTAT.7
#define WCOL 0x40 //SPSTAT.6
#define SSIG 0x80 //SPCTL.7
#define SPEN 0x40 //SPCTL.6
#define DORD 0x20 //SPCTL.5
#define MSTR 0x10 //SPCTL.4
#define CPOL 0x08 //SPCTL.3
#define CPHA 0x04 //SPCTL.2
#define SPDHH 0x00 //CPU_CLK/4
#define SPDH 0x01 //CPU_CLK/16
#define SPDL 0x02 //CPU_CLK/64
#define SPDLL 0x03 //CPU_CLK/128
#endif
//注释该行为模拟SPI, CPOL=0 CPHA=0
#define HARDWARE_SPI
/*******硬件SPI设置*******/
//SPI主机模式, SLAVE需注释
#define MASTER
//主机带SS, 与包括MASTER定义
//#define MASTERWITHSS
//SPI速度 SPDHH, SPDH, SPDL, SPDLL可选
unsigned char _SPI_SPEED = SPDLL;
//CPOL|CPHA = 0|0 = 0
unsigned char _CPx = 0;
//STC8系列需要设置该项, 确定P_SW1的SPI脚位, 取值0-3, 自动移位
unsigned char _SPI_S = 0;
#ifdef MASTERWITHSS
#define MASTER
sbit SPISS = P1 ^ 3; //SPI slave select
#endif
/**************************/
/*******软件SPI设置*******/
sbit SPIMOSI = P1 ^ 3;
sbit SPIMISO = P1 ^ 4;
sbit SPISCLK = P1 ^ 5;
/***********************************************************************
函数名: SPI_Init
描述: 初始化SPI
调用: 无
参数: void
返回值: void
其他说明: 无
/**********************************************************************/
unsigned char SPI_SendByte (unsigned char dat);
/***********************************************************************
函数名: SPI_SendByte
描述: 向SPI总线发送一字节
调用: 无
参数: [unsigned char] dat : 要发送的字节
返回值: [unsigned char] : MISO线上的数据
其他说明: SPI全双工, 接收发送一起进行
/**********************************************************************/
void SPI_Init();
#endif
|
def attrs(self, request):
result = {
'attrs': []
}
kwargs = dict(request.params.items())
for attr in self.obj.attrs(**kwargs):
result['attrs'].append(unclusto(attr))
return dumps(request, result) |
def extract_words(content: str) -> Optional[List[str]]:
junk = 0
fluff = 0
corpus_word = 0
non_corpus_word = 0
total = 0
words = []
tokens = nltk.word_tokenize(content)
if not tokens:
eprint("empty content")
return None
for w in tokens:
total += 1
w = re.sub(r"^[\\\-]+([A-Za-z]+)$", r"\1", w)
w_class = _classify_word(w)
if w_class == "corpus":
corpus_word += 1
words.append(w)
elif w_class == "non-corpus":
non_corpus_word += 1
else:
assert w_class == "none"
if _is_fluff(w):
fluff += 1
else:
eprint(f"junk word '{w}'")
junk += 1
assert len(words) == corpus_word
assert total == corpus_word + fluff + junk + non_corpus_word
if junk / total > 0.3:
eprint("refusing to extract words from content - too much junk")
return None
if corpus_word < 5:
eprint("refusing to extract words from content - too short")
return None
if (prop := corpus_word / (corpus_word + non_corpus_word)) < 0.50:
eprint(
f"refusing to extract words from content - too many words not from the corpus (prop = {prop})")
return None
return words |
/*
* we get here after reading the value in set/add/replace commands. The command
* has been stored in c->item_comm, and the item is ready in c->item.
*/
static void complete_nread(conn* c) {
stats_t *stats = STATS_GET_TLS();
assert(c != NULL);
item *it = c->item;
int comm = c->item_comm;
STATS_LOCK(stats);
stats->set_cmds++;
STATS_UNLOCK(stats);
if (memcmp("\r\n", c->crlf, 2) != 0) {
out_string(c, "CLIENT_ERROR bad data chunk");
} else {
if (store_item(it, comm, c->update_key)) {
out_string(c, "STORED");
} else {
out_string(c, "NOT_STORED");
}
}
item_deref(c->item);
c->item = 0;
} |
package eu.cwsfe.demo;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.Charset;
import java.time.Duration;
import java.util.Base64;
/**
* Sending sms via SmsLabs
*
* @see <a href="https://smslabs.pl/">SmsLabs</a>
* <p>
* Created by <NAME>
*/
public class SmsExample {
public static void main(String[] args) throws IOException, InterruptedException {
sendTestSms();
}
private static void sendTestSms() throws IOException, InterruptedException {
String appKey = "f244...."; //app key z strony
String secretKey = "4d1...."; //secret key z strony
String receiverAddress = "+48111222333"; //numer telefonu z strony
String senderAddress = "SMS TEST"; //nagłówek tekstowy z strony
String msg = "Dzień doberek od Raduś. ĄĘĆŹŃŁÓ 123."; //wysyłana wiadomość
String forEncoding = appKey + ":" + secretKey;
String authToBase64 = Base64.getEncoder().encodeToString(forEncoding.getBytes());
HttpClient client = HttpClient.newBuilder().build();
Charset utf8 = Charset.forName("UTF-8");
String query =
"expiration=0" +
"&phone_number=" + URLEncoder.encode(receiverAddress, utf8) +
"&message=" + URLEncoder.encode(msg, utf8) +
"&sender_id=" + URLEncoder.encode(senderAddress, utf8) +
"&flash=0";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.smslabs.net.pl/apiSms/sendSms/"))
.PUT(HttpRequest.BodyPublishers.ofString(query))
.timeout(Duration.ofSeconds(10))
.header("Authorization", "Basic " + authToBase64)
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("STATUS CODE: " + response.statusCode());
System.out.println("BODY: " + response.body());
}
}
|
Beamforming optimization of wideband MISO systems in the presence of mutual coupling
We introduce a mutual information based optimization for a two-port multiple-input single-output (MISO) antenna system. We develop a complete circuit-level analysis of a compact MISO system in the wideband regime. We design a physically realizable antenna array and study the impact of mutual coupling on the spectral efficiency. Then, we maximize the system’s mutual information by optimizing the beamformer under two different power constraints, namely the total dissipated power and the available power of the amplifiers. By varying the inter-element antenna spacing, we present results for the achievable spectral efficiency under different power amplifier constraints. |
/**
* INTERNAL:
* Append the variable declaration for the type.
*/
public void buildInDeclare(StringBuilder sb, PLSQLargument inArg) {
databaseTypeHelper.declareTarget(sb, inArg, this);
sb.append(" := :");
sb.append(inArg.inIndex);
sb.append(";");
sb.append(NL);
} |
def create_adm_iso_map(countries: list):
adm_iso_map = {}
for feature in countries:
prop = feature['properties']
for key in prop:
prop[key.lower()] = prop.pop(key)
iso = prop['iso_a2']
if iso == '-99':
iso = prop['adm0_a3']
adm = prop['adm0_a3']
if adm in adm_iso_map:
raise ValueError(f'adm exists: {adm}')
adm_iso_map[adm] = iso
adm_iso_map = dict(adm_iso_map, **fix_iso_0_codes)
return adm_iso_map |
<reponame>FLIR/fiftyone<filename>app/src/components/Common/Input.tsx<gh_stars>10-100
import React from "react";
import styled from "styled-components";
import { useTheme } from "../../utils/hooks";
const StyledInputContainer = styled.div`
font-size: 14px;
border-bottom: 1px ${({ theme }) => theme.brand} solid;
position: relative;
margin: 0.5rem 0;
`;
const StyledInput = styled.input`
background-color: transparent;
border: none;
color: ${({ theme }) => theme.font};
height: 2rem;
font-size: 14px;
border: none;
align-items: center;
font-weight: bold;
width: 100%;
&:focus {
border: none;
outline: none;
font-weight: bold;
}
&::placeholder {
color: ${({ theme }) => theme.fontDark};
font-weight: bold;
}
`;
interface InputProps {
color?: string;
placeholder?: string;
validator?: (value: string) => boolean;
setter: (value: string) => void;
value: string;
onEnter?: () => void;
disabled?: boolean;
onFocus?: () => void;
onBlur?: () => void;
onKeyDown?: (event: React.KeyboardEvent<HTMLInputElement>) => void;
}
const Input = React.memo(
({
color = null,
placeholder,
validator = () => true,
setter,
value,
disabled = false,
onEnter,
onFocus,
onBlur,
onKeyDown,
}: InputProps) => {
const theme = useTheme();
color = color ?? theme.brand;
return (
<StyledInputContainer style={{ borderBottom: `1px solid ${color}` }}>
<StyledInput
placeholder={placeholder}
value={value === null ? "" : String(value)}
onChange={(e: React.FormEvent<HTMLInputElement>) => {
if (validator(e.currentTarget.value)) {
setter(e.currentTarget.value);
}
}}
onKeyPress={(e: React.KeyboardEvent<HTMLInputElement>) => {
e.key === "Enter" && onEnter && onEnter();
}}
onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => {
onKeyDown && onKeyDown(e);
}}
style={disabled ? { color: theme.fontDark } : {}}
disabled={disabled}
onFocus={onFocus}
onBlur={onBlur}
/>
</StyledInputContainer>
);
}
);
export default Input;
|
def _choose_float_dtype(dtype, has_offset):
if dtype.itemsize <= 4 and np.issubdtype(dtype, np.floating):
return np.float32
if dtype.itemsize <= 2 and np.issubdtype(dtype, np.integer):
if not has_offset:
return np.float32
return np.float64 |
// FIXME: We shouldn't need to take selectionForInsertion. It should be identical to FrameSelection's current selection.
void TypingCommand::insertText(Document& document, const String& text, const VisibleSelection& selectionForInsertion, Options options, TextCompositionType compositionType)
{
LOG(Editing, "TypingCommand::insertText (text %s)", text.utf8().data());
VisibleSelection currentSelection = document.selection().selection();
String newText = dispatchBeforeTextInsertedEvent(text, selectionForInsertion, compositionType == TextCompositionPending);
if (RefPtr<TypingCommand> lastTypingCommand = lastTypingCommandIfStillOpenForTyping(document)) {
if (lastTypingCommand->endingSelection() != selectionForInsertion) {
lastTypingCommand->setStartingSelection(selectionForInsertion);
lastTypingCommand->setEndingSelection(selectionForInsertion);
}
lastTypingCommand->setIsAutocompletion(options & IsAutocompletion);
lastTypingCommand->setCompositionType(compositionType);
lastTypingCommand->setShouldRetainAutocorrectionIndicator(options & RetainAutocorrectionIndicator);
lastTypingCommand->setShouldPreventSpellChecking(options & PreventSpellChecking);
lastTypingCommand->insertTextAndNotifyAccessibility(newText, options & SelectInsertedText);
return;
}
auto cmd = TypingCommand::create(document, InsertText, newText, options, compositionType);
applyTextInsertionCommand(document.frame(), cmd.get(), selectionForInsertion, currentSelection);
} |
import * as cdk from '@aws-cdk/core';
import * as kms from '@aws-cdk/aws-kms';
import { SopsSecretsManager } from './sops-secrets-cdk-dev';
export class SopsExampleStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
new SopsSecretsManager(this, 'TestSops', {
path: '../sample_secret.yaml',
kmsKey: new kms.Key(this, 'key'),
mappings: {
'fgr-kanbber-key1': {
path: ['key1'],
},
'fgr-kanbber-key2': {
path: ['key2'],
},
},
fileType: 'yaml',
});
}
}
|
def run(data_dict: dict, algo: Union['viterbi', 'map'], K: int, seed: int, lengths: Optional[int],
D: Optional[int], N_iter: int = 1000, reps: int = 20, where: str = 'colab', data: str = 'dummy',
**kwargs):
X = data_dict['train_data']
if where == 'colab':
from tqdm.notebook import tqdm
else:
from tqdm import tqdm
torch.manual_seed(seed)
np.random.seed(seed)
min_neg_loglik = 1e10
Ls = np.tile(np.nan, (reps, N_iter))
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
for r in tqdm(range(reps)):
temperr = io.StringIO()
sys.stderr = temperr
model = hmm.GaussianHMM(K, "full", n_iter=N_iter, tol=1e-20,
verbose=True, algorithm=algo, init_params='')
model = utils.fill_hmmlearn_params(model, *utils.init_params(
K, D, X=X, par={'dtype': torch.float64}, perturb=True), device)
_ = model.fit(X, lengths)
contents = temperr.getvalue()
temperr.close()
Lr = [ float(contents.split()[i])
for i in range(1, len(contents.split()), 3) ]
Lr = [ -lr / len(lengths) for lr in Lr ]
actual_iters = len(Lr)
Lr += [np.nan] * (N_iter - actual_iters)
Ls[r, :] = Lr
sys.stderr = sys.__stderr__
min_neg_loglik = min(Lr + [min_neg_loglik])
if min_neg_loglik in Lr:
best_model = model
log_t0 = (torch.tensor(best_model.startprob_, dtype=torch.float64) + 1e-20).log()
log_T = (torch.tensor(best_model.transmat_, dtype=torch.float64) + 1e-20).log().T
M = best_model.means_.T
Cov = best_model.covars_
_, state_probabilities = best_model.score_samples(X, lengths=lengths)
return {'log_likelihood': Ls,
'log_T': log_T,
'log_t0': log_t0,
'M': M,
'covariances': Cov,
'state_probabilities': state_probabilities} |
#!/usr/bin/env python3.6
import argparse
from tino.gitlab_parser.stage_jobs import get_stage_jobs
from tino.gitlab_parser.stages import get_stages
def format_options(options):
return ' '.join(options)
parser = argparse.ArgumentParser()
parser.add_argument("cmd", help="stages, stage-jobs, job")
parser.add_argument("-stage", help="the stage to query")
args = parser.parse_args()
if args.cmd == "stages":
print(format_options(get_stages()))
elif args.cmd == "stage-jobs":
if args.stage is None:
parser.error("stage-jobs requires -stage")
print(format_options(get_stage_jobs(args.stage)))
|
import os, sys
import numpy as np
from . import Parameters
import matplotlib.pyplot as plt
def convert_2_txt(file_path):
"""Identifies if file needs to be converted to txt"""
if (file_path.find(".txt") < 0):
new_path = file_path + ".txt"
os.rename(file_path, new_path)
file_path = new_path
return file_path
def add_data_columns(file_path, chord, theta, h, cutoff):
"""Check to see if new columns of rotated data have been added and add if needed"""
file_object = open(file_path,"r")
headers = file_object.readline()
variable_names = np.array(headers.replace(",", " ").replace("_","-").strip().split())
var_count = len(variable_names)
x_wallshear_col = np.where(variable_names == "x-wall-shear")
y_wallshear_col = np.where(variable_names == "y-wall-shear")
if (headers.find("x-rotated")<0):
#If this header column does not exist, it means the data has not yet been processed
c, s= np.cos(theta), np.sin(theta)
R = np.array(((c, -s), (s, c)))
data = np.empty((0,var_count+3))
variable_names = [np.append(variable_names, np.array(['x-rotated', 'y-rotated', 'calculated-wallshear']))]
data = variable_names
for line in file_object:
# Get data from each line and calculate the rotated position
cols = np.array([float(i) for i in line.replace(","," ").strip().split()])
cols[2] = cols[2] - h
xyR = np.dot(R, cols[1:3]) + [chord/2, 0]
# Filter to only collect data for the leading edge of the correct surface
top_bottom = int(1 if xyR[1] > 0 else -1)
frontal_region = int(1 if xyR[0] < cutoff *chord else -1)
if top_bottom*theta > 0 and frontal_region == 1:
wallshear = cols[x_wallshear_col]*np.cos(theta)-cols[y_wallshear_col]*np.sin(theta)
cols = np.concatenate((cols, xyR, wallshear))
data = np.append(data, [cols], axis=0)
x_rotated_col = var_count
# Sort data
set_data = data[1:,:].astype(float)
sorted_data = set_data[set_data[:, var_count].argsort()]
final_data = np.append(variable_names, sorted_data, axis=0)
else:
final_data = [np.array(variable_names)]
x_rotated_col = int(np.where(variable_names == "x-rotated")[0])
for line in file_object:
cols = np.array([float(i) for i in line.replace(","," ").strip().split()])
# Filter to only collect data for the leading edge of the correct surface
top_bottom = int(1 if cols[-2] > 0 else -1)
frontal_region = int(1 if cols[-3] < cutoff *chord else -1)
if top_bottom*theta > 0 and frontal_region == 1:
final_data = np.append(final_data, [cols], axis=0)
file_object.close()
return final_data
def wallshearData(Files, FoilDyn, FoilGeo, cutoff =0.2):
"""Go into wall shear folder and process raw data"""
data_path = Files.data_path
if Files.org_path == 'None':
savePath = Files.folder_path+"\\_mod-"
else:
savePath = Files.org_path + "\\" + FoilGeo.geo_name + "-" + "{:.2f}".format(FoilDyn.reduced_frequency).replace(".","") + "-"
file_names = [f for f in os.listdir(data_path) if os.path.isfile(os.path.join(data_path, f))]
file_names = list(filter(lambda x:(x.find("les") >= 0 or x.find("wall") >= 0 or x.find(FoilGeo.geo_name) >= 0), file_names))
if data_path == os.path.dirname(os.path.realpath(__file__)) + r"\Tests\Assets":
FoilDyn.update_totalCycles(2,0)
modfiles = list(filter(lambda x:(x.find("mod-") >= 0), file_names))
for x in modfiles:
os.remove(data_path+"\\"+x)
file_names = [f for f in os.listdir(data_path) if os.path.isfile(os.path.join(data_path, f))]
file_names = list(filter(lambda x:(x.find("les") >= 0 or x.find("wall") >0 or x.find(FoilGeo.geo_name) >= 0), file_names))
temp_database = np.empty([0,3])
ct = 0
file_names = sorted(file_names)
last_time_step = int(file_names[-1].split('-')[-1].split('.')[0])
if last_time_step > round(last_time_step, -3):
start_time_step = round(last_time_step, -3)
else:
start_time_step = round(last_time_step, -3) - 1000
for x in range(len(file_names)):
file_path = convert_2_txt(data_path+"\\"+file_names[x])
time_step = int(file_names[x].split('-')[-1].split('.')[0])
if time_step > start_time_step and round(FoilDyn.theta[time_step],3) != 0: # and time_step % 10 == 0:
final_data = add_data_columns(file_path, FoilDyn.chord, FoilDyn.theta[time_step], FoilDyn.h[time_step], cutoff)
np.savetxt(savePath + str(time_step) + '.txt', final_data[:-1,:], fmt="%s")
final_data = final_data[1:,:].astype(float)
processed_data = np.transpose(np.append([final_data[:,-3]], [final_data[:,-1]], axis=0))
processed_data2 = np.append(processed_data, np.full((processed_data.shape[0],1), time_step).astype(int) , axis=1)
temp_database = np.append(temp_database, processed_data2, axis=0)
x_data = processed_data[1:,-2].astype(float)/FoilDyn.chord
wallshear = processed_data[1:,-1].astype(float)
if np.min(wallshear) < 0 and wallshear[0] > 0 and ct < 4:
if ct == 0:
shed_time = time_step
shed_x = x_data
shed_wallshear = wallshear
x_wallshear = shed_x[np.argmin(wallshear)]
ct = ct + 1
elif ct == 4:
ct = 10
fig, axs = plt.subplots(3)
print("Output Results:\nVortex is shed at time step = %s \nVortex Position = %s" % (shed_time,x_wallshear))
desired_steps = np.unique(temp_database[:,-1]).astype(int)[-9:]
temp_set = np.empty([0,3])
filtered_data = np.empty([0,3])
for step in desired_steps:
filtered_data = temp_database[temp_database[:,-1]==step,:]
axs[0].plot(filtered_data[:,0]/FoilDyn.chord,filtered_data[:,1], label = step)
temp_x = temp_database[temp_database[:, -1] == step,:][np.argmin(temp_database[temp_database[:, -1] == step,1]),0]
temp_ws = np.min(temp_database[temp_database[:, -1] == step,1])
temp_set = np.append(temp_set, [[step, temp_x, temp_ws]], axis=0)
axs[1].plot(temp_set[:,0], temp_set[:,2])
axs[2].plot(temp_set[:,0], temp_set[:,1]/FoilDyn.chord)
axs[0].legend()
axs[0].grid()
axs[1].grid()
axs[2].grid()
fig.suptitle("k = " + str(FoilDyn.reduced_frequency))
axs[0].set(xlabel='x position along the chord, [x/C]', ylabel='Wall Shear')
axs[1].set(xlabel='time step [s]', ylabel='Wall Shear')
axs[2].set(xlabel='time step [s]', ylabel='x position along the chord, [x/C]')
if Parameters.specialCase() == False:
print("Exit plots to end procedure")
plt.show()
try:
shed_time
except NameError:
shed_time = 0
x_wallshear = -1
print("Vortex has not shed within the simulated time line.")
return shed_time, x_wallshear
|
export const assertNotUndefined: (value: unknown, rationale: string) => asserts value = (value, rationale) => {
if (value === undefined) {
throw new Error(`value unexpectedly undefined - rationale was ${rationale}`)
}
}
|
Predictors of transitions across stages of alcohol use and disorders in an adult population with heterogeneous ethnic restrictions regarding drinking.
AIMS
To disaggregate associations with alcohol use disorder relative to those with early alcohol use stages in an adult population. We estimated prevalence rates and sociodemographic correlates for the opportunity to drink and transitions into lifetime alcohol use, regular use, and alcohol use disorder.
DESIGN
A retrospective, cross-sectional population survey within a family panel study.
SETTING
Chitwan in Nepal, an ethnically diverse setting with heterogeneous ethnic restrictions regarding alcohol.
PARTICIPANTS
10,714 individuals aged 15 to 59 (response rate=93%).
MEASUREMENTS
The Nepal-specific Composite International Diagnostic Interview assessed lifetime alcohol use opportunity, any use, regular use, disorder, and sociodemographic characteristics.
FINDINGS
Seventy percent of the population had the opportunity to drink, 38% had lifetime alcohol use, 32% had regular alcohol use, and 6% developed an alcohol use disorder. Compared with high caste Hindus, all other ethnicities had greater odds of early stage transitions (Odds ratios (OR) ranged from 1.3 to 2.0 ), but not of development of disorder. Male sex was associated with greater odds of all transitions, from opportunity (OR=5.7; ) to development of disorder (OR=2.0; ). The youngest cohort had higher odds of all transitions, from opportunity (OR=4.9; ) to development of disorder (OR=9.3; ). Higher education was associated with lower odds of all transitions except opportunity (from use (OR=0.8; ) to the development of disorder (OR=0.7; ).
CONCLUSIONS
The prevalence of lifetime alcohol use among adults in Nepal appears to be low, but the overall prevalence of disorder is similar to other countries. Sociodemographic correlates of early alcohol use transitions differ from those associated with later transitions; while sex and age cohort were associated with all transitions, ethnicity was associated with early transitions (opportunity, lifetime use, regular use), but not later transitions (use and regular use to disorder). |
export = Scratch3MotionBlocks;
declare class Scratch3MotionBlocks {
constructor(runtime: any);
/**
* The runtime instantiating this block package.
* @type {Runtime}
*/
runtime: any;
/**
* Retrieve the block primitives implemented by this package.
* @return {object.<string, Function>} Mapping of opcode to Function.
*/
getPrimitives(): any;
getMonitored(): {
motion_xposition: {
isSpriteSpecific: boolean;
getId: (targetId: any) => string;
};
motion_yposition: {
isSpriteSpecific: boolean;
getId: (targetId: any) => string;
};
motion_direction: {
isSpriteSpecific: boolean;
getId: (targetId: any) => string;
};
};
moveSteps(args: any, util: any): void;
goToXY(args: any, util: any): void;
getTargetXY(targetName: any, util: any): number[];
goTo(args: any, util: any): void;
turnRight(args: any, util: any): void;
turnLeft(args: any, util: any): void;
pointInDirection(args: any, util: any): void;
pointTowards(args: any, util: any): void;
glide(args: any, util: any): void;
glideTo(args: any, util: any): void;
ifOnEdgeBounce(args: any, util: any): void;
setRotationStyle(args: any, util: any): void;
changeX(args: any, util: any): void;
setX(args: any, util: any): void;
changeY(args: any, util: any): void;
setY(args: any, util: any): void;
getX(args: any, util: any): any;
getY(args: any, util: any): any;
getDirection(args: any, util: any): any;
limitPrecision(coordinate: any): any;
}
|
Image copyright AP Image caption Anti-austerity protesters traditionally gather in Syntagma Square in front of the Greek parliament
Eurozone ministers have signed off the next 8.3bn euro (£6.8bn; $11.4bn) instalment of Greece's bailout.
A first tranche of 6.3bn euros will be paid at the end of April, Eurogroup chairman Jeroen Dijsselbloem said at a meeting of finance ministers in Athens.
Two more payments of 1bn euros will be made in June and July, he added.
Ahead of the meeting, demonstrators were barred from parts of Athens including Syntagma Square, the focus of recent anti-austerity protests.
Greece, the current chair of the EU presidency, continues to struggle with high debt and unemployment.
Discussions at Tuesday and Wednesday's meetings include Greece's austerity programme and market reforms demanded under the terms of its international bailouts.
Renewed confidence
The latest bailout is one of the last Greece will get from the eurozone. The International Monetary Fund will continue to pay its instalments for some months.
It comes after the Greek parliament narrowly passed a raft of reforms, mainly to open up retail sectors to competition.
Image copyright AP Image caption Many people in Greece have felt the effects of spending cuts
The BBC's Mark Lowen in Athens says the latest bailout announcement comes amid renewed optimism about Greece's economic recovery.
Greece has wiped out its deficit, except for interest on its debt, and is forecast to exit six years of recession this year.
Athens hopes the progress will spur the Eurozone to consider debt relief in the coming months, by lowering the interest rate on its loans or extending the repayment period, our correspondent adds.
But unions and left-wing groups have called for mass protests on Tuesday.
They say people are still suffering under the austerity measures implemented under the bailout terms.
Unemployment is running at 27%, and many Greeks are still feeling the effects of tax rises and spending cuts.
It is unclear whether protesters will attempt to enter prohibited areas and try to reach Syntagma Square.
Athens has enforced protests bans in the past, including when German Chancellor Angela Merkel made high-profile visits. |
#include "stm32f0xx_hal.h"
#include "ds18b20.h"
#include "my_1wire.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "delay_us.h"
#include "cmsis_os.h"
#define SPAD_SIZE 9
uint8_t ds18b20_buf[SPAD_SIZE];
void ds18b20_start_conversion(void)
{
taskENTER_CRITICAL();
my_1wire_reset();
my_1wire_write_byte(0xcc);
my_1wire_write_byte(0x44);
taskEXIT_CRITICAL();
}
int16_t ds18b20_get_temp(void)
{
taskENTER_CRITICAL();
my_1wire_reset();
my_1wire_write_byte(0xcc);
my_1wire_write_byte(0xbe);
my_1wire_read_bytes(ds18b20_buf, SPAD_SIZE);
taskEXIT_CRITICAL();
return ds18b20_buf[0] | ds18b20_buf[1] << 8;
}
|
def remove_collider(self, collider: type) -> None:
if collider in self.colliders:
self.colliders.remove(collider) |
Story highlights Jane Sanders was president of the college from 2004-2011
The school closed last year and there is a reported investigation into it
Washington (CNN) Sen. Bernie Sanders on Tuesday defended his wife, Jane Sanders, amid reports of a potential federal investigation related to her time helming the now-defunct Burlington College.
Sanders declined when asked on CNN's "Erin Burnett OutFront" to say whether or not his wife was under investigation by the FBI.
"My wife is about the most honest person I know," Sanders said.
Sanders' former campaign manager, Jeff Weaver, confirmed Jane Sanders has hired lawyer Larry Robbins to represent her in the possible probe. Weaver said the FBI had not contacted either Jane or Bernie Sanders in connection to any such investigation. A person close to the senator said Sanders was represented by Rich Cassidy, a longtime lawyer for the family.
Both the FBI field office in Albany, New York and the US Attorney's Office in Vermont would not comment, and the Justice Department has not yet responded to a request for comment on the matter.
Read More |
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
zc_args: dict = {"ip_version": IPVersion.V4Only}
adapters = await network.async_get_adapters(hass)
ipv6 = False
if _async_zc_has_functional_dual_stack():
if any(adapter["enabled"] and adapter["ipv6"] for adapter in adapters):
ipv6 = True
zc_args["ip_version"] = IPVersion.All
elif not any(adapter["enabled"] and adapter["ipv4"] for adapter in adapters):
zc_args["ip_version"] = IPVersion.V6Only
ipv6 = True
if not ipv6 and network.async_only_default_interface_enabled(adapters):
zc_args["interfaces"] = InterfaceChoice.Default
else:
zc_args["interfaces"] = [
str(source_ip)
for source_ip in await network.async_get_enabled_source_ips(hass)
if not source_ip.is_loopback
and not (isinstance(source_ip, IPv6Address) and source_ip.is_global)
and not (
isinstance(source_ip, IPv6Address)
and zc_args["ip_version"] == IPVersion.V4Only
)
and not (
isinstance(source_ip, IPv4Address)
and zc_args["ip_version"] == IPVersion.V6Only
)
]
aio_zc = await _async_get_instance(hass, **zc_args)
zeroconf = cast(HaZeroconf, aio_zc.zeroconf)
zeroconf_types, homekit_models = await asyncio.gather(
async_get_zeroconf(hass), async_get_homekit(hass)
)
discovery = ZeroconfDiscovery(hass, zeroconf, zeroconf_types, homekit_models, ipv6)
await discovery.async_setup()
async def _async_zeroconf_hass_start(_event: Event) -> None:
uuid = await instance_id.async_get(hass)
await _async_register_hass_zc_service(hass, aio_zc, uuid)
async def _async_zeroconf_hass_stop(_event: Event) -> None:
await discovery.async_stop()
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_zeroconf_hass_stop)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _async_zeroconf_hass_start)
return True |
/**
* This is the obstacle command which gives damage to any attacker that goes over it
*/
public class DamageObstacleCommand extends ObstacleCommand implements BackEndCommand {
public DamageObstacleCommand(Obstacle damageObstacle) {
super(damageObstacle);
}
@Override
protected void damageTarget(LevelController level, int id) {
if(!((DamageObstacle)getObstacle()).getAttackers().contains(id)) {
DamageElementCommand command = new DamageElementCommand((Attacker) level.getActiveElements().get(id), ((DamageObstacle) getObstacle()).getDamage());
command.execute(level);
}
((DamageObstacle)getObstacle()).getAttackers().add(id);
}
} |
def grad(self):
if has_torch_function_unary(self):
return handle_torch_function(Tensor.grad.__get__, (self,), self)
return self._grad |
// CacheRoot returns the root for caching - it removes any leading path segments
// from a provided path, leaving just the relative path under the registry name.
// Example:
// uri: github.com/ksonnet/parts/tree/master/long/path/incubator
// path: long/path/incubator/parts.yaml
// output: incubator/parts.yaml
func (gh *GitHub) CacheRoot(name, path string) (string, error) {
if gh == nil {
return "", errors.Errorf("nil receiver")
}
if gh.hd == nil {
return "", errors.Errorf("registry %v not correctly initialized - missing hubDescriptor", gh.name)
}
root := gh.hd.regRepoPath
rebasedAbs := strings.TrimPrefix(strings.TrimPrefix(path, "/"), root)
rebased := strings.TrimPrefix(rebasedAbs, "/")
return filepath.Join(name, rebased), nil
} |
def _GetFirefoxConfig(self, file_object, display_name):
to_read = min(file_object.get_size(), self._INITIAL_CACHE_FILE_SIZE)
while file_object.get_offset() < to_read:
offset = file_object.get_offset()
try:
cache_record_header, _ = self._ReadCacheEntry(
file_object, display_name, self._MINUMUM_BLOCK_SIZE)
record_size = (
self._CACHE_RECORD_HEADER_SIZE +
cache_record_header.request_size +
cache_record_header.info_size)
if record_size >= 4096:
block_size = 4096
elif record_size >= 1024:
block_size = 1024
else:
block_size = 256
return self.FIREFOX_CACHE_CONFIG(block_size, offset)
except IOError:
logging.debug('[{0:s}] {1:s}:{2:d}: Invalid record.'.format(
self.NAME, display_name, offset))
raise errors.UnableToParseFile(
'Could not find a valid cache record. Not a Firefox cache file.') |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root)
{
vector<TreeNode*> stk;
TreeNode *p = root;
vector<int> lst;
while(p!=nullptr || !stk.empty())
{
while(p != nullptr)
{
stk.push_back(p);
p = p->left;
}
if(!stk.empty())
{
p = stk[stk.size()-1];
stk.pop_back();
lst.push_back(p->val);
p = p->right;
}
}
return lst;
}
vector<TreeNode*> generateTrees(int n)
{
}
} |
def create_cloned_volume(self, volume, src_vref):
(_data, _sfaccount, model) = self._do_clone_volume(
src_vref['id'],
src_vref['project_id'],
volume)
return model |
Globalists Wage War on Free Speech and the Press
Linda West
Infowars.com
September 5, 2012
Despite legal battles raging over 10 years and a noticeable lack of terrorist activity in that time, the LAPD is moving ahead as the first police department in the U.S. to implement Special Order 1, a policy which will allow the police to detain and arrest you if you are taking photos or videotaping certain buildings deemed by them as “suspicious activity”. The problem being of course – what exactly is considered suspicious activity?
Take for instance the innocent man Greggory Moore who was confronted for shooting pictures on his front lawn just because it happened to have the court house in the background. Eight policemen were called by “good citizen spies” to confront and interrogate him while he was held with his hands behind his back then patted down. Other photographers have experienced similar heinous police behavior and even been threatened with being put on the FBI watch list for taking pictures at the airport.
This new police policy will make such instances more common, as they clearly put photography itself under suspicion. It reads:
The National Press Photographers Association (NPPA) wrote a letter to the sheriff’s department. “It is one thing for law enforcement to act when there is probable cause,” said Mickey H Osterricher, the association’s general counsel. “It is quite another to abuse that discretion in order to create a climate that chills free speech under the pretext of safety and security.”
LA Sheriff Leroy Baca said, “While taking pictures in itself is not a crime, in our heightened state of national security, a courthouse is a Homeland Security hard target, and as such, supplemental security precautions are in place. We would be remiss in our professional duties if we did not investigate all incidents which appear to be suspicious.”
When asked by an Infowars reporter about the new policy, the commanding officer at LAPD responded, “You really only have to be careful about airports and filming TSA– you can’t do that.” When asked if it was still “legal” to film police on duty doing such despicable things as hitting defenseless protesters, etc., he confirmed that, “Yes you can still video that.”
Despite the commanding officer’s reply, according to the law it is perfectly legal to film TSA agents and the airport.
Chief Michael Downing, in charge of the Department of Counter-Terrorism and Special Operations Bureau, declared this to be absolutely necessary, claiming that terror cells are active in L.A. right now. However, there has been no evidence offered up to actually support this claim. What is certain, is that now even animal rights groups have been added to the “terrorist watch list along with veterans and preppers.”
In any case the über open ended “suspicious” action could practically account for anything the police deem it to, as witnessed by the innocent man that was hassled on his own front lawn.
The most troubling aspect, beside the complete slaughter of the first amendment, is that DHS and other Federal agencies are given grants and special funding for their agreement to participate in specific Homeland Security programs – just like this.
The larger question remains – just what are we willing to give up in the name of supposed “protection”? And is a police state that attacks you on your own front lawn something we are willing to live with in the name of safety? Another shocking signpost on the road to total tyranny and proof the globalist occupying this country have declared war on free speech and the press.
LAPD Terror Policy |
<reponame>reesretuta/dropshipping-icons
export declare const cisMinusCircle: string[]; |
#!/usr/bin/env python3
import os
import sys
import deepzoom
# Only if input is trusted
deepzoom.PIL.Image.MAX_IMAGE_PIXELS = None
def generate_dzi(source_image_path, output_dzi_path):
# Create Deep Zoom Image creator with weird parameters
creator = deepzoom.ImageCreator(
tile_size=512,
tile_overlap=1,
tile_format="jpg",
image_quality=0.8,
resize_filter=None,
)
# Create Deep Zoom image pyramid from source
creator.create(source_image_path, output_dzi_path)
# output must be a .dzi file
if (len(sys.argv) == 3):
generate_dzi(sys.argv[1], sys.argv[2])
|
package util
import (
"fmt"
"github.com/drud/ddev/pkg/globalconfig"
"github.com/drud/ddev/pkg/nodeps"
"github.com/sirupsen/logrus"
"math/rand"
osexec "os/exec"
"os/user"
"runtime"
"strings"
"time"
"github.com/drud/ddev/pkg/output"
"github.com/fatih/color"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
// Failed will print a red error message and exit with failure.
func Failed(format string, a ...interface{}) {
if a != nil {
//output.UserOut.Fatalf(format, a...)
output.UserErr.Fatalf(format, a...)
//output.UserOut.WithField("level", "fatal").Fatalf(format, a...)
} else {
output.UserErr.Fatal(format)
//output.UserOut.WithField("level", "fatal").Fatal(format)
}
}
// Error will print an red error message but will not exit.
func Error(format string, a ...interface{}) {
if a != nil {
output.UserErr.Errorf(format, a...)
} else {
output.UserErr.Error(format)
}
}
// Warning will present the user with warning text.
func Warning(format string, a ...interface{}) {
if a != nil {
output.UserErr.Warnf(format, a...)
} else {
output.UserErr.Warn(format)
}
}
// Success will indicate an operation succeeded with colored confirmation text.
func Success(format string, a ...interface{}) {
format = color.CyanString(format)
if a != nil {
output.UserOut.Infof(format, a...)
} else {
output.UserOut.Info(format)
}
}
// FormatPlural is a simple wrapper which returns different strings based on the count value.
func FormatPlural(count int, single string, plural string) string {
if count == 1 {
return single
}
return plural
}
var letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
// SetLetterBytes exists solely so that tests can override the default characters used by
// RandString. It should probably be avoided for 'normal' operations.
// this is actually used in utils_test.go (test only) so we set nolint on it.
// nolint: deadcode
func SetLetterBytes(lb string) {
letterBytes = lb
}
// RandString returns a random string of given length n.
func RandString(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
// AskForConfirmation requests a y/n from user.
func AskForConfirmation() bool {
response := GetInput("")
okayResponses := []string{"y", "yes"}
nokayResponses := []string{"n", "no", ""}
responseLower := strings.ToLower(response)
if nodeps.ArrayContainsString(okayResponses, responseLower) {
return true
} else if nodeps.ArrayContainsString(nokayResponses, responseLower) {
return false
} else {
output.UserOut.Println("Please type yes or no and then press enter:")
return AskForConfirmation()
}
}
// MapKeysToArray takes the keys of the map and turns them into a string array
func MapKeysToArray(mapWithKeys map[string]interface{}) []string {
result := make([]string, 0, len(mapWithKeys))
for v := range mapWithKeys {
result = append(result, v)
}
return result
}
// GetContainerUIDGid() returns the uid and gid (and string forms) to be used running most containers.
func GetContainerUIDGid() (uidStr string, gidStr string, username string) {
curUser, err := user.Current()
CheckErr(err)
uidStr = curUser.Uid
gidStr = curUser.Gid
username = curUser.Username
//// Windows userids are non numeric,
//// so we have to run as arbitrary user 1000. We may have a host uidStr/gidStr greater in other contexts,
//// 1000 seems not to cause file permissions issues at least on docker-for-windows.
if runtime.GOOS == "windows" {
uidStr = "1000"
gidStr = "1000"
parts := strings.Split(curUser.Username, `\`)
username = parts[len(parts)-1]
username = strings.ReplaceAll(username, " ", "")
username = strings.ToLower(username)
}
return uidStr, gidStr, username
}
// IsCommandAvailable uses shell's "command" to find out if a command is available
// https://siongui.github.io/2018/03/16/go-check-if-command-exists/
// This lives here instead of in fileutil to avoid unecessary import cycles.
func IsCommandAvailable(cmdName string) bool {
_, err := osexec.LookPath(cmdName)
if err == nil {
return true
}
return false
}
// GetFirstWord just returns the first space-separated word in a string.
func GetFirstWord(s string) string {
arr := strings.Split(s, " ")
return arr[0]
}
// On Windows we'll need the path to bash to execute anything.
// Returns empty string if not found, path if found
func FindWindowsBashPath() string {
windowsBashPath, err := osexec.LookPath(`C:\Program Files\Git\bin\bash.exe`)
if err != nil {
// This one could come back with the WSL bash, in which case we may have some trouble.
windowsBashPath, err = osexec.LookPath("bash.exe")
if err != nil {
fmt.Println("Not loading custom commands; bash is not in PATH")
return ""
}
}
return windowsBashPath
}
// TimeTrack determines the amount of time a function takes to return. Timing starts when it is called.
// It returns an anonymous function that, when called, will print the elapsed run time.
// It tracks if DDEV_VERBOSE is set
func TimeTrack(start time.Time, name string) func() {
if globalconfig.DdevVerbose {
logrus.Printf("starting %s at %v\n", name, start.Format("15:04:05"))
return func() {
if globalconfig.DdevVerbose {
elapsed := time.Since(start)
logrus.Printf("PERF: %s took %.2fs", name, elapsed.Seconds())
}
}
}
return func() {
}
}
|
<reponame>saeedahadian/sample-nestjs-typeorm-mysql<gh_stars>0
import * as Joi from 'joi';
export default Joi.object({
APP_NAME: Joi.string(),
APP_ENV: Joi.string()
.valid('development', 'production', 'test', 'provision')
.default('development'),
APP_HOST: Joi.string().hostname().default('http://127.0.0.1:3000'),
APP_PORT: Joi.number().port().default(3000),
});
|
<gh_stars>10-100
package io.opensphere.mantle.data.geom.style;
import io.opensphere.mantle.data.DataTypeInfo;
import io.opensphere.mantle.data.element.MetaDataProvider;
import io.opensphere.mantle.data.element.VisualizationState;
import io.opensphere.mantle.data.geom.MapGeometrySupport;
/**
* The Interface FeatureIndividualGeometryBuilderData.
*
* Provides data for individual geometries that are built by
* {@link FeatureVisualizationStyle}s.
*/
public interface FeatureIndividualGeometryBuilderData
{
/**
* Gets the {@link DataTypeInfo}.
*
* @return the data type
*/
DataTypeInfo getDataType();
/**
* Gets the element id.
*
* @return the element id
*/
long getElementId();
/**
* Gets the geometry id.
*
* @return the geometry id
*/
long getGeomId();
/**
* Gets the {@link MetaDataProvider}.
*
* @return the {@link MetaDataProvider}
*/
MetaDataProvider getMDP();
/**
* Gets the {@link MapGeometrySupport}.
*
* @return the {@link MapGeometrySupport}
*/
MapGeometrySupport getMGS();
/**
* Gets the {@link VisualizationState}.
*
* @return the {@link VisualizationState}
*/
VisualizationState getVS();
}
|
<reponame>IISmichinaboy/alps-boot<filename>alps-commons/src/main/java/com/xmi/alps/commons/collect/Collections.java
package com.xmi.alps.commons.collect;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* Collections
*
* @author miwanqiang
* @date 2022/1/7
*/
public class Collections {
/**
* 判断集合是空
* @param collection
* @return
*/
public static <T> boolean isEmpty(Collection<T> collection) {
return collection == null || collection.isEmpty();
}
/**
* 判断集合非空
* @param collection
* @return
*/
public static <T> boolean isNotEmpty(Collection<T> collection) {
return collection == null || collection.isEmpty();
}
/**
* 遍历处理集合
* @param collection
* @param consumer
* @param <T>
*/
public static <T> void foreach(Collection<T> collection, Consumer<? super T> consumer) {
if (isNotEmpty(collection)) {
collection.stream().forEach(consumer);
}
}
/**
* 集合转换成List
* @param collection
* @param <T>
*/
public static <T> List<T> toList(Collection<T> collection) {
if (isNotEmpty(collection)) {
return collection.stream().collect(Collectors.toList());
}
return new ArrayList<T>();
}
}
|
<filename>src/main/java/ynn/mylogo/parser/ast/AbstractStatement.java
package ynn.mylogo.parser.ast;
import ynn.mylogo.parser.Token;
public abstract class AbstractStatement extends AbstractNode {
public AbstractStatement(Token token) {
super(token);
}
}
|
Conceptualization of Conceivable Worlds of a Person in Altered States of Consciousness
The article describes the ways of conceptualizing the conceivable worlds in altered states of mind at the example of the main character’s conceivable world in Chuck Palahniuk's "Fight Club". From the conducted analysis it can be seen that the world of people in altered states of consciousness can expand significantly. This hypertrophied expansion goes along the axis of space and time. This expansion of the mental world goes along with the expansion of the moral and legal boundaries of what is permissible. The main character is trying to change the social order. |
song = input()
def song_decoder(song):
while True:
song = song.replace('WUB', ' ')
if song.find('WUB') == -1:
break
while song.find(' ') is not -1:
song = song.replace(' ', ' ')
return song.strip()
print(song_decoder(song))
|
import { createDecorator } from 'vue-class-component'
export type DebounceOptions =
| number
| {
time: number
}
export function Debounce(options: DebounceOptions): MethodDecorator {
return createDecorator((opts, handler) => {
if (!opts.methods) throw new Error('This decorator must be used on a vue component method.')
const time = typeof options === 'number' ? options : options.time
const originalFn = opts.methods[handler]
let timeoutId = 0
const clear = () => {
if (timeoutId) {
clearTimeout(timeoutId)
timeoutId = 0
}
}
opts.methods[handler] = function(...args: any[]) {
clear()
timeoutId = setTimeout(() => {
timeoutId = 0
originalFn.apply(this, args)
}, time)
}
})
}
|
Variation in susceptibility to benznidazole in isolates derived from Trypanosoma cruzi parental strains.
In this work, the susceptibility to benznidazole of two parental Trypanosoma cruzi strains, Colombian and Berenice-78, was compared to isolates obtained from dogs infected with these strains for several years. In order to evaluate the susceptibility to benznidazole two groups of mice were infected with one of five distinct populations isolated from dogs as well as the two parental strains of T. cruzi. The first group was treated with benznidazole during the acute phase and the second remained untreated controls. The animals were considered cured when parasitological and serological tests remained persistently negative. Mice infected with the Colombian strain and its isolates Colombian (A and B) did not cure after treatment. On the other hand, all animals infected with Berenice-78 were cured by benznidazole treatment. However, 100%, 50% and 70% of cure rates were observed in animals infected with the isolates Berenice-78 B, C and D, respectively. No significant differences were observed in serological profile of infected control groups, with all animals presenting high antibody levels. However, the ELISA test showed differences in serological patterns between mice inoculated with the different T. cruzi isolates and treated with benznidazole. This variability was dependent on the T. cruzi population used and seemed to be associated with the level of resistance to benznidazole. |
import React from 'react';
import axios from 'axios';
import { PreviewRuntime } from '@teambit/preview';
import { ReactAspect, ReactPreview } from '@teambit/react';
import { Aspect } from '@teambit/harmony';
import { ThemeContext } from '@learn-harmony/movies.theme.theme-context';
// import { ApiContextProvider } from '@learn-harmony/movies.context.api-context-provider';
import { MovieApiContextProvider } from '@learn-harmony/movies.movies.context.movies-api-context';
import { MoviesFavouritesContextProvider } from '@learn-harmony/movies.movies.context.movies-favourites-context';
import { WithPreviewReactConfig, WithPreviewReactAspect } from './with-preview-react.aspect';
export class WithPreviewReactPreview {
constructor(private config: WithPreviewReactConfig) {}
/**
* this is how other aspects can now access the runtime's configured values.
*/
getConfigs() {
return this.config;
}
static runtime: any = PreviewRuntime;
static dependencies: Aspect[] = [ReactAspect];
static async provider([react]: [ReactPreview], config: WithPreviewReactConfig) {
const withPreviewReactPreview = new WithPreviewReactPreview(config);
// register a new provider to wrap all compositions in the symphony-react environment.
react.registerProvider([
({ children }) => {
return <MovieApiContextProvider baseUrl={config.baseMoviesUrl} apiKey={config.apiKey}>{children}</ MovieApiContextProvider>
},
({ children }) => {
return <MoviesFavouritesContextProvider >{children}</MoviesFavouritesContextProvider>
},
ThemeContext as any
]);
return withPreviewReactPreview;
}
}
WithPreviewReactAspect.addRuntime(WithPreviewReactPreview);
|
/* initialisation code for the grab-from-grid plugin */
void datgrid_init(void)
{
int i;
if (screen) {
if (SCREEN_H < 400) {
griddle_dlg[0].h = griddle_dlg[0].h * 2/3;
for (i=1; griddle_dlg[i].proc; i++) {
griddle_dlg[i].y = griddle_dlg[i].y * 2/3;
if (griddle_dlg[i].h > 32)
griddle_dlg[i].h -= 8;
}
}
}
sprintf(griddle_xgrid, "%d", get_config_int("grabber", "griddle_xgrid", 32));
sprintf(griddle_ygrid, "%d", get_config_int("grabber", "griddle_ygrid", 32));
if (stricmp(get_config_string("grabber", "griddle_mode", ""), "grid") == 0) {
griddle_dlg[GRIDDLE_DLG_BOXES].flags &= ~D_SELECTED;
griddle_dlg[GRIDDLE_DLG_GRID].flags |= D_SELECTED;
}
else {
griddle_dlg[GRIDDLE_DLG_BOXES].flags |= D_SELECTED;
griddle_dlg[GRIDDLE_DLG_GRID].flags &= ~D_SELECTED;
}
if (strpbrk(get_config_string("grabber", "griddle_empties", ""), "yY1"))
griddle_dlg[GRIDDLE_DLG_EMPTIES].flags |= D_SELECTED;
else
griddle_dlg[GRIDDLE_DLG_EMPTIES].flags &= ~D_SELECTED;
if (strpbrk(get_config_string("grabber", "griddle_autocrop", ""), "yY1"))
griddle_dlg[GRIDDLE_DLG_AUTOCROP].flags |= D_SELECTED;
else
griddle_dlg[GRIDDLE_DLG_AUTOCROP].flags &= ~D_SELECTED;
griddle_dlg[GRIDDLE_DLG_TYPE].d1 = get_config_int("grabber", "griddle_type", 0);
} |
/**
* An object creator that uses methods only found in certain JVMs to create a new constructor if needed.
*
* @deprecated This creator is no longer used and will be removed in a future version.
*/
@Deprecated
public class SunReflectiveCreator extends ReflectiveCreator {
private static SerializableClassRegistry registry = SerializableClassRegistry.getInstanceUnchecked();
/**
* {@inheritDoc} This implementation will attempt to create a new constructor if one is not available.
*/
protected <T> Constructor<T> getNewConstructor(final Class<T> clazz) {
return registry.lookup(clazz).getNoInitConstructor();
}
} |
A Multi-Agent Approach for Personalized Hypertension Risk Prediction
Hypertension is a global health problem and a leading factor in severe and life-threatening cardiovascular diseases (CVD) and stroke. The onset is dependent on individual lifestyle choices, and no single root cause of the condition exists. Various machine learning solutions are proposed for the early diagnosis of hypertension and its prediction, but they are based on standard guidelines and do not provide personalized solutions. Current models mainly rely on batch learning methods and do not readily learn the new incoming data. There is also a lack of an intelligent technique for handling anomalies in data, which leads to unreliable prediction results. In this paper, an integrated multi-agent-based hypertension risk prediction system is proposed that detects and computes missing values in the time series and provides personalized hypertension risk predictions. The proposed solution incorporates Gaussian mixture models for enhancing the input data, and an Online Infinite Echo State Gaussian Process (OIESGP) is used to obtain real-time prediction distribution of blood pressure. The prediction system readily absorbs new incoming data, and the model is updated to learn any new patterns in the data. The hypertension risk score is estimated using the Framingham hypertension risk estimator, and a 4-year hypertension risk is computed. The prediction performance of the proposed model is evaluated on blood pressure data gathered from the Malaysian population using mean absolute error, mean square error, and root-mean-square errors. The experimental results indicate that the proposed prediction model exhibits greater prediction accuracy than existing state-of-the-art online prediction methods. |
/**
* Base StructureDefinition for Duration Type: A length of time.
*/
@DatatypeDef(name="Duration")
public class Duration extends Quantity implements ICompositeType {
private static final long serialVersionUID = 0L;
/**
* Constructor
*/
public Duration() {
super();
}
public String fhirType() {
return "Duration";
}
public Duration copy() {
Duration dst = new Duration();
copyValues(dst);
return dst;
}
public void copyValues(Duration dst) {
super.copyValues(dst);
}
protected Duration typedCopy() {
return copy();
}
} |
<filename>libgeppa/src/main/java/net/cattaka/libgeppa/bluetooth/IBluetoothAdapter.java
package net.cattaka.libgeppa.bluetooth;
import java.util.Set;
public interface IBluetoothAdapter {
public boolean isEnabled();
public Set<IBluetoothDevice> getBondedDevices();
}
|
/**
* plays smoke particles and a sound at player's location for all players.
* levelIn has a sweet spot of 16-19 where fire particles are played.
* @param world Server world
* @param player Server player
* @param levelIn Int representing the amount of smoke to generate. Expects a scale of 0-20 (or higher if you dare)
*/
public static void usePipe(ServerWorld world, ServerPlayerEntity player, int levelIn) {
playPipeEffect(world, player, levelIn);
playPipeUseSound(world, player);
/* Disabled for now.
EffectInstance effect = player.getActivePotionEffect(Effects.RESISTANCE);
if (effect == null) {
effect = new EffectInstance(Effects.RESISTANCE, 0, 1);
}
effect.combine();
*/
if (levelIn >= 5) {
player.addPotionEffect(new EffectInstance(Effects.RESISTANCE, (levelIn / 5) * 4 * 20, 0));
}
} |
PO2 Ryan Casiban went missing Wednesday in the middle of his duty as desk officer. Photos by Jude Torres, ABS-CBN News
CEBU - A police officer of Cordova Police Station has gone missing after tagging retired police generals Marcelo Garbo Jr. and Vicente Loot as members of a drug syndicate.
Police Officer 2 Ryan Casiban left office in the middle of his duty as desk officer around 3 a.m. Wednesday and has not been seen since.
According to PO2 Laurencio, Casiban was supposed to be the desk officer of their police station from 8 p.m. Tuesday until 8 a.m. Wednesday.
Casiban left his post riding his service motorcycle and brought with him an M-16 rifle and the station's mobile phone, which is used as the station's hotline.
Before leaving his post, Casiban tagged police officials in a blotter report.
"Gen. Garbo and Gen. Loot (members of a ) drug syndicate of the Philippines because of big drug money protected by his men (in) PNP organization," Casiban wrote.
The same statement has been recorded earlier in page 153 of the police blotter.
Casiban, likewise, wrote another entry in the police blotter, wherein he said: "I want to write what is justice for all to stop all illegal drugs. God is in me," with his signature.
Casiban's police uniform, the service motorcycle, and the M-16 rifle he brought with him were later found abandoned in a bushy area in Sitio Naga, Barangay Babag II, Lapu-Lapu City.
At around 3:30 a.m., Casiban sent a message to former Cordova Chief of Police, Senior Inspector Zosimo Jabas Jr. In his message, Casiban told Jabas that he is being hunted by a certain Atan Tajanlangit.
Casiban is also asking for Jabas' help as he wants to surrender to President Rodrigo Duterte.
Wagwag, who is also a desk officer, described Casiban as a very silent person. He also does not have any record of involvement in illegal drugs.
Authorities are still searching for Casiban.
Police Regional Director Chief Supt. Noli Taliño, on the other hand, said that they will check if Casiban is suffering from psychological problems.
Garbo and Loot have both been accused by Duterte of protecting drug networks.
READ: Duterte links 5 top cops to drug trade |
/**
* Clear the queue of all queued requests without processing them.
*/
public void clear() {
synchronized (queue) {
queue.clear();
}
} |
<filename>frontend/packages/topology/src/utils/anchor-utils.ts
import Point from '../geom/Point';
const getEllipseAnchorPoint = (
center: Point,
width: number,
height: number,
reference: Point,
): Point => {
const { x, y } = reference;
if (width === 0 || height === 0 || (center.x === x && center.y === y)) {
return center;
}
const dispX = (center.x - x) / (width / 2);
const dispY = (center.y - y) / (height / 2);
const len = Math.sqrt(dispX * dispX + dispY * dispY);
const newLength = len - 1;
const lenProportion = newLength / len;
return new Point((center.x - x) * lenProportion + x, (center.y - y) * lenProportion + y);
};
const getRectAnchorPoint = (
center: Point,
width: number,
height: number,
reference: Point,
): Point => {
let dx = reference.x - center.x;
let dy = reference.y - center.y;
if ((dx === 0 && dy === 0) || (width === 0 && height === 0)) {
return center;
}
const scale =
0.5 /
Math.max(width === 0 ? 0 : Math.abs(dx) / width, height === 0 ? 0 : Math.abs(dy) / height);
dx *= scale;
dy *= scale;
return center.clone().translate(dx, dy);
};
const svgPointToPoint = (p: SVGPoint): Point => {
return new Point(p.x, p.y);
};
const distanceToPoint = (p: Point, reference: Point): number => {
const dx = p.x - reference.x;
const dy = p.y - reference.y;
return dx * dx + dy * dy;
};
const isBetween = (a: number, b1: number, b2: number): boolean => {
return Math.ceil(a) >= Math.min(b1, b2) && Math.floor(a) <= Math.max(b1, b2);
};
const getLinesIntersection = (line1: [Point, Point], line2: [Point, Point]): Point | null => {
const line1xDelta = line1[0].x - line1[1].x;
const line1yDelta = line1[0].y - line1[1].y;
const line2xDelta = line2[0].x - line2[1].x;
const line2yDelta = line2[0].y - line2[1].y;
const denominator = line1xDelta * line2yDelta - line1yDelta * line2xDelta;
if (denominator === 0) {
// parallel lines do not intersect
return null;
}
const d1 = line1[0].x * line1[1].y - line1[0].y * line1[1].x;
const d2 = line2[0].x * line2[1].y - line2[0].y * line2[1].x;
const xValue = d1 * line2xDelta - line1xDelta * d2;
const yValue = d1 * line2yDelta - d2 * line1yDelta;
const intersection: Point = new Point(xValue / denominator, yValue / denominator);
if (
!isBetween(intersection.x, line1[0].x, line1[1].x) ||
!isBetween(intersection.y, line1[0].y, line1[1].y) ||
!isBetween(intersection.x, line2[0].x, line2[1].x) ||
!isBetween(intersection.y, line2[0].y, line2[1].y)
) {
// intersection is not in range
return null;
}
return intersection;
};
const getPathIntersectionPoint = (pathNode: SVGPathElement, line: [Point, Point]): Point => {
const pathLength = pathNode.getTotalLength();
const numSegments = Math.min(Math.round(pathLength / 5), 100);
for (let i = 0; i < numSegments; i++) {
const pos1 = pathNode.getPointAtLength((pathLength * i) / numSegments);
const pos2 = pathNode.getPointAtLength((pathLength * (i + 1)) / numSegments);
const intersectPoint = getLinesIntersection(
[svgPointToPoint(pos1), svgPointToPoint(pos2)],
line,
);
if (intersectPoint) {
return intersectPoint;
}
}
// No intersection found, return the center point
const pathBox = pathNode.getBBox();
return new Point(pathBox.x + pathBox.width / 2, pathBox.y + pathBox.height / 2);
};
const getPathClosestPoint = (pathNode: SVGPathElement, reference: Point) => {
const pathLength = pathNode.getTotalLength();
let precision = 8;
let best: SVGPoint = pathNode.getPointAtLength(0);
let bestLength = 0;
let bestDistance = Infinity;
// linear scan for coarse approximation
for (let scanLength = 0; scanLength <= pathLength; scanLength += precision) {
const scan: SVGPoint = pathNode.getPointAtLength(scanLength);
const scanDistance: number = distanceToPoint(svgPointToPoint(scan), reference);
if (scanDistance < bestDistance) {
best = scan;
bestLength = scanLength;
bestDistance = scanDistance;
}
}
// binary search for precise estimate
precision /= 2;
while (precision > 0.5) {
const beforeLength: number = bestLength - precision;
const before: SVGPoint = pathNode.getPointAtLength(beforeLength);
const beforeDistance: number = distanceToPoint(svgPointToPoint(before), reference);
if (beforeLength >= 0 && beforeDistance < bestDistance) {
best = before;
bestLength = beforeLength;
bestDistance = beforeDistance;
} else {
const afterLength: number = bestLength + precision;
const after: SVGPoint = pathNode.getPointAtLength(afterLength);
const afterDistance: number = distanceToPoint(svgPointToPoint(after), reference);
if (afterLength <= pathLength && afterDistance < bestDistance) {
best = after;
bestLength = afterLength;
bestDistance = afterDistance;
} else {
precision /= 2;
}
}
}
return svgPointToPoint(best);
};
const getPathAnchorPoint = (
pathNode: SVGPathElement,
reference: Point,
useClosestPathPoint: boolean = false,
) => {
if (useClosestPathPoint) {
return getPathClosestPoint(pathNode, reference);
}
const pathBox = pathNode.getBBox();
const pathCenter = new Point(pathBox.x + pathBox.width / 2, pathBox.y + pathBox.height / 2);
return getPathIntersectionPoint(pathNode, [reference, pathCenter]);
};
const getPolygonAnchorPoint = (polygonNode: SVGPolygonElement, reference: Point) => {
const polygonBox = polygonNode.getBBox();
const polygonCenter = new Point(
polygonBox.x + polygonBox.width / 2,
polygonBox.y + polygonBox.height / 2,
);
const { points } = polygonNode;
let bestPoint: Point = polygonCenter;
let bestDistance = Infinity;
for (let i = 0; i < points.length; i++) {
const intersectPoint: Point | null = getLinesIntersection(
[svgPointToPoint(points[i]), svgPointToPoint(points[i === points.length - 1 ? 0 : i + 1])],
[polygonCenter, reference],
);
if (intersectPoint) {
const intersectDistance: number = distanceToPoint(intersectPoint, reference);
if (intersectDistance < bestDistance) {
bestPoint = intersectPoint;
bestDistance = intersectDistance;
}
}
}
return bestPoint;
};
export { getEllipseAnchorPoint, getRectAnchorPoint, getPathAnchorPoint, getPolygonAnchorPoint };
|
def rows(self):
rows = []
max_row = max(self.cells, key=attrgetter('row')).row
for row_nr in range(1, max_row + 1):
columns_in_row = [cell for cell in self.cells if cell.row == row_nr]
columns_in_row.sort(key=attrgetter('col'))
rows.append(columns_in_row)
return rows |
<reponame>Logicalshift/flo_stream<filename>src/blocking_publisher.rs
use super::publisher::*;
use super::subscriber::*;
use super::message_publisher::*;
use futures::*;
use futures::future::{BoxFuture};
use futures::channel::oneshot;
///
/// A blocking publisher is a publisher that blocks messages until it has enough subscribers
///
/// This is useful for cases where a publisher is being used asynchronously and wants to ensure that
/// its messages are sent to at least one subscriber. Once the required number of subscribers is
/// reached, this will not block again even if some subscribers are dropped.
///
pub struct BlockingPublisher<Message> {
/// True if there are not currently enouogh subscribers in this publisher
insufficient_subscribers: bool,
/// The number of required subscribers
required_subscribers: usize,
/// The publisher where messages will be relayed
publisher: Publisher<Message>,
/// Futures to be notified when there are enough subscribers for this publisher
notify_futures: Vec<oneshot::Sender<()>>
}
impl<Message: Clone> BlockingPublisher<Message> {
///
/// Creates a new blocking publisher
///
/// This publisher will refuse to receive any items until at least required_subscribers are connected.
/// The buffer size indicates the number of queued items permitted per buffer.
///
pub fn new(required_subscribers: usize, buffer_size: usize) -> BlockingPublisher<Message> {
BlockingPublisher {
insufficient_subscribers: required_subscribers != 0,
required_subscribers: required_subscribers,
publisher: Publisher::new(buffer_size),
notify_futures: vec![]
}
}
///
/// Returns a future that will complete when this publisher has enough subscribers
///
/// This is useful as a way to avoid blocking with `wait_send` when setting up the publisher
///
pub fn when_fully_subscribed(&mut self) -> impl Future<Output=Result<(), oneshot::Canceled>>+Send {
let receiver = if self.insufficient_subscribers {
// Return a future that will be notified when we have enough subscribers
let (sender, receiver) = oneshot::channel();
// Notify when there are enough subscribers
self.notify_futures.push(sender);
Some(receiver)
} else {
None
};
async {
if let Some(receiver) = receiver {
receiver.await
} else {
Ok(())
}
}
}
}
impl<Message: 'static+Send+Clone> MessagePublisher for BlockingPublisher<Message> {
type Message = Message;
fn subscribe(&mut self) -> Subscriber<Message> {
// Create the subscription
let subscription = self.publisher.subscribe();
// Wake the sink if we get enough subscribers
if self.insufficient_subscribers && self.publisher.count_subscribers() >= self.required_subscribers {
// We now have enough subscribers
self.insufficient_subscribers = false;
// Notify any futures that are waiting on this publisher
self.notify_futures.drain(..)
.for_each(|sender| { sender.send(()).ok(); });
}
// Result is our new subscription
subscription
}
///
/// Reserves a space for a message with the subscribers, returning when it's ready
///
fn when_ready(&mut self) -> BoxFuture<'static, MessageSender<Message>> {
// If there are not enough subscribers, wait for there to be enough subscribers
let when_subscribed = if self.insufficient_subscribers {
Some(self.when_fully_subscribed())
} else {
None
};
let when_ready = self.publisher.when_ready();
// Wait for there to be enough subscribers before waiting for the publisher to become ready
Box::pin(async move {
if let Some(when_subscribed) = when_subscribed {
when_subscribed.await.ok();
}
when_ready.await
})
}
///
/// Waits until all subscribers have consumed all pending messages
///
fn when_empty(&mut self) -> BoxFuture<'static, ()> {
let when_subscribed = if self.insufficient_subscribers {
Some(self.when_fully_subscribed())
} else {
None
};
let when_empty = self.publisher.when_empty();
Box::pin(async move {
if let Some(when_subscribed) = when_subscribed {
when_subscribed.await.ok();
}
when_empty.await
})
}
///
/// Returns true if this publisher is closed (will not publish any further messages to its subscribers)
///
fn is_closed(&self) -> bool { self.publisher.is_closed() }
///
/// Future that returns when this publisher is closed
///
fn when_closed(&self) -> BoxFuture<'static, ()> {
self.publisher.when_closed()
}
}
|
/**
* IP whitelist cache
*
* @author aaron.li
**/
public class SystemConfigCache {
private final Logger LOG = LoggerFactory.getLogger(SystemConfigCache.class);
private static SystemConfigCache cache = new SystemConfigCache();
/**
* IP address list
*/
private static ConcurrentSkipListSet<String> IP_ADDRESS_LIST = new ConcurrentSkipListSet<>();
private SystemConfigCache() {
}
public static SystemConfigCache getInstance() {
return cache;
}
/**
* Does the IP address exist in the whitelist
*/
public boolean isExistIp(String ip) {
if (StringUtil.isEmpty(ip)) {
return false;
}
// wildcard,matching all
String widCard = "*";
for (String ipAddr : IP_ADDRESS_LIST) {
// Starting with a wildcard indicates full matching
if (ipAddr.startsWith(widCard)) {
return true;
}
int widCardIndex = ipAddr.indexOf(widCard);
// Wildcard exists
if (widCardIndex > -1) {
ipAddr = ipAddr.substring(0, widCardIndex);
if (ip.startsWith(ipAddr)) {
return true;
}
} else {
// The absence of wildcards indicates an accurate match
if (ipAddr.equals(ip)) {
return true;
}
}
}
return false;
}
/**
* Check whether the cache is empty
*/
public boolean cacheIsEmpty() {
return IP_ADDRESS_LIST.isEmpty();
}
/**
* Refresh cache
*/
public synchronized boolean refreshCache() {
try {
GlobalConfigService service = GatewayServer.CONTEXT.getBean(GlobalConfigService.class);
GatewayConfigModel gatewayConfig = service.getGatewayConfig();
if (null == gatewayConfig) {
IP_ADDRESS_LIST.clear();
return true;
}
String gatewayIpWhiteStr = gatewayConfig.ipWhiteList;
gatewayIpWhiteStr = StringUtil.isEmpty(gatewayIpWhiteStr) ? "" : gatewayIpWhiteStr.trim();
// Extract IP address list
List<String> gatewayIpWhiteList = IpAddressUtil.parseStringToIpList(gatewayIpWhiteStr);
if (CollectionUtils.isEmpty(gatewayIpWhiteList)) {
IP_ADDRESS_LIST.clear();
return true;
}
List<String> delIpList = new ArrayList<>();
for (String ip : IP_ADDRESS_LIST) {
if (!gatewayIpWhiteList.contains(ip)) {
delIpList.add(ip);
}
}
IP_ADDRESS_LIST.removeAll(delIpList);
IP_ADDRESS_LIST.addAll(gatewayIpWhiteList);
return true;
} catch (Exception e) {
LOG.error("Refreshing IP whitelist cache exception :", e);
}
return false;
}
} |
/**
* Provides a simple example of LINKing to a CICS program using JCICS,
* passing a byte array for a COMMAREA. In this example, the COMMAREA
* byte array is constructed using a JZOS generated class.
*
* This class executes in an OSGi JVM server environment.
*/
public class LinkProg2 extends LinkProgCommon
{
/**
* Name of the COBOL program to be invoked.
*/
private static final String PROG_NAME = "EDUPGM";
/**
* Constructor used to pass data to superclass constructor.
*
* @param prog - the program reference we will be manipulating in this example.
*/
private LinkProg2(Program prog)
{
super(prog);
}
/**
* Main entry point to a CICS OSGi program.
* This can be called via a LINK or a 3270 attach.
*
* The fully qualified name of this class should be added to the CICS-MainClass
* entry in the parent OSGi bundle's manifest.
*/
public static void main(String[] args)
{
// Get details about our current CICS task
Task task = Task.getTask();
task.out.println(" - Starting LinkProg2");
// Create a reference to the Program we will invoke
Program prog = new Program();
// Specify the properties on the program
prog.setName(PROG_NAME);
// Don't syncpoint between remote links, this is the default
// Setting true ensures each linked program runs in its own UOW and
// allows the a remote server program to use a syncpoint command
prog.setSyncOnReturn(false);
// Create a new instance of the class
LinkProg2 lp = new LinkProg2(prog);
// build commarea byte array using JZOS record
JZOSCommareaWrapper cw = lp.buildCommarea();
// Invoke the LINK to CICS program converting the record to a byte array
lp.linkProg(cw.getByteBuffer());
// Get output data from commarea
// Use the getters from the commarea record to access the output fields
// in the returned commarea
String resultStr = cw.getResultText();
Integer resultCode = cw.getResultCode();
// Completion message
String msg = MessageFormat.format("Returned from link to {0} with rc({1}) {2}",
prog.getName(), resultCode, resultStr);
task.out.println(msg);
}
/**
* Link to the CICS COBOL program and catch any errors from CICS.
*
* @param commarea - byte array as input and output commarea
*/
private void linkProg(byte[] commarea) {
try {
// LINK to the CICS program
this.prog.link(commarea);
}
catch (CicsConditionException cce) {
// Crude error handling to keep logic simple
throw new RuntimeException(cce);
}
}
/**
* Build the commarea using the supplied JZOS wrapper
* and set the input fields as required.
*
* @return JZOS COMMAREA record for EDUPGM copybook
*/
private JZOSCommareaWrapper buildCommarea() {
// Create a new instance of the generated class
JZOSCommareaWrapper cw = new JZOSCommareaWrapper();
cw.setBinaryDigit(1);
cw.setCharacterString("hello");
cw.setNumericString(1234);
cw.setPackedDigit(123456789);
cw.setSignedPacked(-100);
cw.setBool("1");
// Return the constructed object
return cw;
}
} |
/*
* Function to free HW resource allocated for ING_VLAN_TAG_ACTION_PROFILE_TABLE
* for the given VLAN action set.
*/
int
_bcm_field_td3_vlan_action_hw_free(int unit, _field_entry_t *f_ent, uint32 flags)
{
_field_action_t *fa;
int rv = BCM_E_NONE;
if (f_ent->group->stage_id != _BCM_FIELD_STAGE_LOOKUP) {
return (BCM_E_NONE);
}
for (fa = f_ent->actions; fa != NULL; fa = fa->next) {
switch (fa->action) {
case bcmFieldActionVlanActions:
if ((flags & _FP_ACTION_RESOURCE_FREE) &&
(_FP_INVALID_INDEX != fa->hw_index)) {
rv = _bcm_trx_vlan_action_profile_entry_delete(unit,
fa->hw_index);
if (BCM_E_NOT_FOUND == rv) {
LOG_ERROR(BSL_LS_BCM_FP,
(BSL_META_U(unit,
"Warning: Failed to delete the profile index of"
" Action 'VlanActions' for Entry %d "
"\n"),
f_ent->eid));
rv = BCM_E_NONE;
}
BCM_IF_ERROR_RETURN(rv);
fa->hw_index = _FP_INVALID_INDEX;
}
if ((flags & _FP_ACTION_OLD_RESOURCE_FREE) &&
(_FP_INVALID_INDEX != fa->old_index)) {
rv = _bcm_trx_vlan_action_profile_entry_delete(unit,
fa->old_index);
BCM_IF_ERROR_RETURN(rv);
fa->old_index = _FP_INVALID_INDEX;
}
break;
default:
break;
}
}
return (rv);
} |
Classical Many-particle Clusters in Two Dimensions
We report on a study of a classical, finite system of confined particles in two dimensions with a two-body repulsive interaction. We first develop a simple analytical method to obtain equilibrium configurations and energies for few particles. When the confinement is harmonic, we prove that the first transition from a single shell occurs when the number of particles changes from five to six. The shell structure in the case of an arbitrary number of particles is shown to be independent of the strength of the interaction but dependent only on its functional form. It is also independent of the magnetic field strength when included. We further study the effect of the functional form of the confinement potential on the shell structure. Finally we report some interesting results when a three-body interaction is included, albeit in a particular model.
I. INTRODUCTION
Two dimensional clusters or "artificial atoms" have attracted considerable attention in recent years . A cluster of a finite number of charged particles confined by an external potential may be regarded as an "artificial atom". There are several examples of such systems from mesoscopic systems to the astroplasma system. In observed systems such as electrons on a liquid helium film , drops of colloidal suspensions and confined dusty particles , the dynamics is essentially classical. On the other hand, in mesoscopic systems like quantum dots, quantum effects may not be negligible . The actual Hamiltonians which capture the full dynamics of these systems are rather complicated. However, several studies assuming model systems have been carried out. In particular, there have been studies on the ordering and transitions of charged particles in two dimensions .
In a recent Monte Carlo study, Bedanov and Peeters (see also Bolten and Rossler ) have analysed the classical ground state of a system of confined, charged particles interacting through the Coulomb interaction. By minimising the classical energy, they obtain numerically the shell structure in a cluster of N particles. They have systematically listed the shell structure in a "Mendeleev" table for N ≤ 52, and for a few large clusters. Similar results are available also for logarithmic two-body interaction . An important fact that follows from this Mendeleev table is that the charged particles, confined in a parabolic potential, arrange themselves in concentric shells where each shell may be thought of as an annulus whose width is much smaller than the radius. For particular numbers, N = 6, 19, 37, ... these annuli are almost precisely circles. These are called magic numbers. There are further systematics (approximate) in this table. Up to N = 5, the particles in the ground state configuration arrange themselves on a circle. For N = 6, there are five particles on the circle and one in the centre (circle-dot) in the ground state. With the addition of more particles, a second shell starts forming until the arrangement has 5 particles in the inner shell and 10 particles on the outer shell, ie N = 15. Addition of one more particle (N = 16), creates a configuration similar to N = 15 with the extra particle at the centre. It is interesting to note that the multi-shell structure was experimentally observed by Christian Myer more than a hundred years ago. He observed these geometric transitions in a system involving magnetic needles floating on water, confined by a bar magnet held above the surface. The result, as quoted by J. J. Thompson, notes that five magnetic needles always remained on the circumference of a circle whereas the sixth one, when added, always drifted to the middle. Notice that the interaction between magnetic needles is different from Coulomb interaction. Nevertheless the observed phenomenon bears resemblance to the numerical results.
At least up to N = 50, the geometric transition from 5 to 6, that is from a circle to a circle-dot, forms a template for the innermost shell. To a very good approximation, the number of shells for any N, in the Mendeleev table , may be deduced as follows: Write a given N as a sum of non-repeating multiples of five and a remainder. The number of terms in the sum is the number of shells. For example, N = 48 may be written as N = 5+10+15+13. This, in our way of looking, corresponds to having four shells. (It is not expected that this will hold for large N since the system goes into a hexagonal arrangement in the bulk.) The main theme of the paper is this geometric transition from circle to circle-dot configuration when the number of particles changes from 5 to 6. We also derive some general results concerning the shell-structure for arbitrary N.
In this paper we first consider a cluster of N particles in which the repulsive two-body potential is a power-law. The classical system we are interested in, to begin with, consists of N particles of equal mass m, confined in an oscillator potential, in a uniform magnetic field and interacting via a two-body potential. The Hamiltonian of such a system of particles is given by where r i and p i denote the position and momentum vectors of the particle with index i. The vector potential, for a uniform magnetic field in the symmetric gauge, is given by where ω L is the Larmor frequency and r ij = r i − r j . The power ν (positive) is kept arbitrary. The Coulomb Hamiltonian is recovered by choosing ν = 1/2. We also consider the case when the two-body interaction is of the form −β i,j( =i) log(r 2 ij /ρ 2 ) which is repulsive for r 2 ij < ρ 2 (see Appendix A). This may be closer to the real situation as also the ν = 1/2 (Coulomb) case for electrons in a quantum dot . Recently, the ν = 1 (inverse square interaction) case has also been analysed in detail because of its relevance to quantum dot systems. In addition, this case nicely lends itself to analytical manipulations. We devise a simple analytical method to obtain the classical ground state energy in two steps. First, we extremise the energy for a fixed total angular momentum J (which is conserved), and then minimise this energy with respect to J. This has two advantages. It reflects the quantum degeneracy of the lowest Landau level for electrons in a uniform magnetic field in the absence of any interaction, at the classical level itself and secondly it allows one to do the second step of the minimisation over the quantised values of the angular momentum. Here, however, we restrict ourselves to a classical analysis only and derive some exact results analytically for the equilibrium configurations.
In Section II, we show that: 1. The configurations extremising the energy, modulo overall scale, are independent of the parameters of the Hamiltonian and also of the angular momentum J so long as the repulsive two-body potential falls off as a power-law with the relative distance and the confinement is harmonic. Only the overall length scale is sensitive to these details.
2. Two special configurations, one in which all the N particles are on a circle (referred to as ) and the one in which N − 1 are on a circle with one at the center (referred to as ) are always equilibrium configurations. We give exact analytical expressions for the corresponding energy for all N and ν. The has lower energy for N ≤ 5 while has lower energy for N ≥ 6. In fact the is the ground state for all N ≤ 5 while is the ground state for N = 6, 7, 8. (This is a well known result for Coulomb interaction but is also true in the general case considered below for arbitrary ν up to a maximum value which depends on the number of particles.) This geometric transition in the ground state is the first one to occur and is independent of the precise form of the repulsive interaction.
3. While it is known numerically that for N ≥ 9 and for Coulomb potential the minimum energy configurations exhibit approximate multi-shell structure, the special configurations provide an upper bound on the minimum energy for a whole class of interactions that we consider here. The results presented in this section are an elaboration of our previous work .
In Section III, we consider the effect of confinement on the geometric transition which occurs for N from 5 to 6. The one-body confinement in eq.(1) is generalised to The oscillator confinement is recovered for γ = 1. Surprisingly, we find that there exists a critical value of ν above which the first geometric transition always occurs between 5 and 6 for γ > 1 and between 4 and 5 for γ < 1.
In Section IV, we consider the effect of three-body perturbations on this geometric transition. We do so by using a particular model Hamiltonian whose exact quantum mechanical ground state energy and wave function are known in a limit to be defined later. While this again has interesting properties in its own right, it is included here primarily to study its effect on shell formation. Some of questions relating to three-body perturbations are being studied and will be published else where .
We conclude in Section V with some comments and future prospects. Appendix A contains some general results concerning the logarithmic interaction potential. Details of our numerical simulations are discussed in Appendix B. These are used to check our results with ref. for the case of Coulomb potential and then extended to other forms of the potential.
II. GEOMETRY OF CLUSTERS IN PARABOLIC CONFINEMENT
In this section we consider the classical equilibrium configurations of the Hamiltonian given by eq.(1). The Hamiltonian can be written in terms of dimensionless units by introducing a length scale l = (h/(mω) which is the basic oscillator length. All distances are measured in terms of this basic length unit. Note thath is introduced only as a convenience so that the energy is measured in units ofhω and does not have any other significance as in the quantum case. The analysis presented in this paper is entirely classical. The momenta are measured in units ofh/l.
The new Hamiltonian in these scaled units, but keeping the same notation, may be written as where j i = x i p iy − y i p ix , α = ω L ω and g = β hω (l) 2ν . Unless otherwise mentioned the summations run from 1 to N hereafter. While the original coupling constant β was dimensional the new coupling constant g is dimensionless. Hereafter we assume all the energies are measured in units ofhω and do not write the units explicitly.
To find the equilibrium configurations we carry out the variation in two steps. For the first step of the variation we introduce the function where j i are the single particle angular momenta and λ is the Lagrange multiplier which enforces the constraint J = i j i . Setting δF = 0, where the variation is done in the full phase space variables, gives the necessary equations to determine the equilibrium configuration in the phase space, This is the basic set of equations. Any solution to this set of equations describes an equilibrium configuration which could be a local minimum/maximum or a saddle point. We also remark that while the Hamiltonian is written in a particular symmetric gauge, the variational equations given above are actually gauge invariant. The main advantage of introducing F instead of H for variation is that it allows us to keep the dependence of the variational equations on the magnetic field even at the classical level. If we vary H separately this advantage is lost. We may also include the case of logarithmic interaction by simply setting the power ν = 0 and by setting the prefactor to 4g instead of 4gν in eq.(7). To avoid confusion, however, we briefly discuss the results for the logarithmic case separately in Appendix A. First we present a qualitative but general analysis of this basic set of equations without making any assumptions. To make the analysis simple, we introduce an auxiliary variable, The total angular momentum may now be written in terms of this auxiliary variable as where we have made use of eqs. (5,6). It is convenient to express r i = R s i where R is a common scale factor which may be taken to be the radius of the farthest particle, say the N th one, and s i denotes the internal variables. Therefore since s 2 N = 1 by choice. Using eq.(7) and eliminating λ-dependence using eq.(9), we have Taking the scalar product with s i and dividing both sides by s 2 i ( = 0), we get Note that the LHS is independent of the particle index i. Thus we have N − 1 independent of equations of the type Further by taking the cross product with s i and dividing by s i , we get, which provides a further set of N conditions on the internal coordinates s i . Notice that these conditions are manifestly scale invariant. Together, eqs. (13,14) provide the 2N − 1 necessary equations for determining the s i and the angles θ i . These determining equations are also completely independent of α, J and g. We have, therefore, the result that (s 1 , s 2 , ..., s N −1 , θ 1 , θ 2 , ..., θ N ) are independent of the magnetic field (α), the total angular momentum J and the interaction strength g. These parameters, however, determine the overall scale R through eq. (12). In fact since s 2 N = 1, the corresponding equation may be taken to be the determining equation for R in terms of the parameters of the Hamiltonian, Thus we have a very general result that the geometry, that is, the configuration modulo a common scale factor, or the shell structure of the equilibrium configuration is independent of the parameters of the Hamiltonian. The overall size of the system depends on the external magnetic field strength as well as on the total angular momentum J. (For further details on the influence of the magnetic field on the inter-shell rotation and diffusion, see ref. ). The shell structure, however, depends on the nature of the repulsive interaction through the parameter ν but not its strength. The above analysis is valid even if any one of the s i is zero, i.e., one particle being at the origin of the coordinate system, in which case we have two equations less (not more than one particle can be at the origin). Note that the statement above applies to all the extremum configurations and is not just restricted to the local minima . In Fig.1 we have shown the typical shell structure for the ground state of 25 particles as a function of J and ν. It is easy to see that the shell structure, i.e., the number of particles in each shell and their relative orientation, is unchanged with J (modulo overall rotation). The shells get distorted with changes in ν. Note that the system size has been normalised to the same value in Fig.1 for convenience in display.
The energy of the equilibrium configuration can be easily computed by noting that the auxiliary variable φ defined in eq.(8) is related to the two-body potential energy by where the RHS is proportional to the potential energy due to interaction. Since the RHS and φ are positive definite we have the condition (1 + α 2 )φ 2 > J 2 . In the absence of the magnetic field we may set J = 0 since the true ground state has zero angular momentum. In this limit, the above equation reduces to which implies that the confinement energy is ν times the interaction energy. For ν = 1 both are equal, which is not surprising, since in this limit the interaction energy scales like the kinetic energy term. We may in fact regard the above statement as a "virial" theorem valid for all equilibrium configurations. We have, for the energy at the extrema, where φ = R 2 φ and φ is independent of J. This is the energy of the equilibrium configuration in a given J sector. A few comments are in order here. Consider the case when g = 0, which corresponds to the case of non-interacting confined particles in a magnetic field. This is an exactly solvable problem. ¿From eq.(16) we have, which implies either (1) φ = 0 and therefore J = 0 or (2) (1 + α 2 )φ 2 = J 2 . The first of these solutions is the trivial solution which one obtains by directly extremising the Hamiltonian. The classical solution in this case is independent of the magnetic field. The second solution, on the other hand, can be obtained only by imposing the condition of fixed J during extremisation. Equivalently, we vary the function F and not just H. The energy for a given J is then given by which is the energy of confined particles in a magnetic field. Further if we remove the confinement potential, the ground state energy is zero for all J ≤ 0 which is the solution for the lowest Landau level. (In the quantum mechanical case the zero point energy has to be added to the solution.). Thus the variational method in which the function F is extremised not only yields the correct energy but also the correct quantum degeneracy, which is infinite in this case. In the general case when g = 0, the second step in the extremisation involves extremising the energy with respect to J, that is ∂E/∂J = 0, since R depends on J. Differentiating R w.r.t. J in eq.(15) and cancelling the overall powers of R, we have Eliminating the derivative term in the above equations, we get the following solutions at equilibrium for each configuration: Substituting for J in eq.(15), we get where An important point to note here is that this energy E is independent of the magnetic field and its dependence on g is explicit. The dependence on N and ν is, however, involved. The angular momentum J extremising the energy depends on the magnetic field and is zero in the absence of the magnetic field as it should be. The expressions given thus far, though, are valid independent of the geometry of the clusters and are exact (for approximate solutions see eqs. (8,9) in ref. for the special case of Coulomb interaction). We now specialise the general results given above to specific configurations which also happen to be ground states (global minima) for some N. While the results that we obtain are completely analytical and exact, the choice of configurations is based on the earlier numerical work . We have also checked the veracity of these results independently using numerical methods as outlined in Appendix B.
The geometry of the clusters (or shells) is dependent on φ and A(ν, N), which are as yet unspecified. The equations for the equilibrium configurations admit many solutions for a given N and ν. In particular, there are two special configurations which are always solutions, viz (i) all the N particles are on a circle, and (ii) N − 1 particles are on the circle with one particle at the center, . For these two cases, only the overall scale factor R is to be determined. The angles θ ij /2 are simply multiples of π/N and π/(N − 1) respectively. These configurations, however, need not be local minima in general. In particular, it has been numerically proved that for N ≤ 5 the circle configuration is indeed the global minimum energy configuration (ground state) whereas for 6 ≤ N ≤ 8 it is the circle-dot which is the ground state in the case of Coulomb interaction ( ν = 1/2 ). The ground state exhibits multiple shell formation for N ≥ 9. In what follows we prove analytically that the first transition which occurs for N from 5 to 6 is independent of ν. However, both and remain ground states for N = 5 and N = 6 respectively only for ν up to a ν min . In Fig.2, we display the eigenvalues of the Hessian (matrix of second derivatives) of the effective potential (see eq(B.1)) as a function of ν. When N = 5, the eigenvalues are positive definite up to ν = 2.4 for both and configurations. Both these configurations therefore correspond to local minima, but the calculation of the energy shows clearly that the has lower energy and is in fact the ground state, confirming the earlier numerical calculations with ν = 1/2. When N = 6, the eigenvalues are positive all the way up to ν = 10 (modulo a zero eigenvalue related to the rotational invariance) for the configuration. Hence it is a local minimum. However the configuration ceases to be a local minimum for ν > 0.484 and becomes a saddle point since one of the eigenvalues becomes negative. It is possible that there are other configurations, other than the ones considered here, which are also local minima. They are not relevant to the analysis that is to follow. For the circle case, we have, for N particles, and therefore the energy is given by where .
The second equality follows from the fact that for the symmetric configuration on the circle, In the case of circle-dot, we have, for N particles , since there are now N − 1 particles on the circle and one at the centre. Therefore the energy is given by where The extra 1 on the RHS is the contribution of the particle at the center.
To ascertain which of the two configurations and has lower energy we look at the following ratio for the same number of particles: where λ (ν) Note that in general the ratio f depends only on N and ν but not on the other parameters of the model Hamiltonian. Obviously the circle is a lower energy configuration iff f < 1. We claim that, for all ν > 0, Further the function f (ν, N) crosses unity exactly once for N between 5 and 6 and nowhere else. In Fig.3, we show the numerical values of the function f (ν, N) as a function of N for various values of ν. The result can be easily checked for ν = 1 since in this case λ which reproduces the claims made above, for ν = 1. For ν << 1, again the proof is straightforward and we include it here since it will be relevant to the case of logarithmic interaction later. For very small ν we make use of the identity that for any a, a ν ≈ 1 + ν log(a). Using this identity λ N may be written as, where Here we have used the identity, N −1 k=1 sin( kπ N ) = N 2 N−1 . Further we also approximate (N/N − 1) ν+1 ≈ (N/N − 1)(1 + ν log(N/N − 1)). Substituting for λ N in f , we have where is independent of ν. Clearly, whether f is less than or greater than unity depends on whether µ N is negative or positive. However the properties of µ N cannot be dependent on ν. It is now easy to see that µ N is negative for N ≤ 5 and positive otherwise. Hence the proof. Therefore, for N ≥ 6, the ground state must have multi-shell structure (including possibly ). Note that the ratio f > 1 or f < 1 says nothing about whether the or is the ground state, or even local minimum. What it does say is that, if f > 1, then can not be the ground state, independent of its stability properties. Therefore, whatever be the ground state it must have at least two shells (with one shell possibly trivial as in ). This statement is independent of ν. Thus we conclude that the first geometric transition is independent of ν, g and J . Independent of the calculation of f , we know from numerical calculations that is the ground state for 2 ≤ N ≤ 5 and is the ground state for 6 ≤ N ≤ 8 for ν < ν max where ν max is determined from the eigenvalues of the Hessian.
One could have also arrived at the conclusion that for N = 6 multi-shells must form, by studying the eigenvalues of the Hessian. This however is harder to compute analytically and also is not conclusive for small values of ν for which is still a local minimum. The criterion in terms of f > 1 is, however, easy and conclusive.
It therefore appears that the organisation of many-body clusters in two dimensions into shells is a robust phenomenon, independent of the nature of the repulsive two-body interaction and also independent of the Hamiltonian parameters but dependent only on the number of particles in the cluster. In particular, the first geometric transition for the ground state from circle to circle-dot configuration occurs after N = 5. The robustness of this transition seems to emerge purely from the number theoretic properties of the ratio of the energies in these two configurations. The results of this section are, however, restricted to parabolic confinement. In the next section, we analyse the effect of confinement on the geometry of clusters.
III. EFFECT OF CONFINEMENT
While the parabolic confinement is a simple and popular choice for model systems, real systems may be more complicated. In this section, we consider a generalisation of the form of the confinement potential and study its effects on the cluster properties. For our study we choose a form of the confinement potential proposed by Partoens and Peeters who have studied the influence of the form of the confinement potential and the interaction potential using numerical methods as well as an approximate Thomson model. To keep the analysis simple we do not include the magnetic field. The Hamiltonian in dimensionless units may be written as where γ characterises the confinement potential. While γ = 1 corresponds to parabolic potential, we keep it arbitrary. The variational equations for extrema of F defined in equation (4) are straightforward to write. As before, one can eliminate the Lagrange multiplier in favour of J and φ (defined in eq. (8)). The equilibrium configurations are then determined by, Taking the cross product in eq.(43) with r i gives N equations which are exactly the same as before in Section II. Taking the dot product with r i and dividing by r 2 i , however, gives the LHS which is dependent on the index i. Thus the parabolic confinement is special in this regard, since for γ = 1 the LHS is independent of i. This fact was crucial for the conclusion that the shell structure does not dependent on the total angular momentum J. In the absence of the magnetic field, we may assume that the ground state has J = 0, in which case the i-dependence of the LHS may be easily eliminated as in Sec.I. The following analysis is therefore true for all J = 0 equilibrium configurations in general and in particular for the ground state.
Once again the shell structure is independent of the interaction strength. To see this we introduce an auxiliary variable, Expressing r i = R s i , R being a common scale factor (say the radius of the N th particle), we write since s 2 N = 1 by choice, as in Sec.II. The basic equation determining the configuration space coordinates then takes the form Taking the scalar product with s i and dividing both sides by (s 2 i ) γ ( = 0), we get Note that the LHS is independent of the particle index i and the RHS is different from the parabolic case. However, we still have N − 1 independent of equations of the type j(j =i) Further by taking the cross product with s i and dividing by s i , we get, which is independent of γ and therefore is identical to the parabolic case. This equation provides a further set of N conditions on the internal coordinates s i . Together eqs.(48,49) provide the 2N − 1 necessary equations for determining the s i and the angles θ i and are completely independent of g and g ′ . These, the strengths of confinement and interaction potentials, determine the overall scale R through eq.(47). Setting i = N in eq.(47), we get Thus we have the result that the geometry or the shell structure of the equilibrium configuration is independent of the parameters of the Hamiltonian, which only restrict the overall size of the system. Next we compute the energy of the equilibrium configurations. To this end we note that the auxiliary variable φ γ defined in eq.(44) is related to the two-body potential energy by, where the RHS is proportional to the potential energy due to interaction. Therefore, which implies that the γ times the confinement energy is ν times the interaction energy. This is the generalised "virial theorem" valid for arbitrary confinement. We have, for the energy at the extrema, This expression for energy is valid for all equilibrium configurations. The scale R may be calculated from eq.(50) and is given by where and is independent of γ. This definition of A(ν, N) is the same as in the parabolic case.
We now consider the effect of confinement on the geometric transition for N from 5 to 6. As shown in the previous section for parabolic confinement, the configuration changes from circle to circle-dot independent of ν. We first give expressions for the energy for these two configurations for any N.
For the circle case, we have, for N particles, and therefore the energy is given by where A (ν, N) is given in eq.(28).
In the case of circle-dot, we have, for N particles, since there are now N − 1 particles on the circle and one at the centre. Therefore the energy is given by where A (ν, N) = A (ν, N − 1) + 1 (60) as before.
To ascertain which of these two configurations and has lower energy we look at the ratio for the same number of particles, N, where λ (ν) N is given in eq.(33) in the previous section. The effect of the confinement is therefore entirely contained in the prefactor whose exponent contains γ. The values of ν range from 0.5 to 4 as in Fig. 3.
In Fig.4, we show the behaviour of f as a function of N for typical values of ν and γ. The pattern seen in Fig.4 may be summarised in two parts: 1. For γ < 1, the first geometric transition occurs before N = 5. As ν increases the transition moves towards N = 5 but never beyond. In fact there exists ν min after which the transition always occurs between 4 and 5 for N.
2. For γ > 1, the first geometric transition occurs after N = 6. As ν increases the transition moves towards N = 5. For ν > ν min the transition always occurs between 5 and 6 for N.
In the case of Coulomb interaction it was already known that the transition occurs either before N = 5 (γ < 1) or after N = 6 (γ > 1) . However the fact that the transition always occurs around N = 5 after some ν min is, to our knowledge, a new result.
IV. EFFECT OF THREE-BODY PERTURBATIONS
In this section we consider a model Hamiltonian with a three-body interaction. While classically three-body interactions are not naturally introduced, quantum correlations can of course introduce effective many-body terms. The primary motivation for considering the three-body term here is to see if the shell structure survives under this perturbation. The effect of the three-body term is interesting and non-trivial on the first geometric transitions. The model Hamiltonian, in dimensionless units, is given by where g 1 and g 2 are in general kept arbitrary. Notice that when g 2 = 0, this reduces to the model Hamiltonian analysed in section II with ν = 1. The quantum mechanics with this model Hamiltonian (g 2 = 0) has some interesting applications to quantum dots and is considered in detail in ref. . The model Hamiltonian given above has a very interesting limit. When g 1 = g 2 = g 2 , the quantum mechanical ground state and an infinite tower of states may be solved for exactly . Solving the Schroedinger equation, Hψ 0 = E 0 ψ 0 , for the ground state we obtain and the ground state energy is given by In what follows we keep g 1 and g 2 arbitrary and comment on the case g 1 = g 2 later.
The classical analysis of the model Hamiltonian is done as before by extremising the Hamiltonian in the full phase space. As in the previous section we concentrate only on the case where the total angular momentum, J = 0 , which implies that p i = 0 and the equilibrium configurations are obtained as solutions of the equations Again these equilibrium configurations may be local minima/maxima or saddle points. The general analysis of these equations proceeds as in section II. Since there are two coupling constants g 1 and g 2 , the shell structure does depend on these parameters, unlike in the earlier models, except in the special case when the two are equal. Taking the dot product on both sides of the above equation with r i and summing over the index i, we get, Therefore the confinement energy is again equal to the interaction energy including the two-and three-body terms. Using this, the energy in any equilibrium configuration may be calculated: where s i are internal variables and R is the overall scale, which may be taken to be the distance of the farthest particle from the origin. We now specialise to specific configurations namely the circle and the circle-dot. It may be easily checked that these configurations are allowed equilibrium configurations for all N. These, however, need not be local minima for all N. For these two cases, only the overall scale factor R is to be determined. The angles θ ij /2, as before, are simply multiples of π/N and π/(N − 1) respectively. For the circle case, we have, for N particles, and therefore the energy, after some algebra, is given by In the case of circle-dot, we have, for N particles, since there are now N − 1 particles on the circle and one at the centre. Therefore the energy is given by Interestingly, in the limit g 1 = g 2 = g 2 , we have the important result which is the same as the quantum mechanical ground state energy without the zero point fluctuation. The two configurations are also degenerate in this limit. We may therefore use either of these two classical configurations as a starting point for calculating the quantum corrections. Since the quadratic fluctuations reproduce the zero point energy the higher order corrections must be either vanishing or spurious. Coming back to the general case, g 1 = g 2 , we would like to examine the effect of threebody terms in the interaction on the first geometric transition from circle to circle-dot configuration. Note that in the absence of the three-body terms, circle is the ground state up to 5 particles and circle dot is the ground state for N = 6. To ascertain which of these two configurations and has lower energy in the presence of the three-body perturbations, it is sufficient to look at the ratio of the energies for the same number of particles: where b is the ratio g 2 /g 1 of the strengths of the two terms. Obviously the circle is a lower energy configuration iff f < 1. Fig. 5. First, at b = 1, the ratio is 1 since the two configurations are degenerate in this limit. For b < 1, circle has lower energy for N ≤ 5 and therefore f < 1. The ratio crosses unity when N changes from 5 to 6 at exactly the same point no matter what the value of b is. It is as if the three-body perturbation has no effect on this geometric transition. The energies of course explicitly depend on the coupling constants. However, for b > 1, circle has higher energy for N ≤ 5 and therefore f > 1. Again the ratio crosses unity between 5 and 6 and for all N > 6, circle configuration has lower energy. This can be seen analytically also, from eq.(73).
However, it turns out neither the circle nor the circle-dot configuration can be the ground state when b > 1, that is when the three-body term dominates the two-body term in the Hamiltonian. In fact the ground state is one when all particles on a line, where the particle positions are determined by the zeros of the Hermite polynomial of order N . We must, however, point out that the above results are specific to the form of the Hamiltonian. Whether three-body interactions, in general, have a similar effect is a difficult question to answer.
V. DISCUSSION
To summarise, we have discussed the shell structure of particle clusters in the presence of external confinement. To begin with, we have assumed harmonic confinement and the interaction is two-body. Following the analysis in section II, it appears that the organisation of many-body clusters in two dimensions into shells is a robust phenomenon, independent of the nature of the repulsive two-body interaction and also independent of the Hamiltonian parameters but dependent only on the number of particles in the cluster. In particular, the first geometric transition for the ground state from circle to circle-dot configuration occurs after N = 5. The robustness of this transition seems to emerge purely from the number theoretic properties of the ratios of the energies in these two configurations. A different type of confinement may in fact destroy the robustness of this transition for small ν. The interesting point, however, is that after some critical ν max , once again the results look similar to that of the parabolic confinement.
Further, the presence of three-body terms in the interaction does not seem to affect the geometric transition as long as it remains a weak perturbation. Interestingly enough, within the model Hamiltonian we have analysed, there exists a critical point when the geometric transition changes dramatically as the perturbation strength is varied. Most importantly, the classical energy is the same as the quantum mechanical energy (without the zero point fluctuations) in the limit when the strengths of the two-and three-body terms are equal. It would be interesting to check if this is true of other many-body models where the quantum ground state is exactly known.
While the existence of the shell structure is numerically well established, the analytical understanding of the existence of the shells is lacking. It would be interesting to know how many distinct extremal configurations there are . While the first transition seems to indicate the formation of shells, a deeper understanding of the Mendeleev table is clearly called for. It would also be interesting to study quantum corrections using these classical configurations as a starting point. Such a study would be of relevance to systems in which quantum corrections are non-negligible, as in, say, quantum dot systems. Some of the aforementioned questions are being probed further.
it is easy to demonstrate that the shell structure is independent of g (and also of the magnetic field, when included) as in Sec. I of the paper. Note that the equation above is manifestly independent of the arbitrary scale ρ introduced in the Hamiltonian. Further simplification occurs if we note that for any equilibrium configuration the auxiliary variable, φ is given by and the energy for the equilibrium configuration is given by We now calculate the energy for specific configurations, namely circle and the circle-dot. For the circle case, we have, for N particles distributed symmetrically, In the case of circle-dot, for N particles with N − 1 particles distributed symmetrically on the circle and one at the centre, the energy is given by It is not possible in general to calculate these energies unless we specify the arbitrary scale ρ. However, to ascertain which of these two configurations and has lower energy it is sufficient to look at the difference for the same number of particles, that is, where µ N is already defined in Sec. II. Clearly the circle configuration has lower (higher) energy if µ N is negative (positive). Note that this statement is independent of the arbitrary scale and also the interaction strength. It is now easy to see that µ N is negative for N ≤ 5 and positive otherwise. Therefore the first geometric transition from circle to circle-dot occurs when the number of particles changes from 5 to 6, as in the case of power-law potentials.
Appendix B: Numerical Simulations
In this appendix we briefly discuss the numerical simulations carried out for multi-shell configurations. The analysis is carried out for the Hamiltonian given in Section II for parabolic confinement and may be adapted easily for other model systems discussed in Sections III and IV. Also collected are some results on the eigenvalues of the Hessian of the effective potential at the extrema. From eq.(7) it is easy to see that the same may be obtained as ∇V ef f ( r i ) = 0, where The equilibrium configurations thus are obtained by minimising V ef f numerically. For this we use the version of the conjugate gradient method which uses line minimisation. Since V ef f is positive definite and we use line minimisation, we are guaranteed to reach the extrema which are either local minima or some times saddle points but never local maxima. For a given number of particles, we choose several initial configurations graphically and compare the energies at the local minima. We also check that a local extremum reached is actually a local minimum by computing the eigenvalues of the Hessian of V ef f at the extremum. We verify the "Mendeleev" table of Bedanov and Peeters completely for the special case of Coulomb interaction, i.e. when ν = 1/2.
The Hessian of V ef f can be computed easily. It turns out that of the 2N eigenvalues (for N particles), four can be obtained exactly. These also provide a check on the numerically determined eigenvalues. That the numerically determined eigenvalues contain the exact eigenvalues is also verified. Since the geometry of the extrema is independent of J, this analysis is done for zero magnetic field and J = 0. At an arbitrary point in the configuration the elements of the Hessian matrix of V ef f are given by The eigenvalue equation for this matrix is From these equations, four exact eigenvalues and eigenvectors can be deduced immediately: 1. Both the equilibrium equations and the eigenvalue equations are manifestly rotationally covariant. One therefore expects µ = 0 to be an eigenvalue with the corresponding eigenvector R i denoting the rotation of the r i . This is indeed the case. Explicitly, µ = 0 and R i = ρk × r i ∀ i = 1...N solves the eigenvalue equation when r i satisfy the equilibrium equations. Here ρ is an arbitrary, non-zero factor since the eigenvalue equations are homogeneous.
2. If R i = ρ r i for all i = 1...N, then, using the equilibrium equations, it follows that the eigenvalue equations are satisfied with µ = 2(1 + ν). Thus the equilibrium configurations themselves constitute an eigenvector with an eigenvalue which depends only ν.
In particular it is common to all extrema for every N.
3. It is immediately obvious that if R i = a ∀ i, then the RHS of the eigenvalue equations vanishes and µ = 1 is the corresponding eigenvalue. As there are two independent choices for the two dimensional vector a, this eigenvalue is doubly degenerate. Note that this eigenvalue is totally independent even of the equilibrium equations.
As all these eigenvalues are common to all extrema, the remaining eigenvalues must distinguish saddle points, local minima and local maxima. Apart from providing a check on numerical simulations, these should also prove useful in computing the semi-classical corrections to the classical energies. |
Feminism and Performance: A Post-Disciplinary Couple
Feminist studies resulted from activist challenges to the very institutionalization of knowledge. Feminist studies, like studies of performance imagine their ground in embodied actions performed, somehow, socially, breaking down disciplinary boundaries to create a ‘field’ of study regarded as ‘interdisciplinary’. However, the term ‘post-disciplinary’, now in current usage, announces a different relationship to fields of study than the earlier term ‘interdisciplinary’ might connote. ‘Interdisciplinary’ is a term that signals a sense of a unified field, produced through the historical convergence of subcultures, social structures, and training practices. ‘Post-disciplinary’ retains nothing of the notion that a shared consciousness, or a shared objective, brings together a broad range of discrete studies. Instead, it suggests that the organizing structures of disciplines themselves will not hold. Only conditional conjunctions of social and intellectual forces exist, at which scholarship and performance may be produced. |
// New is a builder for the Poll type
func New(title string, description string, options []Option, expiry int64) Poll {
uid := uuid.New().String()
created := time.Now().Unix()
return Poll{
ID: uid,
Title: title,
Description: description,
Votes: 0,
Options: options,
Created: created,
Modified: created,
Expiry: expiry,
}
} |
// This example runs four worker threads rendering parts of the image independently at different
// paces in a sort of double buffered way.
//
// +---+---+
// | 0 | 1 |
// +---+---+
// | 2 | 3 |
// +---+---+
//
// Each worker thread waits for an image to render into, sleeps for a while, does the drawing, then
// sends the image back and waits for the next one.
//
// The GUI thread holds an image per image part at all times and these images are painted on a
// DrawingArea in its 'draw' signal handler whenever needed.
//
// Additionally the GUI thread has a channel for receiving the images from the worker threads. If
// there is a new image, the old image stored by the GUI thread is replaced with the new one and
// the old image is sent back to the worker thread. Then the appropriate part of the DrawingArea is
// invalidated prompting a redraw.
//
// The two images per thread are allocated and initialized once and sent back and forth repeatedly.
fn build_ui(application: >k::Application) {
let window = ApplicationWindow::new(application);
let area = DrawingArea::new();
window.add(&area);
area.set_size_request(WIDTH * 2, HEIGHT * 2);
// Create the initial, green image
let initial_image = draw_initial();
// This is the channel for sending results from the worker thread to the main thread
// For every received image, queue the corresponding part of the DrawingArea for redrawing
let (ready_tx, ready_rx) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
let mut images = Vec::new();
let mut origins = Vec::new();
let mut workers = Vec::new();
for thread_num in 0..4 {
// This is the channel for sending image from the GUI thread to the workers so that the
// worker can draw the new content into them
let (tx, rx) = mpsc::channel();
// Copy the initial image in two images for the workers
let image0 = initial_image.clone();
let image1 = initial_image.clone();
// Store the first one in our vec. This is the one that would be drawn in the very
// beginning by the DrawingArea.
images.push(RefCell::new(image0));
// Send the second one immediately to the worker thread for drawing the new content
let _ = tx.send(image1);
// Store for each worker thread its render rectangle inside the DrawingArea
origins.push(match thread_num {
0 => (0, 0),
1 => (WIDTH, 0),
2 => (0, HEIGHT),
3 => (WIDTH, HEIGHT),
_ => unreachable!(),
});
// And remember the sender side of the channel that allows the GUI thread to send back
// images to the worker thread
workers.push(tx);
let x = (WIDTH - origins[thread_num].0) as f64;
let y = (HEIGHT - origins[thread_num].1) as f64;
let delay = Duration::from_millis((100 << thread_num) - 5);
// Spawn the worker thread
thread::spawn(clone!(@strong ready_tx => move || {
let mut n = 0;
for mut image in rx.iter() {
n = (n + 1) % 0x10000;
// Draw an arc with a weirdly calculated radius
image.with_surface(|surface| {
let cr = Context::new(surface);
draw_slow(&cr, delay, x, y, 1.2_f64.powi(((n as i32) << thread_num) % 32));
surface.flush();
});
// Send the finished image back to the GUI thread
let _ = ready_tx.send((thread_num, image));
}
}));
}
// The connect-draw signal and the timeout handler closures have to be 'static, and both need
// to have access to our images and related state.
let workspace = Rc::new((images, origins, workers));
// Whenever the drawing area has to be redrawn, render the latest images in the correct
// locations
area.connect_draw(
clone!(@weak workspace => @default-return Inhibit(false), move |_, cr| {
let (ref images, ref origins, _) = *workspace;
for (image, origin) in images.iter().zip(origins.iter()) {
image.borrow_mut().with_surface(|surface| {
draw_image_if_dirty(&cr, surface, *origin, (WIDTH, HEIGHT));
});
}
Inhibit(false)
}),
);
ready_rx.attach(None, move |(thread_num, image)| {
let (ref images, ref origins, ref workers) = *workspace;
// Swap the newly received image with the old stored one and send the old one back to
// the worker thread
let tx = &workers[thread_num];
let image = images[thread_num].replace(image);
let _ = tx.send(image);
area.queue_draw_area(origins[thread_num].0, origins[thread_num].1, WIDTH, HEIGHT);
Continue(true)
});
window.show_all();
} |
package org.openapitools.codegen.typescript.typescriptnode;
import io.swagger.v3.oas.models.OpenAPI;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.TypeScriptNodeClientCodegen;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TypeScriptNodeClientCodegenTest {
@Test
public void convertVarName() throws Exception {
TypeScriptNodeClientCodegen codegen = new TypeScriptNodeClientCodegen();
Assert.assertEquals(codegen.toVarName("name"), "name");
Assert.assertEquals(codegen.toVarName("$name"), "$name");
Assert.assertEquals(codegen.toVarName("nam$$e"), "nam$$e");
Assert.assertEquals(codegen.toVarName("user-name"), "userName");
Assert.assertEquals(codegen.toVarName("user_name"), "userName");
Assert.assertEquals(codegen.toVarName("user|name"), "userName");
Assert.assertEquals(codegen.toVarName("user !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~name"), "user$Name");
}
@Test
public void testSnapshotVersion() {
OpenAPI api = TestUtils.createOpenAPI();
TypeScriptNodeClientCodegen codegen = new TypeScriptNodeClientCodegen();
codegen.additionalProperties().put("npmName", "@openapi/typescript-angular-petstore");
codegen.additionalProperties().put("snapshot", true);
codegen.additionalProperties().put("npmVersion", "1.0.0-SNAPSHOT");
codegen.processOpts();
codegen.preprocessOpenAPI(api);
Assert.assertTrue(codegen.getNpmVersion().matches("^1.0.0-SNAPSHOT.[0-9]{12}$"));
codegen = new TypeScriptNodeClientCodegen();
codegen.additionalProperties().put("npmName", "@openapi/typescript-angular-petstore");
codegen.additionalProperties().put("snapshot", true);
codegen.additionalProperties().put("npmVersion", "3.0.0-M1");
codegen.processOpts();
codegen.preprocessOpenAPI(api);
Assert.assertTrue(codegen.getNpmVersion().matches("^3.0.0-M1-SNAPSHOT.[0-9]{12}$"));
}
@Test
public void testWithoutSnapshotVersion() {
OpenAPI api = TestUtils.createOpenAPI();
TypeScriptNodeClientCodegen codegen = new TypeScriptNodeClientCodegen();
codegen.additionalProperties().put("npmName", "@openapi/typescript-angular-petstore");
codegen.additionalProperties().put("snapshot", false);
codegen.additionalProperties().put("npmVersion", "1.0.0-SNAPSHOT");
codegen.processOpts();
codegen.preprocessOpenAPI(api);
Assert.assertTrue(codegen.getNpmVersion().matches("^1.0.0-SNAPSHOT$"));
codegen = new TypeScriptNodeClientCodegen();
codegen.additionalProperties().put("npmName", "@openapi/typescript-angular-petstore");
codegen.additionalProperties().put("snapshot", false);
codegen.additionalProperties().put("npmVersion", "3.0.0-M1");
codegen.processOpts();
codegen.preprocessOpenAPI(api);
Assert.assertTrue(codegen.getNpmVersion().matches("^3.0.0-M1$"));
}
}
|
Officers reportedly reprimanded Lilly Allen, 10, earlier this week, saying the traditional game’s outline she drew on the pavement was akin to criminal damage.
The schoolgirl was said to have been given the warning by two unnamed officers as she played the centuries-old skipping outside her home in Ramsgate, Kent, the Sun reported.
She was issued the warning after making the outlines in white chalk, which washes away in rain.
Her father, Robert Allen, 51, was left angered by the suggestions and has since lodged a formal complaint to Kent Police over the incident, which occurred on Monday.
After posting a picture of the grid on his Facebook page, the pub entertainer joked: “I call her Banksy now.”
Scores of his friends commented on the posting, labelling the police comments as “ridiculous”.
Jeanette Elliott wrote: “It's crazy it's what we all did as kids the worlds gone mad!”
Vernon Vandell added: “Poor copper.....how many weeks basic training do they have to do before they are 'qualified'? He'll be nicking the toddlers for leaving tricycles unattende [sic] next!”
It is understood that police were today “trying to establish” which officers may have spoken to the girl.
“We cannot currently trace any car being in the area at the time,” one source told The Daily Telegraph.
Mr Allen, who is known as Bob, was unavailable for comment today. But he told the tabloid newspaper: “Two policemen in a car drove up to her and said it was illegal to draw on the floor as it was criminal damage.
"I am absolutely seething they have done this."
A Kent Police spokesman said in a statement: "We are trying to trace the officers, who are reported to have made this comment.
"From the circumstances described, it would not appear to have been necessary to advise the young girl that chalking a hopscotch grid may be criminal damage and illegal."
Hopscotch, which children hop from box to box in a set pattern, has been played for centuries and is so popular many schools and playgrounds have grids inbuilt. |
def __load_section(self, raw_section: Dict[str, Any]) -> "Section":
return Section(
int(raw_section["id"]),
raw_section["name"],
raw_section["type"],
raw_section["is_sub_section"],
raw_section["original_video"],
int(raw_section["width"]),
int(raw_section["height"]),
Fraction(raw_section["fps"]),
float(raw_section["duration"]),
raw_section["project_name"],
raw_section["in_project_video"],
raw_section["in_project_thumbnail"],
int(raw_section["in_project_id"]),
) |
/**
* public class LynxExtModule extends ExtModule {
*
* @Override public Map<Integer, LynxUIComponent> createComponents() {
* HashMap<Integer, LynxUIComponent> map = new HashMap<>();
* LynxUIComponent component = new LynxLabelComponent();
* component.collectMethodSpecList();
* map.put(2, component);
* return map;
* }
* }
*/
public class ModuleGenUtil {
public static TypeSpec genModuleClass(ModuleSpec moduleSpec) {
TypeSpec.Builder classSpec = TypeSpec.classBuilder(moduleSpec.moduleName)
.addModifiers(Modifier.PUBLIC).superclass(LynxModule.class);
if (moduleSpec.uiComponentSpecs != null && moduleSpec.uiComponentSpecs.size() > 0) {
MethodSpec createComponents = genCreateUIComponents(moduleSpec.uiComponentSpecs);
classSpec.addMethod(createComponents);
}
if (moduleSpec.jsComponentSpecs != null && moduleSpec.jsComponentSpecs.size() > 0) {
MethodSpec genJSComponent = genRegisterFunctionObject(moduleSpec.jsComponentSpecs);
classSpec.addMethod(genJSComponent);
}
return classSpec.build();
}
private static MethodSpec genCreateUIComponents(List<ComponentSpec> componentSpecList) {
MethodSpec.Builder createComponents = MethodSpec.methodBuilder("createUIComponents")
.addAnnotation(Override.class).addModifiers(Modifier.PUBLIC)
.returns(ParameterizedTypeName.get(Map.class,
Integer.class, LynxUIComponent.class));
createComponents
.addStatement("java.util.HashMap<Integer, LynxUIComponent> map = new java.util.HashMap<>()");
for (int i = 0; i < componentSpecList.size(); i++) {
ComponentSpec m = componentSpecList.get(i);
String fullClassPath = m.packageName + "." + m.genClassName;
createComponents.addStatement("$L component$L = new $L()",
fullClassPath, i, fullClassPath);
createComponents.addStatement("component$L.registerMethodSpecList()", i);
createComponents.addStatement("map.put($L, component$L)", m.type, i);
createComponents.addStatement("com.lynx.utils.RegisterUtil.nativeRegisterTag($L,$S)", m.type, m.tagName);
}
createComponents.addStatement("return map");
return createComponents.build();
}
private static MethodSpec genRegisterFunctionObject(List<ComponentSpec> componentSpecList) {
MethodSpec.Builder registerFunctionObject =
MethodSpec.methodBuilder("registerFunctionObject")
.addAnnotation(Override.class).addModifiers(Modifier.PUBLIC)
.addParameter(LynxRuntime.class, "runtime");
for (int i = 0; i < componentSpecList.size(); i++) {
ComponentSpec m = componentSpecList.get(i);
String fullClassPath = m.packageName + "." + m.genClassName;
registerFunctionObject.addStatement("$L component$L = new $L(new $L(runtime))",
fullClassPath, i, fullClassPath, m.fullAnnotationClassName);
registerFunctionObject.addStatement("runtime.registerModule(component$L, $S)",
i, m.jsObjectName);
}
return registerFunctionObject.build();
}
} |
<gh_stars>0
#!/usr/bin/env python
# Author: <NAME>
# Assistant Dependencies
import argparse
import os.path
import json
import threading
import google.auth.transport.requests
import google.oauth2.credentials
from time import sleep
from google.assistant.library import Assistant
from google.assistant.library.event import EventType
from google.assistant.library.file_helpers import existing_file
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk
import commands
# Endpoint for Assistant
DEVICE_API_URL = 'https://embeddedassistant.googleapis.com/v1alpha2'
class MyAssistant(object):
def __init__(self, window):
self.window = window
self._task = threading.Thread(target=self._run_task)
self._can_start_conversation = True
self._assistant = None
def start(self):
self._task.start()
def _run_task(self):
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument(
'--credentials',
type=existing_file,
metavar='OAUTH2_CREDENTIALS_FILE',
default=os.path.join(
os.path.expanduser('~/.config'),
'google-oauthlib-tool',
'credentials.json'
),
help='Path to store and read OAuth2 credentials'
)
parser.add_argument(
'--device_model_id',
type=str,
metavar='DEVICE_MODEL_ID',
required=True,
help='Device id'
)
parser.add_argument('--project_id', type=str,
metavar='PROJECT_ID', required=False,
help='The project ID used to register device '
+ 'instances.')
# Project Id is optional
args = parser.parse_args()
with open(args.credentials, 'r') as f:
credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f))
with Assistant(credentials, args.device_model_id) as assistant:
self._assistant = assistant
events = assistant.start()
if args.project_id:
self.register_device(args.project_id, credentials,
args.device_model_id, assistant.device_id)
for event in events:
self._process_event(event, assistant.device_id)
def register_device(self, project_id, credentials, device_model_id, device_id):
"""Register the device if needed.
Registers a new assistant device if an instance with the given id
does not already exists for this model.
Args:
project_id(str): The project ID used to register device instance.
credentials(google.oauth2.credentials.Credentials): The Google
OAuth2 credentials of the user to associate the device
instance with.
device_model_id: The registered device model ID.
device_id: The device ID of the new instance.
"""
base_url = '/'.join([DEVICE_API_URL, 'projects', project_id, 'devices'])
device_url = '/'.join([base_url, device_id])
session = google.auth.transport.requests.AuthorizedSession(credentials)
r = session.get(device_url)
print(device_url, r.status_code)
if r.status_code == 404:
print('Registering....', end='', flush=True)
r = session.post(base_url, data=json.dumps({
'id': device_id,
'model_id': device_model_id,
}))
if r.status_code != 200:
raise Exception('failed to register device: ' + r.text)
print('\rDevice registered.')
def process_device_actions(self, event, device_id):
if 'inputs' in event.args:
for i in event.args['inputs']:
if i['intent'] == 'action.devices.EXECUTE':
for c in i['payload']['commands']:
for dev in c['devices']:
if dev['id'] == device_id:
if 'execution' in c:
for e in c['execution']:
if e['params']:
yield e['command'], e['params']
else:
yield e['command'], None
def process_command(self, cmd):
if cmd == 'google':
commands.Sound('up')
self._assistant.stop_conversation()
elif cmd == 'sound down':
commands.Sound('down')
self._assistant.stop_conversation()
def _process_event(self, event, device_id):
if event.type == EventType.ON_START_FINISHED:
self.window.printTranscript(event, 'LEFT')
elif event.type == EventType.ON_CONVERSATION_TURN_STARTED:
self.window.printTranscript("Listening...", 'LEFT')
elif event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED and event.args:
self.window.printTranscript(event.args, 'RIGHT')
# self.process_command(event.args['text'].lower())
elif event.type == EventType.ON_DEVICE_ACTION:
for command, params in self.process_device_actions(event, device_id):
print(event)
print("Executing command", command, 'with params', str(params))
elif event.type == EventType.ON_RESPONDING_STARTED:
self.window.printTranscript(event, 'LEFT')
elif event.type == EventType.ON_CONVERSATION_TURN_FINISHED:
self.window.printTranscript("Done.", 'LEFT')
def _on_button_pressed(self):
if self._can_start_conversation:
self._assistant.start_conversation()
class Exchange(Gtk.ListBoxRow):
def __init__(self, data, align):
super(Gtk.ListBoxRow, self).__init__()
self.data = data
self.label = Gtk.Label(data)
if align == 'LEFT':
self.label.set_justify(Gtk.Justification.LEFT)
else:
self.label.set_justify(Gtk.Justification.RIGHT)
self.add(self.label)
# Main Window Class
class MyWindow(Gtk.Window):
def __init__(self):
# Window Configurations
Gtk.Window.__init__(self, title="Jarvis")
self.set_border_width(8)
self.set_default_size(400, 500)
self.set_icon_from_file("./assets/mic.png")
header = Gtk.HeaderBar()
header.set_show_close_button(True)
header.props.title = "Jarvis"
self.set_titlebar(header)
# Main Container
self.box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.box.set_homogeneous(False)
self.add(self.box)
# Main List
listcontainer = Gtk.ScrolledWindow()
self.box.pack_start(listcontainer, True, True, 0)
self.list = Gtk.ListBox()
self.list.set_selection_mode(Gtk.SelectionMode.NONE)
listcontainer.add(self.list)
# Trigger
self.button = Gtk.Button(label="Start")
self.button.connect("clicked", self.on_button_clicked)
Gtk.StyleContext.add_class(self.button.get_style_context(), "suggested-action")
Gtk.StyleContext.add_class(self.button.get_style_context(), "circular")
self.box.pack_start(self.button, False, False, 8)
def on_button_clicked(self, widget):
assistant._on_button_pressed()
self.list.show_all()
def printTranscript(self, text, align):
exchange = Exchange(text, align)
self.list.add(exchange)
self.list.show_all()
def showProgress(self):
self.progressbar = Gtk.ProgressBar()
self.box.pack_start(self.progressbar, True, True, 0)
def do_delete_event(self, event):
self.printTranscript('GoodBye', 'LEFT')
sleep(2)
return False
css = b"""
window.background {
background: white;
}
headerbar, headerbar button {
background: white;
color: black;
}
list {
background: white;
color: #333;
}
row {
background: #eee;
border-radius: 15px;
padding: 6px;
margin-bottom: 6px;
}
.button, .circular, .suggested-action {
background: #546e7a;
}
"""
style_provider = Gtk.CssProvider()
style_provider.load_from_data(css)
Gtk.StyleContext.add_provider_for_screen(
Gdk.Screen.get_default(),
style_provider,
Gtk.STYLE_PROVIDER_PRIORITY_USER
)
window = MyWindow()
window.show_all()
window.connect("destroy", Gtk.main_quit)
assistant = MyAssistant(window)
assistant.start()
Gtk.main()
|
// Called for each tile t of this Area
void Area::AddTileInformation(const BWAPI::TilePosition t, const Tile & tile)
{
++m_tiles;
if (tile.Buildable()) ++m_buildableTiles;
if (tile.GroundHeight() == 1) ++m_highGroundTiles;
if (tile.GroundHeight() == 2) ++m_veryHighGroundTiles;
if (t.x < m_topLeft.x) m_topLeft.x = t.x;
if (t.y < m_topLeft.y) m_topLeft.y = t.y;
if (t.x > m_bottomRight.x) m_bottomRight.x = t.x;
if (t.y > m_bottomRight.y) m_bottomRight.y = t.y;
} |
//
// GameManager.cpp for in /home/gandoulf/epitech/rtype/RtypeSRC/source/Rtype
//
// Made by Gandoulf
// Login <<EMAIL>>
//
// Started on Sat Dec 17 11:53:40 2016 Gandoulf
// Last update Thu Dec 29 11:15:16 2016 Gandoulf
//
#include "Rtype/GameManager.hpp"
#include "Server/Server.hpp"
#include "Utils/Vector.hpp"
namespace rtype
{
GameManager::GameManager(std::string const &name, std::map<int, std::queue<IEvent *>> & event,
std::map<int, std::queue<IEvent *> > &clientInputs,
std::map<int, GameObject *> &clientGO)
: _name(name), _synchroniser(event), _closing(false), _clientInputs(clientInputs),
_clientGO(clientGO)
{
}
GameManager::~GameManager()
{
//TODO delete all Go, message
}
void GameManager::start()
{
_game = instantiate("game.prefab", Vector2F(0,0));
}
void GameManager::stop()
{
Server::closeGameServer(_name);
_closing = true;
}
void GameManager::managerUpdate()
{
if (_closing)
return ;
_chrono.update();
if (!_deleteList.empty())
{
while (_deleteList.size() > 0)
{
std::cout << "deleted obj " << _deleteList.back()->getName() << std::endl;
_gameObjects.deleteObject(_deleteList.back()->getName());
delete _deleteList.back();
_deleteList.pop_back();
}
}
try {
_gameObjects.update();
} catch (std::exception e) {
std::cout << e.what() << std::endl;
}
}
std::queue<IEvent *> *GameManager::getClientEvent(GameObject *go)
{
auto ite = _clientGO.begin();
for (ite; ite != _clientGO.end(); ite++)
if (ite->second->getName() == go->getName())
break;
if (ite != _clientGO.end())
return (&_clientInputs.find(ite->first)->second);
throw GetClientEventError();
}
Synchroniser &GameManager::synchronise()
{
return (_synchroniser);
}
GameObjectManager &GameManager::getGameObjects()
{
return (_gameObjects);
}
GameObject *GameManager::instantiate(std::string const &prefabFile,
Vector2F const &pos,
Vector2F const &scale)
{
GameObject *go = _prefabCreator.instantiate(prefabFile, pos, scale);
if (go != NULL)
{
go->setGameManager(static_cast<IGameManager *>(this));
_gameObjects.addObject(go, go->_dynamic);
}
return (go);
}
void GameManager::destroy(GameObject *gameObject)
{
if (gameObject == NULL)
return ;
if (_gameObjects.getObject(gameObject->getName()) != NULL &&
checkDeleteList(gameObject->getName()) == false)
_deleteList.push_back(gameObject);
}
long double GameManager::deltaTime()
{
return (_chrono.getDeltaTime() / 1000);
}
/* ----------------------------------private---------------------------------- */
bool GameManager::checkDeleteList(std::string const &name)
{
for (int i = 0; i < _deleteList.size(); ++i)
if (_deleteList[i]->getName() == name)
{
return (true);
}
return (false);
}
}
|
import { Context } from '@nuxt/types'
import Auth0Lock from 'auth0-lock'
declare module '@nuxtjs/auth-next' {
interface Auth {
$lock: typeof Auth0Lock
}
}
export default function ({ $auth, $config: { merkaly } }: Context) {
if (merkaly?.AUTH_DOMAIN && merkaly.AUTH_DOMAIN) {
$auth.$lock = new Auth0Lock(merkaly.AUTH_CLIENT_ID, merkaly.AUTH_DOMAIN)
}
return $auth
}
|
def names_and_distribution(self, tablefmt: str = "simple", output_file: str = None, regex: str = r".*",
**kwargs) -> str:
pattern = compile_regex(regex)
datasets = self.filter_dataset(self.datasets.labels, **kwargs)
dataset_labels = {dataset: labels for dataset, labels in datasets.items() if bool(pattern.search(dataset))}
data, headers = [], []
for dataset, values in dataset_labels.items():
row = [dataset]
headers = ["Dataset"]
for dx, abbrev in self.db.abbrev.items():
item = values.get(dx, 0)
if output_file is None:
color = Fore.RED if item == 0 else Fore.GREEN
item = f"{color}{item}{Fore.RESET}"
row.append(item)
headers.append(abbrev)
data.append(row)
if output_file:
df = pd.DataFrame(data, columns=headers)
df.to_csv(output_file, index=None)
return f"Saved to '{output_file}'"
else:
return tabulate(data, headers=headers, tablefmt=tablefmt, showindex=True) |
import { Injectable } from '@angular/core';
import { JwtHelperService } from '@auth0/angular-jwt';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class AuthService {
static localStorageKey = 'AuthService.token'
static get token() {
return localStorage.getItem(AuthService.localStorageKey)
}
private _tokenChangeSubject = new Subject<string | undefined>()
constructor(
private _jwtHelperService: JwtHelperService,
) { }
hasPermissions(...needed: string[]) {
const thisPermissions = this.permissions
for (const permission of needed) {
if (!thisPermissions.includes(permission)) {
return false
}
}
return true
}
get isAuthenticated() {
return !this._jwtHelperService.isTokenExpired(this.token)
}
get token() {
return AuthService.token
}
set token(token: string | undefined) {
if (token) {
localStorage.setItem(AuthService.localStorageKey, token)
} else {
localStorage.removeItem(AuthService.localStorageKey)
}
this._tokenChangeSubject.next(token)
}
get decodedToken() {
return this._jwtHelperService.decodeToken(this.token)
}
get permissions() {
return ((this.decodedToken || {}).permissions || []) as string[]
}
get tokenChange() {
return this._tokenChangeSubject.asObservable()
}
}
|
import { IScope, ILocationService, IComponentOptions } from 'angular';
import { JSONWebToken, User, JWT, ClaimName, UserNameType, CredentialId } from '@digitalpersona/core';
import { ServiceError, IPolicyService, ResourceActions, ContextualInfo, PolicyInfo, Policy, IAuthService } from '@digitalpersona/services';
import { CardsReader, FingerprintReader, SampleFormat } from '@digitalpersona/devices';
import { CredInfo } from '../tokens/configuration/credInfo';
import { IdentityService } from '../../identity';
import template from './signin.html';
import { StatusAlert, Warning } from '../../common';
export default class SigninControl
{
public static readonly Component: IComponentOptions = {
template,
controller: SigninControl,
};
private identity: User|JSONWebToken;
private busy: boolean = false;
private selected: string;
private credentials: CredInfo[];
private enrolledCredentials?: CredentialId[];
private policies?: PolicyInfo;
private error?: Error;
private fingerprintReader: FingerprintReader;
private cardReader: CardsReader;
public static $inject = ["AuthService", "PolicyService", "$scope", "$location", "$route", "SupportedCredentials", "Identity"];
constructor(
private authService: IAuthService,
private policyService: IPolicyService,
private $scope: IScope,
private $location: ILocationService,
private $route: ng.route.IRouteService,
private supportedCredentials: { all: CredInfo[]},
private identityService: IdentityService,
){
}
public async $onInit() {
this.identity = User.Anonymous();
this.fingerprintReader = new FingerprintReader();
this.cardReader = new CardsReader();
try {
await this.fingerprintReader.startAcquisition(SampleFormat.Intermediate);
this.update();
} catch (err) {
this.updateStatus('Fingerprints', new Warning(err.message));
}
try {
await this.cardReader.subscribe();
this.update();
} catch (err) {
this.updateStatus('Cards', new Warning(err.message));
}
this.updateCredentials();
if (this.$route.current) {
const { username } = this.$route.current.params;
await this.updateIdentity(new User(username, UserNameType.DP));
} else
await this.updateIdentity(User.Anonymous());
this.busy = false;
delete this.error;
}
public $onDestroy() {
//if (typeof this.fingerprintReader !== 'undefined') {
this.fingerprintReader.stopAcquisition();
this.fingerprintReader.off();
//}
//delete this.fingerprintReader;
//if (typeof this.cardReader !== 'undefined') {
this.cardReader.unsubscribe();
this.cardReader.off();
//}
//delete this.cardReader;
}
private updateCredentials() {
if (!this.policies)
this.credentials = this.supportedCredentials.all;
const allowed = this.getAllowedCredentials();
this.credentials = this.supportedCredentials.all
.filter(cred => allowed.includes(cred.id));
if (this.enrolledCredentials) {
const enrolled = this.enrolledCredentials;
this.credentials = this.credentials.filter(cred => enrolled.includes(cred.id));
}
if (!this.selected || !this.credentials.some(cred => cred.name === this.selected))
this.selected = this.credentials[0].name;
}
private getAllowedCredentials() {
if (!this.policies)
return this.supportedCredentials.all.map(cred => cred.id);
const unique = (val: any, idx: number, arr: any[]) => arr.indexOf(val) === idx;
return [].concat.apply([],
this.policies.policyList
.map(and => and.policy.map(or => or.cred_id)))
.filter(unique);
}
// TODO: should be a Policies' method
// TODO: if the user is has enrolled only a password but policy requires multi-factor,
// let the user in but redirect them to the credential enrollment page.
// This way fresh users with a password only will have a chance to comply.
public isEnoughCredentials() {
if (!this.identity) return false;
if (this.identity instanceof User)
return false;
const authenticated = JWT.claims(this.identity)[ClaimName.CredentialsUsed];
if (!authenticated || authenticated.length === 0)
return false;
if (!this.policies)
return true; // any credential is enough
const ids = authenticated.map(cred => cred.id);
const satisfied = this.policies.policyList.some(rule =>
rule.policy.every(el => ids.includes(el.cred_id.toUpperCase())),
);
return satisfied;
}
public get isIdentified() {
return !(this.identity instanceof User);
}
public isSelected(name: string) {
return this.selected && this.selected === name;
}
public isAllowed(name: string) {
return this.getAllowedCredentials().includes(name);
}
public isAuthenticated(cred: CredInfo) {
if (this.identity instanceof User)
return false;
const authenticated = JWT.claims(this.identity)[ClaimName.CredentialsUsed];
return authenticated && authenticated.findIndex((used => used.id.toUpperCase() === cred.id)) >= 0;
}
public updateUsername(value: string) {
this.updateIdentity(new User(value));
}
public show(selected: string) {
console.log(`Showing '${selected}'`);
this.selected = selected;
console.log(this.selected);
}
public getUser(): User {
return (this.identity instanceof User)
? this.identity
: User.fromJWT(this.identity);
}
public setBusy() {
this.busy = true;
delete this.error;
}
public update() {
this.$scope.$apply();
}
public async updateIdentity(identity: User| JSONWebToken) {
if (this.policies && (this.identity === identity)) return;
this.identity = identity;
this.update();
try {
const user = this.getUser();
this.policies = await this.policyService
.GetPolicyInfo(user, "*", ResourceActions.Write, new ContextualInfo());
// if (!user.isAnonymous() && !user.isEveryone())
// this.enrolledCredentials = await this.authService.GetUserCredentials(user);
// else
// delete this.enrolledCredentials;
this.updateCredentials();
} catch (e) {
console.log(e);
}
if (this.isEnoughCredentials()) {
this.identityService.set(this.identity as JSONWebToken);
this.$location.url("/");
}
this.busy = false;
this.$scope.$apply();
}
public async updateToken(token: JSONWebToken) {
if (this.identity === token) return;
if (this.isIdentified) {
// TODO: if we've already identified the user, make sure it is the same user again
}
await this.updateIdentity(token);
this.selectNext();
this.$scope.$apply();
}
// selects next best credential among not entered yet
private selectNext() {
if (this.identity instanceof User) return;
if (!this.policies) return;
const authenticated = JWT.claims(this.identity)[ClaimName.CredentialsUsed];
if (!authenticated) return;
const ids = authenticated.map(cred => cred.id);
const score = (rule: Policy) => this.supportedCredentials.all
.filter(cred => rule.policy.map(p => p.cred_id).includes(cred.id))
.reduce((prev, curr) => prev * curr.strength, 1);
const bestPolicyRules = this.policies.policyList
.sort((a, b) => score(b) - score(a))
.map(rule => rule.policy
.map(cred => cred.cred_id)
.filter(id => !ids.includes(id))) // create a reduced set of ids
.filter(rule => rule.length > 0)
.sort((a, b) => a.length - b.length);
if (bestPolicyRules.length > 0) {
const id = bestPolicyRules[0][0];
const cred = this.supportedCredentials.all.find(c => c.id === id);
if (cred)
this.show(cred.name);
}
}
public updateStatus(cred: string, status?: StatusAlert) {
this.busy = false;
if (status instanceof Error) {
this.error = status;
this.selected = cred;
} else
delete this.error;
// if (error instanceof ServiceError) {
// if (error.code === -2146893033) { // Authentication context expired, drop the token and replace with a user
// this.updateIdentity(this.getUser());
// }
// }
}
public showError(error: ServiceError|Error, cred: string) {
this.busy = false;
if (this.error === error) return;
if (error) {
this.error = error;
this.selected = cred;
} else
delete this.error;
if (error instanceof ServiceError) {
if (error.code === -2146893033) { // Authentication context expired, drop the token and replace with a user
this.updateIdentity(this.getUser());
}
}
this.update();
}
}
|
// MJPG (Motion JPeg) to I420
// TODO(fbarchard): review w and h requirement. dw and dh may be enough.
int MJPGToI420(const uint8* sample,
size_t sample_size,
uint8* y, int y_stride,
uint8* u, int u_stride,
uint8* v, int v_stride,
int w, int h,
int dw, int dh) {
if (sample_size == kUnknownDataSize) {
return -1;
}
MJpegDecoder mjpeg_decoder;
bool ret = mjpeg_decoder.LoadFrame(sample, sample_size);
if (ret && (mjpeg_decoder.GetWidth() != w ||
mjpeg_decoder.GetHeight() != h)) {
mjpeg_decoder.UnloadFrame();
return 1;
}
if (ret) {
I420Buffers bufs = { y, y_stride, u, u_stride, v, v_stride, dw, dh };
if (mjpeg_decoder.GetColorSpace() ==
MJpegDecoder::kColorSpaceYCbCr &&
mjpeg_decoder.GetNumComponents() == 3 &&
mjpeg_decoder.GetVertSampFactor(0) == 2 &&
mjpeg_decoder.GetHorizSampFactor(0) == 2 &&
mjpeg_decoder.GetVertSampFactor(1) == 1 &&
mjpeg_decoder.GetHorizSampFactor(1) == 1 &&
mjpeg_decoder.GetVertSampFactor(2) == 1 &&
mjpeg_decoder.GetHorizSampFactor(2) == 1) {
ret = mjpeg_decoder.DecodeToCallback(&JpegCopyI420, &bufs, dw, dh);
} else if (mjpeg_decoder.GetColorSpace() ==
MJpegDecoder::kColorSpaceYCbCr &&
mjpeg_decoder.GetNumComponents() == 3 &&
mjpeg_decoder.GetVertSampFactor(0) == 1 &&
mjpeg_decoder.GetHorizSampFactor(0) == 2 &&
mjpeg_decoder.GetVertSampFactor(1) == 1 &&
mjpeg_decoder.GetHorizSampFactor(1) == 1 &&
mjpeg_decoder.GetVertSampFactor(2) == 1 &&
mjpeg_decoder.GetHorizSampFactor(2) == 1) {
ret = mjpeg_decoder.DecodeToCallback(&JpegI422ToI420, &bufs, dw, dh);
} else if (mjpeg_decoder.GetColorSpace() ==
MJpegDecoder::kColorSpaceYCbCr &&
mjpeg_decoder.GetNumComponents() == 3 &&
mjpeg_decoder.GetVertSampFactor(0) == 1 &&
mjpeg_decoder.GetHorizSampFactor(0) == 1 &&
mjpeg_decoder.GetVertSampFactor(1) == 1 &&
mjpeg_decoder.GetHorizSampFactor(1) == 1 &&
mjpeg_decoder.GetVertSampFactor(2) == 1 &&
mjpeg_decoder.GetHorizSampFactor(2) == 1) {
ret = mjpeg_decoder.DecodeToCallback(&JpegI444ToI420, &bufs, dw, dh);
} else if (mjpeg_decoder.GetColorSpace() ==
MJpegDecoder::kColorSpaceYCbCr &&
mjpeg_decoder.GetNumComponents() == 3 &&
mjpeg_decoder.GetVertSampFactor(0) == 1 &&
mjpeg_decoder.GetHorizSampFactor(0) == 4 &&
mjpeg_decoder.GetVertSampFactor(1) == 1 &&
mjpeg_decoder.GetHorizSampFactor(1) == 1 &&
mjpeg_decoder.GetVertSampFactor(2) == 1 &&
mjpeg_decoder.GetHorizSampFactor(2) == 1) {
ret = mjpeg_decoder.DecodeToCallback(&JpegI411ToI420, &bufs, dw, dh);
} else if (mjpeg_decoder.GetColorSpace() ==
MJpegDecoder::kColorSpaceGrayscale &&
mjpeg_decoder.GetNumComponents() == 1 &&
mjpeg_decoder.GetVertSampFactor(0) == 1 &&
mjpeg_decoder.GetHorizSampFactor(0) == 1) {
ret = mjpeg_decoder.DecodeToCallback(&JpegI400ToI420, &bufs, dw, dh);
} else {
mjpeg_decoder.UnloadFrame();
return 1;
}
}
return 0;
} |
ANCIENT GREECE - ARISTOPHANES - ECCLESIAZUSAE (Comedy, Greek, 392 BCE , 1,183 lines)
Introduction
Back to Top of Page
“Ecclesiazusae” (Gr: “Ekklesiazousai”), also known by the titles “The Assembly Women”, “The Congress Women” or “Women in Parliament” among others, is a late comedy by the ancient Greek playwright Aristophanes, dating from 392 BCE . Similar in theme to his “Lysistrata” in that a large portion of the comedy comes from women involving themselves in politics, the play is a satire on a communistic utopia enforced by the women of Athens under their leader Praxagora.
Synopsis
Back to Top of Page
Dramatis Personae
PRAXAGORA
BLEPYRUS, husband of Praxagora
WOMEN
A MAN
CHREMES
A CITIZEN
HERALD
A GIRL
A YOUNG MAN
THREE OLD WOMEN
A SERVANT MAID to Praxagora
CHORUS OF WOMEN
Once in power, Praxagora realizes that she has to come up with some novel and radical proposals. She and the other women then institute a communist-like government in which the state feeds, houses and generally takes care of every Athenian. Both property and women are to be henceforth held in common, and they enforce an idea of equality by allowing every man to sleep with every woman, so long as the man first sleeps with an ugly woman before he may sleep with a beautiful one.
All slaves are to be publicly owned, and are to to carry out the work currently done by poor people leaving everyone else to live a life of leisure. All individual households are to be knocked together to form a communal dwelling and all citizens are to dine at the public expense in the various public halls of the city, the particular place of each being determined by lot.
The play ends with a gigantic communal banquet (the elaborate menu of which is given in burlesque) and with the jubilation of the women over their triumphs.
Analysis
Back to Top of Page
“Ecclesiazusae” was written towards the end of Aristophanes’ life, around 392 BCE , after a 13 year gap in our knowledge of his work (although he continued to write during this time, the works are all lost). It is not considered one of his best plays, and perhaps lacks the wit and ingenuity of “Lysistrata”, the play which it most resembles.
It was written after the loss of the Peloponnesian War with Sparta in 404 BCE , the brief reign of terror under the Thirty Tyrants, the restoration of democracy under Thrasybulus in 403 BCE , the trial and execution of Socrates in 399 BCE , and the start of a new war with Corinth in 395 BCE . The so-called Golden Age of Athens was therefore long gone by the time this play was being written. Although democracy of sorts had been re-established, the idea of women participating in politics and citizenship, and the very title “The Women of the Assembly”, would have been considered an amusing oxymoron by the male Greek audience.
The “Republic” of Plato had been written, and probably delivered in the form of oral lectures at Athens, only two or three years before (even if it was not officially published until some twenty years later), and it had no doubt excited a considerable sensation. “Ecclesiazusae” is therefore probably at least as much a satire on the idea of an ideal republic founded upon communistic principles, as it is on the idea of women in politics. The Aristophanic and Platonic utopias share many aspects in common, including the community of property the community of women and sexual equality. Praxagora’s goal, however, unlike Plato’s, is increased democracy.
The strong, organized women in the play are contrasted with the effeminate and ineffectual men, which is Aristophanes’ comment on the dissolute state of Athenian politics. As in “Lysistrata”, the women’s power is exercised both politically and sexually.
Although the play has traditionally trailed along in the shadow of plays like “Lysistrata” and “Thesmophoriazusae”, it is more revolutionary technically than either of its predecessors, and it is sometimes considered a kind of missing link between the classical traditions of Old Comedy and New (or at least Middle) Comedy. The action moves along swiftly, especially given that the role of the Chorus has been reduced to practically nothing, although towards the middle of the play the action seems to grind to halt, and the humour begins to turn too much on a repetition of the same basic joke. Interestingly, Praxagora, the protagonist, baldly states in line 724 that, having launched her new social order and achieved her dream, she is now leaving the play. Although the succeeding scenes follow from her innovation, she does not actually control them, and one has the sense of the play losing its way and falling apart somewhat.
The play contains the longest word in Greek, transliterated as “lopadotemachoselachogaleokranioleipsanodrimupotrimmatosilphioliparomelitoaktakexhumenokich-
lepikossuphophattoperisteralektruonoptopiphallidokinklopeleioplagoosiraiobaphetragalopterugon”, which translates as the name of a dish compounded of all kinds of dainties, fish, flesh, fowl and sauces.
Resources
Back to Top of Page
English translation (Internet Classics Archive): http://classics.mit.edu/Aristophanes/eccles.html
Greek version with word-by-word translation (Perseus Project): http://www.perseus.tufts.edu/hopper/text.jsp?doc=Perseus:text:1999.01.0029 |
/*
* Decompiled with CFR 0.150.
*/
package us.myles.viaversion.libs.javassist.bytecode.analysis;
import java.io.PrintStream;
import us.myles.viaversion.libs.javassist.CtClass;
import us.myles.viaversion.libs.javassist.CtMethod;
import us.myles.viaversion.libs.javassist.Modifier;
import us.myles.viaversion.libs.javassist.NotFoundException;
import us.myles.viaversion.libs.javassist.bytecode.BadBytecode;
import us.myles.viaversion.libs.javassist.bytecode.CodeAttribute;
import us.myles.viaversion.libs.javassist.bytecode.CodeIterator;
import us.myles.viaversion.libs.javassist.bytecode.ConstPool;
import us.myles.viaversion.libs.javassist.bytecode.Descriptor;
import us.myles.viaversion.libs.javassist.bytecode.InstructionPrinter;
import us.myles.viaversion.libs.javassist.bytecode.MethodInfo;
import us.myles.viaversion.libs.javassist.bytecode.analysis.Analyzer;
import us.myles.viaversion.libs.javassist.bytecode.analysis.Frame;
import us.myles.viaversion.libs.javassist.bytecode.analysis.Type;
public final class FramePrinter {
private final PrintStream stream;
public FramePrinter(PrintStream stream) {
this.stream = stream;
}
public static void print(CtClass clazz, PrintStream stream) {
new FramePrinter(stream).print(clazz);
}
public void print(CtClass clazz) {
CtMethod[] methods = clazz.getDeclaredMethods();
for (int i = 0; i < methods.length; ++i) {
this.print(methods[i]);
}
}
private String getMethodString(CtMethod method) {
try {
return Modifier.toString(method.getModifiers()) + " " + method.getReturnType().getName() + " " + method.getName() + Descriptor.toString(method.getSignature()) + ";";
}
catch (NotFoundException e) {
throw new RuntimeException(e);
}
}
public void print(CtMethod method) {
Frame[] frames;
this.stream.println("\n" + this.getMethodString(method));
MethodInfo info = method.getMethodInfo2();
ConstPool pool = info.getConstPool();
CodeAttribute code = info.getCodeAttribute();
if (code == null) {
return;
}
try {
frames = new Analyzer().analyze(method.getDeclaringClass(), info);
}
catch (BadBytecode e) {
throw new RuntimeException(e);
}
int spacing = String.valueOf(code.getCodeLength()).length();
CodeIterator iterator = code.iterator();
while (iterator.hasNext()) {
int pos;
try {
pos = iterator.next();
}
catch (BadBytecode e) {
throw new RuntimeException(e);
}
this.stream.println(pos + ": " + InstructionPrinter.instructionString(iterator, pos, pool));
this.addSpacing(spacing + 3);
Frame frame = frames[pos];
if (frame == null) {
this.stream.println("--DEAD CODE--");
continue;
}
this.printStack(frame);
this.addSpacing(spacing + 3);
this.printLocals(frame);
}
}
private void printStack(Frame frame) {
this.stream.print("stack [");
int top = frame.getTopIndex();
for (int i = 0; i <= top; ++i) {
if (i > 0) {
this.stream.print(", ");
}
Type type = frame.getStack(i);
this.stream.print(type);
}
this.stream.println("]");
}
private void printLocals(Frame frame) {
this.stream.print("locals [");
int length = frame.localsLength();
for (int i = 0; i < length; ++i) {
Type type;
if (i > 0) {
this.stream.print(", ");
}
this.stream.print((type = frame.getLocal(i)) == null ? "empty" : type.toString());
}
this.stream.println("]");
}
private void addSpacing(int count) {
while (count-- > 0) {
this.stream.print(' ');
}
}
}
|
#ifndef SSE2NEON_H
#define SSE2NEON_H
// This header file provides a simple API translation layer
// between SSE intrinsics to their corresponding Arm/Aarch64 NEON versions
//
// This header file does not yet translate all of the SSE intrinsics.
//
// Contributors to this work are:
// <NAME> <<EMAIL>>
// <NAME> <<EMAIL>>
// <NAME> <<EMAIL>>
// <NAME> <<EMAIL>>
// <NAME> <<EMAIL>>
// <NAME> <<EMAIL>>
// <NAME> <<EMAIL>>
// <NAME> <<EMAIL>>
// <NAME> <<EMAIL>>
// <NAME> (easyaspi314) <<EMAIL>>
// <NAME> <<EMAIL>>
/*
* The MIT license:
*
* 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.
*/
#if defined(__GNUC__) || defined(__clang__)
#pragma push_macro("FORCE_INLINE")
#pragma push_macro("ALIGN_STRUCT")
#define FORCE_INLINE static inline __attribute__((always_inline))
#define ALIGN_STRUCT(x) __attribute__((aligned(x)))
#else
#error "Macro name collisions may happens with unknown compiler"
#ifdef FORCE_INLINE
#undef FORCE_INLINE
#endif
#define FORCE_INLINE static inline
#ifndef ALIGN_STRUCT
#define ALIGN_STRUCT(x) __declspec(align(x))
#endif
#endif
#include <stdint.h>
#include <stdlib.h>
#include <arm_neon.h>
/**
* MACRO for shuffle parameter for _mm_shuffle_ps().
* Argument fp3 is a digit[0123] that represents the fp from argument "b"
* of mm_shuffle_ps that will be placed in fp3 of result. fp2 is the same
* for fp2 in result. fp1 is a digit[0123] that represents the fp from
* argument "a" of mm_shuffle_ps that will be places in fp1 of result.
* fp0 is the same for fp0 of result.
*/
#define _MM_SHUFFLE(fp3, fp2, fp1, fp0) \
(((fp3) << 6) | ((fp2) << 4) | ((fp1) << 2) | ((fp0)))
/* indicate immediate constant argument in a given range */
#define __constrange(a, b) const
typedef float32x2_t __m64;
typedef float32x4_t __m128;
typedef int64x2_t __m128i;
// ******************************************
// type-safe casting between types
// ******************************************
#define vreinterpretq_m128_f16(x) vreinterpretq_f32_f16(x)
#define vreinterpretq_m128_f32(x) (x)
#define vreinterpretq_m128_f64(x) vreinterpretq_f32_f64(x)
#define vreinterpretq_m128_u8(x) vreinterpretq_f32_u8(x)
#define vreinterpretq_m128_u16(x) vreinterpretq_f32_u16(x)
#define vreinterpretq_m128_u32(x) vreinterpretq_f32_u32(x)
#define vreinterpretq_m128_u64(x) vreinterpretq_f32_u64(x)
#define vreinterpretq_m128_s8(x) vreinterpretq_f32_s8(x)
#define vreinterpretq_m128_s16(x) vreinterpretq_f32_s16(x)
#define vreinterpretq_m128_s32(x) vreinterpretq_f32_s32(x)
#define vreinterpretq_m128_s64(x) vreinterpretq_f32_s64(x)
#define vreinterpretq_f16_m128(x) vreinterpretq_f16_f32(x)
#define vreinterpretq_f32_m128(x) (x)
#define vreinterpretq_f64_m128(x) vreinterpretq_f64_f32(x)
#define vreinterpretq_u8_m128(x) vreinterpretq_u8_f32(x)
#define vreinterpretq_u16_m128(x) vreinterpretq_u16_f32(x)
#define vreinterpretq_u32_m128(x) vreinterpretq_u32_f32(x)
#define vreinterpretq_u64_m128(x) vreinterpretq_u64_f32(x)
#define vreinterpretq_s8_m128(x) vreinterpretq_s8_f32(x)
#define vreinterpretq_s16_m128(x) vreinterpretq_s16_f32(x)
#define vreinterpretq_s32_m128(x) vreinterpretq_s32_f32(x)
#define vreinterpretq_s64_m128(x) vreinterpretq_s64_f32(x)
#define vreinterpretq_m128i_s8(x) vreinterpretq_s64_s8(x)
#define vreinterpretq_m128i_s16(x) vreinterpretq_s64_s16(x)
#define vreinterpretq_m128i_s32(x) vreinterpretq_s64_s32(x)
#define vreinterpretq_m128i_s64(x) (x)
#define vreinterpretq_m128i_u8(x) vreinterpretq_s64_u8(x)
#define vreinterpretq_m128i_u16(x) vreinterpretq_s64_u16(x)
#define vreinterpretq_m128i_u32(x) vreinterpretq_s64_u32(x)
#define vreinterpretq_m128i_u64(x) vreinterpretq_s64_u64(x)
#define vreinterpretq_s8_m128i(x) vreinterpretq_s8_s64(x)
#define vreinterpretq_s16_m128i(x) vreinterpretq_s16_s64(x)
#define vreinterpretq_s32_m128i(x) vreinterpretq_s32_s64(x)
#define vreinterpretq_s64_m128i(x) (x)
#define vreinterpretq_u8_m128i(x) vreinterpretq_u8_s64(x)
#define vreinterpretq_u16_m128i(x) vreinterpretq_u16_s64(x)
#define vreinterpretq_u32_m128i(x) vreinterpretq_u32_s64(x)
#define vreinterpretq_u64_m128i(x) vreinterpretq_u64_s64(x)
// A struct is defined in this header file called 'SIMDVec' which can be used
// by applications which attempt to access the contents of an _m128 struct
// directly. It is important to note that accessing the __m128 struct directly
// is bad coding practice by Microsoft: @see:
// https://msdn.microsoft.com/en-us/library/ayeb3ayc.aspx
//
// However, some legacy source code may try to access the contents of an __m128
// struct directly so the developer can use the SIMDVec as an alias for it. Any
// casting must be done manually by the developer, as you cannot cast or
// otherwise alias the base NEON data type for intrinsic operations.
//
// union intended to allow direct access to an __m128 variable using the names
// that the MSVC compiler provides. This union should really only be used when
// trying to access the members of the vector as integer values. GCC/clang
// allow native access to the float members through a simple array access
// operator (in C since 4.6, in C++ since 4.8).
//
// Ideally direct accesses to SIMD vectors should not be used since it can cause
// a performance hit. If it really is needed however, the original __m128
// variable can be aliased with a pointer to this union and used to access
// individual components. The use of this union should be hidden behind a macro
// that is used throughout the codebase to access the members instead of always
// declaring this type of variable.
typedef union ALIGN_STRUCT(16) SIMDVec {
float m128_f32[4]; // as floats - do not to use this. Added for convenience.
int8_t m128_i8[16]; // as signed 8-bit integers.
int16_t m128_i16[8]; // as signed 16-bit integers.
int32_t m128_i32[4]; // as signed 32-bit integers.
int64_t m128_i64[2]; // as signed 64-bit integers.
uint8_t m128_u8[16]; // as unsigned 8-bit integers.
uint16_t m128_u16[8]; // as unsigned 16-bit integers.
uint32_t m128_u32[4]; // as unsigned 32-bit integers.
uint64_t m128_u64[2]; // as unsigned 64-bit integers.
} SIMDVec;
// casting using SIMDVec
#define vreinterpretq_nth_u64_m128i(x, n) (((SIMDVec *) &x)->m128_u64[n])
#define vreinterpretq_nth_u32_m128i(x, n) (((SIMDVec *) &x)->m128_u32[n])
// ******************************************
// Backwards compatibility for compilers with lack of specific type support
// ******************************************
// Older gcc does not define vld1q_u8_x4 type
#if defined(__GNUC__) && !defined(__clang__)
#if __GNUC__ <= 9
FORCE_INLINE uint8x16x4_t vld1q_u8_x4(const uint8_t *p)
{
uint8x16x4_t ret;
ret.val[0] = vld1q_u8(p + 0);
ret.val[1] = vld1q_u8(p + 16);
ret.val[2] = vld1q_u8(p + 32);
ret.val[3] = vld1q_u8(p + 48);
return ret;
}
#endif
#endif
// ******************************************
// Set/get methods
// ******************************************
// Loads one cache line of data from address p to a location closer to the
// processor. https://msdn.microsoft.com/en-us/library/84szxsww(v=vs.100).aspx
FORCE_INLINE void _mm_prefetch(const void *p, int i)
{
(void)i;
__builtin_prefetch(p);
}
// extracts the lower order floating point value from the parameter :
// https://msdn.microsoft.com/en-us/library/bb514059%28v=vs.120%29.aspx?f=255&MSPPError=-2147217396
FORCE_INLINE float _mm_cvtss_f32(__m128 a)
{
return vgetq_lane_f32(vreinterpretq_f32_m128(a), 0);
}
// Sets the 128-bit value to zero
// https://msdn.microsoft.com/en-us/library/vstudio/ys7dw0kh(v=vs.100).aspx
FORCE_INLINE __m128i _mm_setzero_si128(void)
{
return vreinterpretq_m128i_s32(vdupq_n_s32(0));
}
// Clears the four single-precision, floating-point values.
// https://msdn.microsoft.com/en-us/library/vstudio/tk1t2tbz(v=vs.100).aspx
FORCE_INLINE __m128 _mm_setzero_ps(void)
{
return vreinterpretq_m128_f32(vdupq_n_f32(0));
}
// Sets the four single-precision, floating-point values to w.
//
// r0 := r1 := r2 := r3 := w
//
// https://msdn.microsoft.com/en-us/library/vstudio/2x1se8ha(v=vs.100).aspx
FORCE_INLINE __m128 _mm_set1_ps(float _w)
{
return vreinterpretq_m128_f32(vdupq_n_f32(_w));
}
// Sets the four single-precision, floating-point values to w.
// https://msdn.microsoft.com/en-us/library/vstudio/2x1se8ha(v=vs.100).aspx
FORCE_INLINE __m128 _mm_set_ps1(float _w)
{
return vreinterpretq_m128_f32(vdupq_n_f32(_w));
}
// Sets the four single-precision, floating-point values to the four inputs.
// https://msdn.microsoft.com/en-us/library/vstudio/afh0zf75(v=vs.100).aspx
FORCE_INLINE __m128 _mm_set_ps(float w, float z, float y, float x)
{
float __attribute__((aligned(16))) data[4] = {x, y, z, w};
return vreinterpretq_m128_f32(vld1q_f32(data));
}
// Sets the four single-precision, floating-point values to the four inputs in
// reverse order.
// https://msdn.microsoft.com/en-us/library/vstudio/d2172ct3(v=vs.100).aspx
FORCE_INLINE __m128 _mm_setr_ps(float w, float z, float y, float x)
{
float __attribute__((aligned(16))) data[4] = {w, z, y, x};
return vreinterpretq_m128_f32(vld1q_f32(data));
}
// Sets the 8 signed 16-bit integer values in reverse order.
//
// Return Value
// r0 := w0
// r1 := w1
// ...
// r7 := w7
FORCE_INLINE __m128i _mm_setr_epi16(short w0,
short w1,
short w2,
short w3,
short w4,
short w5,
short w6,
short w7)
{
int16_t __attribute__((aligned(16)))
data[8] = {w0, w1, w2, w3, w4, w5, w6, w7};
return vreinterpretq_m128i_s16(vld1q_s16((int16_t *) data));
}
// Sets the 4 signed 32-bit integer values in reverse order
// https://technet.microsoft.com/en-us/library/security/27yb3ee5(v=vs.90).aspx
FORCE_INLINE __m128i _mm_setr_epi32(int i3, int i2, int i1, int i0)
{
int32_t __attribute__((aligned(16))) data[4] = {i3, i2, i1, i0};
return vreinterpretq_m128i_s32(vld1q_s32(data));
}
// Sets the 16 signed 8-bit integer values to b.
//
// r0 := b
// r1 := b
// ...
// r15 := b
//
// https://msdn.microsoft.com/en-us/library/6e14xhyf(v=vs.100).aspx
FORCE_INLINE __m128i _mm_set1_epi8(signed char w)
{
return vreinterpretq_m128i_s8(vdupq_n_s8(w));
}
// Sets the 8 signed 16-bit integer values to w.
//
// r0 := w
// r1 := w
// ...
// r7 := w
//
// https://msdn.microsoft.com/en-us/library/k0ya3x0e(v=vs.90).aspx
FORCE_INLINE __m128i _mm_set1_epi16(short w)
{
return vreinterpretq_m128i_s16(vdupq_n_s16(w));
}
// Sets the 16 signed 8-bit integer values.
// https://msdn.microsoft.com/en-us/library/x0cx8zd3(v=vs.90).aspx
FORCE_INLINE __m128i _mm_set_epi8(signed char b15,
signed char b14,
signed char b13,
signed char b12,
signed char b11,
signed char b10,
signed char b9,
signed char b8,
signed char b7,
signed char b6,
signed char b5,
signed char b4,
signed char b3,
signed char b2,
signed char b1,
signed char b0)
{
int8_t __attribute__((aligned(16)))
data[16] = {(int8_t) b0, (int8_t) b1, (int8_t) b2, (int8_t) b3,
(int8_t) b4, (int8_t) b5, (int8_t) b6, (int8_t) b7,
(int8_t) b8, (int8_t) b9, (int8_t) b10, (int8_t) b11,
(int8_t) b12, (int8_t) b13, (int8_t) b14, (int8_t) b15};
return (__m128i) vld1q_s8(data);
}
// Sets the 8 signed 16-bit integer values.
// https://msdn.microsoft.com/en-au/library/3e0fek84(v=vs.90).aspx
FORCE_INLINE __m128i _mm_set_epi16(short i7,
short i6,
short i5,
short i4,
short i3,
short i2,
short i1,
short i0)
{
int16_t __attribute__((aligned(16)))
data[8] = {i0, i1, i2, i3, i4, i5, i6, i7};
return vreinterpretq_m128i_s16(vld1q_s16(data));
}
// Sets the 16 signed 8-bit integer values in reverse order.
// https://msdn.microsoft.com/en-us/library/2khb9c7k(v=vs.90).aspx
FORCE_INLINE __m128i _mm_setr_epi8(signed char b0,
signed char b1,
signed char b2,
signed char b3,
signed char b4,
signed char b5,
signed char b6,
signed char b7,
signed char b8,
signed char b9,
signed char b10,
signed char b11,
signed char b12,
signed char b13,
signed char b14,
signed char b15)
{
int8_t __attribute__((aligned(16)))
data[16] = {(int8_t) b0, (int8_t) b1, (int8_t) b2, (int8_t) b3,
(int8_t) b4, (int8_t) b5, (int8_t) b6, (int8_t) b7,
(int8_t) b8, (int8_t) b9, (int8_t) b10, (int8_t) b11,
(int8_t) b12, (int8_t) b13, (int8_t) b14, (int8_t) b15};
return (__m128i) vld1q_s8(data);
}
// Sets the 4 signed 32-bit integer values to i.
//
// r0 := i
// r1 := i
// r2 := i
// r3 := I
//
// https://msdn.microsoft.com/en-us/library/vstudio/h4xscxat(v=vs.100).aspx
FORCE_INLINE __m128i _mm_set1_epi32(int _i)
{
return vreinterpretq_m128i_s32(vdupq_n_s32(_i));
}
// Sets the 2 signed 64-bit integer values to i.
// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/whtfzhzk(v=vs.100)
FORCE_INLINE __m128i _mm_set1_epi64(int64_t _i)
{
return vreinterpretq_m128i_s64(vdupq_n_s64(_i));
}
// Sets the 2 signed 64-bit integer values to i.
// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_set1_epi64x&expand=4961
FORCE_INLINE __m128i _mm_set1_epi64x(int64_t _i)
{
return vreinterpretq_m128i_s64(vdupq_n_s64(_i));
}
// Sets the 4 signed 32-bit integer values.
// https://msdn.microsoft.com/en-us/library/vstudio/019beekt(v=vs.100).aspx
FORCE_INLINE __m128i _mm_set_epi32(int i3, int i2, int i1, int i0)
{
int32_t __attribute__((aligned(16))) data[4] = {i0, i1, i2, i3};
return vreinterpretq_m128i_s32(vld1q_s32(data));
}
// Returns the __m128i structure with its two 64-bit integer values
// initialized to the values of the two 64-bit integers passed in.
// https://msdn.microsoft.com/en-us/library/dk2sdw0h(v=vs.120).aspx
FORCE_INLINE __m128i _mm_set_epi64x(int64_t i1, int64_t i2)
{
int64_t __attribute__((aligned(16))) data[2] = {i2, i1};
return vreinterpretq_m128i_s64(vld1q_s64(data));
}
// Stores four single-precision, floating-point values.
// https://msdn.microsoft.com/en-us/library/vstudio/s3h4ay6y(v=vs.100).aspx
FORCE_INLINE void _mm_store_ps(float *p, __m128 a)
{
vst1q_f32(p, vreinterpretq_f32_m128(a));
}
// Stores four single-precision, floating-point values.
// https://msdn.microsoft.com/en-us/library/44e30x22(v=vs.100).aspx
FORCE_INLINE void _mm_storeu_ps(float *p, __m128 a)
{
vst1q_f32(p, vreinterpretq_f32_m128(a));
}
// Stores four 32-bit integer values as (as a __m128i value) at the address p.
// https://msdn.microsoft.com/en-us/library/vstudio/edk11s13(v=vs.100).aspx
FORCE_INLINE void _mm_store_si128(__m128i *p, __m128i a)
{
vst1q_s32((int32_t *) p, vreinterpretq_s32_m128i(a));
}
// Stores four 32-bit integer values as (as a __m128i value) at the address p.
// https://msdn.microsoft.com/en-us/library/vstudio/edk11s13(v=vs.100).aspx
FORCE_INLINE void _mm_storeu_si128(__m128i *p, __m128i a)
{
vst1q_s32((int32_t *) p, vreinterpretq_s32_m128i(a));
}
// Stores the lower single - precision, floating - point value.
// https://msdn.microsoft.com/en-us/library/tzz10fbx(v=vs.100).aspx
FORCE_INLINE void _mm_store_ss(float *p, __m128 a)
{
vst1q_lane_f32(p, vreinterpretq_f32_m128(a), 0);
}
// Reads the lower 64 bits of b and stores them into the lower 64 bits of a.
// https://msdn.microsoft.com/en-us/library/hhwf428f%28v=vs.90%29.aspx
FORCE_INLINE void _mm_storel_epi64(__m128i *a, __m128i b)
{
uint64x1_t hi = vget_high_u64(vreinterpretq_u64_m128i(*a));
uint64x1_t lo = vget_low_u64(vreinterpretq_u64_m128i(b));
*a = vreinterpretq_m128i_u64(vcombine_u64(lo, hi));
}
// Stores the lower two single-precision floating point values of a to the
// address p.
//
// *p0 := a0
// *p1 := a1
//
// https://msdn.microsoft.com/en-us/library/h54t98ks(v=vs.90).aspx
FORCE_INLINE void _mm_storel_pi(__m64 *p, __m128 a)
{
*p = vget_low_f32(a);
}
// Stores the upper two single-precision, floating-point values of a to the
// address p.
//
// *p0 := a2
// *p1 := a3
//
// https://msdn.microsoft.com/en-us/library/a7525fs8(v%3dvs.90).aspx
FORCE_INLINE void _mm_storeh_pi(__m64 * p, __m128 a)
{
*p = vget_high_f32(a);
}
// Loads a single single-precision, floating-point value, copying it into all
// four words
// https://msdn.microsoft.com/en-us/library/vstudio/5cdkf716(v=vs.100).aspx
FORCE_INLINE __m128 _mm_load1_ps(const float *p)
{
return vreinterpretq_m128_f32(vld1q_dup_f32(p));
}
#define _mm_load_ps1 _mm_load1_ps
// Sets the lower two single-precision, floating-point values with 64
// bits of data loaded from the address p; the upper two values are passed
// through from a.
//
// Return Value
// r0 := *p0
// r1 := *p1
// r2 := a2
// r3 := a3
//
// https://msdn.microsoft.com/en-us/library/s57cyak2(v=vs.100).aspx
FORCE_INLINE __m128 _mm_loadl_pi(__m128 a, __m64 const *p)
{
return vreinterpretq_m128_f32(
vcombine_f32(vld1_f32((const float32_t *) p), vget_high_f32(a)));
}
// Sets the upper two single-precision, floating-point values with 64
// bits of data loaded from the address p; the lower two values are passed
// through from a.
//
// r0 := a0
// r1 := a1
// r2 := *p0
// r3 := *p1
//
// https://msdn.microsoft.com/en-us/library/w92wta0x(v%3dvs.100).aspx
FORCE_INLINE __m128 _mm_loadh_pi(__m128 a, __m64 const *p)
{
return vreinterpretq_m128_f32(
vcombine_f32(vget_low_f32(a), vld1_f32((const float32_t *) p)));
}
// Loads four single-precision, floating-point values.
// https://msdn.microsoft.com/en-us/library/vstudio/zzd50xxt(v=vs.100).aspx
FORCE_INLINE __m128 _mm_load_ps(const float *p)
{
return vreinterpretq_m128_f32(vld1q_f32(p));
}
// Loads four single-precision, floating-point values.
// https://msdn.microsoft.com/en-us/library/x1b16s7z%28v=vs.90%29.aspx
FORCE_INLINE __m128 _mm_loadu_ps(const float *p)
{
// for neon, alignment doesn't matter, so _mm_load_ps and _mm_loadu_ps are
// equivalent for neon
return vreinterpretq_m128_f32(vld1q_f32(p));
}
// Loads an single - precision, floating - point value into the low word and
// clears the upper three words.
// https://msdn.microsoft.com/en-us/library/548bb9h4%28v=vs.90%29.aspx
FORCE_INLINE __m128 _mm_load_ss(const float *p)
{
return vreinterpretq_m128_f32(vsetq_lane_f32(*p, vdupq_n_f32(0), 0));
}
FORCE_INLINE __m128i _mm_loadl_epi64(__m128i const *p)
{
/* Load the lower 64 bits of the value pointed to by p into the
* lower 64 bits of the result, zeroing the upper 64 bits of the result.
*/
return vreinterpretq_m128i_s32(vcombine_s32(vld1_s32((int32_t const *) p), vcreate_s32(0)));
}
// ******************************************
// Logic/Binary operations
// ******************************************
// Compares for inequality.
// https://msdn.microsoft.com/en-us/library/sf44thbx(v=vs.100).aspx
FORCE_INLINE __m128 _mm_cmpneq_ps(__m128 a, __m128 b)
{
return vreinterpretq_m128_u32(vmvnq_u32(
vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))));
}
// Computes the bitwise AND-NOT of the four single-precision, floating-point
// values of a and b.
//
// r0 := ~a0 & b0
// r1 := ~a1 & b1
// r2 := ~a2 & b2
// r3 := ~a3 & b3
//
// https://msdn.microsoft.com/en-us/library/vstudio/68h7wd02(v=vs.100).aspx
FORCE_INLINE __m128 _mm_andnot_ps(__m128 a, __m128 b)
{
return vreinterpretq_m128_s32(
vbicq_s32(vreinterpretq_s32_m128(b),
vreinterpretq_s32_m128(a))); // *NOTE* argument swap
}
// Computes the bitwise AND of the 128-bit value in b and the bitwise NOT of the
// 128-bit value in a.
//
// r := (~a) & b
//
// https://msdn.microsoft.com/en-us/library/vstudio/1beaceh8(v=vs.100).aspx
FORCE_INLINE __m128i _mm_andnot_si128(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s32(
vbicq_s32(vreinterpretq_s32_m128i(b),
vreinterpretq_s32_m128i(a))); // *NOTE* argument swap
}
// Computes the bitwise AND of the 128-bit value in a and the 128-bit value in
// b.
//
// r := a & b
//
// https://msdn.microsoft.com/en-us/library/vstudio/6d1txsa8(v=vs.100).aspx
FORCE_INLINE __m128i _mm_and_si128(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s32(
vandq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)));
}
// Computes the bitwise AND of the four single-precision, floating-point values
// of a and b.
//
// r0 := a0 & b0
// r1 := a1 & b1
// r2 := a2 & b2
// r3 := a3 & b3
//
// https://msdn.microsoft.com/en-us/library/vstudio/73ck1xc5(v=vs.100).aspx
FORCE_INLINE __m128 _mm_and_ps(__m128 a, __m128 b)
{
return vreinterpretq_m128_s32(
vandq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b)));
}
// Computes the bitwise OR of the four single-precision, floating-point values
// of a and b.
// https://msdn.microsoft.com/en-us/library/vstudio/7ctdsyy0(v=vs.100).aspx
FORCE_INLINE __m128 _mm_or_ps(__m128 a, __m128 b)
{
return vreinterpretq_m128_s32(
vorrq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b)));
}
// Computes bitwise EXOR (exclusive-or) of the four single-precision,
// floating-point values of a and b.
// https://msdn.microsoft.com/en-us/library/ss6k3wk8(v=vs.100).aspx
FORCE_INLINE __m128 _mm_xor_ps(__m128 a, __m128 b)
{
return vreinterpretq_m128_s32(
veorq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b)));
}
// Computes the bitwise OR of the 128-bit value in a and the 128-bit value in b.
//
// r := a | b
//
// https://msdn.microsoft.com/en-us/library/vstudio/ew8ty0db(v=vs.100).aspx
FORCE_INLINE __m128i _mm_or_si128(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s32(
vorrq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)));
}
// Computes the bitwise XOR of the 128-bit value in a and the 128-bit value in
// b. https://msdn.microsoft.com/en-us/library/fzt08www(v=vs.100).aspx
FORCE_INLINE __m128i _mm_xor_si128(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s32(
veorq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)));
}
// Moves the upper two values of B into the lower two values of A.
//
// r3 := a3
// r2 := a2
// r1 := b3
// r0 := b2
FORCE_INLINE __m128 _mm_movehl_ps(__m128 __A, __m128 __B)
{
float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(__A));
float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(__B));
return vreinterpretq_m128_f32(vcombine_f32(b32, a32));
}
// Moves the lower two values of B into the upper two values of A.
//
// r3 := b1
// r2 := b0
// r1 := a1
// r0 := a0
FORCE_INLINE __m128 _mm_movelh_ps(__m128 __A, __m128 __B)
{
float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(__A));
float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(__B));
return vreinterpretq_m128_f32(vcombine_f32(a10, b10));
}
FORCE_INLINE __m128i _mm_abs_epi32(__m128i a)
{
return vreinterpretq_m128i_s32(vabsq_s32(vreinterpretq_s32_m128i(a)));
}
FORCE_INLINE __m128i _mm_abs_epi16(__m128i a)
{
return vreinterpretq_m128i_s16(vabsq_s16(vreinterpretq_s16_m128i(a)));
}
FORCE_INLINE __m128i _mm_abs_epi8(__m128i a)
{
return vreinterpretq_m128i_s8(vabsq_s8(vreinterpretq_s8_m128i(a)));
}
// Takes the upper 64 bits of a and places it in the low end of the result
// Takes the lower 64 bits of b and places it into the high end of the result.
FORCE_INLINE __m128 _mm_shuffle_ps_1032(__m128 a, __m128 b)
{
float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a));
float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b));
return vreinterpretq_m128_f32(vcombine_f32(a32, b10));
}
// takes the lower two 32-bit values from a and swaps them and places in high
// end of result takes the higher two 32 bit values from b and swaps them and
// places in low end of result.
FORCE_INLINE __m128 _mm_shuffle_ps_2301(__m128 a, __m128 b)
{
float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a)));
float32x2_t b23 = vrev64_f32(vget_high_f32(vreinterpretq_f32_m128(b)));
return vreinterpretq_m128_f32(vcombine_f32(a01, b23));
}
FORCE_INLINE __m128 _mm_shuffle_ps_0321(__m128 a, __m128 b)
{
float32x2_t a21 = vget_high_f32(
vextq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a), 3));
float32x2_t b03 = vget_low_f32(
vextq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b), 3));
return vreinterpretq_m128_f32(vcombine_f32(a21, b03));
}
FORCE_INLINE __m128 _mm_shuffle_ps_2103(__m128 a, __m128 b)
{
float32x2_t a03 = vget_low_f32(
vextq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a), 3));
float32x2_t b21 = vget_high_f32(
vextq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b), 3));
return vreinterpretq_m128_f32(vcombine_f32(a03, b21));
}
FORCE_INLINE __m128 _mm_shuffle_ps_1010(__m128 a, __m128 b)
{
float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a));
float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b));
return vreinterpretq_m128_f32(vcombine_f32(a10, b10));
}
FORCE_INLINE __m128 _mm_shuffle_ps_1001(__m128 a, __m128 b)
{
float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a)));
float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b));
return vreinterpretq_m128_f32(vcombine_f32(a01, b10));
}
FORCE_INLINE __m128 _mm_shuffle_ps_0101(__m128 a, __m128 b)
{
float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a)));
float32x2_t b01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(b)));
return vreinterpretq_m128_f32(vcombine_f32(a01, b01));
}
// keeps the low 64 bits of b in the low and puts the high 64 bits of a in the
// high
FORCE_INLINE __m128 _mm_shuffle_ps_3210(__m128 a, __m128 b)
{
float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a));
float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b));
return vreinterpretq_m128_f32(vcombine_f32(a10, b32));
}
FORCE_INLINE __m128 _mm_shuffle_ps_0011(__m128 a, __m128 b)
{
float32x2_t a11 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(a)), 1);
float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0);
return vreinterpretq_m128_f32(vcombine_f32(a11, b00));
}
FORCE_INLINE __m128 _mm_shuffle_ps_0022(__m128 a, __m128 b)
{
float32x2_t a22 =
vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 0);
float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0);
return vreinterpretq_m128_f32(vcombine_f32(a22, b00));
}
FORCE_INLINE __m128 _mm_shuffle_ps_2200(__m128 a, __m128 b)
{
float32x2_t a00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(a)), 0);
float32x2_t b22 =
vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(b)), 0);
return vreinterpretq_m128_f32(vcombine_f32(a00, b22));
}
FORCE_INLINE __m128 _mm_shuffle_ps_3202(__m128 a, __m128 b)
{
float32_t a0 = vgetq_lane_f32(vreinterpretq_f32_m128(a), 0);
float32x2_t a22 =
vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 0);
float32x2_t a02 = vset_lane_f32(a0, a22, 1); /* TODO: use vzip ?*/
float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b));
return vreinterpretq_m128_f32(vcombine_f32(a02, b32));
}
FORCE_INLINE __m128 _mm_shuffle_ps_1133(__m128 a, __m128 b)
{
float32x2_t a33 =
vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 1);
float32x2_t b11 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 1);
return vreinterpretq_m128_f32(vcombine_f32(a33, b11));
}
FORCE_INLINE __m128 _mm_shuffle_ps_2010(__m128 a, __m128 b)
{
float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a));
float32_t b2 = vgetq_lane_f32(vreinterpretq_f32_m128(b), 2);
float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0);
float32x2_t b20 = vset_lane_f32(b2, b00, 1);
return vreinterpretq_m128_f32(vcombine_f32(a10, b20));
}
FORCE_INLINE __m128 _mm_shuffle_ps_2001(__m128 a, __m128 b)
{
float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a)));
float32_t b2 = vgetq_lane_f32(b, 2);
float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0);
float32x2_t b20 = vset_lane_f32(b2, b00, 1);
return vreinterpretq_m128_f32(vcombine_f32(a01, b20));
}
FORCE_INLINE __m128 _mm_shuffle_ps_2032(__m128 a, __m128 b)
{
float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a));
float32_t b2 = vgetq_lane_f32(b, 2);
float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0);
float32x2_t b20 = vset_lane_f32(b2, b00, 1);
return vreinterpretq_m128_f32(vcombine_f32(a32, b20));
}
// NEON does not support a general purpose permute intrinsic
// Selects four specific single-precision, floating-point values from a and b,
// based on the mask i.
// https://msdn.microsoft.com/en-us/library/vstudio/5f0858x0(v=vs.100).aspx
#if 0 /* C version */
FORCE_INLINE __m128 _mm_shuffle_ps_default(__m128 a,
__m128 b,
__constrange(0, 255) int imm)
{
__m128 ret;
ret[0] = a[imm & 0x3];
ret[1] = a[(imm >> 2) & 0x3];
ret[2] = b[(imm >> 4) & 0x03];
ret[3] = b[(imm >> 6) & 0x03];
return ret;
}
#endif
#define _mm_shuffle_ps_default(a, b, imm) \
__extension__({ \
float32x4_t ret; \
ret = vmovq_n_f32( \
vgetq_lane_f32(vreinterpretq_f32_m128(a), (imm) &0x3)); \
ret = vsetq_lane_f32( \
vgetq_lane_f32(vreinterpretq_f32_m128(a), ((imm) >> 2) & 0x3), \
ret, 1); \
ret = vsetq_lane_f32( \
vgetq_lane_f32(vreinterpretq_f32_m128(b), ((imm) >> 4) & 0x3), \
ret, 2); \
ret = vsetq_lane_f32( \
vgetq_lane_f32(vreinterpretq_f32_m128(b), ((imm) >> 6) & 0x3), \
ret, 3); \
vreinterpretq_m128_f32(ret); \
})
// FORCE_INLINE __m128 _mm_shuffle_ps(__m128 a, __m128 b, __constrange(0,255)
// int imm)
#if defined(__clang__)
#define _mm_shuffle_ps(a, b, imm) \
__extension__({ \
float32x4_t _input1 = vreinterpretq_f32_m128(a); \
float32x4_t _input2 = vreinterpretq_f32_m128(b); \
float32x4_t _shuf = \
__builtin_shufflevector(_input1, _input2, \
(imm) & 0x3, \
((imm) >> 2) & 0x3, \
(((imm) >> 4) & 0x3) + 4, \
(((imm) >> 6) & 0x3) + 4); \
vreinterpretq_m128_f32(_shuf); \
})
#else // generic
#define _mm_shuffle_ps(a, b, imm) \
__extension__({ \
__m128 ret; \
switch (imm) { \
case _MM_SHUFFLE(1, 0, 3, 2): \
ret = _mm_shuffle_ps_1032((a), (b)); \
break; \
case _MM_SHUFFLE(2, 3, 0, 1): \
ret = _mm_shuffle_ps_2301((a), (b)); \
break; \
case _MM_SHUFFLE(0, 3, 2, 1): \
ret = _mm_shuffle_ps_0321((a), (b)); \
break; \
case _MM_SHUFFLE(2, 1, 0, 3): \
ret = _mm_shuffle_ps_2103((a), (b)); \
break; \
case _MM_SHUFFLE(1, 0, 1, 0): \
ret = _mm_movelh_ps((a), (b)); \
break; \
case _MM_SHUFFLE(1, 0, 0, 1): \
ret = _mm_shuffle_ps_1001((a), (b)); \
break; \
case _MM_SHUFFLE(0, 1, 0, 1): \
ret = _mm_shuffle_ps_0101((a), (b)); \
break; \
case _MM_SHUFFLE(3, 2, 1, 0): \
ret = _mm_shuffle_ps_3210((a), (b)); \
break; \
case _MM_SHUFFLE(0, 0, 1, 1): \
ret = _mm_shuffle_ps_0011((a), (b)); \
break; \
case _MM_SHUFFLE(0, 0, 2, 2): \
ret = _mm_shuffle_ps_0022((a), (b)); \
break; \
case _MM_SHUFFLE(2, 2, 0, 0): \
ret = _mm_shuffle_ps_2200((a), (b)); \
break; \
case _MM_SHUFFLE(3, 2, 0, 2): \
ret = _mm_shuffle_ps_3202((a), (b)); \
break; \
case _MM_SHUFFLE(3, 2, 3, 2): \
ret = _mm_movehl_ps((b), (a)); \
break; \
case _MM_SHUFFLE(1, 1, 3, 3): \
ret = _mm_shuffle_ps_1133((a), (b)); \
break; \
case _MM_SHUFFLE(2, 0, 1, 0): \
ret = _mm_shuffle_ps_2010((a), (b)); \
break; \
case _MM_SHUFFLE(2, 0, 0, 1): \
ret = _mm_shuffle_ps_2001((a), (b)); \
break; \
case _MM_SHUFFLE(2, 0, 3, 2): \
ret = _mm_shuffle_ps_2032((a), (b)); \
break; \
default: \
ret = _mm_shuffle_ps_default((a), (b), (imm)); \
break; \
} \
ret; \
})
#endif // not clang
// Takes the upper 64 bits of a and places it in the low end of the result
// Takes the lower 64 bits of a and places it into the high end of the result.
FORCE_INLINE __m128i _mm_shuffle_epi_1032(__m128i a)
{
int32x2_t a32 = vget_high_s32(vreinterpretq_s32_m128i(a));
int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a));
return vreinterpretq_m128i_s32(vcombine_s32(a32, a10));
}
// takes the lower two 32-bit values from a and swaps them and places in low end
// of result takes the higher two 32 bit values from a and swaps them and places
// in high end of result.
FORCE_INLINE __m128i _mm_shuffle_epi_2301(__m128i a)
{
int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a)));
int32x2_t a23 = vrev64_s32(vget_high_s32(vreinterpretq_s32_m128i(a)));
return vreinterpretq_m128i_s32(vcombine_s32(a01, a23));
}
// rotates the least significant 32 bits into the most signficant 32 bits, and
// shifts the rest down
FORCE_INLINE __m128i _mm_shuffle_epi_0321(__m128i a)
{
return vreinterpretq_m128i_s32(
vextq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(a), 1));
}
// rotates the most significant 32 bits into the least signficant 32 bits, and
// shifts the rest up
FORCE_INLINE __m128i _mm_shuffle_epi_2103(__m128i a)
{
return vreinterpretq_m128i_s32(
vextq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(a), 3));
}
// gets the lower 64 bits of a, and places it in the upper 64 bits
// gets the lower 64 bits of a and places it in the lower 64 bits
FORCE_INLINE __m128i _mm_shuffle_epi_1010(__m128i a)
{
int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a));
return vreinterpretq_m128i_s32(vcombine_s32(a10, a10));
}
// gets the lower 64 bits of a, swaps the 0 and 1 elements, and places it in the
// lower 64 bits gets the lower 64 bits of a, and places it in the upper 64 bits
FORCE_INLINE __m128i _mm_shuffle_epi_1001(__m128i a)
{
int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a)));
int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a));
return vreinterpretq_m128i_s32(vcombine_s32(a01, a10));
}
// gets the lower 64 bits of a, swaps the 0 and 1 elements and places it in the
// upper 64 bits gets the lower 64 bits of a, swaps the 0 and 1 elements, and
// places it in the lower 64 bits
FORCE_INLINE __m128i _mm_shuffle_epi_0101(__m128i a)
{
int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a)));
return vreinterpretq_m128i_s32(vcombine_s32(a01, a01));
}
FORCE_INLINE __m128i _mm_shuffle_epi_2211(__m128i a)
{
int32x2_t a11 = vdup_lane_s32(vget_low_s32(vreinterpretq_s32_m128i(a)), 1);
int32x2_t a22 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 0);
return vreinterpretq_m128i_s32(vcombine_s32(a11, a22));
}
FORCE_INLINE __m128i _mm_shuffle_epi_0122(__m128i a)
{
int32x2_t a22 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 0);
int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a)));
return vreinterpretq_m128i_s32(vcombine_s32(a22, a01));
}
FORCE_INLINE __m128i _mm_shuffle_epi_3332(__m128i a)
{
int32x2_t a32 = vget_high_s32(vreinterpretq_s32_m128i(a));
int32x2_t a33 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 1);
return vreinterpretq_m128i_s32(vcombine_s32(a32, a33));
}
// Shuffle packed 8-bit integers in a according to shuffle control mask in the
// corresponding 8-bit element of b, and store the results in dst.
// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_shuffle_epi8&expand=5146
FORCE_INLINE __m128i _mm_shuffle_epi8(__m128i a, __m128i b)
{
int8x16_t tbl = vreinterpretq_s8_m128i(a); // input a
uint8x16_t idx = vreinterpretq_u8_m128i(b); // input b
uint8x16_t idx_masked =
vandq_u8(idx, vdupq_n_u8(0x8F)); // avoid using meaningless bits
#if defined(__aarch64__)
return vreinterpretq_m128i_s8(vqtbl1q_s8(tbl, idx_masked));
#elif defined(__GNUC__)
int8x16_t ret;
// %e and %f represent the even and odd D registers
// respectively.
__asm__(
" vtbl.8 %e[ret], {%e[tbl], %f[tbl]}, %e[idx]\n"
" vtbl.8 %f[ret], {%e[tbl], %f[tbl]}, %f[idx]\n"
: [ret] "=&w" (ret)
: [tbl] "w" (tbl), [idx] "w" (idx_masked));
return vreinterpretq_m128i_s8(ret);
#else
// use this line if testing on aarch64
int8x8x2_t a_split = { vget_low_s8(tbl), vget_high_s8(tbl) };
return vreinterpretq_m128i_s8(
vcombine_s8(
vtbl2_s8(a_split, vget_low_u8(idx_masked)),
vtbl2_s8(a_split, vget_high_u8(idx_masked))
)
);
#endif
}
#if 0 /* C version */
FORCE_INLINE __m128i _mm_shuffle_epi32_default(__m128i a,
__constrange(0, 255) int imm)
{
__m128i ret;
ret[0] = a[imm & 0x3];
ret[1] = a[(imm >> 2) & 0x3];
ret[2] = a[(imm >> 4) & 0x03];
ret[3] = a[(imm >> 6) & 0x03];
return ret;
}
#endif
#define _mm_shuffle_epi32_default(a, imm) \
__extension__({ \
int32x4_t ret; \
ret = vmovq_n_s32( \
vgetq_lane_s32(vreinterpretq_s32_m128i(a), (imm) &0x3)); \
ret = vsetq_lane_s32( \
vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 2) & 0x3), \
ret, 1); \
ret = vsetq_lane_s32( \
vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 4) & 0x3), \
ret, 2); \
ret = vsetq_lane_s32( \
vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 6) & 0x3), \
ret, 3); \
vreinterpretq_m128i_s32(ret); \
})
// FORCE_INLINE __m128i _mm_shuffle_epi32_splat(__m128i a, __constrange(0,255)
// int imm)
#if defined(__aarch64__)
#define _mm_shuffle_epi32_splat(a, imm) \
__extension__({ \
vreinterpretq_m128i_s32( \
vdupq_laneq_s32(vreinterpretq_s32_m128i(a), (imm))); \
})
#else
#define _mm_shuffle_epi32_splat(a, imm) \
__extension__({ \
vreinterpretq_m128i_s32( \
vdupq_n_s32(vgetq_lane_s32(vreinterpretq_s32_m128i(a), (imm)))); \
})
#endif
// Shuffles the 4 signed or unsigned 32-bit integers in a as specified by imm.
// https://msdn.microsoft.com/en-us/library/56f67xbk%28v=vs.90%29.aspx
// FORCE_INLINE __m128i _mm_shuffle_epi32(__m128i a, __constrange(0,255) int
// imm)
#if defined(__clang__)
#define _mm_shuffle_epi32(a, imm) \
__extension__({ \
int32x4_t _input = vreinterpretq_s32_m128i(a); \
int32x4_t _shuf = \
__builtin_shufflevector(_input, _input, \
(imm) & 0x3, ((imm) >> 2) & 0x3, \
((imm) >> 4) & 0x3, ((imm) >> 6) & 0x3); \
vreinterpretq_m128i_s32(_shuf); \
})
#else // generic
#define _mm_shuffle_epi32(a, imm) \
__extension__({ \
__m128i ret; \
switch (imm) { \
case _MM_SHUFFLE(1, 0, 3, 2): \
ret = _mm_shuffle_epi_1032((a)); \
break; \
case _MM_SHUFFLE(2, 3, 0, 1): \
ret = _mm_shuffle_epi_2301((a)); \
break; \
case _MM_SHUFFLE(0, 3, 2, 1): \
ret = _mm_shuffle_epi_0321((a)); \
break; \
case _MM_SHUFFLE(2, 1, 0, 3): \
ret = _mm_shuffle_epi_2103((a)); \
break; \
case _MM_SHUFFLE(1, 0, 1, 0): \
ret = _mm_shuffle_epi_1010((a)); \
break; \
case _MM_SHUFFLE(1, 0, 0, 1): \
ret = _mm_shuffle_epi_1001((a)); \
break; \
case _MM_SHUFFLE(0, 1, 0, 1): \
ret = _mm_shuffle_epi_0101((a)); \
break; \
case _MM_SHUFFLE(2, 2, 1, 1): \
ret = _mm_shuffle_epi_2211((a)); \
break; \
case _MM_SHUFFLE(0, 1, 2, 2): \
ret = _mm_shuffle_epi_0122((a)); \
break; \
case _MM_SHUFFLE(3, 3, 3, 2): \
ret = _mm_shuffle_epi_3332((a)); \
break; \
case _MM_SHUFFLE(0, 0, 0, 0): \
ret = _mm_shuffle_epi32_splat((a), 0); \
break; \
case _MM_SHUFFLE(1, 1, 1, 1): \
ret = _mm_shuffle_epi32_splat((a), 1); \
break; \
case _MM_SHUFFLE(2, 2, 2, 2): \
ret = _mm_shuffle_epi32_splat((a), 2); \
break; \
case _MM_SHUFFLE(3, 3, 3, 3): \
ret = _mm_shuffle_epi32_splat((a), 3); \
break; \
default: \
ret = _mm_shuffle_epi32_default((a), (imm)); \
break; \
} \
ret; \
})
#endif // not clang
// Shuffles the lower 4 signed or unsigned 16-bit integers in a as specified
// by imm.
// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/y41dkk37(v=vs.100)
// FORCE_INLINE __m128i _mm_shufflelo_epi16_function(__m128i a,
// __constrange(0,255) int imm)
#define _mm_shufflelo_epi16_function(a, imm) \
__extension__({ \
int16x8_t ret = vreinterpretq_s16_m128i(a); \
int16x4_t lowBits = vget_low_s16(ret); \
ret = vsetq_lane_s16(vget_lane_s16(lowBits, (imm) &0x3), ret, 0); \
ret = vsetq_lane_s16(vget_lane_s16(lowBits, ((imm) >> 2) & 0x3), ret, \
1); \
ret = vsetq_lane_s16(vget_lane_s16(lowBits, ((imm) >> 4) & 0x3), ret, \
2); \
ret = vsetq_lane_s16(vget_lane_s16(lowBits, ((imm) >> 6) & 0x3), ret, \
3); \
vreinterpretq_m128i_s16(ret); \
})
// FORCE_INLINE __m128i _mm_shufflelo_epi16(__m128i a, __constrange(0,255) int
// imm)
#if defined(__clang__)
#define _mm_shufflelo_epi16(a, imm) \
__extension__({ \
int16x8_t _input = vreinterpretq_s16_m128i(a); \
int16x8_t _shuf = \
__builtin_shufflevector(_input, _input, \
((imm) & 0x3), \
(((imm) >> 2) & 0x3), \
(((imm) >> 4) & 0x3), \
(((imm) >> 6) & 0x3), \
4, 5, 6, 7); \
vreinterpretq_m128i_s16(_shuf); \
})
#else // generic
#define _mm_shufflelo_epi16(a, imm) _mm_shufflelo_epi16_function((a), (imm))
#endif
// Shuffles the upper 4 signed or unsigned 16-bit integers in a as specified
// by imm.
// https://msdn.microsoft.com/en-us/library/13ywktbs(v=vs.100).aspx
// FORCE_INLINE __m128i _mm_shufflehi_epi16_function(__m128i a,
// __constrange(0,255) int imm)
#define _mm_shufflehi_epi16_function(a, imm) \
__extension__({ \
int16x8_t ret = vreinterpretq_s16_m128i(a); \
int16x4_t highBits = vget_high_s16(ret); \
ret = vsetq_lane_s16(vget_lane_s16(highBits, (imm) &0x3), ret, 4); \
ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 2) & 0x3), ret, \
5); \
ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 4) & 0x3), ret, \
6); \
ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 6) & 0x3), ret, \
7); \
vreinterpretq_m128i_s16(ret); \
})
// FORCE_INLINE __m128i _mm_shufflehi_epi16(__m128i a, __constrange(0,255) int
// imm)
#if defined(__clang__)
#define _mm_shufflehi_epi16(a, imm) \
__extension__({ \
int16x8_t _input = vreinterpretq_s16_m128i(a); \
int16x8_t _shuf = \
__builtin_shufflevector(_input, _input, \
0, 1, 2, 3, \
((imm) & 0x3) + 4, \
(((imm) >> 2) & 0x3) + 4, \
(((imm) >> 4) & 0x3) + 4, \
(((imm) >> 6) & 0x3) + 4); \
vreinterpretq_m128i_s16(_shuf); \
})
#else // generic
#define _mm_shufflehi_epi16(a, imm) _mm_shufflehi_epi16_function((a), (imm))
#endif
// Blend packed 16-bit integers from a and b using control mask imm8, and store
// the results in dst.
//
// FOR j := 0 to 7
// i := j*16
// IF imm8[j]
// dst[i+15:i] := b[i+15:i]
// ELSE
// dst[i+15:i] := a[i+15:i]
// FI
// ENDFOR
// FORCE_INLINE __m128i _mm_blend_epi16(__m128i a, __m128i b, __constrange(0,255)
// int imm)
#define _mm_blend_epi16(a, b, imm) \
__extension__({ \
const uint16_t _mask[8] = { \
((imm) & (1 << 0)) ? 0xFFFF : 0x0000, \
((imm) & (1 << 1)) ? 0xFFFF : 0x0000, \
((imm) & (1 << 2)) ? 0xFFFF : 0x0000, \
((imm) & (1 << 3)) ? 0xFFFF : 0x0000, \
((imm) & (1 << 4)) ? 0xFFFF : 0x0000, \
((imm) & (1 << 5)) ? 0xFFFF : 0x0000, \
((imm) & (1 << 6)) ? 0xFFFF : 0x0000, \
((imm) & (1 << 7)) ? 0xFFFF : 0x0000 \
}; \
uint16x8_t _mask_vec = vld1q_u16(_mask); \
uint16x8_t _a = vreinterpretq_u16_m128i(a); \
uint16x8_t _b = vreinterpretq_u16_m128i(b); \
vreinterpretq_m128i_u16(vbslq_u16(_mask_vec, _b, _a)); \
})
// Blend packed 8-bit integers from a and b using mask, and store the results in dst.
//
// FOR j := 0 to 15
// i := j*8
// IF mask[i+7]
// dst[i+7:i] := b[i+7:i]
// ELSE
// dst[i+7:i] := a[i+7:i]
// FI
// ENDFOR
FORCE_INLINE __m128i _mm_blendv_epi8(__m128i _a, __m128i _b, __m128i _mask)
{
// Use a signed shift right to create a mask with the sign bit
uint8x16_t mask = vreinterpretq_u8_s8(vshrq_n_s8(vreinterpretq_s8_m128i(_mask), 7));
uint8x16_t a = vreinterpretq_u8_m128i(_a);
uint8x16_t b = vreinterpretq_u8_m128i(_b);
return vreinterpretq_m128i_u8(vbslq_u8(mask, b, a));
}
/////////////////////////////////////
// Shifts
/////////////////////////////////////
// Shifts the 4 signed 32-bit integers in a right by count bits while shifting
// in the sign bit.
//
// r0 := a0 >> count
// r1 := a1 >> count
// r2 := a2 >> count
// r3 := a3 >> count immediate
FORCE_INLINE __m128i _mm_srai_epi32(__m128i a, int count)
{
return (__m128i) vshlq_s32((int32x4_t) a, vdupq_n_s32(-count));
}
// Shifts the 8 signed 16-bit integers in a right by count bits while shifting
// in the sign bit.
//
// r0 := a0 >> count
// r1 := a1 >> count
// ...
// r7 := a7 >> count
FORCE_INLINE __m128i _mm_srai_epi16(__m128i a, int count)
{
return (__m128i) vshlq_s16((int16x8_t) a, vdupq_n_s16(-count));
}
// Shifts the 8 signed or unsigned 16-bit integers in a left by count bits while
// shifting in zeros.
//
// r0 := a0 << count
// r1 := a1 << count
// ...
// r7 := a7 << count
//
// https://msdn.microsoft.com/en-us/library/es73bcsy(v=vs.90).aspx
#define _mm_slli_epi16(a, imm) \
__extension__({ \
__m128i ret; \
if ((imm) <= 0) { \
ret = a; \
} else if ((imm) > 31) { \
ret = _mm_setzero_si128(); \
} else { \
ret = vreinterpretq_m128i_s16( \
vshlq_n_s16(vreinterpretq_s16_m128i(a), (imm))); \
} \
ret; \
})
// Shifts the 4 signed or unsigned 32-bit integers in a left by count bits while
// shifting in zeros. :
// https://msdn.microsoft.com/en-us/library/z2k3bbtb%28v=vs.90%29.aspx
// FORCE_INLINE __m128i _mm_slli_epi32(__m128i a, __constrange(0,255) int imm)
#define _mm_slli_epi32(a, imm) \
__extension__({ \
__m128i ret; \
if ((imm) <= 0) { \
ret = a; \
} else if ((imm) > 31) { \
ret = _mm_setzero_si128(); \
} else { \
ret = vreinterpretq_m128i_s32( \
vshlq_n_s32(vreinterpretq_s32_m128i(a), (imm))); \
} \
ret; \
})
// Shift packed 64-bit integers in a left by imm8 while shifting in zeros, and
// store the results in dst.
#define _mm_slli_epi64(a, imm) \
__extension__({ \
__m128i ret; \
if ((imm) <= 0) { \
ret = a; \
} else if ((imm) > 63) { \
ret = _mm_setzero_si128(); \
} else { \
ret = vreinterpretq_m128i_s64( \
vshlq_n_s64(vreinterpretq_s64_m128i(a), (imm))); \
} \
ret; \
})
// Shifts the 8 signed or unsigned 16-bit integers in a right by count bits
// while shifting in zeros.
//
// r0 := srl(a0, count)
// r1 := srl(a1, count)
// ...
// r7 := srl(a7, count)
//
// https://msdn.microsoft.com/en-us/library/6tcwd38t(v=vs.90).aspx
#define _mm_srli_epi16(a, imm) \
__extension__({ \
__m128i ret; \
if ((imm) <= 0) { \
ret = a; \
} else if ((imm) > 31) { \
ret = _mm_setzero_si128(); \
} else { \
ret = vreinterpretq_m128i_u16( \
vshrq_n_u16(vreinterpretq_u16_m128i(a), (imm))); \
} \
ret; \
})
// Shifts the 4 signed or unsigned 32-bit integers in a right by count bits
// while shifting in zeros.
// https://msdn.microsoft.com/en-us/library/w486zcfa(v=vs.100).aspx FORCE_INLINE
// __m128i _mm_srli_epi32(__m128i a, __constrange(0,255) int imm)
#define _mm_srli_epi32(a, imm) \
__extension__({ \
__m128i ret; \
if ((imm) <= 0) { \
ret = a; \
} else if ((imm) > 31) { \
ret = _mm_setzero_si128(); \
} else { \
ret = vreinterpretq_m128i_u32( \
vshrq_n_u32(vreinterpretq_u32_m128i(a), (imm))); \
} \
ret; \
})
// Shift packed 64-bit integers in a right by imm8 while shifting in zeros, and
// store the results in dst.
#define _mm_srli_epi64(a, imm) \
__extension__({ \
__m128i ret; \
if ((imm) <= 0) { \
ret = a; \
} else if ((imm) > 63) { \
ret = _mm_setzero_si128(); \
} else { \
ret = vreinterpretq_m128i_u64( \
vshrq_n_u64(vreinterpretq_u64_m128i(a), (imm))); \
} \
ret; \
})
// Shifts the 4 signed 32 - bit integers in a right by count bits while shifting
// in the sign bit.
// https://msdn.microsoft.com/en-us/library/z1939387(v=vs.100).aspx
// FORCE_INLINE __m128i _mm_srai_epi32(__m128i a, __constrange(0,255) int imm)
#define _mm_srai_epi32(a, imm) \
__extension__({ \
__m128i ret; \
if ((imm) <= 0) { \
ret = a; \
} else if ((imm) > 31) { \
ret = vreinterpretq_m128i_s32( \
vshrq_n_s32(vreinterpretq_s32_m128i(a), 16)); \
ret = vreinterpretq_m128i_s32( \
vshrq_n_s32(vreinterpretq_s32_m128i(ret), 16)); \
} else { \
ret = vreinterpretq_m128i_s32( \
vshrq_n_s32(vreinterpretq_s32_m128i(a), (imm))); \
} \
ret; \
})
// Shifts the 128 - bit value in a right by imm bytes while shifting in
// zeros.imm must be an immediate.
//
// r := srl(a, imm*8)
//
// https://msdn.microsoft.com/en-us/library/305w28yz(v=vs.100).aspx
// FORCE_INLINE _mm_srli_si128(__m128i a, __constrange(0,255) int imm)
#define _mm_srli_si128(a, imm) \
__extension__({ \
__m128i ret; \
if ((imm) <= 0) { \
ret = a; \
} else if ((imm) > 15) { \
ret = _mm_setzero_si128(); \
} else { \
ret = vreinterpretq_m128i_s8( \
vextq_s8(vreinterpretq_s8_m128i(a), vdupq_n_s8(0), (imm))); \
} \
ret; \
})
// Shifts the 128-bit value in a left by imm bytes while shifting in zeros. imm
// must be an immediate.
//
// r := a << (imm * 8)
//
// https://msdn.microsoft.com/en-us/library/34d3k2kt(v=vs.100).aspx
// FORCE_INLINE __m128i _mm_slli_si128(__m128i a, __constrange(0,255) int imm)
#define _mm_slli_si128(a, imm) \
__extension__({ \
__m128i ret; \
if ((imm) <= 0) { \
ret = a; \
} else if ((imm) > 15) { \
ret = _mm_setzero_si128(); \
} else { \
ret = vreinterpretq_m128i_s8(vextq_s8( \
vdupq_n_s8(0), vreinterpretq_s8_m128i(a), 16 - (imm))); \
} \
ret; \
})
// Shifts the 8 signed or unsigned 16-bit integers in a left by count bits while
// shifting in zeros.
//
// r0 := a0 << count
// r1 := a1 << count
// ...
// r7 := a7 << count
//
// https://msdn.microsoft.com/en-us/library/c79w388h(v%3dvs.90).aspx
FORCE_INLINE __m128i _mm_sll_epi16(__m128i a, __m128i count)
{
uint64_t c = ((SIMDVec *) &count)->m128_u64[0];
if (c > 15)
return _mm_setzero_si128();
int16x8_t vc = vdupq_n_s16((int16_t) c);
return vreinterpretq_m128i_s16(vshlq_s16(vreinterpretq_s16_m128i(a), vc));
}
// NEON does not provide a version of this function.
// Creates a 16-bit mask from the most significant bits of the 16 signed or
// unsigned 8-bit integers in a and zero extends the upper bits.
// https://msdn.microsoft.com/en-us/library/vstudio/s090c8fk(v=vs.100).aspx
FORCE_INLINE int _mm_movemask_epi8(__m128i a)
{
// Use increasingly wide shifts+adds to collect the sign bits
// together.
// Since the widening shifts would be rather confusing to follow in little endian, everything
// will be illustrated in big endian order instead. This has a different result - the bits
// would actually be reversed on a big endian machine.
// Starting input (only half the elements are shown):
// 89 ff 1d c0 00 10 99 33
uint8x16_t input = vreinterpretq_u8_m128i(a);
// Shift out everything but the sign bits with an unsigned shift right.
//
// Bytes of the vector::
// 89 ff 1d c0 00 10 99 33
// \ \ \ \ \ \ \ \ high_bits = (uint16x4_t)(input >> 7)
// | | | | | | | |
// 01 01 00 01 00 00 01 00
//
// Bits of first important lane(s):
// 10001001 (89)
// \______
// |
// 00000001 (01)
uint16x8_t high_bits = vreinterpretq_u16_u8(vshrq_n_u8(input, 7));
// Merge the even lanes together with a 16-bit unsigned shift right + add.
// 'xx' represents garbage data which will be ignored in the final result.
// In the important bytes, the add functions like a binary OR.
//
// 01 01 00 01 00 00 01 00
// \_ | \_ | \_ | \_ | paired16 = (uint32x4_t)(input + (input >> 7))
// \| \| \| \|
// xx 03 xx 01 xx 00 xx 02
//
// 00000001 00000001 (01 01)
// \_______ |
// \|
// xxxxxxxx xxxxxx11 (xx 03)
uint32x4_t paired16 = vreinterpretq_u32_u16(vsraq_n_u16(high_bits, high_bits, 7));
// Repeat with a wider 32-bit shift + add.
// xx 03 xx 01 xx 00 xx 02
// \____ | \____ | paired32 = (uint64x1_t)(paired16 + (paired16 >> 14))
// \| \|
// xx xx xx 0d xx xx xx 02
//
// 00000011 00000001 (03 01)
// \\_____ ||
// '----.\||
// xxxxxxxx xxxx1101 (xx 0d)
uint64x2_t paired32 = vreinterpretq_u64_u32(vsraq_n_u32(paired16, paired16, 14));
// Last, an even wider 64-bit shift + add to get our result in the low 8 bit lanes.
// xx xx xx 0d xx xx xx 02
// \_________ | paired64 = (uint8x8_t)(paired32 + (paired32 >> 28))
// \|
// xx xx xx xx xx xx xx d2
//
// 00001101 00000010 (0d 02)
// \ \___ | |
// '---. \| |
// xxxxxxxx 11010010 (xx d2)
uint8x16_t paired64 = vreinterpretq_u8_u64(vsraq_n_u64(paired32, paired32, 28));
// Extract the low 8 bits from each 64-bit lane with 2 8-bit extracts.
// xx xx xx xx xx xx xx d2
// || return paired64[0]
// d2
// Note: Little endian would return the correct value 4b (01001011) instead.
return vgetq_lane_u8(paired64, 0) | ((int)vgetq_lane_u8(paired64, 8) << 8);
}
// NEON does not provide this method
// Creates a 4-bit mask from the most significant bits of the four
// single-precision, floating-point values.
// https://msdn.microsoft.com/en-us/library/vstudio/4490ys29(v=vs.100).aspx
FORCE_INLINE int _mm_movemask_ps(__m128 a)
{
// Uses the exact same method as _mm_movemask_epi8, see that for details
uint32x4_t input = vreinterpretq_u32_m128(a);
// Shift out everything but the sign bits with a 32-bit unsigned shift right.
uint64x2_t high_bits = vreinterpretq_u64_u32(vshrq_n_u32(input, 31));
// Merge the two pairs together with a 64-bit unsigned shift right + add.
uint8x16_t paired = vreinterpretq_u8_u64(vsraq_n_u64(high_bits, high_bits, 31));
// Extract the result.
return vgetq_lane_u8(paired, 0) | (vgetq_lane_u8(paired, 8) << 2);
}
// Compute the bitwise AND of 128 bits (representing integer data) in a and
// mask, and return 1 if the result is zero, otherwise return 0.
// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_test_all_zeros&expand=5871
FORCE_INLINE int _mm_test_all_zeros(__m128i a, __m128i mask)
{
int64x2_t a_and_mask =
vandq_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(mask));
return (vgetq_lane_s64(a_and_mask, 0) | vgetq_lane_s64(a_and_mask, 1)) ? 0
: 1;
}
// ******************************************
// Math operations
// ******************************************
// Subtracts the four single-precision, floating-point values of a and b.
//
// r0 := a0 - b0
// r1 := a1 - b1
// r2 := a2 - b2
// r3 := a3 - b3
//
// https://msdn.microsoft.com/en-us/library/vstudio/1zad2k61(v=vs.100).aspx
FORCE_INLINE __m128 _mm_sub_ps(__m128 a, __m128 b)
{
return vreinterpretq_m128_f32(
vsubq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)));
}
// Subtract 2 packed 64-bit integers in b from 2 packed 64-bit integers in a,
// and store the results in dst.
// r0 := a0 - b0
// r1 := a1 - b1
FORCE_INLINE __m128i _mm_sub_epi64(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s64(
vsubq_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(b)));
}
// Subtracts the 4 signed or unsigned 32-bit integers of b from the 4 signed or
// unsigned 32-bit integers of a.
//
// r0 := a0 - b0
// r1 := a1 - b1
// r2 := a2 - b2
// r3 := a3 - b3
//
// https://msdn.microsoft.com/en-us/library/vstudio/fhh866h0(v=vs.100).aspx
FORCE_INLINE __m128i _mm_sub_epi32(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s32(
vsubq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)));
}
FORCE_INLINE __m128i _mm_sub_epi16(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s16(
vsubq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b)));
}
FORCE_INLINE __m128i _mm_sub_epi8(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s8(
vsubq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b)));
}
// Subtracts the 8 unsigned 16-bit integers of bfrom the 8 unsigned 16-bit
// integers of a and saturates..
// https://technet.microsoft.com/en-us/subscriptions/index/f44y0s19(v=vs.90).aspx
FORCE_INLINE __m128i _mm_subs_epu16(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u16(
vqsubq_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b)));
}
// Subtracts the 16 unsigned 8-bit integers of b from the 16 unsigned 8-bit
// integers of a and saturates.
//
// r0 := UnsignedSaturate(a0 - b0)
// r1 := UnsignedSaturate(a1 - b1)
// ...
// r15 := UnsignedSaturate(a15 - b15)
//
// https://technet.microsoft.com/en-us/subscriptions/yadkxc18(v=vs.90)
FORCE_INLINE __m128i _mm_subs_epu8(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u8(
vqsubq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b)));
}
// Subtracts the 8 signed 16-bit integers of b from the 8 signed 16-bit integers
// of a and saturates.
//
// r0 := SignedSaturate(a0 - b0)
// r1 := SignedSaturate(a1 - b1)
// ...
// r7 := SignedSaturate(a7 - b7)
FORCE_INLINE __m128i _mm_subs_epi16(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s16(
vqsubq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b)));
}
FORCE_INLINE __m128i _mm_adds_epu16(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u16(
vqaddq_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b)));
}
// Negate packed 8-bit integers in a when the corresponding signed
// 8-bit integer in b is negative, and store the results in dst.
// Element in dst are zeroed out when the corresponding element
// in b is zero.
//
// for i in 0..15
// if b[i] < 0
// r[i] := -a[i]
// else if b[i] == 0
// r[i] := 0
// else
// r[i] := a[i]
// fi
// done
FORCE_INLINE __m128i _mm_sign_epi8(__m128i _a, __m128i _b)
{
int8x16_t a = vreinterpretq_s8_m128i(_a);
int8x16_t b = vreinterpretq_s8_m128i(_b);
int8x16_t zero = vdupq_n_s8(0);
// signed shift right: faster than vclt
// (b < 0) ? 0xFF : 0
uint8x16_t ltMask = vreinterpretq_u8_s8(vshrq_n_s8(b, 7));
// (b == 0) ? 0xFF : 0
int8x16_t zeroMask = vreinterpretq_s8_u8(vceqq_s8(b, zero));
// -a
int8x16_t neg = vnegq_s8(a);
// bitwise select either a or neg based on ltMask
int8x16_t masked = vbslq_s8(ltMask, a, neg);
// res = masked & (~zeroMask)
int8x16_t res = vbicq_s8(masked, zeroMask);
return vreinterpretq_m128i_s8(res);
}
// Negate packed 16-bit integers in a when the corresponding signed
// 16-bit integer in b is negative, and store the results in dst.
// Element in dst are zeroed out when the corresponding element
// in b is zero.
//
// for i in 0..7
// if b[i] < 0
// r[i] := -a[i]
// else if b[i] == 0
// r[i] := 0
// else
// r[i] := a[i]
// fi
// done
FORCE_INLINE __m128i _mm_sign_epi16(__m128i _a, __m128i _b)
{
int16x8_t a = vreinterpretq_s16_m128i(_a);
int16x8_t b = vreinterpretq_s16_m128i(_b);
int16x8_t zero = vdupq_n_s16(0);
// signed shift right: faster than vclt
// (b < 0) ? 0xFFFF : 0
uint16x8_t ltMask = vreinterpretq_u16_s16(vshrq_n_s16(b, 15));
// (b == 0) ? 0xFFFF : 0
int16x8_t zeroMask = vreinterpretq_s16_u16(vceqq_s16(b, zero));
// -a
int16x8_t neg = vnegq_s16(a);
// bitwise select either a or neg based on ltMask
int16x8_t masked = vbslq_s16(ltMask, a, neg);
// res = masked & (~zeroMask)
int16x8_t res = vbicq_s16(masked, zeroMask);
return vreinterpretq_m128i_s16(res);
}
// Negate packed 32-bit integers in a when the corresponding signed
// 32-bit integer in b is negative, and store the results in dst.
// Element in dst are zeroed out when the corresponding element
// in b is zero.
//
// for i in 0..3
// if b[i] < 0
// r[i] := -a[i]
// else if b[i] == 0
// r[i] := 0
// else
// r[i] := a[i]
// fi
// done
FORCE_INLINE __m128i _mm_sign_epi32(__m128i _a, __m128i _b)
{
int32x4_t a = vreinterpretq_s32_m128i(_a);
int32x4_t b = vreinterpretq_s32_m128i(_b);
int32x4_t zero = vdupq_n_s32(0);
// signed shift right: faster than vclt
// (b < 0) ? 0xFFFFFFFF : 0
uint32x4_t ltMask = vreinterpretq_u32_s32(vshrq_n_s32(b, 31));
// (b == 0) ? 0xFFFFFFFF : 0
int32x4_t zeroMask = vreinterpretq_s32_u32(vceqq_s32(b, zero));
// neg = -a
int32x4_t neg = vnegq_s32(a);
// bitwise select either a or neg based on ltMask
int32x4_t masked = vbslq_s32(ltMask, a, neg);
// res = masked & (~zeroMask)
int32x4_t res = vbicq_s32(masked, zeroMask);
return vreinterpretq_m128i_s32(res);
}
// Computes the average of the 16 unsigned 8-bit integers in a and the 16
// unsigned 8-bit integers in b and rounds.
//
// r0 := (a0 + b0) / 2
// r1 := (a1 + b1) / 2
// ...
// r15 := (a15 + b15) / 2
//
// https://msdn.microsoft.com/en-us/library/vstudio/8zwh554a(v%3dvs.90).aspx
FORCE_INLINE __m128i _mm_avg_epu8(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u8(
vrhaddq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b)));
}
// Computes the average of the 8 unsigned 16-bit integers in a and the 8
// unsigned 16-bit integers in b and rounds.
//
// r0 := (a0 + b0) / 2
// r1 := (a1 + b1) / 2
// ...
// r7 := (a7 + b7) / 2
//
// https://msdn.microsoft.com/en-us/library/vstudio/y13ca3c8(v=vs.90).aspx
FORCE_INLINE __m128i _mm_avg_epu16(__m128i a, __m128i b)
{
return (__m128i) vrhaddq_u16(vreinterpretq_u16_m128i(a),
vreinterpretq_u16_m128i(b));
}
// Adds the four single-precision, floating-point values of a and b.
//
// r0 := a0 + b0
// r1 := a1 + b1
// r2 := a2 + b2
// r3 := a3 + b3
//
// https://msdn.microsoft.com/en-us/library/vstudio/c9848chc(v=vs.100).aspx
FORCE_INLINE __m128 _mm_add_ps(__m128 a, __m128 b)
{
return vreinterpretq_m128_f32(
vaddq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)));
}
// adds the scalar single-precision floating point values of a and b.
// https://msdn.microsoft.com/en-us/library/be94x2y6(v=vs.100).aspx
FORCE_INLINE __m128 _mm_add_ss(__m128 a, __m128 b)
{
float32_t b0 = vgetq_lane_f32(vreinterpretq_f32_m128(b), 0);
float32x4_t value = vsetq_lane_f32(b0, vdupq_n_f32(0), 0);
// the upper values in the result must be the remnants of <a>.
return vreinterpretq_m128_f32(vaddq_f32(a, value));
}
// Adds the 4 signed or unsigned 64-bit integers in a to the 4 signed or
// unsigned 32-bit integers in b.
// https://msdn.microsoft.com/en-us/library/vstudio/09xs4fkk(v=vs.100).aspx
FORCE_INLINE __m128i _mm_add_epi64(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s64(
vaddq_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(b)));
}
// Adds the 4 signed or unsigned 32-bit integers in a to the 4 signed or
// unsigned 32-bit integers in b.
//
// r0 := a0 + b0
// r1 := a1 + b1
// r2 := a2 + b2
// r3 := a3 + b3
//
// https://msdn.microsoft.com/en-us/library/vstudio/09xs4fkk(v=vs.100).aspx
FORCE_INLINE __m128i _mm_add_epi32(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s32(
vaddq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)));
}
// Adds the 8 signed or unsigned 16-bit integers in a to the 8 signed or
// unsigned 16-bit integers in b.
// https://msdn.microsoft.com/en-us/library/fceha5k4(v=vs.100).aspx
FORCE_INLINE __m128i _mm_add_epi16(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s16(
vaddq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b)));
}
// Adds the 16 signed or unsigned 8-bit integers in a to the 16 signed or
// unsigned 8-bit integers in b.
// https://technet.microsoft.com/en-us/subscriptions/yc7tcyzs(v=vs.90)
FORCE_INLINE __m128i _mm_add_epi8(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s8(
vaddq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b)));
}
// Adds the 8 signed 16-bit integers in a to the 8 signed 16-bit integers in b
// and saturates.
//
// r0 := SignedSaturate(a0 + b0)
// r1 := SignedSaturate(a1 + b1)
// ...
// r7 := SignedSaturate(a7 + b7)
//
// https://msdn.microsoft.com/en-us/library/1a306ef8(v=vs.100).aspx
FORCE_INLINE __m128i _mm_adds_epi16(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s16(
vqaddq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b)));
}
// Adds the 16 unsigned 8-bit integers in a to the 16 unsigned 8-bit integers in
// b and saturates..
// https://msdn.microsoft.com/en-us/library/9hahyddy(v=vs.100).aspx
FORCE_INLINE __m128i _mm_adds_epu8(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u8(
vqaddq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b)));
}
// Multiplies the 8 signed or unsigned 16-bit integers from a by the 8 signed or
// unsigned 16-bit integers from b.
//
// r0 := (a0 * b0)[15:0]
// r1 := (a1 * b1)[15:0]
// ...
// r7 := (a7 * b7)[15:0]
//
// https://msdn.microsoft.com/en-us/library/vstudio/9ks1472s(v=vs.100).aspx
FORCE_INLINE __m128i _mm_mullo_epi16(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s16(
vmulq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b)));
}
// Multiplies the 4 signed or unsigned 32-bit integers from a by the 4 signed or
// unsigned 32-bit integers from b.
// https://msdn.microsoft.com/en-us/library/vstudio/bb531409(v=vs.100).aspx
FORCE_INLINE __m128i _mm_mullo_epi32(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s32(
vmulq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)));
}
// Multiplies the four single-precision, floating-point values of a and b.
//
// r0 := a0 * b0
// r1 := a1 * b1
// r2 := a2 * b2
// r3 := a3 * b3
//
// https://msdn.microsoft.com/en-us/library/vstudio/22kbk6t9(v=vs.100).aspx
FORCE_INLINE __m128 _mm_mul_ps(__m128 a, __m128 b)
{
return vreinterpretq_m128_f32(
vmulq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)));
}
// Multiply the low unsigned 32-bit integers from each packed 64-bit element in
// a and b, and store the unsigned 64-bit results in dst.
//
// r0 := (a0 & 0xFFFFFFFF) * (b0 & 0xFFFFFFFF)
// r1 := (a2 & 0xFFFFFFFF) * (b2 & 0xFFFFFFFF)
FORCE_INLINE __m128i _mm_mul_epu32(__m128i a, __m128i b)
{
// vmull_u32 upcasts instead of masking, so we downcast.
uint32x2_t a_lo = vmovn_u64(vreinterpretq_u64_m128i(a));
uint32x2_t b_lo = vmovn_u64(vreinterpretq_u64_m128i(b));
return vreinterpretq_m128i_u64(vmull_u32(a_lo, b_lo));
}
// Multiply the low signed 32-bit integers from each packed 64-bit element in
// a and b, and store the signed 64-bit results in dst.
//
// r0 := (int64_t)(int32_t)a0 * (int64_t)(int32_t)b0
// r1 := (int64_t)(int32_t)a2 * (int64_t)(int32_t)b2
FORCE_INLINE __m128i _mm_mul_epi32(__m128i a, __m128i b)
{
// vmull_s32 upcasts instead of masking, so we downcast.
int32x2_t a_lo = vmovn_s64(vreinterpretq_s64_m128i(a));
int32x2_t b_lo = vmovn_s64(vreinterpretq_s64_m128i(b));
return vreinterpretq_m128i_s64(vmull_s32(a_lo, b_lo));
}
// Multiplies the 8 signed 16-bit integers from a by the 8 signed 16-bit
// integers from b.
//
// r0 := (a0 * b0) + (a1 * b1)
// r1 := (a2 * b2) + (a3 * b3)
// r2 := (a4 * b4) + (a5 * b5)
// r3 := (a6 * b6) + (a7 * b7)
// https://msdn.microsoft.com/en-us/library/yht36sa6(v=vs.90).aspx
FORCE_INLINE __m128i _mm_madd_epi16(__m128i a, __m128i b)
{
int32x4_t low = vmull_s16(vget_low_s16(vreinterpretq_s16_m128i(a)),
vget_low_s16(vreinterpretq_s16_m128i(b)));
int32x4_t high = vmull_s16(vget_high_s16(vreinterpretq_s16_m128i(a)),
vget_high_s16(vreinterpretq_s16_m128i(b)));
int32x2_t low_sum = vpadd_s32(vget_low_s32(low), vget_high_s32(low));
int32x2_t high_sum = vpadd_s32(vget_low_s32(high), vget_high_s32(high));
return vreinterpretq_m128i_s32(vcombine_s32(low_sum, high_sum));
}
// Multiply packed signed 16-bit integers in a and b, producing intermediate signed
// 32-bit integers. Shift right by 15 bits while rounding up, and store the
// packed 16-bit integers in dst.
//
// r0 := Round(((int32_t)a0 * (int32_t)b0) >> 15)
// r1 := Round(((int32_t)a1 * (int32_t)b1) >> 15)
// r2 := Round(((int32_t)a2 * (int32_t)b2) >> 15)
// ...
// r7 := Round(((int32_t)a7 * (int32_t)b7) >> 15)
FORCE_INLINE __m128i _mm_mulhrs_epi16(__m128i a, __m128i b)
{
// Has issues due to saturation
// return vreinterpretq_m128i_s16(vqrdmulhq_s16(a, b));
// Multiply
int32x4_t mul_lo = vmull_s16(vget_low_s16(vreinterpretq_s16_m128i(a)),
vget_low_s16(vreinterpretq_s16_m128i(b)));
int32x4_t mul_hi = vmull_s16(vget_high_s16(vreinterpretq_s16_m128i(a)),
vget_high_s16(vreinterpretq_s16_m128i(b)));
// Rounding narrowing shift right
// narrow = (int16_t)((mul + 16384) >> 15);
int16x4_t narrow_lo = vrshrn_n_s32(mul_lo, 15);
int16x4_t narrow_hi = vrshrn_n_s32(mul_hi, 15);
// Join together
return vreinterpretq_m128i_s16(vcombine_s16(narrow_lo, narrow_hi));
}
// Vertically multiply each unsigned 8-bit integer from a with the corresponding
// signed 8-bit integer from b, producing intermediate signed 16-bit integers.
// Horizontally add adjacent pairs of intermediate signed 16-bit integers,
// and pack the saturated results in dst.
//
// FOR j := 0 to 7
// i := j*16
// dst[i+15:i] := Saturate_To_Int16( a[i+15:i+8]*b[i+15:i+8] + a[i+7:i]*b[i+7:i] )
// ENDFOR
FORCE_INLINE __m128i _mm_maddubs_epi16(__m128i _a, __m128i _b)
{
// This would be much simpler if x86 would choose to zero extend OR sign extend,
// not both.
// This could probably be optimized better.
uint16x8_t a = vreinterpretq_u16_m128i(_a);
int16x8_t b = vreinterpretq_s16_m128i(_b);
// Zero extend a
int16x8_t a_odd = vreinterpretq_s16_u16(vshrq_n_u16(a, 8));
int16x8_t a_even = vreinterpretq_s16_u16(vbicq_u16(a, vdupq_n_u16(0xff00)));
// Sign extend by shifting left then shifting right.
int16x8_t b_even = vshrq_n_s16(vshlq_n_s16(b, 8), 8);
int16x8_t b_odd = vshrq_n_s16(b, 8);
// multiply
int16x8_t prod1 = vmulq_s16(a_even, b_even);
int16x8_t prod2 = vmulq_s16(a_odd, b_odd);
// saturated add
return vreinterpretq_m128i_s16(vqaddq_s16(prod1, prod2));
}
// Computes the absolute difference of the 16 unsigned 8-bit integers from a
// and the 16 unsigned 8-bit integers from b.
//
// Return Value
// Sums the upper 8 differences and lower 8 differences and packs the
// resulting 2 unsigned 16-bit integers into the upper and lower 64-bit
// elements.
//
// r0 := abs(a0 - b0) + abs(a1 - b1) +...+ abs(a7 - b7)
// r1 := 0x0
// r2 := 0x0
// r3 := 0x0
// r4 := abs(a8 - b8) + abs(a9 - b9) +...+ abs(a15 - b15)
// r5 := 0x0
// r6 := 0x0
// r7 := 0x0
FORCE_INLINE __m128i _mm_sad_epu8(__m128i a, __m128i b)
{
uint16x8_t t = vpaddlq_u8(vabdq_u8((uint8x16_t) a, (uint8x16_t) b));
uint16_t r0 = t[0] + t[1] + t[2] + t[3];
uint16_t r4 = t[4] + t[5] + t[6] + t[7];
uint16x8_t r = vsetq_lane_u16(r0, vdupq_n_u16(0), 0);
return (__m128i) vsetq_lane_u16(r4, r, 4);
}
// Divides the four single-precision, floating-point values of a and b.
//
// r0 := a0 / b0
// r1 := a1 / b1
// r2 := a2 / b2
// r3 := a3 / b3
//
// https://msdn.microsoft.com/en-us/library/edaw8147(v=vs.100).aspx
FORCE_INLINE __m128 _mm_div_ps(__m128 a, __m128 b)
{
float32x4_t recip0 = vrecpeq_f32(vreinterpretq_f32_m128(b));
float32x4_t recip1 =
vmulq_f32(recip0, vrecpsq_f32(recip0, vreinterpretq_f32_m128(b)));
return vreinterpretq_m128_f32(vmulq_f32(vreinterpretq_f32_m128(a), recip1));
}
// Divides the scalar single-precision floating point value of a by b.
// https://msdn.microsoft.com/en-us/library/4y73xa49(v=vs.100).aspx
FORCE_INLINE __m128 _mm_div_ss(__m128 a, __m128 b)
{
float32_t value =
vgetq_lane_f32(vreinterpretq_f32_m128(_mm_div_ps(a, b)), 0);
return vreinterpretq_m128_f32(
vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0));
}
// This version does additional iterations to improve accuracy. Between 1 and 4
// recommended. Computes the approximations of reciprocals of the four
// single-precision, floating-point values of a.
// https://msdn.microsoft.com/en-us/library/vstudio/796k1tty(v=vs.100).aspx
FORCE_INLINE __m128 recipq_newton(__m128 in, int n)
{
int i;
float32x4_t recip = vrecpeq_f32(vreinterpretq_f32_m128(in));
for (i = 0; i < n; ++i) {
recip =
vmulq_f32(recip, vrecpsq_f32(recip, vreinterpretq_f32_m128(in)));
}
return vreinterpretq_m128_f32(recip);
}
// Computes the approximations of reciprocals of the four single-precision,
// floating-point values of a.
// https://msdn.microsoft.com/en-us/library/vstudio/796k1tty(v=vs.100).aspx
FORCE_INLINE __m128 _mm_rcp_ps(__m128 in)
{
float32x4_t recip = vrecpeq_f32(vreinterpretq_f32_m128(in));
recip = vmulq_f32(recip, vrecpsq_f32(recip, vreinterpretq_f32_m128(in)));
return vreinterpretq_m128_f32(recip);
}
// Computes the approximations of square roots of the four single-precision,
// floating-point values of a. First computes reciprocal square roots and then
// reciprocals of the four values.
//
// r0 := sqrt(a0)
// r1 := sqrt(a1)
// r2 := sqrt(a2)
// r3 := sqrt(a3)
//
// https://msdn.microsoft.com/en-us/library/vstudio/8z67bwwk(v=vs.100).aspx
FORCE_INLINE __m128 _mm_sqrt_ps(__m128 in)
{
float32x4_t recipsq = vrsqrteq_f32(vreinterpretq_f32_m128(in));
float32x4_t sq = vrecpeq_f32(recipsq);
// ??? use step versions of both sqrt and recip for better accuracy?
return vreinterpretq_m128_f32(sq);
}
// Computes the approximation of the square root of the scalar single-precision
// floating point value of in.
// https://msdn.microsoft.com/en-us/library/ahfsc22d(v=vs.100).aspx
FORCE_INLINE __m128 _mm_sqrt_ss(__m128 in)
{
float32_t value =
vgetq_lane_f32(vreinterpretq_f32_m128(_mm_sqrt_ps(in)), 0);
return vreinterpretq_m128_f32(
vsetq_lane_f32(value, vreinterpretq_f32_m128(in), 0));
}
// Computes the approximations of the reciprocal square roots of the four
// single-precision floating point values of in.
// https://msdn.microsoft.com/en-us/library/22hfsh53(v=vs.100).aspx
FORCE_INLINE __m128 _mm_rsqrt_ps(__m128 in)
{
return vreinterpretq_m128_f32(vrsqrteq_f32(vreinterpretq_f32_m128(in)));
}
// Computes the maximums of the four single-precision, floating-point values of
// a and b.
// https://msdn.microsoft.com/en-us/library/vstudio/ff5d607a(v=vs.100).aspx
FORCE_INLINE __m128 _mm_max_ps(__m128 a, __m128 b)
{
return vreinterpretq_m128_f32(
vmaxq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)));
}
// Computes the minima of the four single-precision, floating-point values of a
// and b.
// https://msdn.microsoft.com/en-us/library/vstudio/wh13kadz(v=vs.100).aspx
FORCE_INLINE __m128 _mm_min_ps(__m128 a, __m128 b)
{
return vreinterpretq_m128_f32(
vminq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)));
}
// Computes the maximum of the two lower scalar single-precision floating point
// values of a and b.
// https://msdn.microsoft.com/en-us/library/s6db5esz(v=vs.100).aspx
FORCE_INLINE __m128 _mm_max_ss(__m128 a, __m128 b)
{
float32_t value = vgetq_lane_f32(
vmaxq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0);
return vreinterpretq_m128_f32(
vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0));
}
// Computes the minimum of the two lower scalar single-precision floating point
// values of a and b.
// https://msdn.microsoft.com/en-us/library/0a9y7xaa(v=vs.100).aspx
FORCE_INLINE __m128 _mm_min_ss(__m128 a, __m128 b)
{
float32_t value = vgetq_lane_f32(
vminq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0);
return vreinterpretq_m128_f32(
vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0));
}
// Computes the pairwise maxima of the 16 unsigned 8-bit integers from a and the
// 16 unsigned 8-bit integers from b.
// https://msdn.microsoft.com/en-us/library/st6634za(v=vs.100).aspx
FORCE_INLINE __m128i _mm_max_epu8(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u8(
vmaxq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b)));
}
// Computes the pairwise minima of the 16 unsigned 8-bit integers from a and the
// 16 unsigned 8-bit integers from b.
// https://msdn.microsoft.com/ko-kr/library/17k8cf58(v=vs.100).aspxx
FORCE_INLINE __m128i _mm_min_epu8(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u8(
vminq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b)));
}
// Computes the pairwise minima of the 8 signed 16-bit integers from a and the 8
// signed 16-bit integers from b.
// https://msdn.microsoft.com/en-us/library/vstudio/6te997ew(v=vs.100).aspx
FORCE_INLINE __m128i _mm_min_epi16(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s16(
vminq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b)));
}
// Computes the pairwise maxima of the 8 signed 16-bit integers from a and the 8
// signed 16-bit integers from b.
// https://msdn.microsoft.com/en-us/LIBRary/3x060h7c(v=vs.100).aspx
FORCE_INLINE __m128i _mm_max_epi16(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s16(
vmaxq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b)));
}
// epi versions of min/max
// Computes the pariwise maximums of the four signed 32-bit integer values of a
// and b.
//
// A 128-bit parameter that can be defined with the following equations:
// r0 := (a0 > b0) ? a0 : b0
// r1 := (a1 > b1) ? a1 : b1
// r2 := (a2 > b2) ? a2 : b2
// r3 := (a3 > b3) ? a3 : b3
//
// https://msdn.microsoft.com/en-us/library/vstudio/bb514055(v=vs.100).aspx
FORCE_INLINE __m128i _mm_max_epi32(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s32(
vmaxq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)));
}
// Computes the pariwise minima of the four signed 32-bit integer values of a
// and b.
//
// A 128-bit parameter that can be defined with the following equations:
// r0 := (a0 < b0) ? a0 : b0
// r1 := (a1 < b1) ? a1 : b1
// r2 := (a2 < b2) ? a2 : b2
// r3 := (a3 < b3) ? a3 : b3
//
// https://msdn.microsoft.com/en-us/library/vstudio/bb531476(v=vs.100).aspx
FORCE_INLINE __m128i _mm_min_epi32(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s32(
vminq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)));
}
// Multiplies the 8 signed 16-bit integers from a by the 8 signed 16-bit
// integers from b.
//
// r0 := (a0 * b0)[31:16]
// r1 := (a1 * b1)[31:16]
// ...
// r7 := (a7 * b7)[31:16]
//
// https://msdn.microsoft.com/en-us/library/vstudio/59hddw1d(v=vs.100).aspx
FORCE_INLINE __m128i _mm_mulhi_epi16(__m128i a, __m128i b)
{
/* FIXME: issue with large values because of result saturation */
// int16x8_t ret = vqdmulhq_s16(vreinterpretq_s16_m128i(a),
// vreinterpretq_s16_m128i(b)); /* =2*a*b */ return
// vreinterpretq_m128i_s16(vshrq_n_s16(ret, 1));
int16x4_t a3210 = vget_low_s16(vreinterpretq_s16_m128i(a));
int16x4_t b3210 = vget_low_s16(vreinterpretq_s16_m128i(b));
int32x4_t ab3210 = vmull_s16(a3210, b3210); /* 3333222211110000 */
int16x4_t a7654 = vget_high_s16(vreinterpretq_s16_m128i(a));
int16x4_t b7654 = vget_high_s16(vreinterpretq_s16_m128i(b));
int32x4_t ab7654 = vmull_s16(a7654, b7654); /* 7777666655554444 */
uint16x8x2_t r =
vuzpq_u16(vreinterpretq_u16_s32(ab3210), vreinterpretq_u16_s32(ab7654));
return vreinterpretq_m128i_u16(r.val[1]);
}
// Computes pairwise add of each argument as single-precision, floating-point
// values a and b.
// https://msdn.microsoft.com/en-us/library/yd9wecaa.aspx
FORCE_INLINE __m128 _mm_hadd_ps(__m128 a, __m128 b)
{
#if defined(__aarch64__)
return vreinterpretq_m128_f32(vpaddq_f32(
vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); // AArch64
#else
float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a));
float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a));
float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b));
float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b));
return vreinterpretq_m128_f32(
vcombine_f32(vpadd_f32(a10, a32), vpadd_f32(b10, b32)));
#endif
}
// Computes pairwise add of each argument as a 16-bit signed or unsigned integer
// values a and b.
FORCE_INLINE __m128i _mm_hadd_epi16(__m128i _a, __m128i _b)
{
int16x8_t a = vreinterpretq_s16_m128i(_a);
int16x8_t b = vreinterpretq_s16_m128i(_b);
#if defined(__aarch64__)
return vreinterpretq_m128i_s16(vpaddq_s16(a, b));
#else
return vreinterpretq_m128i_s16(
vcombine_s16(
vpadd_s16(vget_low_s16(a), vget_high_s16(a)),
vpadd_s16(vget_low_s16(b), vget_high_s16(b))
)
);
#endif
}
// Computes pairwise difference of each argument as a 16-bit signed or unsigned integer
// values a and b.
FORCE_INLINE __m128i _mm_hsub_epi16(__m128i _a, __m128i _b)
{
int32x4_t a = vreinterpretq_s32_m128i(_a);
int32x4_t b = vreinterpretq_s32_m128i(_b);
// Interleave using vshrn/vmovn
// [a0|a2|a4|a6|b0|b2|b4|b6]
// [a1|a3|a5|a7|b1|b3|b5|b7]
int16x8_t ab0246 = vcombine_s16(vmovn_s32(a), vmovn_s32(b));
int16x8_t ab1357 = vcombine_s16(vshrn_n_s32(a, 16), vshrn_n_s32(b, 16));
// Subtract
return vreinterpretq_m128i_s16(vsubq_s16(ab0246, ab1357));
}
// Computes saturated pairwise sub of each argument as a 16-bit signed
// integer values a and b.
FORCE_INLINE __m128i _mm_hadds_epi16(__m128i _a, __m128i _b)
{
int32x4_t a = vreinterpretq_s32_m128i(_a);
int32x4_t b = vreinterpretq_s32_m128i(_b);
// Interleave using vshrn/vmovn
// [a0|a2|a4|a6|b0|b2|b4|b6]
// [a1|a3|a5|a7|b1|b3|b5|b7]
int16x8_t ab0246 = vcombine_s16(vmovn_s32(a), vmovn_s32(b));
int16x8_t ab1357 = vcombine_s16(vshrn_n_s32(a, 16), vshrn_n_s32(b, 16));
// Saturated add
return vreinterpretq_m128i_s16(vqaddq_s16(ab0246, ab1357));
}
// Computes saturated pairwise difference of each argument as a 16-bit signed
// integer values a and b.
FORCE_INLINE __m128i _mm_hsubs_epi16(__m128i _a, __m128i _b)
{
int32x4_t a = vreinterpretq_s32_m128i(_a);
int32x4_t b = vreinterpretq_s32_m128i(_b);
// Interleave using vshrn/vmovn
// [a0|a2|a4|a6|b0|b2|b4|b6]
// [a1|a3|a5|a7|b1|b3|b5|b7]
int16x8_t ab0246 = vcombine_s16(vmovn_s32(a), vmovn_s32(b));
int16x8_t ab1357 = vcombine_s16(vshrn_n_s32(a, 16), vshrn_n_s32(b, 16));
// Saturated subtract
return vreinterpretq_m128i_s16(vqsubq_s16(ab0246, ab1357));
}
// Computes pairwise add of each argument as a 32-bit signed or unsigned integer
// values a and b.
FORCE_INLINE __m128i _mm_hadd_epi32(__m128i _a, __m128i _b)
{
int32x4_t a = vreinterpretq_s32_m128i(_a);
int32x4_t b = vreinterpretq_s32_m128i(_b);
return vreinterpretq_m128i_s32(
vcombine_s32(
vpadd_s32(vget_low_s32(a), vget_high_s32(a)),
vpadd_s32(vget_low_s32(b), vget_high_s32(b))
)
);
}
// Computes pairwise difference of each argument as a 32-bit signed or unsigned integer
// values a and b.
FORCE_INLINE __m128i _mm_hsub_epi32(__m128i _a, __m128i _b)
{
int64x2_t a = vreinterpretq_s64_m128i(_a);
int64x2_t b = vreinterpretq_s64_m128i(_b);
// Interleave using vshrn/vmovn
// [a0|a2|b0|b2]
// [a1|a2|b1|b3]
int32x4_t ab02 = vcombine_s32(vmovn_s64(a), vmovn_s64(b));
int32x4_t ab13 = vcombine_s32(vshrn_n_s64(a, 32), vshrn_n_s64(b, 32));
// Subtract
return vreinterpretq_m128i_s32(vsubq_s32(ab02, ab13));
}
// ******************************************
// Compare operations
// ******************************************
// Compares for less than
// https://msdn.microsoft.com/en-us/library/vstudio/f330yhc8(v=vs.100).aspx
FORCE_INLINE __m128 _mm_cmplt_ps(__m128 a, __m128 b)
{
return vreinterpretq_m128_u32(
vcltq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)));
}
// Compares for greater than.
//
// r0 := (a0 > b0) ? 0xffffffff : 0x0
// r1 := (a1 > b1) ? 0xffffffff : 0x0
// r2 := (a2 > b2) ? 0xffffffff : 0x0
// r3 := (a3 > b3) ? 0xffffffff : 0x0
//
// https://msdn.microsoft.com/en-us/library/vstudio/11dy102s(v=vs.100).aspx
FORCE_INLINE __m128 _mm_cmpgt_ps(__m128 a, __m128 b)
{
return vreinterpretq_m128_u32(
vcgtq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)));
}
// Compares for greater than or equal.
// https://msdn.microsoft.com/en-us/library/vstudio/fs813y2t(v=vs.100).aspx
FORCE_INLINE __m128 _mm_cmpge_ps(__m128 a, __m128 b)
{
return vreinterpretq_m128_u32(
vcgeq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)));
}
// Compares for less than or equal.
//
// r0 := (a0 <= b0) ? 0xffffffff : 0x0
// r1 := (a1 <= b1) ? 0xffffffff : 0x0
// r2 := (a2 <= b2) ? 0xffffffff : 0x0
// r3 := (a3 <= b3) ? 0xffffffff : 0x0
//
// https://msdn.microsoft.com/en-us/library/vstudio/1s75w83z(v=vs.100).aspx
FORCE_INLINE __m128 _mm_cmple_ps(__m128 a, __m128 b)
{
return vreinterpretq_m128_u32(
vcleq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)));
}
// Compares for equality.
// https://msdn.microsoft.com/en-us/library/vstudio/36aectz5(v=vs.100).aspx
FORCE_INLINE __m128 _mm_cmpeq_ps(__m128 a, __m128 b)
{
return vreinterpretq_m128_u32(
vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)));
}
// Compares the 16 signed or unsigned 8-bit integers in a and the 16 signed or
// unsigned 8-bit integers in b for equality.
// https://msdn.microsoft.com/en-us/library/windows/desktop/bz5xk21a(v=vs.90).aspx
FORCE_INLINE __m128i _mm_cmpeq_epi8(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u8(
vceqq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b)));
}
// Compares the 8 signed or unsigned 16-bit integers in a and the 8 signed or
// unsigned 16-bit integers in b for equality.
// https://msdn.microsoft.com/en-us/library/2ay060te(v=vs.100).aspx
FORCE_INLINE __m128i _mm_cmpeq_epi16(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u16(
vceqq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b)));
}
// Compare packed 32-bit integers in a and b for equality, and store the results
// in dst
FORCE_INLINE __m128i _mm_cmpeq_epi32(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u32(
vceqq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)));
}
// Compare packed 64-bit integers in a and b for equality, and store the results
// in dst
FORCE_INLINE __m128i _mm_cmpeq_epi64(__m128i a, __m128i b)
{
#if defined(__aarch64__)
return vreinterpretq_m128i_u64(
vceqq_u64(vreinterpretq_u64_m128i(a), vreinterpretq_u64_m128i(b)));
#else
// ARMv7 lacks vceqq_u64
// (a == b) -> (a_lo == b_lo) && (a_hi == b_hi)
uint32x4_t cmp = vceqq_u32(vreinterpretq_u32_m128i(a), vreinterpretq_u32_m128i(b));
uint32x4_t swapped = vrev64q_u32(cmp);
return vreinterpretq_m128i_u32(vandq_u32(cmp, swapped));
#endif
}
// Compares the 16 signed 8-bit integers in a and the 16 signed 8-bit integers
// in b for lesser than.
// https://msdn.microsoft.com/en-us/library/windows/desktop/9s46csht(v=vs.90).aspx
FORCE_INLINE __m128i _mm_cmplt_epi8(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u8(
vcltq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b)));
}
// Compares the 16 signed 8-bit integers in a and the 16 signed 8-bit integers
// in b for greater than.
//
// r0 := (a0 > b0) ? 0xff : 0x0
// r1 := (a1 > b1) ? 0xff : 0x0
// ...
// r15 := (a15 > b15) ? 0xff : 0x0
//
// https://msdn.microsoft.com/zh-tw/library/wf45zt2b(v=vs.100).aspx
FORCE_INLINE __m128i _mm_cmpgt_epi8(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u8(
vcgtq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b)));
}
// Compares the 8 signed 16-bit integers in a and the 8 signed 16-bit integers
// in b for less than.
//
// r0 := (a0 < b0) ? 0xffff : 0x0
// r1 := (a1 < b1) ? 0xffff : 0x0
// ...
// r7 := (a7 < b7) ? 0xffff : 0x0
//
// https://technet.microsoft.com/en-us/library/t863edb2(v=vs.100).aspx
FORCE_INLINE __m128i _mm_cmplt_epi16(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u16(
vcltq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b)));
}
// Compares the 8 signed 16-bit integers in a and the 8 signed 16-bit integers
// in b for greater than.
//
// r0 := (a0 > b0) ? 0xffff : 0x0
// r1 := (a1 > b1) ? 0xffff : 0x0
// ...
// r7 := (a7 > b7) ? 0xffff : 0x0
//
// https://technet.microsoft.com/en-us/library/xd43yfsa(v=vs.100).aspx
FORCE_INLINE __m128i _mm_cmpgt_epi16(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u16(
vcgtq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b)));
}
// Compares the 4 signed 32-bit integers in a and the 4 signed 32-bit integers
// in b for less than.
// https://msdn.microsoft.com/en-us/library/vstudio/4ak0bf5d(v=vs.100).aspx
FORCE_INLINE __m128i _mm_cmplt_epi32(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u32(
vcltq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)));
}
// Compares the 4 signed 32-bit integers in a and the 4 signed 32-bit integers
// in b for greater than.
// https://msdn.microsoft.com/en-us/library/vstudio/1s9f2z0y(v=vs.100).aspx
FORCE_INLINE __m128i _mm_cmpgt_epi32(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u32(
vcgtq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)));
}
// Compares the 2 signed 64-bit integers in a and the 2 signed 64-bit integers
// in b for greater than.
FORCE_INLINE __m128i _mm_cmpgt_epi64(__m128i a, __m128i b)
{
#if defined(__aarch64__)
return vreinterpretq_m128i_u64(
vcgtq_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(b)));
#else
// ARMv7 lacks vcgtq_s64.
// This is based off of Clang's SSE2 polyfill:
// (a > b) -> ((a_hi > b_hi) || (a_lo > b_lo && a_hi == b_hi))
// Mask the sign bit out since we need a signed AND an unsigned comparison
// and it is ugly to try and split them.
int32x4_t mask = vreinterpretq_s32_s64(vdupq_n_s64(0x80000000ull));
int32x4_t a_mask = veorq_s32(vreinterpretq_s32_m128i(a), mask);
int32x4_t b_mask = veorq_s32(vreinterpretq_s32_m128i(b), mask);
// Check if a > b
int64x2_t greater = vreinterpretq_s64_u32(vcgtq_s32(a_mask, b_mask));
// Copy upper mask to lower mask
// a_hi > b_hi
int64x2_t gt_hi = vshrq_n_s64(greater, 63);
// Copy lower mask to upper mask
// a_lo > b_lo
int64x2_t gt_lo = vsliq_n_s64(greater, greater, 32);
// Compare for equality
int64x2_t equal = vreinterpretq_s64_u32(vceqq_s32(a_mask, b_mask));
// Copy upper mask to lower mask
// a_hi == b_hi
int64x2_t eq_hi = vshrq_n_s64(equal, 63);
// a_hi > b_hi || (a_lo > b_lo && a_hi == b_hi)
int64x2_t ret = vorrq_s64(gt_hi, vandq_s64(gt_lo, eq_hi));
return vreinterpretq_m128i_s64(ret);
#endif
}
// Compares the four 32-bit floats in a and b to check if any values are NaN.
// Ordered compare between each value returns true for "orderable" and false for
// "not orderable" (NaN).
// https://msdn.microsoft.com/en-us/library/vstudio/0h9w00fx(v=vs.100).aspx see
// also:
// http://stackoverflow.com/questions/8627331/what-does-ordered-unordered-comparison-mean
// http://stackoverflow.com/questions/29349621/neon-isnanval-intrinsics
FORCE_INLINE __m128 _mm_cmpord_ps(__m128 a, __m128 b)
{
// Note: NEON does not have ordered compare builtin
// Need to compare a eq a and b eq b to check for NaN
// Do AND of results to get final
uint32x4_t ceqaa =
vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a));
uint32x4_t ceqbb =
vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b));
return vreinterpretq_m128_u32(vandq_u32(ceqaa, ceqbb));
}
// Compares the lower single-precision floating point scalar values of a and b
// using a less than operation. :
// https://msdn.microsoft.com/en-us/library/2kwe606b(v=vs.90).aspx Important
// note!! The documentation on MSDN is incorrect! If either of the values is a
// NAN the docs say you will get a one, but in fact, it will return a zero!!
FORCE_INLINE int _mm_comilt_ss(__m128 a, __m128 b)
{
uint32x4_t a_not_nan =
vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a));
uint32x4_t b_not_nan =
vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b));
uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan);
uint32x4_t a_lt_b =
vcltq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b));
return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_lt_b), 0) != 0) ? 1 : 0;
}
// Compares the lower single-precision floating point scalar values of a and b
// using a greater than operation. :
// https://msdn.microsoft.com/en-us/library/b0738e0t(v=vs.100).aspx
FORCE_INLINE int _mm_comigt_ss(__m128 a, __m128 b)
{
// return vgetq_lane_u32(vcgtq_f32(vreinterpretq_f32_m128(a),
// vreinterpretq_f32_m128(b)), 0);
uint32x4_t a_not_nan =
vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a));
uint32x4_t b_not_nan =
vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b));
uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan);
uint32x4_t a_gt_b =
vcgtq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b));
return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_gt_b), 0) != 0) ? 1 : 0;
}
// Compares the lower single-precision floating point scalar values of a and b
// using a less than or equal operation. :
// https://msdn.microsoft.com/en-us/library/1w4t7c57(v=vs.90).aspx
FORCE_INLINE int _mm_comile_ss(__m128 a, __m128 b)
{
// return vgetq_lane_u32(vcleq_f32(vreinterpretq_f32_m128(a),
// vreinterpretq_f32_m128(b)), 0);
uint32x4_t a_not_nan =
vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a));
uint32x4_t b_not_nan =
vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b));
uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan);
uint32x4_t a_le_b =
vcleq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b));
return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_le_b), 0) != 0) ? 1 : 0;
}
// Compares the lower single-precision floating point scalar values of a and b
// using a greater than or equal operation. :
// https://msdn.microsoft.com/en-us/library/8t80des6(v=vs.100).aspx
FORCE_INLINE int _mm_comige_ss(__m128 a, __m128 b)
{
// return vgetq_lane_u32(vcgeq_f32(vreinterpretq_f32_m128(a),
// vreinterpretq_f32_m128(b)), 0);
uint32x4_t a_not_nan =
vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a));
uint32x4_t b_not_nan =
vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b));
uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan);
uint32x4_t a_ge_b =
vcgeq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b));
return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_ge_b), 0) != 0) ? 1 : 0;
}
// Compares the lower single-precision floating point scalar values of a and b
// using an equality operation. :
// https://msdn.microsoft.com/en-us/library/93yx2h2b(v=vs.100).aspx
FORCE_INLINE int _mm_comieq_ss(__m128 a, __m128 b)
{
// return vgetq_lane_u32(vceqq_f32(vreinterpretq_f32_m128(a),
// vreinterpretq_f32_m128(b)), 0);
uint32x4_t a_not_nan =
vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a));
uint32x4_t b_not_nan =
vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b));
uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan);
uint32x4_t a_eq_b =
vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b));
return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_eq_b), 0) != 0) ? 1 : 0;
}
// Compares the lower single-precision floating point scalar values of a and b
// using an inequality operation. :
// https://msdn.microsoft.com/en-us/library/bafh5e0a(v=vs.90).aspx
FORCE_INLINE int _mm_comineq_ss(__m128 a, __m128 b)
{
// return !vgetq_lane_u32(vceqq_f32(vreinterpretq_f32_m128(a),
// vreinterpretq_f32_m128(b)), 0);
uint32x4_t a_not_nan =
vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a));
uint32x4_t b_not_nan =
vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b));
uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan));
uint32x4_t a_neq_b = vmvnq_u32(
vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)));
return (vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_neq_b), 0) != 0) ? 1 : 0;
}
// according to the documentation, these intrinsics behave the same as the
// non-'u' versions. We'll just alias them here.
#define _mm_ucomilt_ss _mm_comilt_ss
#define _mm_ucomile_ss _mm_comile_ss
#define _mm_ucomigt_ss _mm_comigt_ss
#define _mm_ucomige_ss _mm_comige_ss
#define _mm_ucomieq_ss _mm_comieq_ss
#define _mm_ucomineq_ss _mm_comineq_ss
// ******************************************
// Conversions
// ******************************************
// Converts the four single-precision, floating-point values of a to signed
// 32-bit integer values using truncate.
// https://msdn.microsoft.com/en-us/library/vstudio/1h005y6x(v=vs.100).aspx
FORCE_INLINE __m128i _mm_cvttps_epi32(__m128 a)
{
return vreinterpretq_m128i_s32(vcvtq_s32_f32(vreinterpretq_f32_m128(a)));
}
// Converts the four signed 32-bit integer values of a to single-precision,
// floating-point values
// https://msdn.microsoft.com/en-us/library/vstudio/36bwxcx5(v=vs.100).aspx
FORCE_INLINE __m128 _mm_cvtepi32_ps(__m128i a)
{
return vreinterpretq_m128_f32(vcvtq_f32_s32(vreinterpretq_s32_m128i(a)));
}
// Converts the four unsigned 8-bit integers in the lower 16 bits to four
// unsigned 32-bit integers.
FORCE_INLINE __m128i _mm_cvtepu8_epi16(__m128i a)
{
uint8x16_t u8x16 = vreinterpretq_u8_m128i(a); /* xxxx xxxx xxxx DCBA */
uint16x8_t u16x8 = vmovl_u8(vget_low_u8(u8x16)); /* 0x0x 0x0x 0D0C 0B0A */
return vreinterpretq_m128i_u16(u16x8);
}
// Converts the four unsigned 8-bit integers in the lower 32 bits to four
// unsigned 32-bit integers.
// https://msdn.microsoft.com/en-us/library/bb531467%28v=vs.100%29.aspx
FORCE_INLINE __m128i _mm_cvtepu8_epi32(__m128i a)
{
uint8x16_t u8x16 = vreinterpretq_u8_m128i(a); /* xxxx xxxx xxxx DCBA */
uint16x8_t u16x8 = vmovl_u8(vget_low_u8(u8x16)); /* 0x0x 0x0x 0D0C 0B0A */
uint32x4_t u32x4 = vmovl_u16(vget_low_u16(u16x8)); /* 000D 000C 000B 000A */
return vreinterpretq_m128i_u32(u32x4);
}
// Converts the two unsigned 8-bit integers in the lower 16 bits to two
// unsigned 64-bit integers.
FORCE_INLINE __m128i _mm_cvtepu8_epi64(__m128i a)
{
uint8x16_t u8x16 = vreinterpretq_u8_m128i(a); /* xxxx xxxx xxxx xxBA */
uint16x8_t u16x8 = vmovl_u8(vget_low_u8(u8x16)); /* 0x0x 0x0x 0x0x 0B0A */
uint32x4_t u32x4 = vmovl_u16(vget_low_u16(u16x8)); /* 000x 000x 000B 000A */
uint64x2_t u64x2 = vmovl_u32(vget_low_u32(u32x4)); /* 0000 000B 0000 000A */
return vreinterpretq_m128i_u64(u64x2);
}
// Converts the four unsigned 8-bit integers in the lower 16 bits to four
// unsigned 32-bit integers.
FORCE_INLINE __m128i _mm_cvtepi8_epi16(__m128i a)
{
int8x16_t s8x16 = vreinterpretq_s8_m128i(a); /* xxxx xxxx xxxx DCBA */
int16x8_t s16x8 = vmovl_s8(vget_low_s8(s8x16)); /* 0x0x 0x0x 0D0C 0B0A */
return vreinterpretq_m128i_s16(s16x8);
}
// Converts the four unsigned 8-bit integers in the lower 32 bits to four
// unsigned 32-bit integers.
FORCE_INLINE __m128i _mm_cvtepi8_epi32(__m128i a)
{
int8x16_t s8x16 = vreinterpretq_s8_m128i(a); /* xxxx xxxx xxxx DCBA */
int16x8_t s16x8 = vmovl_s8(vget_low_s8(s8x16)); /* 0x0x 0x0x 0D0C 0B0A */
int32x4_t s32x4 = vmovl_s16(vget_low_s16(s16x8)); /* 000D 000C 000B 000A */
return vreinterpretq_m128i_s32(s32x4);
}
// Converts the two signed 8-bit integers in the lower 32 bits to four
// signed 64-bit integers.
FORCE_INLINE __m128i _mm_cvtepi8_epi64(__m128i a)
{
int8x16_t s8x16 = vreinterpretq_s8_m128i(a); /* xxxx xxxx xxxx xxBA */
int16x8_t s16x8 = vmovl_s8(vget_low_s8(s8x16)); /* 0x0x 0x0x 0x0x 0B0A */
int32x4_t s32x4 = vmovl_s16(vget_low_s16(s16x8)); /* 000x 000x 000B 000A */
int64x2_t s64x2 = vmovl_s32(vget_low_s32(s32x4)); /* 0000 000B 0000 000A */
return vreinterpretq_m128i_s64(s64x2);
}
// Converts the four signed 16-bit integers in the lower 64 bits to four signed
// 32-bit integers.
FORCE_INLINE __m128i _mm_cvtepi16_epi32(__m128i a)
{
return vreinterpretq_m128i_s32(
vmovl_s16(vget_low_s16(vreinterpretq_s16_m128i(a))));
}
// Converts the two signed 16-bit integers in the lower 32 bits two signed
// 32-bit integers.
FORCE_INLINE __m128i _mm_cvtepi16_epi64(__m128i a)
{
int16x8_t s16x8 = vreinterpretq_s16_m128i(a); /* xxxx xxxx xxxx 0B0A */
int32x4_t s32x4 = vmovl_s16(vget_low_s16(s16x8)); /* 000x 000x 000B 000A */
int64x2_t s64x2 = vmovl_s32(vget_low_s32(s32x4)); /* 0000 000B 0000 000A */
return vreinterpretq_m128i_s64(s64x2);
}
// Converts the four unsigned 16-bit integers in the lower 64 bits to four unsigned
// 32-bit integers.
FORCE_INLINE __m128i _mm_cvtepu16_epi32(__m128i a)
{
return vreinterpretq_m128i_u32(
vmovl_u16(vget_low_u16(vreinterpretq_u16_m128i(a))));
}
// Converts the two unsigned 16-bit integers in the lower 32 bits to two unsigned
// 64-bit integers.
FORCE_INLINE __m128i _mm_cvtepu16_epi64(__m128i a)
{
uint16x8_t u16x8 = vreinterpretq_u16_m128i(a); /* xxxx xxxx xxxx 0B0A */
uint32x4_t u32x4 = vmovl_u16(vget_low_u16(u16x8)); /* 000x 000x 000B 000A */
uint64x2_t u64x2 = vmovl_u32(vget_low_u32(u32x4)); /* 0000 000B 0000 000A */
return vreinterpretq_m128i_u64(u64x2);
}
// Converts the two unsigned 32-bit integers in the lower 64 bits to two unsigned
// 64-bit integers.
FORCE_INLINE __m128i _mm_cvtepu32_epi64(__m128i a)
{
return vreinterpretq_m128i_u64(
vmovl_u32(vget_low_u32(vreinterpretq_u32_m128i(a))));
}
// Converts the two signed 32-bit integers in the lower 64 bits to two signed
// 64-bit integers.
FORCE_INLINE __m128i _mm_cvtepi32_epi64(__m128i a)
{
return vreinterpretq_m128i_s64(
vmovl_s32(vget_low_s32(vreinterpretq_s32_m128i(a))));
}
// Converts the four single-precision, floating-point values of a to signed
// 32-bit integer values.
//
// r0 := (int) a0
// r1 := (int) a1
// r2 := (int) a2
// r3 := (int) a3
//
// https://msdn.microsoft.com/en-us/library/vstudio/xdc42k5e(v=vs.100).aspx
// *NOTE*. The default rounding mode on SSE is 'round to even', which ArmV7-A
// does not support! It is supported on ARMv8-A however.
FORCE_INLINE __m128i _mm_cvtps_epi32(__m128 a)
{
#if defined(__aarch64__)
return vreinterpretq_m128i_s32(vcvtnq_s32_f32(a));
#else
uint32x4_t signmask = vdupq_n_u32(0x80000000);
float32x4_t half = vbslq_f32(signmask, vreinterpretq_f32_m128(a),
vdupq_n_f32(0.5f)); /* +/- 0.5 */
int32x4_t r_normal = vcvtq_s32_f32(vaddq_f32(
vreinterpretq_f32_m128(a), half)); /* round to integer: [a + 0.5]*/
int32x4_t r_trunc =
vcvtq_s32_f32(vreinterpretq_f32_m128(a)); /* truncate to integer: [a] */
int32x4_t plusone = vreinterpretq_s32_u32(vshrq_n_u32(
vreinterpretq_u32_s32(vnegq_s32(r_trunc)), 31)); /* 1 or 0 */
int32x4_t r_even = vbicq_s32(vaddq_s32(r_trunc, plusone),
vdupq_n_s32(1)); /* ([a] + {0,1}) & ~1 */
float32x4_t delta = vsubq_f32(
vreinterpretq_f32_m128(a),
vcvtq_f32_s32(r_trunc)); /* compute delta: delta = (a - [a]) */
uint32x4_t is_delta_half = vceqq_f32(delta, half); /* delta == +/- 0.5 */
return vreinterpretq_m128i_s32(vbslq_s32(is_delta_half, r_even, r_normal));
#endif
}
// Moves the least significant 32 bits of a to a 32-bit integer.
// https://msdn.microsoft.com/en-us/library/5z7a9642%28v=vs.90%29.aspx
FORCE_INLINE int _mm_cvtsi128_si32(__m128i a)
{
return vgetq_lane_s32(vreinterpretq_s32_m128i(a), 0);
}
// Extracts the low order 64-bit integer from the parameter.
// https://msdn.microsoft.com/en-us/library/bb531384(v=vs.120).aspx
FORCE_INLINE uint64_t _mm_cvtsi128_si64(__m128i a)
{
return vgetq_lane_s64(vreinterpretq_s64_m128i(a), 0);
}
// Moves 32-bit integer a to the least significant 32 bits of an __m128 object,
// zero extending the upper bits.
//
// r0 := a
// r1 := 0x0
// r2 := 0x0
// r3 := 0x0
//
// https://msdn.microsoft.com/en-us/library/ct3539ha%28v=vs.90%29.aspx
FORCE_INLINE __m128i _mm_cvtsi32_si128(int a)
{
return vreinterpretq_m128i_s32(vsetq_lane_s32(a, vdupq_n_s32(0), 0));
}
// Moves 64-bit integer a to the least significant 64 bits of an __m128 object,
// zero extending the upper bits.
//
// r0 := a
// r1 := 0x0
FORCE_INLINE __m128i _mm_cvtsi64_si128(int64_t a)
{
return vreinterpretq_m128i_s64(vsetq_lane_s64(a, vdupq_n_s64(0), 0));
}
// Applies a type cast to reinterpret four 32-bit floating point values passed
// in as a 128-bit parameter as packed 32-bit integers.
// https://msdn.microsoft.com/en-us/library/bb514099.aspx
FORCE_INLINE __m128i _mm_castps_si128(__m128 a)
{
return vreinterpretq_m128i_s32(vreinterpretq_s32_m128(a));
}
// Applies a type cast to reinterpret four 32-bit integers passed in as a
// 128-bit parameter as packed 32-bit floating point values.
// https://msdn.microsoft.com/en-us/library/bb514029.aspx
FORCE_INLINE __m128 _mm_castsi128_ps(__m128i a)
{
return vreinterpretq_m128_s32(vreinterpretq_s32_m128i(a));
}
// Loads 128-bit value. :
// https://msdn.microsoft.com/en-us/library/atzzad1h(v=vs.80).aspx
FORCE_INLINE __m128i _mm_load_si128(const __m128i *p)
{
return vreinterpretq_m128i_s32(vld1q_s32((const int32_t *) p));
}
// Loads 128-bit value. :
// https://msdn.microsoft.com/zh-cn/library/f4k12ae8(v=vs.90).aspx
FORCE_INLINE __m128i _mm_loadu_si128(const __m128i *p)
{
return vreinterpretq_m128i_s32(vld1q_s32((const int32_t *) p));
}
// _mm_lddqu_si128 functions the same as _mm_loadu_si128.
#define _mm_lddqu_si128 _mm_loadu_si128
// ******************************************
// Miscellaneous Operations
// ******************************************
// Shifts the 8 signed 16-bit integers in a right by count bits while shifting
// in the sign bit.
//
// r0 := a0 >> count
// r1 := a1 >> count
// ...
// r7 := a7 >> count
//
// https://msdn.microsoft.com/en-us/library/3c9997dk(v%3dvs.90).aspx
FORCE_INLINE __m128i _mm_sra_epi16(__m128i a, __m128i count)
{
int64_t c = (int64_t) vget_low_s64((int64x2_t) count);
if (c > 15)
return _mm_cmplt_epi16(a, _mm_setzero_si128());
return vreinterpretq_m128i_s16(vshlq_s16((int16x8_t) a, vdupq_n_s16(-c)));
}
// Shifts the 4 signed 32-bit integers in a right by count bits while shifting
// in the sign bit.
//
// r0 := a0 >> count
// r1 := a1 >> count
// r2 := a2 >> count
// r3 := a3 >> count
//
// https://msdn.microsoft.com/en-us/library/ce40009e(v%3dvs.100).aspx
FORCE_INLINE __m128i _mm_sra_epi32(__m128i a, __m128i count)
{
int64_t c = (int64_t) vget_low_s64((int64x2_t) count);
if (c > 31)
return _mm_cmplt_epi32(a, _mm_setzero_si128());
return vreinterpretq_m128i_s32(vshlq_s32((int32x4_t) a, vdupq_n_s32(-c)));
}
// Packs the 16 signed 16-bit integers from a and b into 8-bit integers and
// saturates.
// https://msdn.microsoft.com/en-us/library/k4y4f7w5%28v=vs.90%29.aspx
FORCE_INLINE __m128i _mm_packs_epi16(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s8(
vcombine_s8(vqmovn_s16(vreinterpretq_s16_m128i(a)),
vqmovn_s16(vreinterpretq_s16_m128i(b))));
}
// Packs the 16 signed 16 - bit integers from a and b into 8 - bit unsigned
// integers and saturates.
//
// r0 := UnsignedSaturate(a0)
// r1 := UnsignedSaturate(a1)
// ...
// r7 := UnsignedSaturate(a7)
// r8 := UnsignedSaturate(b0)
// r9 := UnsignedSaturate(b1)
// ...
// r15 := UnsignedSaturate(b7)
//
// https://msdn.microsoft.com/en-us/library/07ad1wx4(v=vs.100).aspx
FORCE_INLINE __m128i _mm_packus_epi16(const __m128i a, const __m128i b)
{
return vreinterpretq_m128i_u8(
vcombine_u8(vqmovun_s16(vreinterpretq_s16_m128i(a)),
vqmovun_s16(vreinterpretq_s16_m128i(b))));
}
// Packs the 8 signed 32-bit integers from a and b into signed 16-bit integers
// and saturates.
//
// r0 := SignedSaturate(a0)
// r1 := SignedSaturate(a1)
// r2 := SignedSaturate(a2)
// r3 := SignedSaturate(a3)
// r4 := SignedSaturate(b0)
// r5 := SignedSaturate(b1)
// r6 := SignedSaturate(b2)
// r7 := SignedSaturate(b3)
//
// https://msdn.microsoft.com/en-us/library/393t56f9%28v=vs.90%29.aspx
FORCE_INLINE __m128i _mm_packs_epi32(__m128i a, __m128i b)
{
return vreinterpretq_m128i_s16(
vcombine_s16(vqmovn_s32(vreinterpretq_s32_m128i(a)),
vqmovn_s32(vreinterpretq_s32_m128i(b))));
}
// Packs the 8 unsigned 32-bit integers from a and b into unsigned 16-bit integers
// and saturates.
//
// r0 := UnsignedSaturate(a0)
// r1 := UnsignedSaturate(a1)
// r2 := UnsignedSaturate(a2)
// r3 := UnsignedSaturate(a3)
// r4 := UnsignedSaturate(b0)
// r5 := UnsignedSaturate(b1)
// r6 := UnsignedSaturate(b2)
// r7 := UnsignedSaturate(b3)
FORCE_INLINE __m128i _mm_packus_epi32(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u16(
vcombine_u16(vqmovn_u32(vreinterpretq_u32_m128i(a)),
vqmovn_u32(vreinterpretq_u32_m128i(b))));
}
// Interleaves the lower 8 signed or unsigned 8-bit integers in a with the lower
// 8 signed or unsigned 8-bit integers in b.
//
// r0 := a0
// r1 := b0
// r2 := a1
// r3 := b1
// ...
// r14 := a7
// r15 := b7
//
// https://msdn.microsoft.com/en-us/library/xf7k860c%28v=vs.90%29.aspx
FORCE_INLINE __m128i _mm_unpacklo_epi8(__m128i a, __m128i b)
{
#if defined(__aarch64__)
return vreinterpretq_m128i_s8(vzip1q_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b)));
#else
int8x8_t a1 = vreinterpret_s8_s16(vget_low_s16(vreinterpretq_s16_m128i(a)));
int8x8_t b1 = vreinterpret_s8_s16(vget_low_s16(vreinterpretq_s16_m128i(b)));
int8x8x2_t result = vzip_s8(a1, b1);
return vreinterpretq_m128i_s8(vcombine_s8(result.val[0], result.val[1]));
#endif
}
// Interleaves the lower 4 signed or unsigned 16-bit integers in a with the
// lower 4 signed or unsigned 16-bit integers in b.
//
// r0 := a0
// r1 := b0
// r2 := a1
// r3 := b1
// r4 := a2
// r5 := b2
// r6 := a3
// r7 := b3
//
// https://msdn.microsoft.com/en-us/library/btxb17bw%28v=vs.90%29.aspx
FORCE_INLINE __m128i _mm_unpacklo_epi16(__m128i a, __m128i b)
{
#if defined(__aarch64__)
return vreinterpretq_m128i_s16(vzip1q_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b)));
#else
int16x4_t a1 = vget_low_s16(vreinterpretq_s16_m128i(a));
int16x4_t b1 = vget_low_s16(vreinterpretq_s16_m128i(b));
int16x4x2_t result = vzip_s16(a1, b1);
return vreinterpretq_m128i_s16(vcombine_s16(result.val[0], result.val[1]));
#endif
}
// Interleaves the lower 2 signed or unsigned 32 - bit integers in a with the
// lower 2 signed or unsigned 32 - bit integers in b.
//
// r0 := a0
// r1 := b0
// r2 := a1
// r3 := b1
//
// https://msdn.microsoft.com/en-us/library/x8atst9d(v=vs.100).aspx
FORCE_INLINE __m128i _mm_unpacklo_epi32(__m128i a, __m128i b)
{
#if defined(__aarch64__)
return vreinterpretq_m128i_s32(vzip1q_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)));
#else
int32x2_t a1 = vget_low_s32(vreinterpretq_s32_m128i(a));
int32x2_t b1 = vget_low_s32(vreinterpretq_s32_m128i(b));
int32x2x2_t result = vzip_s32(a1, b1);
return vreinterpretq_m128i_s32(vcombine_s32(result.val[0], result.val[1]));
#endif
}
FORCE_INLINE __m128i _mm_unpacklo_epi64(__m128i a, __m128i b)
{
int64x1_t a_l = vget_low_s64(vreinterpretq_s64_m128i(a));
int64x1_t b_l = vget_low_s64(vreinterpretq_s64_m128i(b));
return vreinterpretq_m128i_s64(vcombine_s64(a_l, b_l));
}
// Selects and interleaves the lower two single-precision, floating-point values
// from a and b.
//
// r0 := a0
// r1 := b0
// r2 := a1
// r3 := b1
//
// https://msdn.microsoft.com/en-us/library/25st103b%28v=vs.90%29.aspx
FORCE_INLINE __m128 _mm_unpacklo_ps(__m128 a, __m128 b)
{
#if defined(__aarch64__)
return vreinterpretq_m128_f32(vzip1q_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)));
#else
float32x2_t a1 = vget_low_f32(vreinterpretq_f32_m128(a));
float32x2_t b1 = vget_low_f32(vreinterpretq_f32_m128(b));
float32x2x2_t result = vzip_f32(a1, b1);
return vreinterpretq_m128_f32(vcombine_f32(result.val[0], result.val[1]));
#endif
}
// Selects and interleaves the upper two single-precision, floating-point values
// from a and b.
//
// r0 := a2
// r1 := b2
// r2 := a3
// r3 := b3
//
// https://msdn.microsoft.com/en-us/library/skccxx7d%28v=vs.90%29.aspx
FORCE_INLINE __m128 _mm_unpackhi_ps(__m128 a, __m128 b)
{
#if defined(__aarch64__)
return vreinterpretq_m128_f32(vzip2q_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)));
#else
float32x2_t a1 = vget_high_f32(vreinterpretq_f32_m128(a));
float32x2_t b1 = vget_high_f32(vreinterpretq_f32_m128(b));
float32x2x2_t result = vzip_f32(a1, b1);
return vreinterpretq_m128_f32(vcombine_f32(result.val[0], result.val[1]));
#endif
}
// Interleaves the upper 8 signed or unsigned 8-bit integers in a with the upper
// 8 signed or unsigned 8-bit integers in b.
//
// r0 := a8
// r1 := b8
// r2 := a9
// r3 := b9
// ...
// r14 := a15
// r15 := b15
//
// https://msdn.microsoft.com/en-us/library/t5h7783k(v=vs.100).aspx
FORCE_INLINE __m128i _mm_unpackhi_epi8(__m128i a, __m128i b)
{
#if defined(__aarch64__)
return vreinterpretq_m128i_s8(vzip2q_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b)));
#else
int8x8_t a1 =
vreinterpret_s8_s16(vget_high_s16(vreinterpretq_s16_m128i(a)));
int8x8_t b1 =
vreinterpret_s8_s16(vget_high_s16(vreinterpretq_s16_m128i(b)));
int8x8x2_t result = vzip_s8(a1, b1);
return vreinterpretq_m128i_s8(vcombine_s8(result.val[0], result.val[1]));
#endif
}
// Interleaves the upper 4 signed or unsigned 16-bit integers in a with the
// upper 4 signed or unsigned 16-bit integers in b.
//
// r0 := a4
// r1 := b4
// r2 := a5
// r3 := b5
// r4 := a6
// r5 := b6
// r6 := a7
// r7 := b7
//
// https://msdn.microsoft.com/en-us/library/03196cz7(v=vs.100).aspx
FORCE_INLINE __m128i _mm_unpackhi_epi16(__m128i a, __m128i b)
{
#if defined(__aarch64__)
return vreinterpretq_m128i_s16(vzip2q_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b)));
#else
int16x4_t a1 = vget_high_s16(vreinterpretq_s16_m128i(a));
int16x4_t b1 = vget_high_s16(vreinterpretq_s16_m128i(b));
int16x4x2_t result = vzip_s16(a1, b1);
return vreinterpretq_m128i_s16(vcombine_s16(result.val[0], result.val[1]));
#endif
}
// Interleaves the upper 2 signed or unsigned 32-bit integers in a with the
// upper 2 signed or unsigned 32-bit integers in b.
// https://msdn.microsoft.com/en-us/library/65sa7cbs(v=vs.100).aspx
FORCE_INLINE __m128i _mm_unpackhi_epi32(__m128i a, __m128i b)
{
#if defined(__aarch64__)
return vreinterpretq_m128i_s32(vzip2q_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)));
#else
int32x2_t a1 = vget_high_s32(vreinterpretq_s32_m128i(a));
int32x2_t b1 = vget_high_s32(vreinterpretq_s32_m128i(b));
int32x2x2_t result = vzip_s32(a1, b1);
return vreinterpretq_m128i_s32(vcombine_s32(result.val[0], result.val[1]));
#endif
}
// Interleaves the upper signed or unsigned 64-bit integer in a with the
// upper signed or unsigned 64-bit integer in b.
//
// r0 := a1
// r1 := b1
FORCE_INLINE __m128i _mm_unpackhi_epi64(__m128i a, __m128i b)
{
int64x1_t a_h = vget_high_s64(vreinterpretq_s64_m128i(a));
int64x1_t b_h = vget_high_s64(vreinterpretq_s64_m128i(b));
return vreinterpretq_m128i_s64(vcombine_s64(a_h, b_h));
}
// shift to right
// https://msdn.microsoft.com/en-us/library/bb514041(v=vs.120).aspx
// http://blog.csdn.net/hemmingway/article/details/44828303
// Clang requires a macro here, as it is extremely picky about c being a literal.
#define _mm_alignr_epi8(a, b, c) ((__m128i) vextq_s8((int8x16_t) (b), (int8x16_t) (a), (c)))
// Extracts the selected signed or unsigned 8-bit integer from a and zero
// extends.
// FORCE_INLINE int _mm_extract_epi8(__m128i a, __constrange(0,16) int imm)
#define _mm_extract_epi8(a, imm) \
vgetq_lane_u8(vreinterpretq_u8_m128i(a), (imm))
// Inserts the least significant 8 bits of b into the selected 8-bit integer
// of a.
// FORCE_INLINE __m128i _mm_insert_epi8(__m128i a, const int b,
// __constrange(0,16) int imm)
#define _mm_insert_epi8(a, b, imm) \
__extension__({ \
vreinterpretq_m128i_s8( \
vsetq_lane_s8((b), vreinterpretq_s8_m128i(a), (imm))); \
})
// Extracts the selected signed or unsigned 16-bit integer from a and zero
// extends.
// https://msdn.microsoft.com/en-us/library/6dceta0c(v=vs.100).aspx
// FORCE_INLINE int _mm_extract_epi16(__m128i a, __constrange(0,8) int imm)
#define _mm_extract_epi16(a, imm) \
vgetq_lane_u16(vreinterpretq_u16_m128i(a), (imm))
// Inserts the least significant 16 bits of b into the selected 16-bit integer
// of a.
// https://msdn.microsoft.com/en-us/library/kaze8hz1%28v=vs.100%29.aspx
// FORCE_INLINE __m128i _mm_insert_epi16(__m128i a, const int b,
// __constrange(0,8) int imm)
#define _mm_insert_epi16(a, b, imm) \
__extension__({ \
vreinterpretq_m128i_s16( \
vsetq_lane_s16((b), vreinterpretq_s16_m128i(a), (imm))); \
})
// Extracts the selected signed or unsigned 32-bit integer from a and zero
// extends.
// FORCE_INLINE int _mm_extract_epi32(__m128i a, __constrange(0,4) int imm)
#define _mm_extract_epi32(a, imm) \
vgetq_lane_s32(vreinterpretq_s32_m128i(a), (imm))
// Inserts the least significant 32 bits of b into the selected 32-bit integer
// of a.
// FORCE_INLINE __m128i _mm_insert_epi32(__m128i a, const int b,
// __constrange(0,4) int imm)
#define _mm_insert_epi32(a, b, imm) \
__extension__({ \
vreinterpretq_m128i_s32( \
vsetq_lane_s32((b), vreinterpretq_s32_m128i(a), (imm))); \
})
// Extracts the selected signed or unsigned 64-bit integer from a and zero
// extends.
// FORCE_INLINE __int64 _mm_extract_epi64(__m128i a, __constrange(0,2) int imm)
#define _mm_extract_epi64(a, imm) \
vgetq_lane_s64(vreinterpretq_s64_m128i(a), (imm))
// Inserts the least significant 64 bits of b into the selected 64-bit integer
// of a.
// FORCE_INLINE __m128i _mm_insert_epi64(__m128i a, const __int64 b,
// __constrange(0,2) int imm)
#define _mm_insert_epi64(a, b, imm) \
__extension__({ \
vreinterpretq_m128i_s64( \
vsetq_lane_s64((b), vreinterpretq_s64_m128i(a), (imm))); \
})
// ******************************************
// Crypto Extensions
// ******************************************
#if defined(__ARM_FEATURE_CRYPTO)
// Wraps vmull_p64
FORCE_INLINE uint64x2_t _sse2neon_vmull_p64(uint64x1_t _a, uint64x1_t _b)
{
poly64_t a = vget_lane_p64(vreinterpret_p64_u64(_a), 0);
poly64_t b = vget_lane_p64(vreinterpret_p64_u64(_b), 0);
return vreinterpretq_u64_p128(vmull_p64(a, b));
}
#else // ARMv7 polyfill
// ARMv7/some A64 lacks vmull_p64, but it has vmull_p8.
//
// vmull_p8 calculates 8 8-bit->16-bit polynomial multiplies, but we need a
// 64-bit->128-bit polynomial multiply.
//
// It needs some work and is somewhat slow, but it is still faster than all
// known scalar methods.
//
// Algorithm adapted to C from https://www.workofard.com/2017/07/ghash-for-low-end-cores/,
// which is adapted from "Fast Software Polynomial Multiplication on
// ARM Processors Using the NEON Engine" by <NAME>, <NAME>,
// <NAME> and <NAME> (https://hal.inria.fr/hal-01506572)
static uint64x2_t _sse2neon_vmull_p64(uint64x1_t _a, uint64x1_t _b)
{
poly8x8_t a = vreinterpret_p8_u64(_a);
poly8x8_t b = vreinterpret_p8_u64(_b);
// Masks
uint8x16_t k48_32 = vcombine_u8(vcreate_u8(0x0000ffffffffffff), vcreate_u8(0x00000000ffffffff));
uint8x16_t k16_00 = vcombine_u8(vcreate_u8(0x000000000000ffff), vcreate_u8(0x0000000000000000));
// Do the multiplies, rotating with vext to get all combinations
uint8x16_t d = vreinterpretq_u8_p16(vmull_p8(a, b)); // D = A0 * B0
uint8x16_t e = vreinterpretq_u8_p16(vmull_p8(a, vext_p8(b, b, 1))); // E = A0 * B1
uint8x16_t f = vreinterpretq_u8_p16(vmull_p8(vext_p8(a, a, 1), b)); // F = A1 * B0
uint8x16_t g = vreinterpretq_u8_p16(vmull_p8(a, vext_p8(b, b, 2))); // G = A0 * B2
uint8x16_t h = vreinterpretq_u8_p16(vmull_p8(vext_p8(a, a, 2), b)); // H = A2 * B0
uint8x16_t i = vreinterpretq_u8_p16(vmull_p8(a, vext_p8(b, b, 3))); // I = A0 * B3
uint8x16_t j = vreinterpretq_u8_p16(vmull_p8(vext_p8(a, a, 3), b)); // J = A3 * B0
uint8x16_t k = vreinterpretq_u8_p16(vmull_p8(a, vext_p8(b, b, 4))); // L = A0 * B4
// Add cross products
uint8x16_t l = veorq_u8(e, f); // L = E + F
uint8x16_t m = veorq_u8(g, h); // M = G + H
uint8x16_t n = veorq_u8(i, j); // N = I + J
// Interleave. Using vzip1 and vzip2 prevents Clang from emitting TBL instructions.
#if defined(__aarch64__)
uint8x16_t lm_p0 = vreinterpretq_u8_u64(vzip1q_u64(vreinterpretq_u64_u8(l), vreinterpretq_u64_u8(m)));
uint8x16_t lm_p1 = vreinterpretq_u8_u64(vzip2q_u64(vreinterpretq_u64_u8(l), vreinterpretq_u64_u8(m)));
uint8x16_t nk_p0 = vreinterpretq_u8_u64(vzip1q_u64(vreinterpretq_u64_u8(n), vreinterpretq_u64_u8(k)));
uint8x16_t nk_p1 = vreinterpretq_u8_u64(vzip2q_u64(vreinterpretq_u64_u8(n), vreinterpretq_u64_u8(k)));
#else
uint8x16_t lm_p0 = vcombine_u8(vget_low_u8(l), vget_low_u8(m));
uint8x16_t lm_p1 = vcombine_u8(vget_high_u8(l), vget_high_u8(m));
uint8x16_t nk_p0 = vcombine_u8(vget_low_u8(n), vget_low_u8(k));
uint8x16_t nk_p1 = vcombine_u8(vget_high_u8(n), vget_high_u8(k));
#endif
// t0 = (L) (P0 + P1) << 8
// t1 = (M) (P2 + P3) << 16
uint8x16_t t0t1_tmp = veorq_u8(lm_p0, lm_p1);
uint8x16_t t0t1_h = vandq_u8(lm_p1, k48_32);
uint8x16_t t0t1_l = veorq_u8(t0t1_tmp, t0t1_h);
// t2 = (N) (P4 + P5) << 24
// t3 = (K) (P6 + P7) << 32
uint8x16_t t2t3_tmp = veorq_u8(nk_p0, nk_p1);
uint8x16_t t2t3_h = vandq_u8(nk_p1, k16_00);
uint8x16_t t2t3_l = veorq_u8(t2t3_tmp, t2t3_h);
// De-interleave
#if defined(__aarch64__)
uint8x16_t t0 = vreinterpretq_u8_u64(vuzp1q_u64(vreinterpretq_u64_u8(t0t1_l), vreinterpretq_u64_u8(t0t1_h)));
uint8x16_t t1 = vreinterpretq_u8_u64(vuzp2q_u64(vreinterpretq_u64_u8(t0t1_l), vreinterpretq_u64_u8(t0t1_h)));
uint8x16_t t2 = vreinterpretq_u8_u64(vuzp1q_u64(vreinterpretq_u64_u8(t2t3_l), vreinterpretq_u64_u8(t2t3_h)));
uint8x16_t t3 = vreinterpretq_u8_u64(vuzp2q_u64(vreinterpretq_u64_u8(t2t3_l), vreinterpretq_u64_u8(t2t3_h)));
#else
uint8x16_t t1 = vcombine_u8(vget_high_u8(t0t1_l), vget_high_u8(t0t1_h));
uint8x16_t t0 = vcombine_u8(vget_low_u8(t0t1_l), vget_low_u8(t0t1_h));
uint8x16_t t3 = vcombine_u8(vget_high_u8(t2t3_l), vget_high_u8(t2t3_h));
uint8x16_t t2 = vcombine_u8(vget_low_u8(t2t3_l), vget_low_u8(t2t3_h));
#endif
// Shift the cross products
uint8x16_t t0_shift = vextq_u8(t0, t0, 15); // t0 << 8
uint8x16_t t1_shift = vextq_u8(t1, t1, 14); // t1 << 16
uint8x16_t t2_shift = vextq_u8(t2, t2, 13); // t2 << 24
uint8x16_t t3_shift = vextq_u8(t3, t3, 12); // t3 << 32
// Accumulate the products
uint8x16_t cross1 = veorq_u8(t0_shift, t1_shift);
uint8x16_t cross2 = veorq_u8(t2_shift, t3_shift);
uint8x16_t mix = veorq_u8(d, cross1);
uint8x16_t r = veorq_u8(mix, cross2);
return vreinterpretq_u64_u8(r);
}
#endif // ARMv7 polyfill
FORCE_INLINE __m128i _mm_clmulepi64_si128(__m128i _a, __m128i _b, const int imm)
{
uint64x2_t a = vreinterpretq_u64_m128i(_a);
uint64x2_t b = vreinterpretq_u64_m128i(_b);
switch (imm & 0x11) {
case 0x00: return vreinterpretq_m128i_u64(_sse2neon_vmull_p64(vget_low_u64(a), vget_low_u64(b)));
case 0x01: return vreinterpretq_m128i_u64(_sse2neon_vmull_p64(vget_high_u64(a), vget_low_u64(b)));
case 0x10: return vreinterpretq_m128i_u64(_sse2neon_vmull_p64(vget_low_u64(a), vget_high_u64(b)));
case 0x11: return vreinterpretq_m128i_u64(_sse2neon_vmull_p64(vget_high_u64(a), vget_high_u64(b)));
default: abort();
}
}
#if !defined(__ARM_FEATURE_CRYPTO) && defined(__aarch64__)
// In the absence of crypto extensions, implement aesenc using regular neon
// intrinsics instead. See:
// https://www.workofard.com/2017/01/accelerated-aes-for-the-arm64-linux-kernel/
// https://www.workofard.com/2017/07/ghash-for-low-end-cores/ and
// https://github.com/ColinIanKing/linux-next-mirror/blob/b5f466091e130caaf0735976648f72bd5e09aa84/crypto/aegis128-neon-inner.c#L52
// for more information Reproduced with permission of the author.
FORCE_INLINE __m128i _mm_aesenc_si128(__m128i EncBlock, __m128i RoundKey)
{
static const uint8_t crypto_aes_sbox[256] = {
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b,
0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26,
0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2,
0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed,
0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f,
0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14,
0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d,
0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f,
0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11,
0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f,
0xb0, 0x54, 0xbb, 0x16};
static const uint8_t shift_rows[] = {0x0, 0x5, 0xa, 0xf, 0x4, 0x9,
0xe, 0x3, 0x8, 0xd, 0x2, 0x7,
0xc, 0x1, 0x6, 0xb};
static const uint8_t ror32by8[] = {0x1, 0x2, 0x3, 0x0, 0x5, 0x6, 0x7, 0x4,
0x9, 0xa, 0xb, 0x8, 0xd, 0xe, 0xf, 0xc};
uint8x16_t v;
uint8x16_t w = vreinterpretq_u8_m128i(EncBlock);
// shift rows
w = vqtbl1q_u8(w, vld1q_u8(shift_rows));
// sub bytes
v = vqtbl4q_u8(vld1q_u8_x4(crypto_aes_sbox), w);
v = vqtbx4q_u8(v, vld1q_u8_x4(crypto_aes_sbox + 0x40), w - 0x40);
v = vqtbx4q_u8(v, vld1q_u8_x4(crypto_aes_sbox + 0x80), w - 0x80);
v = vqtbx4q_u8(v, vld1q_u8_x4(crypto_aes_sbox + 0xc0), w - 0xc0);
// mix columns
w = (v << 1) ^ (uint8x16_t)(((int8x16_t) v >> 7) & 0x1b);
w ^= (uint8x16_t) vrev32q_u16((uint16x8_t) v);
w ^= vqtbl1q_u8(v ^ w, vld1q_u8(ror32by8));
// add round key
return vreinterpretq_m128i_u8(w) ^ RoundKey;
}
#elif defined(__ARM_FEATURE_CRYPTO)
// Implements equivalent of 'aesenc' by combining AESE (with an empty key) and
// AESMC and then manually applying the real key as an xor operation This
// unfortunately means an additional xor op; the compiler should be able to
// optimise this away for repeated calls however See
// https://blog.michaelbrase.com/2018/05/08/emulating-x86-aes-intrinsics-on-armv8-a
// for more details.
inline __m128i _mm_aesenc_si128(__m128i a, __m128i b)
{
return vreinterpretq_m128i_u8(
vaesmcq_u8(vaeseq_u8(vreinterpretq_u8_m128i(a), vdupq_n_u8(0))) ^
vreinterpretq_u8_m128i(b));
}
#endif
// ******************************************
// Streaming Extensions
// ******************************************
// Guarantees that every preceding store is globally visible before any
// subsequent store.
// https://msdn.microsoft.com/en-us/library/5h2w73d1%28v=vs.90%29.aspx
FORCE_INLINE void _mm_sfence(void)
{
__sync_synchronize();
}
// Stores the data in a to the address p without polluting the caches. If the
// cache line containing address p is already in the cache, the cache will be
// updated.Address p must be 16 - byte aligned.
// https://msdn.microsoft.com/en-us/library/ba08y07y%28v=vs.90%29.aspx
FORCE_INLINE void _mm_stream_si128(__m128i *p, __m128i a)
{
vst1q_s64((int64_t *) p, vreinterpretq_s64_m128i(a));
}
// Cache line containing p is flushed and invalidated from all caches in the
// coherency domain. :
// https://msdn.microsoft.com/en-us/library/ba08y07y(v=vs.100).aspx
FORCE_INLINE void _mm_clflush(void const *p)
{
(void)p;
// no corollary for Neon?
}
// Allocate aligned blocks of memory.
// https://software.intel.com/en-us/
// cpp-compiler-developer-guide-and-reference-allocating-and-freeing-aligned-memory-blocks
FORCE_INLINE void *_mm_malloc(size_t size, size_t align)
{
void *ptr;
if (align == 1)
return malloc(size);
if (align == 2 || (sizeof(void *) == 8 && align == 4))
align = sizeof(void *);
if (!posix_memalign(&ptr, align, size))
return ptr;
return NULL;
}
FORCE_INLINE void _mm_free(void *addr)
{
free(addr);
}
#if defined(__GNUC__) || defined(__clang__)
#pragma pop_macro("ALIGN_STRUCT")
#pragma pop_macro("FORCE_INLINE")
#endif
#endif
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
//package codeforces;
import java.util.Scanner;
/**
*
* @author DELL
*/
public class Sale {
public static void InsertionSort(int []A){
int i=0,key=0,j=0;
for(i=1;i<A.length;++i){
key = A[i];
j=i-1;
while(j>=0 && A[j]>key){
A[j+1] = A[j];
j--;
}
A[j+1]=key;
}
}
public static void solve(){
Scanner nera = new Scanner(System.in);
int x = nera.nextInt();
int y = nera.nextInt();
int sum=0;
int a[]= new int[x];
for(int i=0;i<x;++i){
a[i]=nera.nextInt();
}
InsertionSort(a);
for(int i=0;i<y;++i){
if(a[i]<0)
sum += a[i];
// System.out.println(a[i]);
}
if(sum<=0){
System.out.println(Math.abs(sum));
}else{
System.out.println("0");
}
}
public static void main(String[] args) {
solve();
}
}
|
/**
* Listens to new socket connections, accepts them and start them
*
* @return The newly opened socket connection
* @throws IOException if there were an error opening the connection
*/
@Override
public FileServerThread listenAndAccept() throws IOException {
Socket s = this.getServerSocket().accept();
System.out.println("A file connection was established with a client on the address of " + s.getRemoteSocketAddress());
FileServerThread fsThread = new FileServerThread(s, this);
fsThread.start();
return fsThread;
} |
/*
* cilkplus + dag recorder
*/
#pragma once
#include <cilk/cilk.h>
#include <cilk/cilk_api.h>
#if DAG_RECORDER>=2
#include <dag_recorder.h>
#endif
#define CILK_UNIFY_KEYWORDS 1
#if CILK_UNIFY_KEYWORDS
#define spawn cilk_spawn
#define sync cilk_sync
#endif
/* cilk interface; each cilk procedure (a procedure
that calls spawn or sync) should look like:
cilk int f(int x) {
cilk_begin;
spawn_(cilk_spawn f(x));
spawn_(y = cilk_spawn g(x));
cilk_sync_;
cilk_return(y);
}
- you put cilk begin when it begins
(syntactically, it is a variable declaration,
so you can put other variable decls after it)
- spawn f(x); -> spawn_(cilk_spawn f(x));
- sync -> cilk_sync_;
- return x; -> cilk_return(x)
- return; -> cilk_void_return;
*/
#define cilk_begin_no_prof \
int __cilk_begin__ = 0
#define cilk_return_no_prof(x) do { \
(void)__cilk_begin__; \
return x; \
} while(0)
#define cilk_void_return_no_prof do { \
(void)__cilk_begin__; \
return; \
} while(0)
#define spawn_no_prof(spawn_stmt) spawn_stmt
#define sync_no_prof do { \
cilk_sync; \
} while(0)
#define cilk_begin_with_prof \
int __cilk_begin__ = dr_start_cilk_proc()
#define cilk_return_with_prof_t(type_of_x, x) do { \
type_of_x __cilk_return_value__ = x; \
if (__cilk_begin__) dr_end_task(); \
return __cilk_return_value__; \
} while(0)
#define cilk_return_with_prof(x) do { \
__typeof__(x) __cilk_return_value__ = x; \
if (__cilk_begin__) dr_end_task(); \
return __cilk_return_value__; \
} while(0)
#define cilk_void_return_with_prof do { \
if (__cilk_begin__) dr_end_task(); \
return; \
} while(0)
#define spawn_with_prof(spawn_stmt) do { \
if (__n_outstanding_children__ == 0) dr_begin_section(); \
__n_outstanding_children__++; \
dr_dag_node * __t__ = dr_enter_create_cilk_proc_task(); \
spawn_stmt; \
dr_return_from_create_task(__t__); \
} while (0)
#define spawn_with_prof_(spawn_stmt, file, line) do { \
if (__n_outstanding_children__ == 0) dr_begin_section(); \
__n_outstanding_children__++; \
dr_dag_node * __t__ = dr_enter_create_cilk_proc_task_(file, line); \
spawn_stmt; \
dr_return_from_create_task_(__t__, file, line); \
} while (0)
#define sync_with_prof do { \
if (__n_outstanding_children__ == 0) dr_begin_section(); \
dr_dag_node * __t__ = dr_enter_wait_tasks(); \
cilk_sync; \
dr_return_from_wait_tasks(__t__); \
} while(0)
#define sync_with_prof_(file, line) do { \
if (__n_outstanding_children__ == 0) dr_begin_section(); \
dr_dag_node * __t__ = dr_enter_wait_tasks_(file, line); \
cilk_sync; \
__n_outstanding_children__ = 0; \
dr_return_from_wait_tasks_(__t__, file, line); \
} while(0)
#if DAG_RECORDER>=2
#define cilk_begin cilk_begin_with_prof
#define cilk_return(x) cilk_return_with_prof(x)
#define cilk_return_t(type_of_x, x) cilk_return_with_prof_t(type_of_x, x)
#define cilk_void_return cilk_void_return_with_prof
#define spawn_(spawn_stmt) spawn_with_prof(spawn_stmt)
#define spawn__(spawn_stmt, file, line) spawn_with_prof_(spawn_stmt, file, line)
#define cilk_sync_ sync_with_prof
#define _Cilk_sync_ sync_with_prof
#define sync_ sync_with_prof
#define sync__(file, line) sync_with_prof_(file, line)
#define clkp_mk_task_group \
int __n_outstanding_children__ = 0
#define dr_get_max_workers() __cilkrts_get_nworkers()
#define dr_get_worker() __cilkrts_get_worker_number()
#else
#define cilk_begin cilk_begin_no_prof
#define cilk_return(x) cilk_return_no_prof(x)
#define cilk_return_t(type_of_x, x) cilk_return_no_prof(x)
#define cilk_void_return cilk_void_return_no_prof
#define spawn_(spawn_stmt) spawn_no_prof(spawn_stmt)
#define spawn__(spawn_stmt, file, line) spawn_no_prof(spawn_stmt)
#define cilk_sync_ sync_no_prof
#define _Cilk_sync_ sync_no_prof
#define sync_ sync_no_prof
#define sync__(file, line) sync_no_prof
#define clkp_mk_task_group
#endif
|
// Code generated by YGOT. DO NOT EDIT.
/*
Package aether_2_0_0 is a generated package which contains definitions
of structs which represent a YANG schema. The generated schema can be
compressed by a series of transformations (compression was false
in this case).
This package was generated by /home/smbaker/gopath/pkg/mod/github.com/openconfig/[email protected]/genutil/names.go
using the following YANG input files:
- [email protected]
- [email protected]
- [email protected]
- [email protected]
- [email protected]
- [email protected]
- [email protected]
- [email protected]
Imported modules were sourced from:
- yang/...
*/
package aether_2_0_0
import (
"encoding/json"
"fmt"
"reflect"
"github.com/openconfig/ygot/ygot"
"github.com/openconfig/goyang/pkg/yang"
"github.com/openconfig/ygot/ytypes"
)
// Binary is a type that is used for fields that have a YANG type of
// binary. It is used such that binary fields can be distinguished from
// leaf-lists of uint8s (which are mapped to []uint8, equivalent to
// []byte in reflection).
type Binary []byte
// YANGEmpty is a type that is used for fields that have a YANG type of
// empty. It is used such that empty fields can be distinguished from boolean fields
// in the generated code.
type YANGEmpty bool
var (
SchemaTree map[string]*yang.Entry
)
func init() {
var err error
if SchemaTree, err = UnzipSchema(); err != nil {
panic("schema error: " + err.Error())
}
}
// Schema returns the details of the generated schema.
func Schema() (*ytypes.Schema, error) {
uzp, err := UnzipSchema()
if err != nil {
return nil, fmt.Errorf("cannot unzip schema, %v", err)
}
return &ytypes.Schema{
Root: &Device{},
SchemaTree: uzp,
Unmarshal: Unmarshal,
}, nil
}
// UnzipSchema unzips the zipped schema and returns a map of yang.Entry nodes,
// keyed by the name of the struct that the yang.Entry describes the schema for.
func UnzipSchema() (map[string]*yang.Entry, error) {
var schemaTree map[string]*yang.Entry
var err error
if schemaTree, err = ygot.GzipToSchema(ySchema); err != nil {
return nil, fmt.Errorf("could not unzip the schema; %v", err)
}
return schemaTree, nil
}
// Unmarshal unmarshals data, which must be RFC7951 JSON format, into
// destStruct, which must be non-nil and the correct GoStruct type. It returns
// an error if the destStruct is not found in the schema or the data cannot be
// unmarshaled. The supplied options (opts) are used to control the behaviour
// of the unmarshal function - for example, determining whether errors are
// thrown for unknown fields in the input JSON.
func Unmarshal(data []byte, destStruct ygot.GoStruct, opts ...ytypes.UnmarshalOpt) error {
tn := reflect.TypeOf(destStruct).Elem().Name()
schema, ok := SchemaTree[tn]
if !ok {
return fmt.Errorf("could not find schema for type %s", tn )
}
var jsonTree interface{}
if err := json.Unmarshal([]byte(data), &jsonTree); err != nil {
return err
}
return ytypes.Unmarshal(schema, destStruct, jsonTree, opts...)
}
// AccessProfile_AccessProfile represents the /access-profile/access-profile YANG schema element.
type AccessProfile_AccessProfile struct {
AccessProfile map[string]*AccessProfile_AccessProfile_AccessProfile `path:"access-profile" module:"access-profile"`
}
// IsYANGGoStruct ensures that AccessProfile_AccessProfile implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*AccessProfile_AccessProfile) IsYANGGoStruct() {}
// NewAccessProfile creates a new entry in the AccessProfile list of the
// AccessProfile_AccessProfile struct. The keys of the list are populated from the input
// arguments.
func (t *AccessProfile_AccessProfile) NewAccessProfile(Id string) (*AccessProfile_AccessProfile_AccessProfile, error){
// Initialise the list within the receiver struct if it has not already been
// created.
if t.AccessProfile == nil {
t.AccessProfile = make(map[string]*AccessProfile_AccessProfile_AccessProfile)
}
key := Id
// Ensure that this key has not already been used in the
// list. Keyed YANG lists do not allow duplicate keys to
// be created.
if _, ok := t.AccessProfile[key]; ok {
return nil, fmt.Errorf("duplicate key %v for list AccessProfile", key)
}
t.AccessProfile[key] = &AccessProfile_AccessProfile_AccessProfile{
Id: &Id,
}
return t.AccessProfile[key], nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *AccessProfile_AccessProfile) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["AccessProfile_AccessProfile"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *AccessProfile_AccessProfile) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// AccessProfile_AccessProfile_AccessProfile represents the /access-profile/access-profile/access-profile YANG schema element.
type AccessProfile_AccessProfile_AccessProfile struct {
Description *string `path:"description" module:"access-profile"`
DisplayName *string `path:"display-name" module:"access-profile"`
Filter *string `path:"filter" module:"access-profile"`
Id *string `path:"id" module:"access-profile"`
Type *string `path:"type" module:"access-profile"`
}
// IsYANGGoStruct ensures that AccessProfile_AccessProfile_AccessProfile implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*AccessProfile_AccessProfile_AccessProfile) IsYANGGoStruct() {}
// ΛListKeyMap returns the keys of the AccessProfile_AccessProfile_AccessProfile struct, which is a YANG list entry.
func (t *AccessProfile_AccessProfile_AccessProfile) ΛListKeyMap() (map[string]interface{}, error) {
if t.Id == nil {
return nil, fmt.Errorf("nil value for key Id")
}
return map[string]interface{}{
"id": *t.Id,
}, nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *AccessProfile_AccessProfile_AccessProfile) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["AccessProfile_AccessProfile_AccessProfile"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *AccessProfile_AccessProfile_AccessProfile) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// AetherSubscriber_Subscriber represents the /aether-subscriber/subscriber YANG schema element.
type AetherSubscriber_Subscriber struct {
Ue map[string]*AetherSubscriber_Subscriber_Ue `path:"ue" module:"aether-subscriber"`
}
// IsYANGGoStruct ensures that AetherSubscriber_Subscriber implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*AetherSubscriber_Subscriber) IsYANGGoStruct() {}
// NewUe creates a new entry in the Ue list of the
// AetherSubscriber_Subscriber struct. The keys of the list are populated from the input
// arguments.
func (t *AetherSubscriber_Subscriber) NewUe(Id string) (*AetherSubscriber_Subscriber_Ue, error){
// Initialise the list within the receiver struct if it has not already been
// created.
if t.Ue == nil {
t.Ue = make(map[string]*AetherSubscriber_Subscriber_Ue)
}
key := Id
// Ensure that this key has not already been used in the
// list. Keyed YANG lists do not allow duplicate keys to
// be created.
if _, ok := t.Ue[key]; ok {
return nil, fmt.Errorf("duplicate key %v for list Ue", key)
}
t.Ue[key] = &AetherSubscriber_Subscriber_Ue{
Id: &Id,
}
return t.Ue[key], nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *AetherSubscriber_Subscriber) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["AetherSubscriber_Subscriber"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *AetherSubscriber_Subscriber) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// AetherSubscriber_Subscriber_Ue represents the /aether-subscriber/subscriber/ue YANG schema element.
type AetherSubscriber_Subscriber_Ue struct {
DisplayName *string `path:"display-name" module:"aether-subscriber"`
Enabled *bool `path:"enabled" module:"aether-subscriber"`
Enterprise *string `path:"enterprise" module:"aether-subscriber"`
Id *string `path:"id" module:"aether-subscriber"`
ImsiRangeFrom *uint64 `path:"imsi-range-from" module:"aether-subscriber"`
ImsiRangeTo *uint64 `path:"imsi-range-to" module:"aether-subscriber"`
ImsiWildcard *string `path:"imsi-wildcard" module:"aether-subscriber"`
Priority *uint32 `path:"priority" module:"aether-subscriber"`
Profiles *AetherSubscriber_Subscriber_Ue_Profiles `path:"profiles" module:"aether-subscriber"`
RequestedApn *string `path:"requested-apn" module:"aether-subscriber"`
ServingPlmn *AetherSubscriber_Subscriber_Ue_ServingPlmn `path:"serving-plmn" module:"aether-subscriber"`
}
// IsYANGGoStruct ensures that AetherSubscriber_Subscriber_Ue implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*AetherSubscriber_Subscriber_Ue) IsYANGGoStruct() {}
// ΛListKeyMap returns the keys of the AetherSubscriber_Subscriber_Ue struct, which is a YANG list entry.
func (t *AetherSubscriber_Subscriber_Ue) ΛListKeyMap() (map[string]interface{}, error) {
if t.Id == nil {
return nil, fmt.Errorf("nil value for key Id")
}
return map[string]interface{}{
"id": *t.Id,
}, nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *AetherSubscriber_Subscriber_Ue) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["AetherSubscriber_Subscriber_Ue"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *AetherSubscriber_Subscriber_Ue) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// AetherSubscriber_Subscriber_Ue_Profiles represents the /aether-subscriber/subscriber/ue/profiles YANG schema element.
type AetherSubscriber_Subscriber_Ue_Profiles struct {
AccessProfile map[string]*AetherSubscriber_Subscriber_Ue_Profiles_AccessProfile `path:"access-profile" module:"aether-subscriber"`
ApnProfile *string `path:"apn-profile" module:"aether-subscriber"`
QosProfile *string `path:"qos-profile" module:"aether-subscriber"`
SecurityProfile *string `path:"security-profile" module:"aether-subscriber"`
UpProfile *string `path:"up-profile" module:"aether-subscriber"`
}
// IsYANGGoStruct ensures that AetherSubscriber_Subscriber_Ue_Profiles implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*AetherSubscriber_Subscriber_Ue_Profiles) IsYANGGoStruct() {}
// NewAccessProfile creates a new entry in the AccessProfile list of the
// AetherSubscriber_Subscriber_Ue_Profiles struct. The keys of the list are populated from the input
// arguments.
func (t *AetherSubscriber_Subscriber_Ue_Profiles) NewAccessProfile(AccessProfile string) (*AetherSubscriber_Subscriber_Ue_Profiles_AccessProfile, error){
// Initialise the list within the receiver struct if it has not already been
// created.
if t.AccessProfile == nil {
t.AccessProfile = make(map[string]*AetherSubscriber_Subscriber_Ue_Profiles_AccessProfile)
}
key := AccessProfile
// Ensure that this key has not already been used in the
// list. Keyed YANG lists do not allow duplicate keys to
// be created.
if _, ok := t.AccessProfile[key]; ok {
return nil, fmt.Errorf("duplicate key %v for list AccessProfile", key)
}
t.AccessProfile[key] = &AetherSubscriber_Subscriber_Ue_Profiles_AccessProfile{
AccessProfile: &AccessProfile,
}
return t.AccessProfile[key], nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *AetherSubscriber_Subscriber_Ue_Profiles) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["AetherSubscriber_Subscriber_Ue_Profiles"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *AetherSubscriber_Subscriber_Ue_Profiles) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// AetherSubscriber_Subscriber_Ue_Profiles_AccessProfile represents the /aether-subscriber/subscriber/ue/profiles/access-profile YANG schema element.
type AetherSubscriber_Subscriber_Ue_Profiles_AccessProfile struct {
AccessProfile *string `path:"access-profile" module:"aether-subscriber"`
Allowed *bool `path:"allowed" module:"aether-subscriber"`
}
// IsYANGGoStruct ensures that AetherSubscriber_Subscriber_Ue_Profiles_AccessProfile implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*AetherSubscriber_Subscriber_Ue_Profiles_AccessProfile) IsYANGGoStruct() {}
// ΛListKeyMap returns the keys of the AetherSubscriber_Subscriber_Ue_Profiles_AccessProfile struct, which is a YANG list entry.
func (t *AetherSubscriber_Subscriber_Ue_Profiles_AccessProfile) ΛListKeyMap() (map[string]interface{}, error) {
if t.AccessProfile == nil {
return nil, fmt.Errorf("nil value for key AccessProfile")
}
return map[string]interface{}{
"access-profile": *t.AccessProfile,
}, nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *AetherSubscriber_Subscriber_Ue_Profiles_AccessProfile) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["AetherSubscriber_Subscriber_Ue_Profiles_AccessProfile"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *AetherSubscriber_Subscriber_Ue_Profiles_AccessProfile) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// AetherSubscriber_Subscriber_Ue_ServingPlmn represents the /aether-subscriber/subscriber/ue/serving-plmn YANG schema element.
type AetherSubscriber_Subscriber_Ue_ServingPlmn struct {
Mcc *uint32 `path:"mcc" module:"aether-subscriber"`
Mnc *uint32 `path:"mnc" module:"aether-subscriber"`
Tac *uint32 `path:"tac" module:"aether-subscriber"`
}
// IsYANGGoStruct ensures that AetherSubscriber_Subscriber_Ue_ServingPlmn implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*AetherSubscriber_Subscriber_Ue_ServingPlmn) IsYANGGoStruct() {}
// Validate validates s against the YANG schema corresponding to its type.
func (t *AetherSubscriber_Subscriber_Ue_ServingPlmn) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["AetherSubscriber_Subscriber_Ue_ServingPlmn"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *AetherSubscriber_Subscriber_Ue_ServingPlmn) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// ApnProfile_ApnProfile represents the /apn-profile/apn-profile YANG schema element.
type ApnProfile_ApnProfile struct {
ApnProfile map[string]*ApnProfile_ApnProfile_ApnProfile `path:"apn-profile" module:"apn-profile"`
}
// IsYANGGoStruct ensures that ApnProfile_ApnProfile implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*ApnProfile_ApnProfile) IsYANGGoStruct() {}
// NewApnProfile creates a new entry in the ApnProfile list of the
// ApnProfile_ApnProfile struct. The keys of the list are populated from the input
// arguments.
func (t *ApnProfile_ApnProfile) NewApnProfile(Id string) (*ApnProfile_ApnProfile_ApnProfile, error){
// Initialise the list within the receiver struct if it has not already been
// created.
if t.ApnProfile == nil {
t.ApnProfile = make(map[string]*ApnProfile_ApnProfile_ApnProfile)
}
key := Id
// Ensure that this key has not already been used in the
// list. Keyed YANG lists do not allow duplicate keys to
// be created.
if _, ok := t.ApnProfile[key]; ok {
return nil, fmt.Errorf("duplicate key %v for list ApnProfile", key)
}
t.ApnProfile[key] = &ApnProfile_ApnProfile_ApnProfile{
Id: &Id,
}
return t.ApnProfile[key], nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *ApnProfile_ApnProfile) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["ApnProfile_ApnProfile"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *ApnProfile_ApnProfile) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// ApnProfile_ApnProfile_ApnProfile represents the /apn-profile/apn-profile/apn-profile YANG schema element.
type ApnProfile_ApnProfile_ApnProfile struct {
ApnName *string `path:"apn-name" module:"apn-profile"`
Description *string `path:"description" module:"apn-profile"`
DisplayName *string `path:"display-name" module:"apn-profile"`
DnsPrimary *string `path:"dns-primary" module:"apn-profile"`
DnsSecondary *string `path:"dns-secondary" module:"apn-profile"`
GxEnabled *bool `path:"gx-enabled" module:"apn-profile"`
Id *string `path:"id" module:"apn-profile"`
Mtu *uint32 `path:"mtu" module:"apn-profile"`
}
// IsYANGGoStruct ensures that ApnProfile_ApnProfile_ApnProfile implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*ApnProfile_ApnProfile_ApnProfile) IsYANGGoStruct() {}
// ΛListKeyMap returns the keys of the ApnProfile_ApnProfile_ApnProfile struct, which is a YANG list entry.
func (t *ApnProfile_ApnProfile_ApnProfile) ΛListKeyMap() (map[string]interface{}, error) {
if t.Id == nil {
return nil, fmt.Errorf("nil value for key Id")
}
return map[string]interface{}{
"id": *t.Id,
}, nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *ApnProfile_ApnProfile_ApnProfile) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["ApnProfile_ApnProfile_ApnProfile"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *ApnProfile_ApnProfile_ApnProfile) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// ConnectivityService_ConnectivityService represents the /connectivity-service/connectivity-service YANG schema element.
type ConnectivityService_ConnectivityService struct {
ConnectivityService map[string]*ConnectivityService_ConnectivityService_ConnectivityService `path:"connectivity-service" module:"connectivity-service"`
}
// IsYANGGoStruct ensures that ConnectivityService_ConnectivityService implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*ConnectivityService_ConnectivityService) IsYANGGoStruct() {}
// NewConnectivityService creates a new entry in the ConnectivityService list of the
// ConnectivityService_ConnectivityService struct. The keys of the list are populated from the input
// arguments.
func (t *ConnectivityService_ConnectivityService) NewConnectivityService(Id string) (*ConnectivityService_ConnectivityService_ConnectivityService, error){
// Initialise the list within the receiver struct if it has not already been
// created.
if t.ConnectivityService == nil {
t.ConnectivityService = make(map[string]*ConnectivityService_ConnectivityService_ConnectivityService)
}
key := Id
// Ensure that this key has not already been used in the
// list. Keyed YANG lists do not allow duplicate keys to
// be created.
if _, ok := t.ConnectivityService[key]; ok {
return nil, fmt.Errorf("duplicate key %v for list ConnectivityService", key)
}
t.ConnectivityService[key] = &ConnectivityService_ConnectivityService_ConnectivityService{
Id: &Id,
}
return t.ConnectivityService[key], nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *ConnectivityService_ConnectivityService) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["ConnectivityService_ConnectivityService"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *ConnectivityService_ConnectivityService) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// ConnectivityService_ConnectivityService_ConnectivityService represents the /connectivity-service/connectivity-service/connectivity-service YANG schema element.
type ConnectivityService_ConnectivityService_ConnectivityService struct {
Description *string `path:"description" module:"connectivity-service"`
DisplayName *string `path:"display-name" module:"connectivity-service"`
HssEndpoint *string `path:"hss-endpoint" module:"connectivity-service"`
Id *string `path:"id" module:"connectivity-service"`
SpgwcEndpoint *string `path:"spgwc-endpoint" module:"connectivity-service"`
}
// IsYANGGoStruct ensures that ConnectivityService_ConnectivityService_ConnectivityService implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*ConnectivityService_ConnectivityService_ConnectivityService) IsYANGGoStruct() {}
// ΛListKeyMap returns the keys of the ConnectivityService_ConnectivityService_ConnectivityService struct, which is a YANG list entry.
func (t *ConnectivityService_ConnectivityService_ConnectivityService) ΛListKeyMap() (map[string]interface{}, error) {
if t.Id == nil {
return nil, fmt.Errorf("nil value for key Id")
}
return map[string]interface{}{
"id": *t.Id,
}, nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *ConnectivityService_ConnectivityService_ConnectivityService) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["ConnectivityService_ConnectivityService_ConnectivityService"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *ConnectivityService_ConnectivityService_ConnectivityService) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// Device represents the /device YANG schema element.
type Device struct {
AccessProfile *AccessProfile_AccessProfile `path:"access-profile" module:"access-profile"`
ApnProfile *ApnProfile_ApnProfile `path:"apn-profile" module:"apn-profile"`
ConnectivityService *ConnectivityService_ConnectivityService `path:"connectivity-service" module:"connectivity-service"`
Enterprise *Enterprise_Enterprise `path:"enterprise" module:"enterprise"`
QosProfile *QosProfile_QosProfile `path:"qos-profile" module:"qos-profile"`
SecurityProfile *SecurityProfile_SecurityProfile `path:"security-profile" module:"security-profile"`
Subscriber *AetherSubscriber_Subscriber `path:"subscriber" module:"aether-subscriber"`
UpProfile *UpProfile_UpProfile `path:"up-profile" module:"up-profile"`
}
// IsYANGGoStruct ensures that Device implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*Device) IsYANGGoStruct() {}
// Validate validates s against the YANG schema corresponding to its type.
func (t *Device) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["Device"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *Device) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// Enterprise_Enterprise represents the /enterprise/enterprise YANG schema element.
type Enterprise_Enterprise struct {
Enterprise map[string]*Enterprise_Enterprise_Enterprise `path:"enterprise" module:"enterprise"`
}
// IsYANGGoStruct ensures that Enterprise_Enterprise implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*Enterprise_Enterprise) IsYANGGoStruct() {}
// NewEnterprise creates a new entry in the Enterprise list of the
// Enterprise_Enterprise struct. The keys of the list are populated from the input
// arguments.
func (t *Enterprise_Enterprise) NewEnterprise(Id string) (*Enterprise_Enterprise_Enterprise, error){
// Initialise the list within the receiver struct if it has not already been
// created.
if t.Enterprise == nil {
t.Enterprise = make(map[string]*Enterprise_Enterprise_Enterprise)
}
key := Id
// Ensure that this key has not already been used in the
// list. Keyed YANG lists do not allow duplicate keys to
// be created.
if _, ok := t.Enterprise[key]; ok {
return nil, fmt.Errorf("duplicate key %v for list Enterprise", key)
}
t.Enterprise[key] = &Enterprise_Enterprise_Enterprise{
Id: &Id,
}
return t.Enterprise[key], nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *Enterprise_Enterprise) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["Enterprise_Enterprise"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *Enterprise_Enterprise) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// Enterprise_Enterprise_Enterprise represents the /enterprise/enterprise/enterprise YANG schema element.
type Enterprise_Enterprise_Enterprise struct {
ConnectivityService map[string]*Enterprise_Enterprise_Enterprise_ConnectivityService `path:"connectivity-service" module:"enterprise"`
Description *string `path:"description" module:"enterprise"`
DisplayName *string `path:"display-name" module:"enterprise"`
Id *string `path:"id" module:"enterprise"`
}
// IsYANGGoStruct ensures that Enterprise_Enterprise_Enterprise implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*Enterprise_Enterprise_Enterprise) IsYANGGoStruct() {}
// NewConnectivityService creates a new entry in the ConnectivityService list of the
// Enterprise_Enterprise_Enterprise struct. The keys of the list are populated from the input
// arguments.
func (t *Enterprise_Enterprise_Enterprise) NewConnectivityService(ConnectivityService string) (*Enterprise_Enterprise_Enterprise_ConnectivityService, error){
// Initialise the list within the receiver struct if it has not already been
// created.
if t.ConnectivityService == nil {
t.ConnectivityService = make(map[string]*Enterprise_Enterprise_Enterprise_ConnectivityService)
}
key := ConnectivityService
// Ensure that this key has not already been used in the
// list. Keyed YANG lists do not allow duplicate keys to
// be created.
if _, ok := t.ConnectivityService[key]; ok {
return nil, fmt.Errorf("duplicate key %v for list ConnectivityService", key)
}
t.ConnectivityService[key] = &Enterprise_Enterprise_Enterprise_ConnectivityService{
ConnectivityService: &ConnectivityService,
}
return t.ConnectivityService[key], nil
}
// ΛListKeyMap returns the keys of the Enterprise_Enterprise_Enterprise struct, which is a YANG list entry.
func (t *Enterprise_Enterprise_Enterprise) ΛListKeyMap() (map[string]interface{}, error) {
if t.Id == nil {
return nil, fmt.Errorf("nil value for key Id")
}
return map[string]interface{}{
"id": *t.Id,
}, nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *Enterprise_Enterprise_Enterprise) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["Enterprise_Enterprise_Enterprise"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *Enterprise_Enterprise_Enterprise) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// Enterprise_Enterprise_Enterprise_ConnectivityService represents the /enterprise/enterprise/enterprise/connectivity-service YANG schema element.
type Enterprise_Enterprise_Enterprise_ConnectivityService struct {
ConnectivityService *string `path:"connectivity-service" module:"enterprise"`
Enabled *bool `path:"enabled" module:"enterprise"`
}
// IsYANGGoStruct ensures that Enterprise_Enterprise_Enterprise_ConnectivityService implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*Enterprise_Enterprise_Enterprise_ConnectivityService) IsYANGGoStruct() {}
// ΛListKeyMap returns the keys of the Enterprise_Enterprise_Enterprise_ConnectivityService struct, which is a YANG list entry.
func (t *Enterprise_Enterprise_Enterprise_ConnectivityService) ΛListKeyMap() (map[string]interface{}, error) {
if t.ConnectivityService == nil {
return nil, fmt.Errorf("nil value for key ConnectivityService")
}
return map[string]interface{}{
"connectivity-service": *t.ConnectivityService,
}, nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *Enterprise_Enterprise_Enterprise_ConnectivityService) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["Enterprise_Enterprise_Enterprise_ConnectivityService"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *Enterprise_Enterprise_Enterprise_ConnectivityService) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// QosProfile_QosProfile represents the /qos-profile/qos-profile YANG schema element.
type QosProfile_QosProfile struct {
QosProfile map[string]*QosProfile_QosProfile_QosProfile `path:"qos-profile" module:"qos-profile"`
}
// IsYANGGoStruct ensures that QosProfile_QosProfile implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*QosProfile_QosProfile) IsYANGGoStruct() {}
// NewQosProfile creates a new entry in the QosProfile list of the
// QosProfile_QosProfile struct. The keys of the list are populated from the input
// arguments.
func (t *QosProfile_QosProfile) NewQosProfile(Id string) (*QosProfile_QosProfile_QosProfile, error){
// Initialise the list within the receiver struct if it has not already been
// created.
if t.QosProfile == nil {
t.QosProfile = make(map[string]*QosProfile_QosProfile_QosProfile)
}
key := Id
// Ensure that this key has not already been used in the
// list. Keyed YANG lists do not allow duplicate keys to
// be created.
if _, ok := t.QosProfile[key]; ok {
return nil, fmt.Errorf("duplicate key %v for list QosProfile", key)
}
t.QosProfile[key] = &QosProfile_QosProfile_QosProfile{
Id: &Id,
}
return t.QosProfile[key], nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *QosProfile_QosProfile) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["QosProfile_QosProfile"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *QosProfile_QosProfile) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// QosProfile_QosProfile_QosProfile represents the /qos-profile/qos-profile/qos-profile YANG schema element.
type QosProfile_QosProfile_QosProfile struct {
ApnAmbr *QosProfile_QosProfile_QosProfile_ApnAmbr `path:"apn-ambr" module:"qos-profile"`
Description *string `path:"description" module:"qos-profile"`
DisplayName *string `path:"display-name" module:"qos-profile"`
Id *string `path:"id" module:"qos-profile"`
}
// IsYANGGoStruct ensures that QosProfile_QosProfile_QosProfile implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*QosProfile_QosProfile_QosProfile) IsYANGGoStruct() {}
// ΛListKeyMap returns the keys of the QosProfile_QosProfile_QosProfile struct, which is a YANG list entry.
func (t *QosProfile_QosProfile_QosProfile) ΛListKeyMap() (map[string]interface{}, error) {
if t.Id == nil {
return nil, fmt.Errorf("nil value for key Id")
}
return map[string]interface{}{
"id": *t.Id,
}, nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *QosProfile_QosProfile_QosProfile) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["QosProfile_QosProfile_QosProfile"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *QosProfile_QosProfile_QosProfile) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// QosProfile_QosProfile_QosProfile_ApnAmbr represents the /qos-profile/qos-profile/qos-profile/apn-ambr YANG schema element.
type QosProfile_QosProfile_QosProfile_ApnAmbr struct {
Downlink *uint32 `path:"downlink" module:"qos-profile"`
Uplink *uint32 `path:"uplink" module:"qos-profile"`
}
// IsYANGGoStruct ensures that QosProfile_QosProfile_QosProfile_ApnAmbr implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*QosProfile_QosProfile_QosProfile_ApnAmbr) IsYANGGoStruct() {}
// Validate validates s against the YANG schema corresponding to its type.
func (t *QosProfile_QosProfile_QosProfile_ApnAmbr) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["QosProfile_QosProfile_QosProfile_ApnAmbr"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *QosProfile_QosProfile_QosProfile_ApnAmbr) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// SecurityProfile_SecurityProfile represents the /security-profile/security-profile YANG schema element.
type SecurityProfile_SecurityProfile struct {
SecurityProfile map[string]*SecurityProfile_SecurityProfile_SecurityProfile `path:"security-profile" module:"security-profile"`
}
// IsYANGGoStruct ensures that SecurityProfile_SecurityProfile implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*SecurityProfile_SecurityProfile) IsYANGGoStruct() {}
// NewSecurityProfile creates a new entry in the SecurityProfile list of the
// SecurityProfile_SecurityProfile struct. The keys of the list are populated from the input
// arguments.
func (t *SecurityProfile_SecurityProfile) NewSecurityProfile(Id string) (*SecurityProfile_SecurityProfile_SecurityProfile, error){
// Initialise the list within the receiver struct if it has not already been
// created.
if t.SecurityProfile == nil {
t.SecurityProfile = make(map[string]*SecurityProfile_SecurityProfile_SecurityProfile)
}
key := Id
// Ensure that this key has not already been used in the
// list. Keyed YANG lists do not allow duplicate keys to
// be created.
if _, ok := t.SecurityProfile[key]; ok {
return nil, fmt.Errorf("duplicate key %v for list SecurityProfile", key)
}
t.SecurityProfile[key] = &SecurityProfile_SecurityProfile_SecurityProfile{
Id: &Id,
}
return t.SecurityProfile[key], nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *SecurityProfile_SecurityProfile) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["SecurityProfile_SecurityProfile"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *SecurityProfile_SecurityProfile) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// SecurityProfile_SecurityProfile_SecurityProfile represents the /security-profile/security-profile/security-profile YANG schema element.
type SecurityProfile_SecurityProfile_SecurityProfile struct {
Description *string `path:"description" module:"security-profile"`
DisplayName *string `path:"display-name" module:"security-profile"`
Id *string `path:"id" module:"security-profile"`
Key *string `path:"key" module:"security-profile"`
Opc *string `path:"opc" module:"security-profile"`
Sqn *uint32 `path:"sqn" module:"security-profile"`
}
// IsYANGGoStruct ensures that SecurityProfile_SecurityProfile_SecurityProfile implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*SecurityProfile_SecurityProfile_SecurityProfile) IsYANGGoStruct() {}
// ΛListKeyMap returns the keys of the SecurityProfile_SecurityProfile_SecurityProfile struct, which is a YANG list entry.
func (t *SecurityProfile_SecurityProfile_SecurityProfile) ΛListKeyMap() (map[string]interface{}, error) {
if t.Id == nil {
return nil, fmt.Errorf("nil value for key Id")
}
return map[string]interface{}{
"id": *t.Id,
}, nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *SecurityProfile_SecurityProfile_SecurityProfile) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["SecurityProfile_SecurityProfile_SecurityProfile"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *SecurityProfile_SecurityProfile_SecurityProfile) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// UpProfile_UpProfile represents the /up-profile/up-profile YANG schema element.
type UpProfile_UpProfile struct {
UpProfile map[string]*UpProfile_UpProfile_UpProfile `path:"up-profile" module:"up-profile"`
}
// IsYANGGoStruct ensures that UpProfile_UpProfile implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*UpProfile_UpProfile) IsYANGGoStruct() {}
// NewUpProfile creates a new entry in the UpProfile list of the
// UpProfile_UpProfile struct. The keys of the list are populated from the input
// arguments.
func (t *UpProfile_UpProfile) NewUpProfile(Id string) (*UpProfile_UpProfile_UpProfile, error){
// Initialise the list within the receiver struct if it has not already been
// created.
if t.UpProfile == nil {
t.UpProfile = make(map[string]*UpProfile_UpProfile_UpProfile)
}
key := Id
// Ensure that this key has not already been used in the
// list. Keyed YANG lists do not allow duplicate keys to
// be created.
if _, ok := t.UpProfile[key]; ok {
return nil, fmt.Errorf("duplicate key %v for list UpProfile", key)
}
t.UpProfile[key] = &UpProfile_UpProfile_UpProfile{
Id: &Id,
}
return t.UpProfile[key], nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *UpProfile_UpProfile) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["UpProfile_UpProfile"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *UpProfile_UpProfile) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
// UpProfile_UpProfile_UpProfile represents the /up-profile/up-profile/up-profile YANG schema element.
type UpProfile_UpProfile_UpProfile struct {
AccessControl *string `path:"access-control" module:"up-profile"`
Description *string `path:"description" module:"up-profile"`
DisplayName *string `path:"display-name" module:"up-profile"`
Id *string `path:"id" module:"up-profile"`
UserPlane *string `path:"user-plane" module:"up-profile"`
}
// IsYANGGoStruct ensures that UpProfile_UpProfile_UpProfile implements the yang.GoStruct
// interface. This allows functions that need to handle this struct to
// identify it as being generated by ygen.
func (*UpProfile_UpProfile_UpProfile) IsYANGGoStruct() {}
// ΛListKeyMap returns the keys of the UpProfile_UpProfile_UpProfile struct, which is a YANG list entry.
func (t *UpProfile_UpProfile_UpProfile) ΛListKeyMap() (map[string]interface{}, error) {
if t.Id == nil {
return nil, fmt.Errorf("nil value for key Id")
}
return map[string]interface{}{
"id": *t.Id,
}, nil
}
// Validate validates s against the YANG schema corresponding to its type.
func (t *UpProfile_UpProfile_UpProfile) Validate(opts ...ygot.ValidationOption) error {
if err := ytypes.Validate(SchemaTree["UpProfile_UpProfile_UpProfile"], t, opts...); err != nil {
return err
}
return nil
}
// ΛEnumTypeMap returns a map, keyed by YANG schema path, of the enumerated types
// that are included in the generated code.
func (t *UpProfile_UpProfile_UpProfile) ΛEnumTypeMap() map[string][]reflect.Type { return ΛEnumTypes }
var (
// ySchema is a byte slice contain a gzip compressed representation of the
// YANG schema from which the Go code was generated. When uncompressed the
// contents of the byte slice is a JSON document containing an object, keyed
// on the name of the generated struct, and containing the JSON marshalled
// contents of a goyang yang.Entry struct, which defines the schema for the
// fields within the struct.
ySchema = []byte{
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x5d, 0xdf, 0x73, 0xda, 0x48,
0x12, 0x7e, 0xf7, 0x5f, 0x41, 0xa9, 0x6a, 0xab, 0x60, 0xd7, 0x8a, 0xc1, 0x06, 0xdb, 0xf0, 0x92,
0xf2, 0x6d, 0x36, 0x75, 0x55, 0x9b, 0xdd, 0xcb, 0x6d, 0x6e, 0xef, 0xc5, 0xe6, 0x5c, 0xb2, 0x18,
0x1c, 0x55, 0x40, 0x52, 0xf4, 0x23, 0x8e, 0xcb, 0xe1, 0x7f, 0xbf, 0x92, 0x90, 0x41, 0x80, 0xa4,
0xe9, 0x1e, 0x09, 0x01, 0xf6, 0xb7, 0x0f, 0x59, 0x21, 0x4f, 0x4b, 0x9a, 0xe9, 0x9e, 0xaf, 0x7b,
0x7a, 0xbe, 0x99, 0x79, 0x3a, 0x6a, 0x34, 0x1a, 0x0d, 0xed, 0x4f, 0x63, 0x2a, 0xb4, 0x41, 0x43,
0x1b, 0x89, 0x6f, 0x96, 0x29, 0xb4, 0xe3, 0xf9, 0xdd, 0xdf, 0x2d, 0x7b, 0xa4, 0x0d, 0x1a, 0x9d,
0xe4, 0xe7, 0xaf, 0x8e, 0x3d, 0xb6, 0xee, 0xb5, 0x41, 0xa3, 0x9d, 0xdc, 0x78, 0x67, 0x79, 0xda,
0xa0, 0x31, 0x7f, 0x44, 0x7c, 0xc3, 0x30, 0x4d, 0xe1, 0xfb, 0xba, 0xeb, 0x39, 0x63, 0x6b, 0x22,
0x56, 0xfe, 0xb6, 0xf2, 0x9a, 0xb5, 0x72, 0xc7, 0xab, 0xa5, 0x56, 0x5f, 0xbb, 0xb8, 0xbd, 0xfe,
0xfa, 0xc5, 0x1f, 0x3e, 0x7a, 0x62, 0x6c, 0x7d, 0xdf, 0x78, 0xdb, 0xca, 0x1b, 0x5d, 0xcf, 0x59,
0x7b, 0x4d, 0xfc, 0xe7, 0x4f, 0x4e, 0xe8, 0x99, 0x22, 0x53, 0x74, 0xfe, 0x29, 0xe2, 0xf1, 0xc1,
0xf1, 0x46, 0xf3, 0x27, 0xc4, 0x6f, 0x39, 0xce, 0x2e, 0xf8, 0x4f, 0xc3, 0xbf, 0xf2, 0xee, 0xc3,
0xa9, 0xb0, 0x03, 0x6d, 0xd0, 0x08, 0xbc, 0x50, 0xe4, 0x14, 0x4c, 0x95, 0x8a, 0x3f, 0x6a, 0xa3,
0xd4, 0x6c, 0xe5, 0xce, 0x6c, 0xad, 0xae, 0xeb, 0x4d, 0x4e, 0x6d, 0x7a, 0x9e, 0x0a, 0x24, 0xaa,
0x90, 0xaa, 0x84, 0xa2, 0x1a, 0xa2, 0x8a, 0xa8, 0xaa, 0x62, 0xab, 0x8c, 0xad, 0x3a, 0xba, 0x0a,
0xb3, 0x55, 0x99, 0xa3, 0x52, 0xa9, 0x6a, 0x17, 0x05, 0x46, 0xc2, 0x37, 0x3d, 0xcb, 0x0d, 0x2c,
0xc7, 0x96, 0x37, 0xc3, 0xb2, 0x47, 0x2f, 0x85, 0x24, 0xf5, 0x4a, 0x94, 0xdd, 0x96, 0x14, 0x93,
0x29, 0x9d, 0xa3, 0x7c, 0xa6, 0x11, 0x70, 0x8d, 0x41, 0xd9, 0x28, 0x94, 0x8d, 0x83, 0x6f, 0x24,
0xc5, 0xc6, 0x22, 0x31, 0x9a, 0xc5, 0xeb, 0xfe, 0xf3, 0xe8, 0x0a, 0x5e, 0x4b, 0xfb, 0x81, 0x67,
0xd9, 0xf7, 0x94, 0xc6, 0x7e, 0x06, 0x81, 0x4b, 0x42, 0xd9, 0x0f, 0xc2, 0xbe, 0x0f, 0x3e, 0x6b,
0x83, 0xc6, 0x35, 0xa9, 0x99, 0x68, 0xea, 0x8b, 0x9f, 0xfc, 0x87, 0x65, 0x93, 0xf5, 0xcd, 0x34,
0xe9, 0x0d, 0xb1, 0xff, 0x1a, 0x93, 0x50, 0xe4, 0xe3, 0x5e, 0xae, 0xdc, 0x7b, 0xcf, 0x30, 0xa3,
0x9e, 0xf6, 0xce, 0xba, 0xb7, 0x02, 0x3f, 0x7a, 0x31, 0x59, 0x7e, 0x76, 0xcc, 0x68, 0x0a, 0xe3,
0x7b, 0xfd, 0x4d, 0xd1, 0x6e, 0xd7, 0xd8, 0x18, 0x47, 0xd5, 0x94, 0x1a, 0x1e, 0xa9, 0xc9, 0x17,
0x28, 0x43, 0x1b, 0x59, 0xbe, 0x3b, 0x31, 0x1e, 0x75, 0x7b, 0xde, 0x8f, 0xa8, 0x30, 0x9c, 0x96,
0x02, 0x0e, 0x03, 0x87, 0x81, 0xc3, 0xc0, 0x61, 0x95, 0xa6, 0xb8, 0x04, 0x0c, 0xc7, 0xd5, 0x1a,
0x5b, 0x93, 0x40, 0x78, 0x74, 0x00, 0x4e, 0xca, 0x03, 0x7a, 0x01, 0xbd, 0x80, 0x5e, 0x06, 0xde,
0xb4, 0x01, 0xbd, 0xcf, 0x4d, 0x71, 0x76, 0x0a, 0xe8, 0x8d, 0xaa, 0x65, 0x8d, 0xe8, 0xb0, 0x6b,
0x8d, 0x00, 0xb9, 0x80, 0xdc, 0xbc, 0xb4, 0xa3, 0x2e, 0x35, 0x0f, 0x04, 0xbe, 0x40, 0x5f, 0xa0,
0x6f, 0xba, 0x5a, 0x01, 0xa5, 0xcf, 0x2d, 0xfa, 0x5b, 0x5c, 0x1a, 0x08, 0x0c, 0x04, 0x46, 0xd0,
0x0b, 0xd8, 0x05, 0xec, 0x4a, 0x60, 0x97, 0x35, 0x5f, 0xf7, 0xbb, 0x78, 0x2c, 0x8c, 0x70, 0xb5,
0x0f, 0x96, 0x1f, 0x5c, 0x05, 0x81, 0x64, 0x56, 0xef, 0x0f, 0xcb, 0xfe, 0x6d, 0x22, 0x22, 0xc8,
0xf0, 0x8b, 0xd5, 0x14, 0xa9, 0x3f, 0x55, 0xb2, 0x73, 0xd9, 0xed, 0x9e, 0x5f, 0x74, 0xbb, 0xed,
0x8b, 0xb3, 0x8b, 0x76, 0xbf, 0xd7, 0xeb, 0x9c, 0x77, 0x7a, 0x05, 0xc2, 0xff, 0xf2, 0x46, 0xc2,
0x13, 0xa3, 0x7f, 0x44, 0xdf, 0x6c, 0x87, 0x93, 0x09, 0xab, 0xaa, 0x57, 0xb6, 0xed, 0x04, 0x86,
0x74, 0xe2, 0x51, 0xf3, 0xcd, 0xcf, 0x62, 0x6a, 0xb8, 0x46, 0x8c, 0x04, 0xda, 0xc9, 0x6a, 0xb0,
0x57, 0xfc, 0xb3, 0x68, 0xea, 0xd7, 0x0f, 0xbc, 0xd0, 0x0c, 0x92, 0x84, 0xbb, 0x76, 0x15, 0xcb,
0x7d, 0x9c, 0x8b, 0xdd, 0x16, 0xfc, 0xca, 0xc6, 0xde, 0x19, 0x73, 0xc6, 0x5d, 0x52, 0x77, 0x56,
0x9d, 0xb3, 0x28, 0x08, 0xe4, 0xca, 0xad, 0x56, 0x67, 0xf9, 0xd1, 0xa9, 0x0f, 0xd6, 0x0c, 0xd7,
0x26, 0xb0, 0x2f, 0x52, 0x85, 0x40, 0xbd, 0x20, 0x1b, 0x42, 0x3e, 0xf5, 0xa2, 0xa0, 0xd1, 0x19,
0x8d, 0x2f, 0x51, 0x02, 0x39, 0x0e, 0x03, 0xe9, 0x82, 0x81, 0x6c, 0x52, 0xd2, 0x45, 0xa4, 0x2f,
0xde, 0x54, 0xdf, 0x42, 0x02, 0x61, 0x37, 0xc2, 0x6e, 0x84, 0xdd, 0x08, 0xbb, 0x11, 0x76, 0xab,
0x67, 0x3b, 0xc0, 0x79, 0x03, 0x08, 0x03, 0x84, 0x01, 0xc2, 0xe0, 0xbc, 0xed, 0x14, 0x85, 0xc1,
0x79, 0x03, 0x0e, 0x03, 0x87, 0x81, 0xc3, 0xe0, 0xbc, 0xed, 0x14, 0x86, 0x6d, 0x5f, 0x77, 0x3d,
0x6b, 0x6a, 0x78, 0x8f, 0x0c, 0x14, 0x4e, 0x09, 0x01, 0x84, 0x01, 0xc2, 0x4b, 0x6a, 0x8e, 0xab,
0x1b, 0xa3, 0x91, 0x27, 0x7c, 0x9f, 0x03, 0xc4, 0x7d, 0x42, 0xd9, 0xe4, 0x5b, 0x2a, 0x87, 0xe1,
0xe5, 0x97, 0x7f, 0xeb, 0x32, 0xbe, 0x5d, 0xc5, 0x99, 0x2c, 0x6d, 0xd8, 0x08, 0x02, 0xe1, 0xd9,
0xe4, 0xea, 0x2c, 0x04, 0x9b, 0xcd, 0xeb, 0xb6, 0xde, 0x1f, 0xfe, 0xb8, 0xee, 0xe8, 0xfd, 0xe1,
0xfc, 0xb2, 0x13, 0xff, 0x6f, 0x7e, 0x7d, 0x7a, 0xdd, 0xd6, 0xbb, 0xcf, 0xd7, 0xbd, 0xeb, 0xb6,
0xde, 0x1b, 0xb6, 0x6e, 0x6e, 0xde, 0xb4, 0x9e, 0xce, 0x66, 0x7c, 0xc1, 0xe6, 0x4f, 0xd7, 0x37,
0x37, 0xee, 0xd3, 0x9f, 0xb3, 0xe8, 0xdf, 0x0f, 0xb3, 0xe1, 0x2f, 0xad, 0xb7, 0x1a, 0xf9, 0x6b,
0x87, 0x47, 0x15, 0xfa, 0x08, 0x35, 0x6d, 0x9e, 0x1f, 0x80, 0x36, 0x07, 0x3f, 0xa2, 0x36, 0x37,
0xf4, 0xf1, 0x95, 0xfe, 0x7e, 0xf8, 0xd4, 0x3e, 0xee, 0xce, 0x5a, 0x83, 0x56, 0x73, 0xfd, 0xde,
0xa0, 0xf5, 0xd4, 0x3e, 0xee, 0xcd, 0x9a, 0xcd, 0x8c, 0xbf, 0xbc, 0xcd, 0x7a, 0x46, 0xeb, 0x47,
0xb3, 0xd9, 0x4c, 0xf4, 0xb8, 0xa2, 0xdb, 0xeb, 0x76, 0x67, 0xf8, 0x36, 0xbe, 0x9c, 0xff, 0xbb,
0xb0, 0x0e, 0x52, 0xe1, 0x56, 0xa6, 0x4d, 0x1c, 0xb3, 0x4d, 0xf8, 0x7f, 0x83, 0xe1, 0x2f, 0x83,
0xd6, 0xd3, 0xf9, 0xec, 0xf9, 0x3a, 0xfe, 0xb7, 0xf5, 0xa3, 0xf9, 0xe6, 0xe7, 0x9b, 0x9b, 0x37,
0x6f, 0x7e, 0x6e, 0xcd, 0x2b, 0x90, 0x94, 0xfb, 0x79, 0xfe, 0xd7, 0xb7, 0x83, 0xc1, 0xc6, 0xad,
0x56, 0xf3, 0xa7, 0x37, 0xdb, 0x30, 0xcb, 0x9d, 0x39, 0x62, 0x5f, 0x98, 0x8e, 0x3d, 0x62, 0xbb,
0xe2, 0xa5, 0x18, 0x9c, 0x31, 0x9c, 0x31, 0x9c, 0x31, 0x9c, 0x31, 0x9c, 0x31, 0x9c, 0x31, 0x9c,
0xb1, 0xba, 0x33, 0xbe, 0xff, 0xae, 0x0b, 0xdb, 0xb8, 0x9b, 0x08, 0xc6, 0xb2, 0x84, 0x94, 0x8c,
0x04, 0xca, 0xdf, 0x89, 0xb1, 0x11, 0x4e, 0x62, 0xc7, 0x31, 0x36, 0x26, 0x3e, 0x12, 0x99, 0x70,
0xdb, 0xa9, 0x96, 0xbe, 0x73, 0x9c, 0x89, 0x30, 0x6c, 0x8e, 0xcf, 0xee, 0x60, 0x45, 0x0e, 0x4c,
0x78, 0x8f, 0x4c, 0x38, 0x45, 0x48, 0xc3, 0x72, 0x1c, 0xe4, 0xe4, 0xa9, 0x4d, 0x01, 0x82, 0xca,
0xbc, 0x5a, 0xd3, 0x20, 0xa4, 0x63, 0x6f, 0x54, 0x98, 0x1e, 0x6f, 0x74, 0xba, 0xe7, 0x6d, 0x60,
0x35, 0xb0, 0x7a, 0xd9, 0xd2, 0xa1, 0x65, 0x07, 0x67, 0xa7, 0x0c, 0x8c, 0xbe, 0x20, 0x14, 0xfd,
0xcb, 0xb0, 0xef, 0xc5, 0x4b, 0x41, 0xe8, 0xf3, 0x4b, 0x40, 0xf4, 0xa2, 0x2d, 0x7a, 0xbd, 0xb3,
0x1e, 0x56, 0xef, 0x60, 0xf5, 0x8e, 0xe2, 0xea, 0x9d, 0x65, 0x60, 0x98, 0x77, 0xcd, 0x58, 0xb4,
0xe3, 0xda, 0x8b, 0x45, 0x2d, 0x59, 0x97, 0xbb, 0x59, 0xab, 0x43, 0xae, 0x15, 0xa5, 0x36, 0x94,
0xf5, 0x39, 0xa6, 0x63, 0xdb, 0xc2, 0x0c, 0xac, 0x6f, 0x56, 0xf0, 0xa8, 0xfb, 0xc2, 0x8b, 0x77,
0x5b, 0xcd, 0x5d, 0xa8, 0x93, 0x59, 0xba, 0x86, 0x15, 0x3b, 0xa6, 0xbf, 0x7f, 0x0b, 0x76, 0x4c,
0xbf, 0xb2, 0xf5, 0x3a, 0x24, 0x25, 0xa8, 0x28, 0x43, 0xa2, 0x14, 0x72, 0x34, 0xc6, 0x5a, 0xc1,
0x63, 0xfa, 0x87, 0xb7, 0x80, 0x27, 0x4b, 0x99, 0x6a, 0x30, 0x8e, 0x4d, 0x53, 0x65, 0x26, 0x70,
0xa0, 0xf1, 0x77, 0x91, 0x89, 0xec, 0x2a, 0xfc, 0x06, 0x6d, 0x11, 0x29, 0x12, 0x4e, 0x53, 0x80,
0x3e, 0x9e, 0x60, 0xf0, 0xab, 0xa0, 0x8f, 0x03, 0x85, 0x81, 0xc2, 0x40, 0xe1, 0xbd, 0x43, 0x61,
0x90, 0xc7, 0xe7, 0xd5, 0xfa, 0xec, 0xfb, 0xba, 0xb0, 0x47, 0xae, 0x63, 0xc5, 0x5d, 0x9b, 0x08,
0xc2, 0x2b, 0x52, 0x00, 0x61, 0x80, 0xf0, 0x73, 0x26, 0xda, 0xb3, 0x58, 0x08, 0x8c, 0x49, 0x6f,
0x18, 0xef, 0xde, 0x18, 0x6f, 0x56, 0x2a, 0x07, 0x73, 0xdf, 0x08, 0x29, 0xa8, 0x4d, 0x81, 0xb9,
0xef, 0x24, 0x29, 0xee, 0xde, 0x3f, 0x98, 0x0a, 0x41, 0xc5, 0x9a, 0x1c, 0x90, 0x19, 0xc8, 0x5c,
0x73, 0x58, 0x81, 0xa9, 0xc2, 0x4a, 0xa7, 0x0a, 0xb3, 0x1c, 0x2a, 0xfd, 0x26, 0x7d, 0x16, 0xf1,
0xd7, 0x94, 0xf4, 0xa7, 0xb9, 0xf0, 0x2d, 0xf1, 0xde, 0x4e, 0x26, 0x18, 0xcb, 0x34, 0x81, 0x5a,
0xd5, 0x29, 0x93, 0x90, 0xc2, 0x0e, 0x84, 0xe7, 0x7a, 0x96, 0x5f, 0x30, 0xf5, 0x98, 0x2a, 0x53,
0xc3, 0x84, 0xa3, 0xc8, 0xf4, 0x02, 0x3b, 0x9e, 0x71, 0x8c, 0xfe, 0x57, 0xd5, 0x94, 0x63, 0x41,
0x93, 0xd3, 0x9b, 0x5e, 0xa2, 0x02, 0xb2, 0x27, 0x64, 0x4d, 0x2f, 0x8a, 0x42, 0x07, 0xbd, 0xa7,
0xf3, 0x8b, 0x99, 0xaa, 0x53, 0x03, 0x7f, 0xe9, 0x04, 0x23, 0x6b, 0x36, 0x99, 0x34, 0x14, 0x21,
0x06, 0x44, 0x9d, 0x5d, 0x06, 0x44, 0x42, 0x1a, 0xb7, 0x1d, 0x60, 0x44, 0x54, 0x68, 0x36, 0xd5,
0x84, 0x44, 0x32, 0x73, 0x2a, 0x67, 0x56, 0x55, 0x98, 0x97, 0xe2, 0x20, 0x89, 0x6c, 0x6e, 0x2a,
0x66, 0xa7, 0x68, 0x7e, 0xaa, 0x66, 0x58, 0xda, 0x1c, 0x4b, 0x9b, 0xa5, 0xba, 0x79, 0x32, 0xc7,
0x8d, 0x44, 0x5d, 0x91, 0x23, 0xf9, 0x0d, 0x4d, 0x4d, 0x84, 0x31, 0xf6, 0xc4, 0x58, 0x65, 0x2d,
0xe1, 0x05, 0x6f, 0x2d, 0x61, 0x12, 0x72, 0xf9, 0x83, 0xec, 0xa8, 0x2b, 0xff, 0xbe, 0x35, 0xd2,
0x2a, 0x1a, 0x64, 0x13, 0x9a, 0x53, 0xa3, 0xae, 0x55, 0xcb, 0xb0, 0x79, 0xca, 0x82, 0xb5, 0x25,
0xd2, 0x2c, 0x89, 0xe4, 0x91, 0xdd, 0xa1, 0xd7, 0xa3, 0xd7, 0xd7, 0xd7, 0xeb, 0xe9, 0xeb, 0xe2,
0x36, 0x7a, 0x7d, 0xa7, 0xaa, 0xbe, 0x58, 0xca, 0x4f, 0x27, 0x63, 0x7e, 0x95, 0xf0, 0x8c, 0x94,
0x0d, 0xe0, 0x67, 0x05, 0x2a, 0xc9, 0x0e, 0xf0, 0xb2, 0x04, 0xd4, 0xc6, 0x22, 0x66, 0x0d, 0xf2,
0x46, 0xc9, 0xcb, 0x01, 0x4f, 0xce, 0xa5, 0x62, 0x14, 0xb3, 0x36, 0x82, 0xfe, 0x6d, 0xf1, 0xc0,
0xdb, 0xec, 0x4b, 0x72, 0xd6, 0xa0, 0x5c, 0xd6, 0xf4, 0x35, 0x30, 0x12, 0x31, 0x3c, 0xa8, 0x2b,
0x63, 0x0a, 0x36, 0x0c, 0xa6, 0xae, 0x38, 0x4d, 0x01, 0x4e, 0x62, 0x82, 0xc2, 0xaf, 0x82, 0x93,
0x08, 0x1c, 0x06, 0x0e, 0x03, 0x87, 0xf7, 0x10, 0x87, 0xc1, 0x4a, 0x9c, 0x57, 0xeb, 0xe5, 0x91,
0xb8, 0x00, 0xb9, 0x75, 0x41, 0xee, 0x72, 0x84, 0x08, 0xf2, 0x16, 0x90, 0x97, 0xda, 0x14, 0x38,
0xd0, 0x12, 0x3c, 0x17, 0x55, 0x9e, 0x8b, 0x2c, 0x53, 0x45, 0x67, 0xb2, 0xc8, 0x92, 0x51, 0x3b,
0xa1, 0xab, 0x50, 0xeb, 0x44, 0xa9, 0x0b, 0x85, 0x88, 0xf2, 0xd5, 0xf1, 0xe5, 0xa7, 0x55, 0xa6,
0x0b, 0xe1, 0xb4, 0x4a, 0xb2, 0xea, 0x73, 0xa9, 0x28, 0x45, 0x8d, 0xce, 0x68, 0x7c, 0x89, 0x12,
0xc8, 0xb1, 0x16, 0x4e, 0xab, 0x64, 0xc0, 0x16, 0xe9, 0xb4, 0x4a, 0x63, 0x7a, 0xe7, 0xf1, 0x4e,
0xab, 0x8c, 0x25, 0x0e, 0x80, 0x74, 0x82, 0x8d, 0xa6, 0xd4, 0x42, 0x6b, 0x32, 0xe9, 0x64, 0xe4,
0x3c, 0xd8, 0x13, 0xcb, 0xfe, 0xc2, 0x9f, 0x9c, 0x5e, 0x48, 0xf2, 0x67, 0xa7, 0xdb, 0x2f, 0x61,
0x6a, 0x9a, 0x66, 0x9a, 0xaa, 0x26, 0x5a, 0xda, 0x54, 0x4b, 0x9b, 0xac, 0xba, 0xe9, 0x32, 0x63,
0xe1, 0xad, 0x4f, 0x4d, 0x93, 0xf7, 0x50, 0x5b, 0xb7, 0x3b, 0x0e, 0x1d, 0x85, 0xb7, 0xa7, 0x1a,
0x7f, 0x10, 0x59, 0x6a, 0x30, 0x59, 0x72, 0x24, 0xb5, 0x31, 0xa2, 0x52, 0x95, 0x2f, 0x31, 0xb0,
0x52, 0x18, 0x6c, 0x96, 0x1a, 0x74, 0x56, 0xdd, 0x64, 0xdd, 0xd3, 0x7e, 0xb7, 0x7f, 0x7e, 0x71,
0xda, 0xef, 0xed, 0xb0, 0xed, 0x8e, 0xb6, 0x53, 0x7a, 0x58, 0x23, 0x99, 0x2a, 0x74, 0xd5, 0xdc,
0x55, 0x22, 0x07, 0x67, 0x05, 0x67, 0x05, 0x67, 0x05, 0x67, 0x05, 0x67, 0x05, 0x67, 0x55, 0xd2,
0x59, 0xed, 0x92, 0x40, 0x97, 0xca, 0xd2, 0xe4, 0x5e, 0x13, 0xc7, 0xf9, 0x19, 0xe9, 0xbd, 0x7f,
0x3b, 0xfe, 0xf3, 0x66, 0x97, 0xd9, 0x97, 0x57, 0xae, 0x7d, 0x15, 0x3d, 0x19, 0x5c, 0x39, 0x64,
0x35, 0x70, 0xec, 0x70, 0x75, 0x7e, 0x13, 0x33, 0x85, 0xe5, 0xfc, 0x20, 0xb8, 0x72, 0x55, 0xa1,
0x30, 0x8e, 0x7f, 0x07, 0x0e, 0x03, 0x87, 0x81, 0xc3, 0xe0, 0xca, 0xed, 0x12, 0x86, 0x71, 0xca,
0x17, 0x20, 0x57, 0x15, 0x72, 0x53, 0x43, 0x41, 0x90, 0xe5, 0x00, 0xbd, 0xd4, 0xa6, 0x00, 0x59,
0x0e, 0x64, 0x39, 0x55, 0xb2, 0x1c, 0x21, 0x2b, 0x45, 0xe7, 0xcb, 0xc9, 0x92, 0x50, 0x3b, 0xe1,
0xcb, 0xd1, 0x6b, 0x45, 0xa9, 0x0d, 0x85, 0x31, 0xe7, 0x0b, 0x33, 0xf4, 0xac, 0xe0, 0x51, 0x4e,
0x9b, 0xdb, 0x28, 0x59, 0x03, 0x77, 0xce, 0x17, 0xe6, 0xfe, 0x71, 0xe7, 0xa2, 0x8f, 0xaa, 0x8a,
0x3b, 0x27, 0x6d, 0x7e, 0xae, 0x1a, 0x24, 0xea, 0x20, 0x47, 0x61, 0x2c, 0x16, 0x5d, 0xb6, 0x9a,
0xb8, 0xd1, 0x56, 0xcd, 0x2c, 0xba, 0x4c, 0x35, 0xaa, 0x41, 0x37, 0xce, 0x8c, 0x91, 0x1a, 0xc1,
0x81, 0x86, 0xde, 0x85, 0x46, 0x82, 0x6c, 0x07, 0x42, 0x6e, 0x64, 0x9d, 0x91, 0x75, 0x06, 0x0e,
0x03, 0x87, 0x81, 0xc3, 0xc0, 0x61, 0x64, 0x9d, 0x5f, 0x69, 0xd6, 0x19, 0x90, 0x5b, 0x1b, 0xe4,
0xae, 0x8d, 0x7e, 0x91, 0x7a, 0x06, 0xfe, 0x22, 0xf5, 0xcc, 0xc3, 0xdf, 0x2f, 0x71, 0xa2, 0x99,
0x08, 0xc0, 0x51, 0x61, 0x20, 0x30, 0x10, 0x18, 0x41, 0x2f, 0x40, 0x17, 0xa0, 0xab, 0x0e, 0xba,
0x8e, 0x6b, 0xd2, 0x41, 0x37, 0x2a, 0x0c, 0xd0, 0x05, 0xe8, 0x02, 0x74, 0x01, 0xba, 0x00, 0x5d,
0x75, 0xd0, 0xf5, 0xbf, 0x32, 0xa6, 0xdb, 0xa2, 0xc2, 0x00, 0x5d, 0x80, 0x2e, 0x7f, 0xa9, 0x24,
0x63, 0x89, 0x24, 0x73, 0x69, 0xe4, 0x9e, 0x43, 0x6e, 0x1b, 0x90, 0x5b, 0x76, 0x49, 0x23, 0xf8,
0x6d, 0xcb, 0x70, 0xe4, 0xb5, 0xf3, 0xdb, 0xd6, 0x93, 0x9b, 0xf2, 0x1b, 0x74, 0xba, 0xdb, 0xa7,
0x44, 0xf2, 0x99, 0x25, 0x26, 0xf9, 0xbd, 0x13, 0xf6, 0x9b, 0x4a, 0x75, 0x79, 0xd5, 0x24, 0x31,
0xe2, 0xc2, 0x3b, 0xdf, 0xf4, 0xac, 0x3b, 0xe1, 0x15, 0x70, 0xe1, 0x96, 0x65, 0xea, 0x60, 0xc1,
0x85, 0x77, 0x7b, 0xc8, 0x82, 0x0b, 0xef, 0x2a, 0x63, 0xc1, 0x85, 0x04, 0xde, 0x5b, 0xb8, 0x1f,
0x4c, 0xb7, 0x4c, 0x55, 0x70, 0xa3, 0xae, 0xba, 0x99, 0x6e, 0x59, 0xaa, 0x52, 0x03, 0x71, 0x39,
0xd3, 0xed, 0x75, 0x70, 0x2c, 0x0a, 0xcd, 0xe0, 0x50, 0x83, 0xf0, 0x22, 0x33, 0x41, 0xe6, 0x03,
0x99, 0x0f, 0x70, 0x2c, 0x0e, 0x26, 0xf3, 0x41, 0x3d, 0x13, 0x90, 0x79, 0x16, 0x60, 0x7a, 0xe3,
0xaa, 0xb1, 0x31, 0xf1, 0x01, 0xd6, 0x00, 0x6b, 0xa5, 0x43, 0xfa, 0x88, 0x87, 0xf3, 0xa9, 0x1a,
0xbf, 0xf4, 0x6c, 0xec, 0x0c, 0xfb, 0x27, 0x6c, 0xb9, 0x0d, 0x93, 0x7e, 0x75, 0x26, 0x4d, 0x3f,
0x6d, 0x96, 0x73, 0xca, 0xec, 0xf2, 0x74, 0x59, 0x61, 0x07, 0x83, 0xd5, 0x5d, 0xd2, 0xd7, 0x7f,
0xca, 0x0e, 0x93, 0x05, 0x09, 0x0f, 0x7d, 0xa2, 0xe6, 0xc4, 0x78, 0x58, 0x3d, 0xeb, 0xee, 0xa3,
0x11, 0x04, 0xc2, 0xb3, 0xc9, 0x21, 0xb9, 0x76, 0xdd, 0xd6, 0xfb, 0x86, 0x3e, 0xbe, 0xd2, 0xdf,
0x0f, 0x9f, 0x2e, 0x67, 0x7a, 0xfa, 0x67, 0x97, 0xf3, 0xb3, 0x73, 0x3a, 0xd3, 0x76, 0x43, 0x83,
0x9d, 0xfa, 0x16, 0xa3, 0x0f, 0x46, 0xa5, 0x69, 0xbd, 0xb0, 0x87, 0x5e, 0x78, 0x78, 0xbd, 0x90,
0xbc, 0xa3, 0xba, 0x97, 0x4c, 0x20, 0x31, 0xf7, 0xa7, 0x9d, 0x8b, 0xf1, 0xb6, 0x9a, 0xed, 0xee,
0xe3, 0x56, 0xb3, 0x34, 0x03, 0x53, 0x35, 0xb4, 0xd2, 0x06, 0x57, 0xda, 0xf0, 0xd4, 0x0d, 0x90,
0x39, 0x2e, 0xa5, 0x6e, 0x55, 0x4c, 0x34, 0xcc, 0x15, 0x5c, 0xd3, 0x63, 0x73, 0xd3, 0xc7, 0x9e,
0x33, 0xe5, 0x37, 0x7d, 0x1a, 0xf2, 0xd2, 0x0f, 0x3a, 0xae, 0x25, 0x93, 0xc0, 0x35, 0xe6, 0x32,
0x46, 0x5d, 0xd2, 0xb8, 0xcb, 0x1a, 0x79, 0x65, 0xc6, 0x5e, 0x99, 0xd1, 0x97, 0x37, 0x7e, 0x5e,
0x27, 0x50, 0x48, 0x6b, 0x35, 0x94, 0xf6, 0x5f, 0xde, 0x8c, 0xa1, 0x2c, 0x3b, 0x38, 0xef, 0xaa,
0x28, 0x3b, 0xb1, 0xeb, 0x4b, 0x05, 0x51, 0xb5, 0x7d, 0x99, 0xf9, 0x59, 0xd0, 0x4a, 0xb2, 0xa2,
0x15, 0x75, 0xe8, 0xdc, 0x54, 0x61, 0xd9, 0xe7, 0x54, 0xb0, 0x07, 0xb1, 0xa2, 0xf9, 0x95, 0xce,
0xb2, 0x6e, 0xbb, 0x69, 0x79, 0x73, 0xed, 0xb5, 0xb7, 0xf6, 0x51, 0x3d, 0x52, 0xc3, 0x2d, 0xed,
0x30, 0xcd, 0xc9, 0xc1, 0xa7, 0x7c, 0x68, 0xe0, 0x54, 0xe2, 0x8a, 0x03, 0x07, 0x8e, 0x18, 0x8e,
0x18, 0x8e, 0x18, 0x8e, 0x18, 0x8e, 0x18, 0x8e, 0xf8, 0x75, 0x3b, 0xe2, 0x4a, 0x07, 0xda, 0xcc,
0x23, 0x1b, 0x16, 0x72, 0x6b, 0x24, 0x3a, 0x43, 0x04, 0x9f, 0x85, 0xa7, 0x2f, 0x19, 0x6a, 0x27,
0xa9, 0xcb, 0x50, 0x9c, 0x44, 0xae, 0xfc, 0x64, 0x9e, 0x0d, 0xaa, 0xf1, 0x58, 0xa5, 0x07, 0x6b,
0x32, 0x32, 0x0d, 0x6f, 0xc4, 0x4f, 0x5c, 0x2d, 0x24, 0x91, 0xbb, 0x42, 0xee, 0xaa, 0x96, 0xdc,
0x15, 0xdb, 0x56, 0xb3, 0xc3, 0x65, 0xa6, 0xe1, 0x22, 0x5c, 0x46, 0xb8, 0x7c, 0x00, 0xe1, 0x32,
0x99, 0x8f, 0x97, 0x67, 0xd7, 0x1d, 0x95, 0x78, 0x99, 0xc9, 0xd7, 0x7b, 0xe1, 0x01, 0x73, 0x07,
0x01, 0xf3, 0xd6, 0x9a, 0x16, 0xe1, 0x31, 0xc2, 0xe3, 0x93, 0x85, 0xeb, 0x7e, 0x09, 0x67, 0xb9,
0x51, 0x6a, 0xbc, 0x0d, 0x86, 0x91, 0xeb, 0x59, 0x8e, 0x67, 0x05, 0x8c, 0xbd, 0x66, 0x16, 0x12,
0x74, 0x12, 0x6a, 0x1b, 0xcc, 0x24, 0x30, 0x93, 0xb0, 0x64, 0x77, 0x6b, 0xc9, 0xb6, 0x17, 0xbe,
0x2f, 0x2e, 0x56, 0x0b, 0x24, 0x50, 0x1d, 0xaf, 0x8e, 0xf4, 0x39, 0x50, 0x9d, 0x48, 0xd0, 0xe0,
0xb7, 0x03, 0xf8, 0x3d, 0x3c, 0xf8, 0x25, 0x53, 0xd2, 0x0c, 0xd3, 0x14, 0xbe, 0x2f, 0x3d, 0xc2,
0x20, 0x57, 0x41, 0x6b, 0xf2, 0xbc, 0x44, 0x5f, 0x07, 0x89, 0x3e, 0x24, 0xfa, 0xd8, 0x89, 0x3e,
0x45, 0x93, 0xad, 0xc6, 0x74, 0x91, 0xea, 0x43, 0xaa, 0xef, 0x00, 0x52, 0x7d, 0xf4, 0xa5, 0x2f,
0xb9, 0xd8, 0x7c, 0xa1, 0x20, 0xbb, 0x58, 0x1a, 0x63, 0xb8, 0x83, 0xd5, 0xee, 0x95, 0x7d, 0xc7,
0x1a, 0x69, 0x7b, 0x40, 0xb4, 0x31, 0x26, 0x13, 0xe7, 0x41, 0x94, 0x98, 0x33, 0x78, 0x7e, 0x00,
0x53, 0xcd, 0xa9, 0xb1, 0x70, 0x64, 0xcb, 0x40, 0x20, 0x20, 0xd0, 0xcb, 0x41, 0x20, 0xfa, 0x7a,
0xd2, 0x5c, 0x04, 0xea, 0x1c, 0x44, 0x72, 0x33, 0xd9, 0x1b, 0x49, 0x2d, 0x10, 0x26, 0xed, 0x9b,
0x94, 0x95, 0x7c, 0xa0, 0xed, 0xa3, 0x94, 0x35, 0x56, 0x57, 0xde, 0x57, 0x69, 0xe3, 0x61, 0xa4,
0x7d, 0x96, 0xf6, 0x3c, 0x67, 0xfc, 0x3c, 0x18, 0x3e, 0x51, 0x8e, 0x06, 0xd7, 0x76, 0x31, 0xba,
0x8a, 0x5f, 0xf8, 0x69, 0xf1, 0x92, 0xdb, 0xd4, 0xe5, 0xdf, 0xe2, 0x36, 0xd9, 0xcc, 0xc8, 0xbf,
0xbd, 0x8a, 0xdf, 0x57, 0xb8, 0x65, 0x93, 0x42, 0xb2, 0x9a, 0x30, 0x56, 0x36, 0x5c, 0xbb, 0xc4,
0x70, 0x2f, 0x25, 0xcc, 0x1b, 0xeb, 0xb5, 0x31, 0xd6, 0xc3, 0x58, 0x8f, 0xed, 0x56, 0x4a, 0x04,
0xb4, 0x2a, 0x81, 0x6c, 0x3a, 0x80, 0xb5, 0x07, 0x29, 0x63, 0xcf, 0xfc, 0x6d, 0x8d, 0xea, 0xec,
0xb7, 0xe9, 0x33, 0x45, 0xd9, 0xfd, 0x96, 0x76, 0xcc, 0x2a, 0xfa, 0x2d, 0xfa, 0xed, 0x81, 0xf7,
0xdb, 0xaf, 0x8e, 0x3f, 0x58, 0x3b, 0x89, 0x77, 0xe3, 0x77, 0xbd, 0xfd, 0x96, 0x7c, 0x4c, 0x6c,
0xbe, 0xb5, 0xd3, 0x77, 0x8e, 0x44, 0x0f, 0x46, 0x0f, 0x3e, 0xf0, 0x1e, 0xec, 0x0b, 0x73, 0x90,
0xb5, 0x9b, 0x68, 0xf6, 0xcd, 0x7a, 0xfb, 0x72, 0xe8, 0xaa, 0xf7, 0xe2, 0x94, 0x2c, 0xfa, 0x2f,
0xfa, 0xef, 0x8b, 0xed, 0xbf, 0xa1, 0x3b, 0x58, 0x9a, 0xfa, 0xe6, 0x2f, 0xeb, 0x75, 0x30, 0xb3,
0x88, 0x93, 0xec, 0xea, 0x09, 0x84, 0x6d, 0xd0, 0xbe, 0x3c, 0xf1, 0x35, 0x14, 0x7e, 0x20, 0x46,
0xba, 0xe1, 0x32, 0x4e, 0x5f, 0x58, 0x15, 0x03, 0xa9, 0x0b, 0xa4, 0x2e, 0x6c, 0x01, 0x4b, 0x10,
0x03, 0xad, 0x6b, 0xa3, 0x29, 0xce, 0x3a, 0x20, 0x75, 0xcd, 0xc7, 0x8c, 0xde, 0x37, 0xcb, 0xbe,
0xd7, 0xdd, 0xc9, 0x94, 0x73, 0x0a, 0x4e, 0x5a, 0x0a, 0xe4, 0x2e, 0x90, 0xbb, 0xa6, 0xa6, 0xc9,
0x1f, 0xa7, 0x44, 0x42, 0x18, 0xa0, 0x60, 0x80, 0x52, 0xdb, 0x00, 0x85, 0x6e, 0x70, 0x0d, 0x1e,
0xfb, 0x7b, 0x21, 0xa2, 0xb6, 0x65, 0x83, 0xc2, 0xe4, 0x77, 0x99, 0x15, 0x67, 0x25, 0x97, 0x43,
0x95, 0xdd, 0x92, 0xa1, 0x8a, 0xd5, 0x4f, 0x0a, 0x2b, 0xca, 0x4a, 0xad, 0x24, 0xab, 0xaa, 0xc9,
0xfa, 0xfd, 0xfe, 0x0e, 0x1b, 0x6d, 0x4b, 0x2c, 0x87, 0x61, 0x8d, 0x79, 0xb1, 0xa9, 0xad, 0xe2,
0x68, 0x6c, 0x38, 0x1a, 0x38, 0x9a, 0x3a, 0x1d, 0x8d, 0x0d, 0x47, 0x03, 0x47, 0x03, 0x47, 0x73,
0xc0, 0x8e, 0x26, 0x30, 0x14, 0x1c, 0x4d, 0x24, 0x04, 0x47, 0x03, 0x47, 0x53, 0x9b, 0xa3, 0xa1,
0x1b, 0x1c, 0x1c, 0x0d, 0x1c, 0xcd, 0x96, 0x1c, 0x4d, 0xfc, 0x1f, 0xbc, 0xcd, 0x76, 0x52, 0x70,
0x5b, 0x9e, 0x3d, 0x64, 0x64, 0x72, 0x1b, 0xec, 0x19, 0xc4, 0x4f, 0xf3, 0x87, 0x7f, 0x8c, 0x9e,
0x8d, 0xd3, 0x83, 0x37, 0x84, 0x77, 0x71, 0x7a, 0xb0, 0xc4, 0x1e, 0xe8, 0x47, 0x05, 0x17, 0xab,
0x7e, 0x27, 0x27, 0x03, 0x17, 0xd5, 0x4d, 0x7e, 0x28, 0x70, 0x41, 0x85, 0x28, 0x07, 0x02, 0x17,
0x10, 0x76, 0xe4, 0xc4, 0x9c, 0xad, 0x1c, 0x08, 0xec, 0x7a, 0xce, 0xfe, 0x1d, 0x08, 0x1c, 0x7d,
0x54, 0x65, 0x07, 0x02, 0xcb, 0x39, 0x52, 0x74, 0x4e, 0x54, 0xad, 0x07, 0x04, 0x67, 0xab, 0x86,
0x1b, 0x50, 0xd7, 0x7c, 0x40, 0x70, 0xa6, 0xea, 0xd4, 0x70, 0x5a, 0x7a, 0x40, 0x70, 0xb2, 0x46,
0xc6, 0x74, 0xec, 0xc0, 0x73, 0x26, 0xf4, 0x89, 0xc9, 0x35, 0xb9, 0x03, 0x60, 0x88, 0x14, 0x9b,
0x82, 0xea, 0x18, 0x6b, 0xc7, 0x53, 0x93, 0x85, 0xa6, 0x52, 0x4d, 0x5c, 0x04, 0x86, 0x48, 0x85,
0x51, 0x3d, 0x0e, 0x09, 0xde, 0x6c, 0x8a, 0xb3, 0x53, 0x30, 0x44, 0xe2, 0xb3, 0xda, 0x45, 0x14,
0x05, 0xb9, 0xa4, 0x11, 0xc8, 0xf2, 0xa8, 0xf6, 0x94, 0x10, 0x40, 0x18, 0x20, 0x0c, 0x10, 0x06,
0x08, 0x2b, 0x35, 0x05, 0x36, 0x5f, 0x4b, 0x50, 0xd8, 0xf2, 0xdd, 0x89, 0xf1, 0xa8, 0x27, 0xa3,
0x55, 0x2a, 0x0c, 0xa7, 0xa5, 0x80, 0xc3, 0xc0, 0x61, 0xe0, 0x30, 0x70, 0x58, 0xa5, 0x29, 0x2e,
0x01, 0xc3, 0x8d, 0x97, 0x79, 0x20, 0x3a, 0x20, 0xb7, 0x2e, 0xc8, 0x5d, 0xa6, 0x20, 0xf5, 0xea,
0x4f, 0x46, 0x07, 0xf2, 0x22, 0x0d, 0xf1, 0xa2, 0x91, 0x37, 0xf4, 0x85, 0xa7, 0xbb, 0x13, 0xc3,
0x66, 0x84, 0xbf, 0x29, 0x19, 0x20, 0x31, 0x90, 0x18, 0xc1, 0x2f, 0x20, 0x58, 0xa5, 0x29, 0x4e,
0x7b, 0xbd, 0x57, 0x84, 0xc1, 0x20, 0x5c, 0x54, 0x4a, 0xb8, 0x58, 0xd9, 0x93, 0x20, 0xe3, 0x92,
0xce, 0xb8, 0xf8, 0xdb, 0x4d, 0x56, 0xe4, 0xdf, 0x66, 0x5c, 0xed, 0x84, 0x70, 0x41, 0xad, 0x90,
0xbc, 0x22, 0xb9, 0x0c, 0x8b, 0xa3, 0xd4, 0x67, 0xe6, 0x7d, 0x9e, 0x66, 0xf9, 0xef, 0x8d, 0x2f,
0xe2, 0x2f, 0xc7, 0xd9, 0x74, 0x54, 0xeb, 0x9f, 0xac, 0xa5, 0xff, 0xb4, 0xf2, 0x55, 0xef, 0xc4,
0x37, 0xcb, 0x4c, 0x3e, 0x64, 0x76, 0x34, 0xfb, 0x3f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x01, 0x00,
0x00, 0xff, 0xff, 0x2e, 0xa1, 0xb4, 0xce, 0xa2, 0x7c, 0x01, 0x00,
}
)
// ΛEnumTypes is a map, keyed by a YANG schema path, of the enumerated types that
// correspond with the leaf. The type is represented as a reflect.Type. The naming
// of the map ensures that there are no clashes with valid YANG identifiers.
var ΛEnumTypes = map[string][]reflect.Type{
}
|
On 30 June 1916 2Lt Percy Boswell, like many of his comrades, sat down to write a letter. The young officer in the King’s Own Yorkshire Light Infantry knew roughly what was going to happen the following day, as he told his father.
“The Hun is going to get consummate hell just in this quarter and we are going over the top tomorrow when I hope to spend a few merry hours in chasing the Bosch all over the place,” he predicted with jaunty confidence. “I am absolutely certain that I shall get through all right, but in case the unexpected happens I shall rest content with the knowledge that I have done my duty – and one can’t do more.”
It was, he wrote, “a short note which you will receive only if anything has happened to me during the next few days”. On 1 July Boswell died in the first hour of the Battle of the Somme, aged just 22.
Facebook Twitter Pinterest Percy Boswell’s last letter home. Photograph: Imperial War Museum
The 141 days of the battle across the flat farmland of northern France would eventually claim more than a million Allied and German dead and injured. Boswell was among 57,000 British casualties that first day. More than half of the soldiers in the second wave of the attack were cut down as they crossed the 320 metres of no man’s land. All 25 officers in his battalion, including Boswell, were either killed or wounded.
Somme trench recreated in Welsh castle to salute battle's centenary Read more
His letter is among hundreds written on the eve of battle preserved in the archives of the Imperial War Museum, and revealed to mark the centenary. Many are creased and tattered from being read over and over again by the desolate families.
On Friday, scores of events across Britain and in France will be held to mark the centenary of the battle, which began on 1 July 1916.
The main international ceremony will be at the Thiepval Memorial in France, attended by politicians, descendants of those who fought and hundreds of schoolchildren. The memorial bears the names of 72,000 people whose burial place is unknown.
There will be vigil services on Thursday at Westminster Abbey, and in Cardiff, Edinburgh and Northern Ireland, and a national service of commemoration at Manchester Cathedral on Friday. The service will be relayed to screens, and there will also be parades, exhibitions and free concerts in the city’s Heaton Park, which once served as an assembly point and training ground for troops heading for the front.
The Imperial War Museum in London is opening until midnight on Thursday, the eve of the battle, with special film, music and theatrical events and exhibitions. Admission is free.
Many of the final letters were given to the museum by descendants, along with treasured photographs, and kindly phrased and frequently untrue assurances from officers or chaplains that their loved ones died instantly without suffering. Some came with scraps of personal possessions including John Shaw’s homemade identity tag – he had worked in London as an embosser – with his name and number punched into the metal, made into a bracelet with a cheap watch chain.
Anthony Richards, head of documents and sound at the museum, said although the soldiers were issued with cloth or paper ID tags, some made their own for fear of ending up – as so many did – an unidentifiable corpse in a mass grave.
Shaw’s letter is one of the most extraordinary. He wrote to his mother on 12 October, when he was actually lying on the battlefield mortally wounded. “We went over the top on Sunday 8th and I got wounded. I managed to crawl back to our lines and worse luck here I am. Been here 4 days today and dying for a drink.
“Someone run into us the other day and promised to get us out of it. But we are still here never even brought us any water. I have been shot through the hip and cannot use my right leg. Properly knock up. Pity when one gets a blighty one [a minor wound that would get you sent home] too, after so long.”
Facebook Twitter Pinterest Pte John Shaw. Photograph: Imperial War Museum
Shaw was eventually rescued and brought to hospital in Rouen, but died there on 18 October.
Many were not formal last letters. Thomas Farlam wrote cheerfully in September to ask his wife for a notebook. Annie’s letter, stained with the Somme mud, was found among his possessions after his death on 16 September.
Royston Jones wrote on 10 September to his parents, Amelia and Charles, at home in Hackney, east London, assuring them that he was “quite in the pink” and had got their parcel. He ended: “PS I want some safety razor blades as soon as poss as I have run out of them also.” Five days later he was dead, aged 20.
Neither man’s body was ever identified, and their names are among the 72,000 carved into the Thiepval Memorial.
Facebook Twitter Pinterest John Shaw’s homemade identity tag. Photograph: Andrew Tunnard/Imperial War Museum
After witnessing months of the battle, Albert Baker wrote with foreboding in September: “I am writing this whilst in billets, some three miles behind the Line, not because I feel downhearted at all but because there have been so many killed or mortally wounded near me, and who knows but that it might be my turn next and I could not bear parting without my heartfelt thanks for your innumerable kindnesses.” He asked for his stamp collection to be saved for his youngest brother “as he may take an interest in them when he is older”.
Albert Baker. Photograph: Imperial War Museum
“Once more before I close this not very cheerful epistle, I must thank you again for the way you have brought me up and looked after me, asking you to remember me to all my old friends, particularly Art and Rodney.” He added a postscript: “Who knows but that we may meet again in another sphere, when I shall be able to thank you personally for everything?”
He died on 14 September, shot in the lung, aged 20.
• The centenary of the eve and first day of the Battle of the Somme will be marked by scores of events across Britain and in France, including vigils in many churches on Thursday, and on Friday a two-minute silence, a national service of commemoration in Manchester, and a major international ceremony at the Thiepval Memorial in France attended by politicians, descendants and hundreds of schoolchildren. |
/**
* Date 对象扩展
*/
interface Date {
/**
* 判断是否为闰年
*
* @return boolean
*/
isLeapYear(): boolean;
/**
* 获取季节
*
* @return 季节
*/
getSeason(): number;
/**
* 获取年份中的第几天
*
* @return 年份中的第几天
*/
getDayOfYear(): number;
/**
* 获取年份总天数
*
* @return 年份总天数
*/
getDaysOfYear(): number;
/**
* 将日期时间格式化为字符串
*
* @param format string - the desired format of the date
*
* The format can be combinations of the following:
*
* y - 年
* n - 季度(1 到 4)
* N - 季度名称
* A - 季度中文名称
* M - 月
* f - 月(Jan 到 Dec)
* F - 月(January 到 December)
* C - 月,中文名称
* d - 日
* Y - 年份中的第几天(0 到 365)
* T - 月份有几天(28 到 30)
* j - 每月天数后面的英文后缀(st,nd,rd 或者 th)
* e - 星期几,数字表示,0(表示星期天)到 6(表示星期六)
* E - 星期几,数字表示,1(表示星期一)到 7(表示星期天)
* l - 星期几,文本表示,3 个字母(Mon 到 Sun)
* L - 星期几,完整的文本格式(Sunday 到 Saturday)
* w - 星期几,中文名称
* W - 一月中第几个星期几
* i - 月份中的第几周
* o - 年份中的第几周
* h - 小时(1~12)
* H - 小时(0~23)
* m - 分
* s - 秒
* S - 毫秒
* a - 上午/下午标记
* O - 与格林威治时间相差的小时数
* P - 与格林威治时间相差的小时数,小时和分钟之间有冒号分隔
* Z - 时区
*
* @return 格式化后的日期时间
*/
format(format: string): string;
}
declare var Date: DateConstructor;
/**
* 判断是否为闰年
*
* @return boolean
*/
Date.prototype.isLeapYear = function(): boolean {
const year = this.getFullYear();
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
/**
* 获取季节
*
* @return 季节
*/
Date.prototype.getSeason = function(): number {
const month = this.getMonth();
if (month >= 3 && month <= 5) {
return 0;
} else if(month >= 6 && month <= 8) {
return 1;
} else if(month >= 9 && month <= 11) {
return 2;
} else if(month >= 12 || month <= 2) {
return 3;
} else {
return 0;
}
}
/**
* 获取年份中的第几天
*
* @return 年份中的第几天
*/
Date.prototype.getDayOfYear = function(): number {
const month_days = this.isLeapYear() == true ? [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let days = this.getDate();
for (let m = 0; m < this.getMonth(); m++) {
days += month_days[m];
}
return days;
}
/**
* 获取年份总天数
*
* @return 年份总天数
*/
Date.prototype.getDaysOfYear = function(): number {
return this.isLeapYear() ? 366 : 365;
}
/**
* Format a date object into a string value.
* @param format string - the desired format of the date
*
* The format can be combinations of the following:
*
* y - 年
* n - 季度(1 到 4)
* N - 季度名称
* A - 季度中文名称
* M - 月
* f - 月(Jan 到 Dec)
* F - 月(January 到 December)
* C - 月,中文名称
* d - 日
* Y - 年份中的第几天(0 到 365)
* T - 月份有几天(28 到 30)
* j - 每月天数后面的英文后缀(st,nd,rd 或者 th)
* e - 星期几,数字表示,0(表示星期天)到 6(表示星期六)
* E - 星期几,数字表示,1(表示星期一)到 7(表示星期天)
* l - 星期几,文本表示,3 个字母(Mon 到 Sun)
* L - 星期几,完整的文本格式(Sunday 到 Saturday)
* w - 星期几,中文名称
* W - 一月中第几个星期几
* i - 月份中的第几周
* o - 年份中的第几周
* h - 小时(1~12)
* H - 小时(0~23)
* m - 分
* s - 秒
* S - 毫秒
* a - 上午/下午标记
* O - 与格林威治时间相差的小时数
* P - 与格林威治时间相差的小时数,小时和分钟之间有冒号分隔
* Z - 时区
*
* @return 格式化后的日期时间
*/
Date.prototype.format = function(format: string): string {
if (Object.isString(format) === false) {
throw "Invalid argument format";
}
const $this = this;
const _season_map = {
"N": ["Spring", "Summer", "Autumn", "Winter"],
"A": ["\u6625", "\u590f", "\u79cb", "\u51ac"]
};
const _month_map = {
"f": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
"F": ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
"C": ["\u4E00", "\u4E8C", "\u4E09", "\u56DB", "\u4E94", "\u516D", "\u4E03", "\u516B", "\u4E5D", "\u5341", "\u5341\u4E00", "\u5341\u4E8C"]
};
const _weekday_map = {
"W": ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
"WW": ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
"WC": ["\u65E5", "\u4E00", "\u4E8C", "\u4E09", "\u56DB", "\u4E94", "\u516D"]
};
const seasonFn = () => Math.floor(($this.getMonth() + 3) / 3);
const $funcs:Record<string, Function> = {
// 年
"y": function(pattern: string) {
console.debug("y => pattern: " + pattern);
return ($this.getFullYear() + "").substring(4 - pattern.length);
},
// 季度(1 到 4)
"n": function(pattern: string) {
console.debug("n => pattern: " + pattern);
return seasonFn();
},
// 季度名称
"N": function(pattern: string) {
console.debug("N => pattern: " + pattern);
const n = seasonFn() - 1;
return _season_map["N"][n];
},
// 季度中文名称
"A": function(pattern: string){
console.debug("A => pattern: " + pattern);
const n = seasonFn() - 1;
return _season_map["A"][n];
},
// 月
"M": function(pattern: string) {
console.debug("M => pattern: " + pattern);
const $month = $this.getMonth() + 1;
const result = $month < 10 ? "0" + $month : "" + $month;
return result.substring(2 - pattern.length);
},
// 月(Jan 到 Dec)
"f": function(pattern: string) {
console.debug("f => pattern: " + pattern);
const $month = $this.getMonth();
return _month_map["f"][$month];
},
// 月(January 到 December)
"F": function(pattern: string) {
console.debug("F => pattern: " + pattern);
const $month = $this.getMonth();
return _month_map["F"][$month];
},
// 月,中文名称
"C": function(pattern: string) {
console.debug("C => pattern: " + pattern);
const $month = $this.getMonth();
return _month_map["C"][$month];
},
// 星期数字,0 到 6 表示
"e": function(pattern: string) {
console.debug("e => pattern: " + pattern);
return $this.getDay();
},
// 星期数字,1 到 7 表示
"E": function(pattern: string) {
console.debug("E => pattern: " + pattern);
return $this.getDay() + 1;
},
// 星期英文缩写
"l": function(pattern: string) {
console.debug("l => pattern: " + pattern);
const $weekday = $this.getDay();
return _weekday_map["W"][$weekday];
},
// 星期英文全称
"L": function(pattern: string) {
console.debug("L => pattern: " + pattern);
const $weekday = $this.getDay();
return _weekday_map["WC"][$weekday];
},
// 星期中文名称
"w": function(pattern: string) {
console.debug("w => pattern: " + pattern);
const $weekday = $this.getDay();
return _weekday_map["WC"][$weekday];
},
// 日
"d": function(pattern: string) {
console.debug("d => pattern: " + pattern);
const $date = $this.getDate();
const result = $date < 10 ? "0" + $date : "" + $date;
return result.substring(2 - pattern.length);
},
// 小时
"h": function(pattern: string) {
console.debug("h => pattern: " + pattern);
const $hour = $this.getHours();
const result = $hour < 10 ? "0" + $hour : "" + $hour;
return result.substring(2 - pattern.length);
},
// 分钟
"m": function(pattern: string) {
console.debug("m => pattern: " + pattern);
const $minutes = $this.getMinutes();
const result = $minutes < 10 ? "0" + $minutes : "" + $minutes;
return result.substring(2 - pattern.length);
},
// 秒钟
"s": function(pattern: string) {
console.debug("s => pattern: " + pattern);
const $seconds = $this.getMinutes();
const result = $seconds < 10 ? "0" + $seconds : "" + $seconds;
return result.substring(2 - pattern.length);
},
// 毫秒
"S": function(pattern: string) {
console.debug("S => pattern: " + pattern);
const $mise = $this.getMilliseconds();
const result = $mise < 10 ? "0" + $mise : "" + $mise;
return result.substring(2 - pattern.length);
}
};
return format.replace(/([ynNAMfFCdYTjeElLwWiohHmsSaOPZ])+/g, function(all: string, t: string) {
const fn = $funcs[t];
if(Object.isFunction(fn) === true){
return fn(all);
}
return all;
});
}
|
#include<bits/stdc++.h>
#define _ ios_base::sync_with_stdio(0);
#define i64 long long
using namespace std;
i64 n, x, ans;
int main(){_
while (cin>>n>>x){
ans = 0;
for (int i=1; i<=n; i++){
ans += (x%i==0 && x/i<=n);
}
cout<<ans<<endl;
}
return 0;
}
|
/**
* Runs a matcher which implements the {@link IMatcherMultiSource} interface.
* @param matcher the matcher object
* @param ontologies this is a list of sets of objects where each sets contains different representations of the dame ontologies/ knowledge graph.
* @param inputAlignment the input alignment
* @param parameters the parameters
* @return alignment and parameters
* @throws Exception in case somethign goes wrong
*/
@SuppressWarnings("unchecked")
private static AlignmentAndParameters runIMatcherMultiSource(IMatcherMultiSource matcher, List<Set<Object>> ontologies, Object inputAlignment, Object parameters) throws Exception{
Method matchMethod = getIMatcherMultiSourceMethod(matcher.getClass());
if(matchMethod == null){
LOGGER.error("Could not find match method of object which implements IMatcher. The matcher is not called");
return null;
}
LOGGER.debug("Choosing the following method to extract the parameter types: {}", matchMethod);
Class<?>[] paramTypes = matchMethod.getParameterTypes();
Type[] genericParamTypes = matchMethod.getGenericParameterTypes();
ParameterizedType pType = (ParameterizedType) genericParamTypes[0];
Class<?> modelType = (Class<?>) pType.getActualTypeArguments()[0];
Properties p = TypeTransformerRegistry.getTransformedPropertiesOrNewInstance(parameters);
List<?> transformedModels = TypeTransformerRegistry.getTransformedListOfObjectsMultipleRepresentations(ontologies, modelType, p);
if(transformedModels == null)
return null;
Object transformedInputAlignment = null;
if(inputAlignment == null || inputAlignment.getClass() == Object.class){
try{
transformedInputAlignment = paramTypes[1].newInstance();
}catch(IllegalAccessException | InstantiationException | ExceptionInInitializerError | SecurityException ex){
LOGGER.warn("The optional inputAlignment parameter is null or object and thus a new instance of type {} was created which did not worked out (if you own the class, then you can add an empty constructor). Try to call the matcher with null value.", paramTypes[2], ex);
transformedInputAlignment = null;
}
}else{
transformedInputAlignment = TypeTransformerRegistry.getTransformedObject(inputAlignment, paramTypes[1], p);
if(transformedInputAlignment == null)
return null;
}
Object transformedParameter = null;
if(parameters == null || parameters.getClass() == Object.class){
try{
transformedParameter = paramTypes[2].newInstance();
}catch(IllegalAccessException | InstantiationException | ExceptionInInitializerError | SecurityException ex){
LOGGER.warn("The optional params parameter is null or object and thus a new instance of type {} was created which did not worked out (if you own the class, then you can add an empty constructor). Try to call the matcher with null value.", paramTypes[2], ex);
transformedParameter = null;
}
}else{
transformedParameter = TypeTransformerRegistry.getTransformedObject(parameters, paramTypes[2], p);
if(transformedParameter == null)
return null;
}
Object resultingAlignment = matcher.match(transformedModels, transformedInputAlignment, transformedParameter);
return new AlignmentAndParameters(resultingAlignment, transformedParameter);
} |
<reponame>EnderdracheLP/MultiplayerCore.Quest
#include "main.hpp"
#include "Beatmaps/Providers/MpBeatmapLevelProvider.hpp"
#include "Beatmaps/LocalBeatmapLevel.hpp"
#include "Beatmaps/NetworkBeatmapLevel.hpp"
//#include "Beatmaps/BeatSaverBeatmapLevel.hpp"
using namespace MultiplayerCore::Beatmaps;
using namespace GlobalNamespace;
#include "songloader/shared/API.hpp"
using namespace RuntimeSongLoader::API;
#include "songdownloader/shared/BeatSaverAPI.hpp"
using namespace BeatSaver::API;
namespace MultiplayerCore::Beatmaps::Providers {
/// <summary>
/// Gets an <see cref="GlobalNamespace::IPreviewBeatmapLevel*"/> for the specified level hash.
/// </summary>
/// <param name="levelHash">The hash of the level to get</param>
/// <returns>An <see cref="GlobalNamespace::IPreviewBeatmapLevel*"/> with a matching level hash</returns>
IPreviewBeatmapLevel* MpBeatmapLevelProvider::GetBeatmap(StringW levelHash) {
auto* beatmap = GetBeatmapFromLocalBeatmaps(levelHash);
if (beatmap)
return beatmap;
else {
return GetBeatmapFromBeatSaver(levelHash);
}
}
/// <summary>
/// Gets an <see cref="GlobalNamespace::IPreviewBeatmapLevel*"/> for the specified level hash from local, already downloaded beatmaps.
/// </summary>
/// <param name="levelHash">The hash of the level to get</param>
/// <returns>An <see cref="GlobalNamespace::IPreviewBeatmapLevel*"/> with a matching level hash</returns>
IPreviewBeatmapLevel* MpBeatmapLevelProvider::GetBeatmapFromLocalBeatmaps(StringW levelHash) {
std::optional<GlobalNamespace::CustomPreviewBeatmapLevel*> previewOpt = GetLevelByHash(levelHash);
if (!previewOpt) return nullptr;
return LocalBeatmapLevel::CS_Ctor(levelHash, previewOpt.value())->get_preview();
}
/// <summary>
/// Gets an <see cref="GlobalNamespace::IPreviewBeatmapLevel*"/> for the specified level hash from BeatSaver.
/// </summary>
/// <param name="levelHash">The hash of the level to get</param>
/// <returns>An <see cref="GlobalNamespace::IPreviewBeatmapLevel*"/> with a matching level hash, or null if none was found.</returns>
IPreviewBeatmapLevel* MpBeatmapLevelProvider::GetBeatmapFromBeatSaver(StringW levelHash) {
// std::optional<BeatSaver::Beatmap> beatmap = GetBeatmapByHash(static_cast<std::string>(levelHash));
// if (!beatmap) return nullptr;
// return BeatSaverBeatmapLevel(levelHash, beatmap.value());
return nullptr;
}
//{
// Beatmap ? beatmap = await _beatsaver.BeatmapByHash(levelHash);
// if (beatmap == null)
// return null;
// return new BeatSaverBeatmapLevel(levelHash, beatmap);
//}
/// <summary>
/// Gets an <see cref="GlobalNamespace::IPreviewBeatmapLevel*"/> from the information in the provided packet.
/// </summary>
/// <param name="packet">The packet to get preview data from</param>
/// <returns>An <see cref="GlobalNamespace::IPreviewBeatmapLevel*"/> with a cover from BeatSaver.</returns>
IPreviewBeatmapLevel* MpBeatmapLevelProvider::GetBeatmapFromPacket(MultiplayerCore::Beatmaps::Packets::MpBeatmapPacket* packet) {
return NetworkBeatmapLevel::New_ctor(packet)->get_preview();
}
//= > new NetworkBeatmapLevel(packet, _beatsaver);
} |
<reponame>notifi-network/notifi-sdk-ts<filename>packages/notifi-core/lib/models/TelegramTarget.ts<gh_stars>10-100
/**
* Target object for Telegram accounts
*
* @remarks
* Target object for Telegram accounts
*
* @property {string | null} id - Id of the TelegramTarget used later to be added into a TargetGroup
* @property {string | null} name - Friendly name (must be unique)
* @property {string | null} telegramId - Telegram account for the Target
* @property {boolean} isConfirmed - Is confirmed? After adding, it must be confirmed via Telegram app by the user
* @property {string | null} confirmationUrl - If not confirmed, use this URL to allow the user to start the Telegram bot
*
*/
export type TelegramTarget = Readonly<{
id: string | null;
isConfirmed: boolean;
name: string | null;
telegramId: string | null;
confirmationUrl: string | null;
}>;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.