text
stringlengths 27
775k
|
|---|
# TODO: should this work in v5?
return
Set-StrictMode -Version Latest
function f () {}
Mock f {}
Describe 'Mock at script scope' {
It 't' {
1 | Should -Be 1
}
}
|
#!/bin/bash
cd ~
git clone -b monolith https://github.com/express42/reddit.git
cd reddit
bundle install
# systemctl-ed
#puma -d
echo "[Unit]
Description=puma
[Service]
ExecStart=/usr/local/bin/puma -d
KillMode=process
User=appuser
WorkingDirectory=/home/appuser/reddit
[Install]
WantedBy=multi-user.target" > puma.service
cp puma.service /etc/systemd/system
systemctl daemon-reload
systemctl enable puma.service
# to startup-script:
#systemctl start puma.service
|
package com.dropbox.componentbox.samples.discovery.drawable
import com.dropbox.componentbox.foundation.Image
import com.dropbox.componentbox.foundation.Images
import com.dropbox.componentbox.foundation.RealImage
import com.dropbox.componentbox.foundation.RealMultiplatformRes
actual class DiscoveryImages : Images {
actual val placeholder: Image = RealImage(
name = "Placeholder",
light = RealMultiplatformRes("Placeholder.Light", "drawable-xhdpi/placeholder.webp"),
dark = RealMultiplatformRes("Placeholder.Dark", "drawable-night-xhdpi/placeholder.webp")
)
actual val trafficRoadBlocked: Image = RealImage(
name = "TrafficRoadBlocked",
light = RealMultiplatformRes("TrafficRoadBlocked.Light", "drawable-xhdpi/traffic_road_blocked.webp"),
dark = RealMultiplatformRes("TrafficRoadBlocked.Dark", "drawable-night-xhdpi/traffic_road_blocked.webp")
)
override fun list(): MutableList<Image> = mutableListOf(
placeholder,
trafficRoadBlocked
)
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace numl.AI.Collections
{
/// <summary>
/// A sorted data table.
/// </summary>
/// <typeparam name="TKey1">Parent key type.</typeparam>
/// <typeparam name="TKey2">Child key type.</typeparam>
/// <typeparam name="TValue">Value type.</typeparam>
public class SortedTable<TKey1, TKey2, TValue>
{
private readonly SortedDictionary<TKey1, SortedDictionary<TKey2, TValue>> _Table;
/// <summary>
/// Gets or sets the default table value.
/// </summary>
public TValue DefaultValue { get; set; }
/// <summary>
/// Returns all the keys in the current collection.
/// </summary>
public IEnumerable<TKey1> Keys
{
get { return this._Table.Keys; }
}
/// <summary>
/// Gets or sets the value for the key-key pair. Returns the default value if one is not found at the specified location.
/// </summary>
/// <param name="key1">Parent key.</param>
/// <param name="key2">Child key.</param>
/// <returns><typeparamref name="TValue"/>.</returns>
public TValue this[TKey1 key1, TKey2 key2]
{
get
{
if (key1 == null || key2 == null || !this._Table.ContainsKey(key1) || _Table[key1] == null)
return this.DefaultValue;
return this._Table[key1][key2];
}
set
{
if (this._Table[key1] == null)
this._Table[key1] = new SortedDictionary<TKey2, TValue>();
this._Table[key1][key2] = value;
}
}
/// <summary>
/// Default constructor.
/// </summary>
public SortedTable()
{
this._Table = new SortedDictionary<TKey1, SortedDictionary<TKey2, TValue>>();
this.DefaultValue = default(TValue);
}
/// <summary>
/// Returns all associated child keys for the parent key.
/// </summary>
/// <param name="key">Parent key.</param>
/// <returns>IEnumerable<<typeparamref name="TValue"/>></returns>
public IEnumerable<TKey2> GetKeys(TKey1 key)
{
return this._Table[key]?.Select(s => s.Key);
}
/// <summary>
/// Returns all child key-value pairs for the specified parent key.
/// </summary>
/// <param name="key">Parent key.</param>
/// <returns></returns>
public IEnumerable<KeyValuePair<TKey2, TValue>> GetPairs(TKey1 key)
{
return this._Table[key];
}
/// <summary>
/// Returns all values for the given parent key.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public IEnumerable<TValue> GetValues(TKey1 key)
{
return this._Table[key]?.Select(s => s.Value);
}
/// <summary>
/// Adds the specified parent key to the collection.
/// </summary>
/// <param name="key">Parent key to add.</param>
public void AddKey(TKey1 key)
{
if (!this._Table.ContainsKey(key))
this._Table.Add(key, new SortedDictionary<TKey2, TValue>());
}
/// <summary>
/// Adds or updates the paired value in the collection.
/// </summary>
/// <param name="key">Parent key.</param>
/// <param name="childKey">Child key.</param>
/// <param name="value">Value to add.</param>
public void AddOrUpdate(TKey1 key, TKey2 childKey, TValue value)
{
if (!this._Table.ContainsKey(key))
this._Table.Add(key, new SortedDictionary<TKey2, TValue>());
if (!this._Table[key].ContainsKey(childKey))
this._Table[key].Add(childKey, value);
else
this._Table[key][childKey] = value;
}
/// <summary>
/// Returns <c>True</c> if the specified key exists in the collection, otherwise <c>False</c>.
/// </summary>
/// <param name="key">Parent key.</param>
/// <returns>Boolean.</returns>
public bool ContainsKey(TKey1 key)
{
return this._Table.ContainsKey(key);
}
/// <summary>
/// Returns <c>True</c> if the specified keys exist in the collection, otherwise <c>False</c>.
/// </summary>
/// <param name="key">Parent key.</param>
/// <param name="childKey">Child key.</param>
/// <returns>Boolean.</returns>
public bool ContainsKey(TKey1 key, TKey2 childKey)
{
return this.ContainsKey(key) && this._Table[key].ContainsKey(childKey);
}
/// <summary>
/// Removes all child elements, including the parent, by the specified parent key.
/// </summary>
/// <param name="key">Parent key.</param>
public void Remove(TKey1 key)
{
this._Table.Remove(key);
}
/// <summary>
/// Removes only the value at the specified location.
/// </summary>
/// <param name="key">Parent key.</param>
/// <param name="childKey">Child key.</param>
public void Remove(TKey1 key, TKey2 childKey)
{
if (this._Table.ContainsKey(key))
this._Table[key].Remove(childKey);
}
}
}
|
---
layout: article
title: "「Python」 multiprocessing:像线程一样管理进程"
date: 2019-01-16 10:07:40 +0800
key: py-multiprocessing-20190116
aside:
toc: true
category: [software, python, pystl]
---
<span id='head'></span>
## 什么是 Multiprocessing
## 添加进程 Process
## 存储进程输出 Queue
## 效率对比 threading & multiprocessing
## 进程池 Pool
[map 示例](#map_code),[apply_async 示例](#apply_async_code),[map 测试](#map_test)
## 共享内存 shared memory
## 进程锁 Lock
-------------------
[End](#head)
{:.warning}
# 附录
## A 示例
<span id="map_code">**1. map 示例**</span>
原始代码:
```python
def worker(id):
return id**2
def Demo(length):
for i in range(length):
worker(i)
```
进程池代码:
```python
def poolDemo(length):
p = Pool(processes=4) # processes 默认是 cpu 核的个数,也是并行能力的上线;在上线范围内,核数越多,速度越快
res = p.map(worker, list(range(length))) # 取代 for 循环,res 是返回值
p.close()
p.join()
return res
def main():
res = poolDemo(10)
print(res)
```
`close join 这两句到底是什么意思,可有可无?`{:.warning}
*注:测试时建议用 IO 来测试;数学运算要达到较高数量级后才能体现多进程的优势;*
<span id="apply_async_code">**1. apply_async 示例**</span>
原始代码:
```python
def worker(id):
return id**2
def Demo(length):
for i in range(length):
worker(i)
```
进程池代码:
```python
def poolDemo(length):
p = Pool(processes=4) # processes 默认是 cpu 核的个数,也是并行能力的上线;在上线范围内,核数越多,速度越快
multi_res = [p.apply_async(worker, (i,)) for i in range(length)] # 取代 for 循环,res 是返回值
p.close()
p.join()
return [res.get() for res in multi_res]
def main():
res = poolDemo(10)
print(res)
```
## B 实验
<span id="map_test">**1. map IO 测试**</span>
使用 map 多进程进行文件读写测试:
`大小为 40M 的 txt 文件, 20000 行数据;`
**实验结论**:
- 读操作,并行越多越好;
- 写操作,并行路数在 80 左右最好;
- 写操作时,无论是否使用并行,当进行覆盖写文件时,耗时变长;尤其是这个写覆盖操作会让并行操作失效;
**实验结果**:
| 循环读取次数(次) | 串行执行耗时(秒) | 多进程(秒) | 平均单次耗时(秒) | 提升(倍) |
| --- | --- | --- | --- | --- |
| 1 | 0.158 | 0.216 | | |
| 5 | 0.798 | 0.413 | 0.082 | 1.9 |
| 10 | 1.589 | 0.613 | 0.061 | 2.56 |
| 15 | 2.39 | 1.02 | 0.068 | 2.34 |
| 20 | 3.12 | 1.217 | 0.06 | 2.56 |
| 40 | 6.472 | 2.22s | 0.055 | 2.9 |
| 80 | 12 | 3.935 | 0.049 | 3.5 |
| 160 | 25.38 | 7.33s | 0.045 | 3.46 |
| 循环读&写次数(次) | 串行执行耗时(秒) | 多进程(秒) | 平均单次耗时(秒) | 提升(倍) | **写覆盖**耗时(秒) |
| --- | --- | --- | --- | --- | --- |
| 1 | 0.185 | 0.212 | | | 0.195 |
| 5 | 0.921 | 0.525 | 0.10 | 1.7 | 0.96 |
| 10 | 1.85 | 0.81 | 0.081 | 2.3 | 2 |
| 15 | 2.7 | 1.1 | 0.073 | 2.45 | 3 |
| 20 | 3.72 | 1.417 | 0.07 | 2.62 | 4.6 |
| 40 | 7.376 | 2.53 | 0.063 | 2.9 | 10 |
| 80 | 14.9 | 4.74 | 0.059 | 3.1 | 19 |
| 160 | 31.0 | 19 | 0.118 | 1.6 | 44 |
## C 参考资料
1. Doug Hellmann 著, 苏金国, et al 译. Python3 标准库[M]. 北京:机械工业出版社, 2018.
|
import { ParseMonth } from '../src';
describe('Month utilities tests', () => {
it('ParseMonth(1, "en") should returns January while ParseMonth(24, "en") returns 24', () => {
expect(ParseMonth(1, 'en')).toEqual('January');
expect(ParseMonth(24, 'en')).toEqual(24);
});
});
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import hypothesis.strategies as st
from hypothesis import given
import numpy as np
from caffe2.proto import caffe2_pb2
from caffe2.python import (
brew,
core,
model_helper,
workspace,
)
from caffe2.python.transformations import optimizeForMKLDNN
import caffe2.python.hypothesis_test_util as hu
@unittest.skipIf(not workspace.C.use_mkldnn, "No MKLDNN support.")
class PreConvertTest(hu.HypothesisTestCase):
@given(input_channels=st.integers(15, 16),
batch_size=st.integers(1, 3))
def test_preConvert(self, input_channels, batch_size):
def AddModel(model, data):
conv1 = brew.conv(model, data, 'conv1', dim_in=input_channels,
dim_out=10, kernel=3, stride=1, pad=1, training_mode=1)
deconv1 = brew.conv_transpose(model, conv1, 'deconv1', dim_in=10, dim_out=10,
kernel=2, stride=2, pad=0, training_mode=1)
fc1 = brew.fc(model, deconv1, 'fc1', dim_in=10 * 56 * 56, dim_out=3)
softmax = brew.softmax(model, fc1, 'softmax')
return softmax
def AddTrainingOperators(model, softmax, label):
"""Adds training operators to the model."""
# Compute cross entropy between softmax scores and labels
xent = model.LabelCrossEntropy([softmax, label], 'xent')
# Compute the expected loss
loss = model.AveragedLoss(xent, "loss")
# Use the average loss we just computed to add gradient operators to the model
model.AddGradientOperators([loss])
arg_scope = {"order": "NCHW", 'no_bias': False}
# Create the model helper for the train model
device_opt = core.DeviceOption(caffe2_pb2.IDEEP, 0)
with core.DeviceScope(device_opt):
train_model = model_helper.ModelHelper(name="test_train", arg_scope=arg_scope)
# Add the model definition (fc layers, conv layers, softmax, etc.)
softmax = AddModel(train_model, "X")
AddTrainingOperators(train_model, softmax, "label")
X = np.random.rand(
batch_size, input_channels, 28, 28).astype(np.float32) - 0.5
label = np.random.randint(3, size=batch_size).astype(np.int32)
blob_dict = {}
output_dict = {}
output_dict_cosim = {}
old_ws_name = workspace.CurrentWorkspace()
workspace.FeedBlob('X', X)
workspace.FeedBlob('label', label)
workspace.RunNetOnce(train_model.param_init_net)
for op in train_model.net.Proto().op:
if op.type == "Softmax":
break
for j in range(1, len(op.input)):
blob_dict[op.input[j]] = workspace.FetchBlob(op.input[j])
workspace.CreateNet(train_model.net, overwrite=True)
optimizeForMKLDNN(train_model.net, training_mode=True)
workspace.RunNet(train_model.net)
for op in train_model.net.Proto().op:
for blob in op.output:
output_dict[blob] = workspace.FetchBlob(blob)
workspace.SwitchWorkspace("_device_check_", True)
workspace.FeedBlob('X', X)
workspace.FeedBlob('label', label)
for blob in blob_dict.keys():
workspace.FeedBlob(blob, blob_dict[blob])
workspace.CreateNet(train_model.net, overwrite=True)
workspace.RunNet(train_model.net)
for blob in output_dict.keys():
output_dict_cosim[blob] = workspace.FetchBlob(blob)
for blob in output_dict.keys():
if not np.allclose(output_dict[blob], output_dict_cosim[blob], atol=0.001, rtol=0.0001):
print("blob {} error".format(blob))
print(np.max(np.abs(output_dict[blob] - output_dict_cosim[blob])))
self.assertTrue(False)
workspace.ResetWorkspace()
workspace.SwitchWorkspace(old_ws_name)
if __name__ == "__main__":
unittest.main()
|
import React from 'react';
import { Box } from 'grommet';
import { MarkdownTemplate } from '../../components/MarkdownTemplate';
import Page from '../../components/Page';
const children = `
### deepMerge
A function that recieves two theme objects and returns a theme object that includes
both theme values.
In case different styling are found for the same components on the two themes, the second argument theme will determine the styling.
\`\`\`
import { deepMerge } from 'grommet/utils';
const myCustomTheme = deepMerge(grommet, {
global: {
colors: {
brand: 'red',
},
},
});
const CustomPrimaryButton = () => (
<Grommet theme={myCustomTheme}>
<Box align="center" pad="large" gap="small">
<Button primary label="deepMerge custom button" onClick={() => {}} />
</Box>
<Text>
The Button font is taken from the grommet theme, while its
brand color is taken from myCustomTheme.
</Text>
</Grommet>
);
\`\`\`
`;
export default () => (
<Page>
<Box width="xlarge" alignSelf="center">
<MarkdownTemplate name="Functions" desc="">
{children}
</MarkdownTemplate>
</Box>
</Page>
);
|
# java-tetris-game
Classic Tetris with:
DAS(using KeyListener delay),
Hard Drop,
Ghost Piece,
Hold Piece
|
<?php
/**
* Function to validate usernames from pr0gramm.com
* @see https://github.com/RundesBalli/regex-functions/blob/master/pr0gramm/validUsername.php
*
* @param string The username to be checked.
*
* @return string/boolean On success the validated username will be returned, if not FALSE.
*/
function validUsername($username) {
$regex = '/^[a-zA-Z0-9-_]{2,32}$/';
return (preg_match($regex, trim($username), $matches) === 1) ? $matches[0] : FALSE;
}
?>
|
# 44. Helm 模板使用
上节课和大家一起学习了`Helm`的一些常用操作方法,这节课来和大家一起定义一个`chart`包,了解 Helm 中模板的使用方法。
## 定义 chart
Helm 的 github 上面有一个比较[完整的文档](https://github.com/kubernetes/helm/blob/master/docs/charts.md),建议大家好好阅读下该文档,这里我们来一起创建一个`chart`包。
一个 chart 包就是一个文件夹的集合,文件夹名称就是 chart 包的名称,比如创建一个 hello-world 的 chart 包:
```shell
$ mkdir ./hello-world
$ cd hello-world
```
chart 必须包含定义文件`Chart.yaml`文件,定义文件必须定义两个属性:`name`和`version`(Semantic Versioning 2):
```shell
$ cat <<'EOF' > ./Chart.yaml
name: hello-world
version: 1.0.0
EOF
```
一个 chart 包必须定义用来生成`kubernetes`资源对象的模板文件,这些模板文件定义在 templates 目录下面,这里我们来尝试使用 helm 自定义一个 nginx 服务:
```shell
$ mkdir ./templates
$ cat <<'EOF' > ./templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: hello-world
spec:
replicas: 1
selector:
matchLabels:
app: hello-world
template:
metadata:
labels:
app: hello-world
spec:
containers:
- name: hello-world
image: nginx:1.7.9
ports:
- containerPort: 80
protocol: TCP
EOF
$ cat <<'EOF' > ./templates/service.yaml
apiVersion: v1
kind: Service
metadata:
name: hello-world
spec:
type: NodePort
ports:
- port: 80
targetPort: 80
protocol: TCP
selector:
app: hello-world
EOF
```
上面我们定义的模板是最终一个`release`实例需要运行的资源对象,一个`Deployment`对象,一个`Service`对象,也是以前我们运行一个 nginx 服务需要的两个资源对象。
## 配置 release
上节课我们学习了管理一个 release 整个生命周期的一些方法,install、rollback、upgrade 以及 delete 等等操作,但是仅仅这些命令还不够,我们还需要一些工具来管理`release`。
Helm Chart 模板使用的是[`Go`语言模板](https://golang.org/pkg/text/template/)编写而成,并添加了[`Sprig`库](https://github.com/Masterminds/sprig)中的50多个附件模板函数以及一些其他[特殊的函](https://github.com/kubernetes/helm/blob/master/docs/charts_tips_and_tricks.md)。
模板的值通过`values.yaml`文件提供,现在我们来定义一个`values.yaml`文件,提供 image 镜像的仓库配置:
```shell
$ cat <<'EOF' > ./values.yaml
image:
repository: nginx
tag: 1.7.9
EOF
```
现在我们就可以通过模板中的`.Values`对象来访问`values.yaml`文件提供的值。比如我们将上面的`templates/deployment.yaml`文件中的`image`镜像地址通过`values.yaml`中的`image`对象来替换掉:
```shell
$ cat <<'EOF' > ./templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: hello-world
spec:
replicas: 1
selector:
matchLabels:
app: hello-world
template:
metadata:
labels:
app: hello-world
spec:
containers:
- name: hello-world
image: {{ .Values.image.repository }}:{{ .Values.image.tag }}
ports:
- containerPort: 80
protocol: TCP
EOF
```
## 调试
现在我们的模板文件已经定义好了,但是如果我们想要调试还是非常不方便的,不可能我们每次都去部署一个`release`实例来校验模板是否正确,为此 Helm 为我们提供了`--dry-run --debug`这个可选参数,在执行`helm install`的时候带上这两个参数就可以把对应的 values 值和生成的最终的资源清单文件打印出来,而不会真正的去部署一个`release`实例,比如我们来调试上面创建的 chart 包:
```shell
$ helm install . --dry-run --debug --set image.tag=latest
[debug] Created tunnel using local port: '38359'
[debug] SERVER: "127.0.0.1:38359"
[debug] Original chart version: ""
[debug] CHART PATH: /root/course/kubeadm/helm/hello-world
NAME: calling-turkey
REVISION: 1
RELEASED: Fri Sep 7 23:57:45 2018
CHART: hello-world-1.0.0
USER-SUPPLIED VALUES:
image:
tag: latest
COMPUTED VALUES:
image:
repository: nginx
tag: latest
HOOKS:
MANIFEST:
---
# Source: hello-world/templates/service.yaml
apiVersion: v1
kind: Service
metadata:
name: hello-world
spec:
type: NodePort
ports:
- port: 80
targetPort: 80
protocol: TCP
selector:
app: hello-world
---
# Source: hello-world/templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: hello-world
spec:
replicas: 1
selector:
matchLabels:
app: hello-world
template:
metadata:
labels:
app: hello-world
spec:
containers:
- name: hello-world
image: nginx:latest
ports:
- containerPort: 80
protocol: TCP
```
注意看上面的镜像地址已经被替换成了**nginx:latest**了,这是因为我们用`--set`参数把镜像的 tag 给覆盖掉了,而镜像名称已经被 values.yaml 中的内容替换掉了。
现在我们使用`--dry-run`就可以很容易地测试代码了,不需要每次都去安装一个 release 实例了,但是要注意的是这不能确保 Kubernetes 本身就一定会接受生成的模板,在调试完成后,还是需要去安装一个实际的 release 实例来进行验证的。
## 预定义值
除了使用用户定义的值外,Helm 还内置了许多预定义的值,我们可以在 [Helm 的文档中进行查看]((https://github.com/kubernetes/helm/blob/master/docs/charts.md#predefined-values),比如chang'y常用的有:
* .Release,这个对象描述了 release 本身,提供了比如:.Release.Name(release 名称)、.Release.Time(release 的时间)
* .Chart,表示`Chart.yaml`文件的内容。所有的 Chart 对象都将从该文件中访问。chart 指南中[Charts Guide](https://github.com/kubernetes/helm/blob/master/docs/charts.md#the-chartyaml-file)列出了可用字段,可以前往查看。
* Files:用于引用 Chart 目录中的其他文件。
现在我们来使用预定义的值给上面的资源文件定义一些标签,让我们可以很方便的识别出资源:
```shell
$ cat <<'EOF' > ./templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ printf "%s-%s" .Release.Name .Chart.Name | trunc 63 }}
labels:
app: {{ printf "%s-%s" .Release.Name .Chart.Name | trunc 63 }}
version: {{ .Chart.Version }}
release: {{ .Release.Name }}
spec:
replicas: 1
selector:
matchLabels:
app: {{ printf "%s-%s" .Release.Name .Chart.Name | trunc 63 }}
version: {{ .Chart.Version }}
release: {{ .Release.Name }}
template:
metadata:
labels:
app: {{ printf "%s-%s" .Release.Name .Chart.Name | trunc 63 }}
version: {{ .Chart.Version }}
release: {{ .Release.Name }}
spec:
containers:
- name: hello-world
image: {{ .Values.image.repository }}:{{ .Values.image.tag }}
ports:
- containerPort: 80
protocol: TCP
EOF
$ cat <<'EOF' > ./templates/service.yaml
apiVersion: v1
kind: Service
metadata:
name: {{ printf "%s-%s" .Release.Name .Chart.Name | trunc 63 }}
labels:
app: {{ printf "%s-%s" .Release.Name .Chart.Name | trunc 63 }}
version: {{ .Chart.Version }}
release: {{ .Release.Name }}
spec:
type: NodePort
ports:
- port: 80
targetPort: 80
protocol: TCP
selector:
app: {{ printf "%s-%s" .Release.Name .Chart.Name | trunc 63 }}
EOF
```
我们这里使用`.Release.Name`并上`.Chart.Name`来做为资源的名称:
```
{{ printf "%s-%s" .Release.Name .Chart.Name | trunc 63 }}
```
这里我们加上了一个63个字符的截断,这是因为`kubernetes`资源对象的 labels 和 name 定义被[限制为 63个字符](http://kubernetes.io/docs/user-guide/labels/#syntax-and-character-set),所以需要注意名称的定义长度。
## 模板引用
我们上面定义的模板文件中,可能有的人已经发现了,我们的 labels 定义以及资源名称的定义很多都是重复的:
```yaml
app: {{ printf "%s-%s" .Release.Name .Chart.Name | trunc 63 }}
version: {{ .Chart.Version }}
release: {{ .Release.Name }}
```
我们在 Deployment、Pod、Service 资源对象中都定义了3个相同的 label 标签,而资源名称都是一个比较长的表达式:
```yaml
{{ printf "%s-%s" .Release.Name .Chart.Name | trunc 63 }}
```
如果应用程序非常复杂的话,这种重复的属性就更多了,这显然不是一种很好的方式,如果我们去掉这些 label 标签呢?当然可以,但是这对于资源对象的辨别就会显得困难了。这里我们可以定义一些模板文件来进行引用,就可以很好的解决这个问题。
创建一个`_helpers.tpl`文件用来声明模板中的一部分内容:
> 主意:./templates 目录中已`_`开头的文件不会被看做 kubernetes 的资源清单文件,这些文件不会被发送到 kubernetes 中去。
```shell
$ cat <<'EOF'> ./templates/_helpers.tpl
{{- define "hello-world.release_labels" }}
app: {{ printf "%s-%s" .Release.Name .Chart.Name | trunc 63 }}
version: {{ .Chart.Version }}
release: {{ .Release.Name }}
{{- end }}
{{- define "hello-world.full_name" -}}
{{- printf "%s-%s" .Release.Name .Chart.Name | trunc 63 -}}
{{- end -}}
EOF
```
上面的文件中我们就定义了两个模块:**hello-world.release_labels**和**hello-world.full_name**,这两个模块都可以在模板中进行使用:
> 模板名称都是全局的。由于子 chart 中的模板与顶级模板一起编译,所以需要注意 chart 的命名,这也是为什么
```shell
$ cat <<'EOF' > ./templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ template "hello-world.full_name" . }}
labels:
{{- include "hello-world.release_labels" . | indent 4 }}
spec:
replicas: 1
selector:
matchLabels:
{{- include "hello-world.release_labels" . | indent 6 }}
template:
metadata:
labels:
{{- include "hello-world.release_labels" . | indent 8 }}
spec:
containers:
- name: hello-world
image: {{ .Values.image.repository }}:{{ .Values.image.tag }}
ports:
- containerPort: 80
protocol: TCP
EOF
$ cat <<'EOF' > ./templates/service.yaml
apiVersion: v1
kind: Service
metadata:
name: {{ template "hello-world.full_name" . }}
labels:
{{- include "hello-world.release_labels" . | indent 4 }}
spec:
type: NodePort
ports:
- port: 80
targetPort: 80
protocol: TCP
selector:
app: {{ template "hello-world.full_name" . }}
EOF
```
|
extern crate iron;
extern crate staticfile;
extern crate mount;
use std::io::net::ip::Ipv4Addr;
use iron::{Iron, ServerT, Chain};
use staticfile::Static;
use mount::Mount;
fn main() {
let mut server: ServerT = Iron::new();
// Serve core documentation
server.chain.link(Mount::new("/core", Static::new(Path::new("core/doc/"))));
// Serve core's index.html (from iron)
server.chain.link(Mount::new("/core", Static::new(Path::new("core/doc/iron/"))));
// Serve Iron documentation
server.chain.link(Static::new(Path::new("iron/doc/")));
// Serve Iron's index.html
server.chain.link(Static::new(Path::new("iron/doc/iron/")));
server.listen(Ipv4Addr(127, 0, 0, 1), 80);
}
|
import os
from pathlib import Path
import sys
import supervisely_lib as sly
import pickle
from dotenv import load_dotenv # pip install python-dotenv\
load_dotenv("../debug.env")
load_dotenv("../secret_debug.env", override=True)
my_app = sly.AppService()
api = my_app.public_api
task_id = my_app.task_id
team_id = int(os.environ['context.teamId'])
workspace_id = int(os.environ['context.workspaceId'])
project_id = int(os.environ['modal.state.slyProjectId'])
project_info = api.project.get_info_by_id(project_id)
if project_info is None: # for debug
raise ValueError(f"Project with id={project_id} not found")
# sly.fs.clean_dir(my_app.data_dir) # for debug
project_dir = os.path.join(my_app.data_dir, "visualize_fairMOT")
project_meta = sly.ProjectMeta.from_json(api.project.get_meta(project_id))
model_meta = None
temp_files = os.path.join(project_dir, "temp_files")
if os.path.exists(temp_files): # clean temp
sly.fs.clean_dir(temp_files)
converted_dir = os.path.join(temp_files, "converted_input")
sly.fs.mkdir(converted_dir)
projects_dir = os.path.join(temp_files, "projects")
sly.fs.mkdir(projects_dir)
checkpoints_dir = os.path.join(temp_files, "checkpoints")
sly.fs.mkdir(checkpoints_dir)
local_info_dir = os.path.join(temp_files, "info")
sly.fs.mkdir(local_info_dir)
grid_video_dir = os.path.join(temp_files, "grid_video")
sly.fs.mkdir(grid_video_dir)
output_dir = os.path.join(project_dir, "output_results")
if os.path.exists(output_dir): # clean output
sly.fs.clean_dir(output_dir)
else:
sly.fs.mkdir(output_dir)
root_source_dir = str(Path(os.path.abspath(sys.argv[0])).parents[3])
sly.logger.info(f"Root source directory: {root_source_dir}")
sys.path.append(root_source_dir)
source_path = str(Path(sys.argv[0]).parents[0])
sly.logger.info(f"App source directory: {source_path}")
sys.path.append(source_path)
ui_sources_dir = os.path.join(source_path, "ui")
sly.logger.info(f"UI source directory: {ui_sources_dir}")
sys.path.append(ui_sources_dir)
sly.logger.info(f"Added to sys.path: {ui_sources_dir}")
fair_mot_src = os.path.join(root_source_dir, "src")
sys.path.append(fair_mot_src)
def dump_req(req_objects, filename):
save_path = os.path.join(my_app.data_dir, 'dumps')
os.makedirs(save_path, exist_ok=True)
save_path = os.path.join(save_path, filename)
with open(save_path, 'wb') as dump_file:
pickle.dump(req_objects, dump_file)
def load_dumped(filename):
load_path = os.path.join(my_app.data_dir, 'dumps', filename)
with open(load_path, 'rb') as dumped:
return pickle.load(dumped)
def get_files_paths(src_dir, extensions):
files_paths = []
for root, dirs, files in os.walk(src_dir):
for extension in extensions:
for file in files:
if file.endswith(extension):
file_path = os.path.join(root, file)
files_paths.append(file_path)
return files_paths
|
import { useState, useEffect } from "react";
function useInterval(cb, intervalDuration, startImmediate = false) {
const [intervalId, setIntervalId] = useState(null);
const [isRunning, setIsRunning] = useState(startImmediate);
function start() {
setIsRunning(true);
}
function stop() {
if (isRunning) {
setIsRunning(false);
}
}
useEffect(() => {
if (isRunning) {
const _intervalId = setInterval(cb, intervalDuration);
setIntervalId(_intervalId);
return () => {
clearInterval(_intervalId);
};
}
}, [isRunning]);
return {
start,
stop,
intervalId
};
}
export default useInterval;
|
package Environment;
use strict;
use warnings;
use Module::Path qw/module_path/;
use Path::Class;
use Moose;
use namespace::autoclean;
sub distribution_base_path {
my $that = shift;
my $this_path = module_path(__PACKAGE__);
my $file = file( $this_path );
my $file_dir = $file->parent;
my $distribution_base_path = file( $file_dir . '/../../' );
return $distribution_base_path;
}
sub distribution_path {
my $that = shift;
my $sub_directory_name = shift;
my $distribution_directory_path = join( '/' , $that->distribution_base_path , $sub_directory_name );
return $distribution_directory_path;
}
# TODO : add code to automatically generate methods given a key => path mapping
sub distribution_bin {
my $that = shift;
return $that->distribution_path( "bin" );
}
# TODO : automatically generate based on distribution directories ?
sub summarizers_base {
my $that = shift;
return $that->distribution_path( 'summarizers' );
}
sub third_party_base {
my $that = shift;
return $that->distribution_path( 'third-party' );
}
sub third_party_local {
my $that = shift;
return join( "/" , $that->third_party_base , 'local' );
}
sub third_party_local_bin {
my $that = shift;
return $that->distribution_path( 'third-party/local/bin' );
}
sub data_base {
my $that = shift;
return $that->distribution_path( 'data' );
}
# TODO : specification of data_base is redundant
sub data_bin {
my $that = shift;
return $that->distribution_path( 'data/bin/' );
}
sub data_models_base {
my $that = shift;
return $that->distribution_path( 'data/models' );
}
sub summarizer_base {
my $that = shift;
my $summarizer_id = shift;
return $that->distribution_path( "summarizers/${summarizer_id}" );
}
sub evaluation_bin {
my $that = shift;
return $that->distribution_path( "evaluation/bin" );
}
__PACKAGE__->meta->make_immutable;
1;
|
import { ReactElement } from "react";
import { Box } from "@chakra-ui/core";
import { styles } from "@/src/constants";
function Wrapper(
props: React.PropsWithChildren<React.ReactNode>
): ReactElement {
return (
<>
<Box paddingX={styles.paddingX} maxWidth="1640px" margin="0 auto">
{props.children}
</Box>
</>
);
}
export default Wrapper;
|
---
name: 🖊ODP Vote
about: To track ODP votes
---
## Vote
I am requesting a vote to ...
Do you approve ... ?
## Reactions
- 👍 Approve
- 👎 Deny (please add comment explaining why)
- 👀 Abstain (please add comment explaining why)
## Due to
I'd ask you to cast your vote with 72h (3 days).
## Binding votes
- @maoo
- @mcleo-d
- @bingenito
- @tschady
|
class RestaurantDetail {
RestaurantDetail({
this.error,
this.message,
this.restaurant,
});
bool error;
String message;
Restaurant restaurant;
factory RestaurantDetail.fromJson(Map<String, dynamic> json) =>
RestaurantDetail(
error: json["error"],
message: json["message"],
restaurant: Restaurant.fromJson(json["restaurant"]),
);
}
class Restaurant {
Restaurant({
this.id,
this.name,
this.description,
this.city,
this.address,
this.pictureId,
this.categories,
this.menus,
this.rating,
this.customerReviews,
});
String id;
String name;
String description;
String city;
String address;
String pictureId;
List<Category> categories;
Menus menus;
double rating;
List<CustomerReview> customerReviews;
factory Restaurant.fromJson(Map<String, dynamic> json) => Restaurant(
id: json["id"] == null ? null : json["id"],
name: json["name"] == null ? null : json["name"],
description: json["description"] == null ? null : json["description"],
city: json["city"] == null ? null : json["city"],
address: json["address"] == null ? null : json["address"],
pictureId: json["pictureId"] == null ? null : json["pictureId"],
categories: json["categories"] == null
? null
: List<Category>.from(
json["categories"].map((x) => Category.fromJson(x))),
menus: json["menus"] == null ? null : Menus.fromJson(json["menus"]),
rating: json["rating"] == null ? null : json["rating"].toDouble(),
customerReviews: json["customerReviews"] == null
? null
: List<CustomerReview>.from(
json["customerReviews"].map((x) => CustomerReview.fromJson(x))),
);
}
class Category {
Category({
this.name,
});
String name;
factory Category.fromJson(Map<String, dynamic> json) => Category(
name: json["name"] == null ? null : json["name"],
);
}
class CustomerReview {
CustomerReview({
this.name,
this.review,
this.date,
});
String name;
String review;
String date;
factory CustomerReview.fromJson(Map<String, dynamic> json) => CustomerReview(
name: json["name"] == null ? null : json["name"],
review: json["review"] == null ? null : json["review"],
date: json["date"] == null ? null : json["date"],
);
}
class Menus {
Menus({
this.foods,
this.drinks,
});
List<Category> foods;
List<Category> drinks;
factory Menus.fromJson(Map<String, dynamic> json) => Menus(
foods: json["foods"] == null
? null
: List<Category>.from(
json["foods"].map((x) => Category.fromJson(x))),
drinks: json["drinks"] == null
? null
: List<Category>.from(
json["drinks"].map((x) => Category.fromJson(x))),
);
}
|
# State access
## Readonly
### brightness
Returns color brightness from 0 to 255. (It based RGB)
> [Color contrast](https://www.w3.org/TR/AERT/#color-contrast)
Syntax
``` ts
mooColor.brightness: number;
```
- @returns `number` - 0-255
### isLight
Returns whether color is light or not.
Syntax
``` ts
mooColor.isLight: boolean;
```
- @returns `boolean`
### isDark
Returns whether color is dark or not.
Syntax
``` ts
mooColor.isDark: boolean;
```
- @returns `boolean`
### luminance
Returns luminance value of the color. range from 0 to 1.
> [Relative luminance](https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef)
Syntax
``` ts
mooColor.luminance: number;
```
- @returns `number` - 0 to 1.
## Methods
### contrastRatioWith
Returns contrast ratio with other color. range from 0 to 21.
> [Relative luminance](https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef)
Syntax
``` ts
mooColor.contrastRatioWith(color: Color): number;
```
- @param [`Color`](setter.md#color-data) color - The target color for compare.
- @returns `number` - 0 to 21.
### isContrastEnough
Return true if contrast ratio >= 4.5
> [Contrast (minimum)](https://www.w3.org/WAI/WCAG20/quickref/#qr-visual-audio-contrast-contrast)
Syntax
``` ts
mooColor.isContrastEnough(color: Color): boolean;
```
- @param [`Color`](setter.md#color-data) color - The target color for compare.
- @returns `boolean`
|
import { Entity, Column, PrimaryColumn, OneToMany } from 'typeorm'
import { Comment } from 'src/comments/entities/comment.entity'
import { Favorite } from 'src/favorites/entities/favorite.entity'
@Entity('users')
export class User {
@PrimaryColumn()
id: string
@Column()
displayName: string
@Column()
email: string
@OneToMany(() => Favorite, (favorite) => favorite.user)
favorites: Favorite[]
@OneToMany(() => Comment, (comment) => comment.id)
comments: Comment[]
}
|
import numpy
import scipy
import scipy.stats
MEASURES = [
# Measures from trace files (.exp)
'ClientGlobalRank',
'ClientDataAccessTimeAccumulated',
'ClientLockingTimeAccumulated',
'ClientLocksNL',
'ClientLocksIS',
'ClientLocksIX',
'ClientLocksS',
'ClientLocksSIX',
'ClientLocksX',
'ClientTotalLocks',
'ClientRemoteLocks',
'ClientLocalLocks',
'ClientDeniedLocks',
'ClientGrantedLocks',
'ClientLockRequestTotalTime',
'ClientLockRequestNetworkTime',
'ClientLockRequestQueueingTime',
'ClientLockRequestServerTime',
'ClientVotingTimeAccumulated',
'ClientTotalVotes',
'ClientVotesYes',
'ClientVotesNo',
'ClientEndingTimeAccumulated',
'ClientTotalTransactions',
'ClientTransactionsCommitted',
'ClientTransactionsAborted',
'ClientNewOrderTransactions',
'ClientNewOrderTransactionsCommitted',
'ClientServersContacted',
'ClientExecutionTime',
# Measures added by round-trip to feather
'index',
# Measures added by scripts
'ClientDataAccessTimePerTx',
'ClientEndingTimePerTx',
'ClientExecutionTimePerTx',
'ClientLockRequestNetworkTimePerLock',
'ClientLockRequestQueueingTimePerLock',
'ClientLockRequestServerTimePerLock',
'ClientLockingTimePerTx',
'ClientOtherTimePerTx',
'ClientServersContactedPerTx',
'ClientVotingTimePerTx',
'ClientVotingTimePerVote',
'SystemCommitRate',
'SystemLockingThroughput',
'SystemNewOrderTransactionThroughput',
'SystemSuccessfulTransactionThroughput',
'SystemSuccessfulNewOrderTransactionThroughput',
'SystemTransactionThroughput',
]
MEASURES = MEASURES +\
[m + " mean" for m in MEASURES] + \
[m + " count" for m in MEASURES] + \
[m + " ci950" for m in MEASURES]
DIMENSIONS = [
'distribution',
'isolation_mode',
'mechanism',
'network_delay',
'num_cores',
'num_cores_per_node',
'num_nodes',
'num_server_agents',
'num_server_agents_per_node',
'num_tx_agents',
'num_tx_agents_per_node',
'num_warehouses',
'option1',
'option2',
'percent_remote',
'workload',
'__filename',
]
def summarize(df):
unkown_columns = [c for c in df.columns.values if c not in MEASURES + DIMENSIONS]
if unkown_columns:
raise RuntimeError('Unknown columns "{}"'.format(unkown_columns))
def error(confidence=0.95):
def error_(data):
a = 1.0 * numpy.array(data)
n = len(a)
if n == 1:
return 0
m, se = numpy.mean(a), scipy.stats.sem(a)
return se * scipy.stats.t._ppf((1+confidence)/2., n-1)
error_.__name__ = 'ci' + ''.join([c for c in str(100 * confidence) if c.isdigit()])
return error_
dimensions = [c for c in df.columns.values if c in DIMENSIONS]
aggs = {c : ['mean', 'count', error()] for c in df.columns.values if c in MEASURES}
df = df.groupby(by=[c for c in dimensions if c != '__filename']) \
.agg(aggs).reset_index()
df.columns = [' '.join(col).strip() for col in df.columns.values]
return df
|
import React from 'react';
import './Cases.scss';
const CaseTable = ({ caseHeaders, data, toggleModal }) => {
// let date = new Date(dateTime).toDateString();
const convertDate = (date) => new Date(date).toDateString();
return (
<div className="table-container">
<table>
<tbody>
<tr className="table-header-row">{caseHeaders.map((caseHeader) => <td>{caseHeader.label}</td>)}</tr>
{data.map((row_) => {
const row = row_.item ? row_.item : row_;
// console.log(row);
return (
<tr id={row._id} className="table-detail-row" onClick={() => toggleModal(row)}>
<td>{row.reporter.name}</td>
<td>{row.location.name}</td>
<td>{row.type}</td>
<td>{row.reporter.contact}</td>
<td>{convertDate(row.reportedDateAndTime)}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
};
export default CaseTable;
|
using System.Linq;
using System.Threading.Tasks;
using SteveTheTradeBot.Core.Framework.BaseManagers;
using SteveTheTradeBot.Core.Framework.MessageUtil.Models;
using SteveTheTradeBot.Core.Tests.Helpers;
using SteveTheTradeBot.Dal.Models.Base;
using SteveTheTradeBot.Dal.Persistence;
using SteveTheTradeBot.Dal.Tests;
using FizzWare.NBuilder;
using FluentAssertions;
using Moq;
using NUnit.Framework;
namespace SteveTheTradeBot.Core.Tests.Framework.BaseManagers
{
public abstract class BaseTypedManagerTests<T> : BaseManagerTests where T : BaseDalModelWithId
{
[Test]
public virtual async Task Get_WhenCalledWithId_ShouldReturnSingleRecord()
{
// arrange
Setup();
var addFake = Repository.AddFake();
var guid = addFake.First().Id;
// action
var result = await Lookup.GetById(guid);
// assert
result.Id.Should().Be(guid);
}
[Test]
public virtual async Task GetRecords_WhenCalled_ShouldReturnRecords()
{
// arrange
Setup();
const int expected = 2;
Repository.AddFake(expected);
// action
var result = await Lookup.Get();
// assert
result.Should().HaveCount(expected);
}
protected abstract IRepository<T> Repository { get; }
protected virtual T SampleObject => Builder<T>.CreateNew().WithValidData().Build();
protected abstract BaseLookup<T> Lookup { get; }
}
}
|
program test
logical :: flag1, flag2, flag3, flag4, flag5, flag6
integer :: a = 5
integer :: b = 5
flag1 = a == b
flag2 = a /= b
flag3 = a < b
flag4 = a <= b
flag5 = a > b
flag6 = a >= b
print *,(a + b)
end program test
|
package models
import scalikejdbc.specs2.mutable.AutoRollback
import org.specs2.mutable._
import scalikejdbc._
class ProgramSpec extends Specification {
"Program" should {
val p = Program.syntax("p")
"find by primary keys" in new AutoRollback {
val maybeFound = Program.find(123)
maybeFound.isDefined should beTrue
}
"find by where clauses" in new AutoRollback {
val maybeFound = Program.findBy(sqls.eq(p.pId, 123))
maybeFound.isDefined should beTrue
}
"find all records" in new AutoRollback {
val allResults = Program.findAll()
allResults.size should be_>(0)
}
"count all records" in new AutoRollback {
val count = Program.countAll()
count should be_>(0L)
}
"find all by where clauses" in new AutoRollback {
val results = Program.findAllBy(sqls.eq(p.pId, 123))
results.size should be_>(0)
}
"count by where clauses" in new AutoRollback {
val count = Program.countBy(sqls.eq(p.pId, 123))
count should be_>(0L)
}
"create new record" in new AutoRollback {
val created = Program.create(name = "MyString")
created should not beNull
}
"save a record" in new AutoRollback {
val entity = Program.findAll().head
// TODO modify something
val modified = entity
val updated = Program.save(modified)
updated should not equalTo(entity)
}
"destroy a record" in new AutoRollback {
val entity = Program.findAll().head
val deleted = Program.destroy(entity) == 1
deleted should beTrue
val shouldBeNone = Program.find(123)
shouldBeNone.isDefined should beFalse
}
"perform batch insert" in new AutoRollback {
val entities = Program.findAll()
entities.foreach(e => Program.destroy(e))
val batchInserted = Program.batchInsert(entities)
batchInserted.size should be_>(0)
}
}
}
|
@extends('layout')
@section('styling')
<link rel="stylesheet" type="text/css" href="css/styles.css">
<link rel="stylesheet" type="text/css" href="css/blog.css">
@endsection
@section('content')
<div class="fullHeight">
<main class="textStyling post">
<h3>Persoonlijke SWOT analyse</h3>
<table>
<tr>
<th>Strenghts</th>
<th>Weaknesses</th>
</tr>
<tr>
<td>Doorzettingsvermogen, affiniteit met computers, levendige fantasie en oplossingsgericht</td>
<td>geen lang concentratievermogen als het onderwerp mij niet interesseert</td>
</tr>
<tr>
<th>Opportunities</th>
<th>Threats</th>
</tr>
<tr>
<td>interesse in computers en bedrijven voor technologische vooruitgang</td>
<td>Ik hou niet van urenlang leren maar wil graag dingen toepasbaar maken</td>
</tr>
</table>
</main>
</div>
@endsection
|
package autocomplete.service;
import autocomplete.implementation.Dictionary;
import autocomplete.implementation.Trie;
import java.util.Arrays;
import java.util.List;
public class Service implements TrieService {
private Trie trie;
private Dictionary dictionary = new Dictionary();
private int sizeOfWords;
@Override
public void buildTrie(String[] words) {
sizeOfWords = words.length;
Arrays.stream(words).forEach(dictionary::insert);
}
@Override
public List<String> prefixSearch(String word) {
return dictionary.startsWith(word);
}
@Override
public void setTrie(Trie trie) {
this.trie = trie;
}
@Override
public Trie getTrie() {
return this.trie;
}
public int getSizeOfWords(){
return sizeOfWords;
}
}
|
package net.dankito.banking.fints.transactions.mt940.model
import net.dankito.banking.fints.model.Amount
import net.dankito.utils.multiplatform.Date
open class StatementLine(
/**
* Soll/Haben-Kennung
*
* “C” = Credit (Habensaldo)
* ”D” = Debit (Sollsaldo)
* „RC“ = Storno Haben
* „RD“ = Storno Soll
*
* Max length = 2
*/
val isCredit: Boolean,
val isReversal: Boolean,
/**
* Valuta (JJMMTT)
*
* Length = 6
*/
val valueDate: Date,
/**
* MMTT
*
* Length = 4
*/
val bookingDate: Date?,
/**
* dritte Stelle der Währungsbezeichnung, falls sie zur Unterscheidung notwendig ist
*
* Length = 1
*/
val currencyType: String?,
/**
* Codes see p. 177 bottom - 179
*
* After constant „N“
*
* Max length = 15
*/
val amount: Amount,
/**
* in Kontowährung
*
* Length = 3
*/
val bookingKey: String,
val referenceForTheAccountOwner: String,
val referenceOfTheAccountServicingInstitution: String?,
val supplementaryDetails: String? = null
) {
override fun toString(): String {
return "$valueDate ${if (isCredit) "+" else "-"}$amount"
}
}
|
module PacketFu
# TcpOption is the base class for all TCP options. Note that TcpOption#len
# returns the size of the entire option, while TcpOption#optlen is the struct
# for the TCP Option Length field.
#
# Subclassed options should set the correct TcpOption#kind by redefining
# initialize. They should also deal with various value types there by setting
# them explicitly with an accompanying StructFu#typecast for the setter.
#
# By default, values are presumed to be strings, unless they are Numeric, in
# which case a guess is made to the width of the Numeric based on the given
# optlen.
#
# Note that normally, optlen is /not/ enforced for directly setting values,
# so the user is perfectly capable of setting incorrect lengths.
class TcpOption < Struct.new(:kind, :optlen, :value)
include StructFu
def initialize(args={})
super(
Int8.new(args[:kind]),
Int8.new(args[:optlen])
)
if args[:value].kind_of? Numeric
self[:value] = case args[:optlen]
when 3; Int8.new(args[:value])
when 4; Int16.new(args[:value])
when 6; Int32.new(args[:value])
else; StructFu::String.new.read(args[:value])
end
else
self[:value] = StructFu::String.new.read(args[:value])
end
end
# Returns the object in string form.
def to_s
self[:kind].to_s +
(self[:optlen].value.nil? ? nil : self[:optlen]).to_s +
(self[:value].nil? ? nil : self[:value]).to_s
end
# Reads a string to populate the object.
def read(str)
force_binary(str)
return self if str.nil?
self[:kind].read(str[0,1])
if str[1,1]
self[:optlen].read(str[1,1])
if str[2,1] && optlen.value > 2
self[:value].read(str[2,optlen.value-2])
end
end
self
end
# The default decode for an unknown option. Known options should redefine this.
def decode
unk = "unk-#{self.kind.to_i}"
(self[:optlen].to_i > 2 && self[:value].to_s.size > 1) ? [unk,self[:value]].join(":") : unk
end
# Setter for the "kind" byte of this option.
def kind=(i); typecast i; end
# Setter for the "option length" byte for this option.
def optlen=(i); typecast i; end
# Setter for the value of this option.
def value=(i)
if i.kind_of? Numeric
typecast i
elsif i.respond_to? :to_s
self[:value] = i
else
self[:value] = ''
end
end
# Generally, encoding a value is going to be just a read. Some
# options will treat things a little differently; TS for example,
# takes two values and concatenates them.
def encode(str)
self[:value] = self.class.new(:value => str).value
end
# Returns true if this option has an optlen. Some don't.
def has_optlen?
(kind.value && kind.value < 2) ? false : true
end
# Returns true if this option has a value. Some don't.
def has_value?
(value.respond_to? :to_s && value.to_s.size > 0) ? false : true
end
# End of Line option. Usually used to terminate a string of options.
#
# http://www.networksorcery.com/enp/protocol/tcp/option000.htm
class EOL < TcpOption
def initialize(args={})
super(
args.merge(:kind => 0)
)
end
def decode
"EOL"
end
end
# No Operation option. Usually used to pad out options to fit a 4-byte alignment.
#
# http://www.networksorcery.com/enp/protocol/tcp/option001.htm
class NOP < TcpOption
def initialize(args={})
super(
args.merge(:kind => 1)
)
end
def decode
"NOP"
end
end
# Maximum Segment Size option.
#
# http://www.networksorcery.com/enp/protocol/tcp/option002.htm
class MSS < TcpOption
def initialize(args={})
super(
args.merge(:kind => 2,
:optlen => 4
)
)
self[:value] = Int16.new(args[:value])
end
def value=(i); typecast i; end
# MSS options with lengths other than 4 are malformed.
def decode
if self[:optlen].to_i == 4
"MSS:#{self[:value].to_i}"
else
"MSS-bad:#{self[:value]}"
end
end
end
# Window Size option.
#
# http://www.networksorcery.com/enp/protocol/tcp/option003.htm
class WS < TcpOption
def initialize(args={})
super(
args.merge(:kind => 3,
:optlen => 3
)
)
self[:value] = Int8.new(args[:value])
end
def value=(i); typecast i; end
# WS options with lengths other than 3 are malformed.
def decode
if self[:optlen].to_i == 3
"WS:#{self[:value].to_i}"
else
"WS-bad:#{self[:value]}"
end
end
end
# Selective Acknowlegment OK option.
#
# http://www.networksorcery.com/enp/protocol/tcp/option004.htm
class SACKOK < TcpOption
def initialize(args={})
super(
args.merge(:kind => 4,
:optlen => 2)
)
end
# SACKOK options with sizes other than 2 are malformed.
def decode
if self[:optlen].to_i == 2
"SACKOK"
else
"SACKOK-bad:#{self[:value]}"
end
end
end
# Selective Acknowledgement option.
#
# http://www.networksorcery.com/enp/protocol/tcp/option004.htm
#
# Note that SACK always takes its optlen from the size of the string.
class SACK < TcpOption
def initialize(args={})
super(
args.merge(:kind => 5,
:optlen => ((args[:value] || "").size + 2)
)
)
end
def optlen=(i); typecast i; end
def value=(i)
self[:optlen] = Int8.new(i.to_s.size + 2)
self[:value] = StructFu::String.new(i)
end
def decode
"SACK:#{self[:value]}"
end
def encode(str)
temp_obj = self.class.new(:value => str)
self[:value] = temp_obj.value
self[:optlen] = temp_obj.optlen.value
self
end
end
# Echo option.
#
# http://www.networksorcery.com/enp/protocol/tcp/option006.htm
class ECHO < TcpOption
def initialize(args={})
super(
args.merge(:kind => 6,
:optlen => 6
)
)
end
# ECHO options with lengths other than 6 are malformed.
def decode
if self[:optlen].to_i == 6
"ECHO:#{self[:value]}"
else
"ECHO-bad:#{self[:value]}"
end
end
end
# Echo Reply option.
#
# http://www.networksorcery.com/enp/protocol/tcp/option007.htm
class ECHOREPLY < TcpOption
def initialize(args={})
super(
args.merge(:kind => 7,
:optlen => 6
)
)
end
# ECHOREPLY options with lengths other than 6 are malformed.
def decode
if self[:optlen].to_i == 6
"ECHOREPLY:#{self[:value]}"
else
"ECHOREPLY-bad:#{self[:value]}"
end
end
end
# Timestamp option
#
# http://www.networksorcery.com/enp/protocol/tcp/option008.htm
class TS < TcpOption
def initialize(args={})
super(
args.merge(:kind => 8,
:optlen => 10
)
)
self[:value] = StructFu::String.new.read(args[:value] || "\x00" * 8)
end
# TS options with lengths other than 10 are malformed.
def decode
if self[:optlen].to_i == 10
val1,val2 = self[:value].unpack("NN")
"TS:#{val1};#{val2}"
else
"TS-bad:#{self[:value]}"
end
end
# TS options are in the format of "TS:[timestamp value];[timestamp secret]" Both
# should be written as decimal numbers.
def encode(str)
if str =~ /^([0-9]+);([0-9]+)$/
tsval,tsecr = str.split(";").map {|x| x.to_i}
if tsval <= 0xffffffff && tsecr <= 0xffffffff
self[:value] = StructFu::String.new([tsval,tsecr].pack("NN"))
else
self[:value] = StructFu::String.new(str)
end
else
self[:value] = StructFu::String.new(str)
end
end
end
end
end
|
#!/usr/bin/env ruby
#
require 'rubygems'
require 'json'
require 'bundler'
Bundler.require
require 'sinatra'
require 'sinatra/partial'
#require 'nokogiri'
require_relative 'app/logic/app'
run App
|
require 'git'
module Projects
class Clone < Services::Base
FilesExistsError = Class.new(Error)
def call(project)
if File.exist?(project.local_path) && Dir[File.join(project.local_path, '*')].present?
raise FilesExistsError, "Files for project #{project.name} already exist."
end
dir = File.expand_path('..', project.local_path)
Git.clone project.git, project.slug, path: dir
project
end
end
end
|
#include <iostream>
#include <vector>
using namespace std;
void applay(const vector<int>& vec, void(*func)(int)){
for (int val : vec){
func(val);
}
}
int main (){
vector<int> vec {1,2,3,4};
auto lambda = [](int val){
cout << val << endl;
};
applay(vec, lambda);
return 0;
}
|
//! The LocalCache provides a local KV cache for contracts to do some offchain computation.
//! When we say local, it means that the data stored in the cache is different in different
//! machines of the same contract. And the data might loss when the pruntime restart or caused
//! by some kind of cache expiring machanism.
use alloc::borrow::Cow;
use once_cell::sync::Lazy;
use pink_extension::CacheOp;
use std::{collections::HashMap, sync::RwLock, time::Instant};
pub use pink_extension::chain_extension::StorageQuotaExceeded;
use crate::types::AccountId;
pub static GLOBAL_CACHE: Lazy<RwLock<LocalCache>> = Lazy::new(Default::default);
#[derive(Default, Debug)]
struct Storage {
// Sum of the size of all the keys and values.
size: usize,
kvs: HashMap<Vec<u8>, StorageValue>,
}
#[derive(Debug)]
struct StorageValue {
// Expiration time in seconds since the first call to `now`.
expire_at: u64,
value: Vec<u8>,
}
#[derive(Debug)]
pub struct LocalCache {
// Number of set ops between two GC ops.
gc_interval: u64,
// Accumulated number of set ops since last GC.
sets_since_last_gc: u64,
// Default expiration time in seconds.
default_value_lifetime: u64,
max_cache_size_per_contract: usize,
storages: HashMap<Vec<u8>, Storage>,
}
impl Default for LocalCache {
fn default() -> Self {
Self {
gc_interval: 1000,
sets_since_last_gc: 0,
default_value_lifetime: 3600 * 24 * 7, // 1 week
max_cache_size_per_contract: 10 * 1024 * 1024, // 10MB
storages: Default::default(),
}
}
}
impl LocalCache {
fn maybe_clear_expired(&mut self) {
self.sets_since_last_gc += 1;
if self.sets_since_last_gc == self.gc_interval {
self.sets_since_last_gc = 0;
let now = now();
self.storages.values_mut().for_each(|storage| {
let storage_size = &mut storage.size;
storage.kvs.retain(|k, v| {
if v.expire_at > now {
true
} else {
*storage_size -= v.value.len() + k.len();
false
}
});
});
}
}
pub fn get(&self, id: &[u8], key: &[u8]) -> Option<Vec<u8>> {
let entry = self.storages.get(id)?.kvs.get(key)?;
if entry.expire_at <= now() {
None
} else {
Some(entry.value.to_owned())
}
}
#[cfg(test)]
fn get_include_expired(&self, id: &[u8], key: &[u8]) -> Option<Vec<u8>> {
Some(self.storages.get(id)?.kvs.get(key)?.value.to_owned())
}
pub fn set(
&mut self,
id: Cow<[u8]>,
key: Cow<[u8]>,
value: Cow<[u8]>,
) -> Result<(), StorageQuotaExceeded> {
self.maybe_clear_expired();
let store = self
.storages
.entry(id.into_owned())
.or_insert_with(Storage::default);
let key_len = key.len();
let value_len = value.len();
let prev_value = store.kvs.remove(key.as_ref());
let new_size = match prev_value {
Some(v) => store.size + value_len - v.value.len(),
None => store.size + key_len + value_len,
};
if new_size > self.max_cache_size_per_contract {
return Err(StorageQuotaExceeded);
}
store.size = new_size;
store.kvs.insert(
key.into_owned(),
StorageValue {
expire_at: now().saturating_add(self.default_value_lifetime),
value: value.into_owned(),
},
);
Ok(())
}
pub fn set_expire(&mut self, id: Cow<[u8]>, key: Cow<[u8]>, expire: u64) {
self.maybe_clear_expired();
if expire == 0 {
let _ = self.remove(id.as_ref(), key.as_ref());
} else {
self.storages
.get_mut(id.as_ref())
.and_then(|storage| storage.kvs.get_mut(key.as_ref()))
.map(|v| v.expire_at = now().saturating_add(expire));
}
}
pub fn remove(&mut self, id: &[u8], key: &[u8]) -> Option<Vec<u8>> {
self.maybe_clear_expired();
let store = self.storages.get_mut(id)?;
let v = store.kvs.remove(key).map(|v| v.value);
if let Some(v) = &v {
store.size -= v.len() + key.len();
}
v
}
#[allow(dead_code)]
pub fn remove_storage(&mut self, id: &[u8]) {
let _ = self.storages.remove(id);
}
}
fn now() -> u64 {
static REF_TIME: Lazy<Instant> = Lazy::new(Instant::now);
REF_TIME.elapsed().as_secs()
}
pub fn local_cache_op(contract: &AccountId, op: CacheOp) {
let mut cache = GLOBAL_CACHE.write().unwrap();
let contract: &[u8] = contract.as_ref();
match op {
CacheOp::Set { key, value } => {
let _ = cache.set(contract.into(), key.into(), value.into());
}
CacheOp::SetExpiration { key, expiration } => {
cache.set_expire(contract.into(), key.into(), expiration)
}
CacheOp::Remove { key } => {
let _ = cache.remove(contract, &key);
}
}
}
pub fn local_cache_set(
contract: &[u8],
key: &[u8],
value: &[u8],
) -> Result<(), StorageQuotaExceeded> {
GLOBAL_CACHE
.write()
.unwrap()
.set(contract.into(), key.into(), value.into())
}
pub fn local_cache_get(contract: &[u8], key: &[u8]) -> Option<Vec<u8>> {
GLOBAL_CACHE.read().unwrap().get(contract, key)
}
pub fn local_cache_set_expiration(contract: &[u8], key: &[u8], expiration: u64) {
GLOBAL_CACHE
.write()
.unwrap()
.set_expire(contract.into(), key.into(), expiration)
}
pub fn local_cache_remove(contract: &[u8], key: &[u8]) -> Option<Vec<u8>> {
GLOBAL_CACHE.write().unwrap().remove(contract, key)
}
#[cfg(test)]
mod test {
use super::*;
fn test_cache() -> LocalCache {
LocalCache {
gc_interval: 2,
sets_since_last_gc: 0,
default_value_lifetime: 2,
max_cache_size_per_contract: 1024,
storages: Default::default(),
}
}
fn cow<'a>(s: &'a impl AsRef<[u8]>) -> Cow<'a, [u8]> {
Cow::Borrowed(s.as_ref())
}
fn gc(cache: &mut LocalCache) {
for _ in 0..cache.gc_interval + 1 {
let _ = cache.set(cow(b"_"), cow(b"_"), cow(b"_"));
}
}
fn sleep(secs: u64) {
std::thread::sleep(std::time::Duration::from_secs(secs));
}
fn get_size(cache: &LocalCache, id: &[u8]) -> usize {
cache.storages.get(id).unwrap().size
}
#[test]
fn default_expire_should_work() {
let mut cache = test_cache();
let _ = cache.set(cow(b"id"), cow(b"foo"), cow(b"value"));
assert_eq!(cache.get(b"id", b"foo"), Some(b"value".to_vec()));
sleep(cache.default_value_lifetime);
assert_eq!(cache.get(b"id", b"foo"), None);
assert!(cache.get_include_expired(b"id", b"foo").is_some());
gc(&mut cache);
assert_eq!(cache.get_include_expired(b"id", b"foo"), None);
assert_eq!(get_size(&cache, b"id"), 0);
}
#[test]
fn set_expire_should_work() {
let mut cache = test_cache();
let _ = cache.set(cow(b"id"), cow(b"foo"), cow(b"value"));
assert_eq!(cache.get(b"id", b"foo"), Some(b"value".to_vec()));
cache.set_expire(cow(b"id"), cow(b"foo"), cache.default_value_lifetime + 2);
sleep(cache.default_value_lifetime);
gc(&mut cache);
assert_eq!(cache.get(b"id", b"foo"), Some(b"value".to_vec()));
sleep(2);
gc(&mut cache);
assert_eq!(cache.get_include_expired(b"id", b"foo"), None);
}
#[test]
fn size_limit_should_work() {
let mut cache = test_cache();
cache.max_cache_size_per_contract = 10;
assert!(cache.set(cow(b"id"), cow(b"foo"), cow(b"value")).is_ok());
assert!(cache.set(cow(b"id"), cow(b"bar"), cow(b"value")).is_err());
}
#[test]
fn size_calc() {
let mut cache = test_cache();
assert!(cache.set(cow(b"id"), cow(b"foo"), cow(b"bar")).is_ok());
assert_eq!(get_size(&cache, b"id"), 6);
assert!(cache.set(cow(b"id"), cow(b"foo"), cow(b"foobar")).is_ok());
assert_eq!(get_size(&cache, b"id"), 9);
assert!(cache.set(cow(b"id"), cow(b"foo"), cow(b"foo")).is_ok());
assert_eq!(get_size(&cache, b"id"), 6);
assert!(cache.remove(b"id", b"foo").is_some());
assert_eq!(get_size(&cache, b"id"), 0);
}
}
|
void main() {
dynamic sampleDynamicType = "Hello";
sampleDynamicType = 16;
dynamic sampleSecond = true;
sampleSecond = "TRUE";
}
|
---
title: Sky can wait
date: 2019-02-01 19:00:00
image: "images/masonary-post/post-2.jpg"
topics:
- devotion
- prayer
---
Why do doctors today believe faith heals?
With this title, the magazine Seleções, from August 2001, published a
based on clinical evidence that faith is efficient ally in the recovery of
and in the prevention of diseases.
Hundreds of studies and research document the link between faith and health.
According to statistics, devotion promotes several positive effects. Here are some
Them:
1. Longer life. A survey conducted in the United States with twenty-one
1,000 people, between 1987 and 1995, found a seven-year difference in
life expectancy among those who never attend religious cults and
who attend them more than once a week.
2. General well-being. In a research co-directed by epidemiologist Jeff Levin,
author of God, faith, and health, elderly who considered themselves
had fewer health problems than non-religious ones.
3. Better recovery. Patients comforted by faith presented
three times higher probabilities of survival after cardiac surgeries
according to a 1995 study by dartmouth school of medicine.
4. Firmer heartbeats. In a study conducted in India in 1997,
participants, mostly Hindus, who prayed regularly had seventy
percent less chance of suffering from coronary heart disease.
5. Lower pressure. In a 1989 study conducted with four hundred men,
researchers at Duke University observed a significant protective effect
against high pressure among those who considered religion very
important and attended the church.
6. Good mental health. Attending places of devotion is related to lower rates
depression and anxiety, according to a 1999 survey by Duke University, which
included almost 4,000 seniors.
7. Less stress. People under stress have increased blood pressure
and heart and respiratory rates, reducing immunity, according to Dr.
Herbert Benson of Harvard, author of The Relaxation Response.
He found, in several research, that both meditation and prayer, Tai
chi chuan and Yoga provoke an opposite reaction to stress.
* * *
As we can see, according to medical research, faith contributes in a
efficient in the treatment of human beings, not only in relation to diseases
physical, but also those of the soul.
It is evident that the mind is the real agent of health or disease because it is the
great governor of the body.
And science is humanity's great benefactor, discovering diseases and
promoting healing, now also admitting that there is an important component in the
treatment and prophylaxis of diseases: faith.
Einstein, one of the most respected scientists the world has known, said that
there should be an alliance between science and religion.
According to him, science without religion is paralytic - religion without science is
Blind.
When modern scientists manage to cross the cultural precipice created
over time between faith and science, undoubtedly this approximation will
benefit all mankind.
* * *
Faith has the essential function of providing strength to solve problems for the
rather than push ing them away or free the believer from the testimonies necessary for his
Evolution.
## Source
Redação do Momento Espírita com base no artigo Por que os médicos hoje
acreditam que a fé cura?, de Seleções Reader’s Digest de agosto/2001 e no
verbete Fé, do livro Repositório de sabedoria, v. 1, pelo Espírito Joanna de
Ângelis, psicografia de Divaldo Pereira Franco, ed. Leal.
Em 28.02.2011.
[Original Article (pt-BR)](http://momento.com.br/pt/ler_texto.php?id=2927)
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cmp::Ordering;
use std::mem;
use std::time::Instant;
use crate::frame::{Frame, FrameType};
use crate::recovery::RecoveryToken;
use crate::{CloseError, ConnectionError};
#[derive(Clone, Debug, PartialEq, Ord, Eq)]
/// The state of the Connection.
pub enum State {
Init,
WaitInitial,
Handshaking,
Connected,
Confirmed,
Closing {
error: ConnectionError,
timeout: Instant,
},
Draining {
error: ConnectionError,
timeout: Instant,
},
Closed(ConnectionError),
}
impl State {
#[must_use]
pub fn connected(&self) -> bool {
matches!(self, Self::Connected | Self::Confirmed)
}
#[must_use]
pub fn closed(&self) -> bool {
matches!(self, Self::Closing { .. } | Self::Draining { .. } | Self::Closed(_))
}
}
// Implement Ord so that we can enforce monotonic state progression.
impl PartialOrd for State {
#[allow(clippy::match_same_arms)] // Lint bug: rust-lang/rust-clippy#860
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
if mem::discriminant(self) == mem::discriminant(other) {
return Some(Ordering::Equal);
}
Some(match (self, other) {
(Self::Init, _) => Ordering::Less,
(_, Self::Init) => Ordering::Greater,
(Self::WaitInitial, _) => Ordering::Less,
(_, Self::WaitInitial) => Ordering::Greater,
(Self::Handshaking, _) => Ordering::Less,
(_, Self::Handshaking) => Ordering::Greater,
(Self::Connected, _) => Ordering::Less,
(_, Self::Connected) => Ordering::Greater,
(Self::Confirmed, _) => Ordering::Less,
(_, Self::Confirmed) => Ordering::Greater,
(Self::Closing { .. }, _) => Ordering::Less,
(_, Self::Closing { .. }) => Ordering::Greater,
(Self::Draining { .. }, _) => Ordering::Less,
(_, Self::Draining { .. }) => Ordering::Greater,
(Self::Closed(_), _) => unreachable!(),
})
}
}
/// `StateSignaling` manages whether we need to send HANDSHAKE_DONE and CONNECTION_CLOSE.
/// Valid state transitions are:
/// * Idle -> HandshakeDone: at the server when the handshake completes
/// * HandshakeDone -> Idle: when a HANDSHAKE_DONE frame is sent
/// * Idle/HandshakeDone -> Closing/Draining: when closing or draining
/// * Closing/Draining -> CloseSent: after sending CONNECTION_CLOSE
/// * CloseSent -> Closing: any time a new CONNECTION_CLOSE is needed
/// * -> Reset: from any state in case of a stateless reset
#[derive(Debug, Clone, PartialEq)]
pub enum StateSignaling {
Idle,
HandshakeDone,
/// These states save the frame that needs to be sent.
Closing(Frame),
Draining(Frame),
/// This state saves the frame that might need to be sent again.
/// If it is `None`, then we are draining and don't send.
CloseSent(Option<Frame>),
Reset,
}
impl StateSignaling {
pub fn handshake_done(&mut self) {
if *self != Self::Idle {
debug_assert!(false, "StateSignaling must be in Idle state.");
return;
}
*self = Self::HandshakeDone
}
pub fn send_done(&mut self) -> Option<(Frame, Option<RecoveryToken>)> {
if *self == Self::HandshakeDone {
*self = Self::Idle;
Some((Frame::HandshakeDone, Some(RecoveryToken::HandshakeDone)))
} else {
None
}
}
fn make_close_frame(
error: ConnectionError,
frame_type: FrameType,
message: impl AsRef<str>,
) -> Frame {
let reason_phrase = message.as_ref().as_bytes().to_owned();
Frame::ConnectionClose {
error_code: CloseError::from(error),
frame_type,
reason_phrase,
}
}
pub fn close(
&mut self,
error: ConnectionError,
frame_type: FrameType,
message: impl AsRef<str>,
) {
if *self != Self::Reset {
*self = Self::Closing(Self::make_close_frame(error, frame_type, message));
}
}
pub fn drain(
&mut self,
error: ConnectionError,
frame_type: FrameType,
message: impl AsRef<str>,
) {
if *self != Self::Reset {
*self = Self::Draining(Self::make_close_frame(error, frame_type, message));
}
}
/// If a close is pending, take a frame.
pub fn close_frame(&mut self) -> Option<Frame> {
match self {
Self::Closing(frame) => {
// When we are closing, we might need to send the close frame again.
let frame = mem::replace(frame, Frame::Padding);
*self = Self::CloseSent(Some(frame.clone()));
Some(frame)
}
Self::Draining(frame) => {
// When we are draining, just send once.
let frame = mem::replace(frame, Frame::Padding);
*self = Self::CloseSent(None);
Some(frame)
}
_ => None,
}
}
/// If a close can be sent again, prepare to send it again.
pub fn send_close(&mut self) {
if let Self::CloseSent(Some(frame)) = self {
let frame = mem::replace(frame, Frame::Padding);
*self = Self::Closing(frame);
}
}
/// We just got a stateless reset. Terminate.
pub fn reset(&mut self) {
*self = Self::Reset;
}
}
|
package model
/**
* Возможные действия хоккеиста.
* <p/>
* Хоккеист может совершить действие, если он не сбит с ног ([[model.HockeyistState.KnockedDown]]),
* не отдыхает ([[model.HockeyistState.Resting]]) и уже восстановился после своего предыдущего действия
* (значение [[model.Hockeyist#getRemainingCooldownTicks]] равно `0`).
* <p/>
* Если хоккеист замахивается клюшкой ([[model.HockeyistState.Swinging]]), то из действий ему доступны только
* [[model.ActionType.Strike]] и [[model.ActionType.CancelStrike]].
*/
sealed trait ActionType
object ActionType {
/**
* Ничего не делать.
*/
case object None extends ActionType
/**
* Взять шайбу.
* <p/>
* Если хоккеист уже контролирует шайбу, либо шайба находится вне зоны досягаемости клюшки хоккеиста (смотрите
* документацию к значениям [[model.Game#getStickLength]] и [[model.Game#getStickSector]]), то действие игнорируется.
* <p/>
* В противном случае хоккеист попытается установить контроль над шайбой и, с определённой вероятностью,
* это сделает ((смотрите документацию к [[model.Game#getPickUpPuckBaseChance]]
* и [[model.Game#getTakePuckAwayBaseChance]])).
*/
case object TakePuck extends ActionType
/**
* Замахнуться для удара.
* <p/>
* Хоккеист замахивается для увеличения силы удара. Чем больше тиков пройдёт с момента начала замаха до удара,
* тем большее воздействие будет на попавшие под удар объекты. Максимальное количество учитываемых тиков ограничено
* значением [[model.Game#getMaxEffectiveSwingTicks]].
*/
case object Swing extends ActionType
/**
* Ударить.
* <p/>
* Хоккеист наносит размашистый удар по всем объектам, находящимся в зоне досягаемости его клюшки. Удар может быть
* совершён как с предварительным замахом ([[model.ActionType.Swing]]), так и без него (в этом случае сила удара
* будет меньше).
* <p/>
* Объекты (шайба и хоккеисты, кроме вратарей), попавшие под удар, приобретут некоторый импульс в направлении,
* совпадающим с направлением удара. При ударе по хоккеисту есть также некоторый шанс сбить его с ног.
*/
case object Strike extends ActionType
/**
* Отменить удар.
* <p/>
* Хоккеист выходит из состояния замаха ([[model.ActionType.Swing]]), не совершая удар. Это позволяет
* сэкономить немного выносливости, а также быстрее совершить новое действие
* (смотрите документацию к [[model.Game#getCancelStrikeActionCooldownTicks]]).
* <p/>
* Если хоккеист не совершает замах клюшкой, то действие игнорируется.
*/
case object CancelStrike extends ActionType
/**
* Отдать пас.
* <p/>
* Хоккеист пытается передать контролируемую им шайбу другому хоккеисту. Для этого необходимо указать относительную
* силу паса ([[model.Move#setPassPower]]) и его направление ([[model.Move#setPassAngle]]). В противном случае пас
* будет отдан в направлении, соответствующем направлению хоккеиста, с максимально возможной силой.
* <p/>
* Если хоккеист не контролирует шайбу, то действие игнорируется.
*/
case object Pass extends ActionType
/**
* Заменить активного хоккеиста сидящим на скамейке запасных.
* <p/>
* Замена выполняется только на своей половине поля, при этом расстояние от центра хоккеиста до верхней границы
* игровой площадки не должно превышать [[model.Game#getSubstitutionAreaHeight]]. Дополнительно нужно указать индекс
* хоккеиста ([[model.Move#setTeammateIndex]]), на которого будет произведена замена.
* <p/>
* Если указан некорректный индекс, или скорость хоккеиста превышает [[model.Game#getMaxSpeedToAllowSubstitute]],
* то действие будет проигнорировано.
*/
case object Substitute extends ActionType
/**
* Ни одно из известных действий.
*/
case object Unknown extends ActionType
}
|
import React from 'react'
import ListItem from '../order/ListItem'
const ListItemListContainer = ({ listItems }) => {
const renderListItems = () => {
return listItems.map((listItem, i) => {
return (<ListItem listItem={listItem} key={i} />)
})
}
return (
<div className="active-order-list-item-list-container">
{renderListItems()}
</div>
)
}
export default ListItemListContainer;
|
interface Symbols {
frames: string[]
tick: string
cross: string
}
export const isTTY: boolean
export const symbols: Symbols
|
use std::env;
use std::error;
use std::fs;
/// Reads every record from the file specified in the first command line
/// argument. See `examples/demo.mot` for an example SREC file.
fn main() -> Result<(), Box<dyn error::Error>> {
let args: Vec<String> = env::args().collect();
let path = args
.get(1)
.expect("An SREC file must be provided as a command line argument");
let s = fs::read_to_string(path)?;
let records = srec::reader::read_records(&s);
for record in records {
println!("{:x?}", record?);
}
Ok(())
}
|
#!/bin/sh
rm -rf TMP9
#export GANACHE_OPTIMIZATION_WORKAROUNDS_ENV_VAR=--ganacheOptimizationWorkarounds
doit() {
./generate-contract-set.sh 5 1 10 10 10 30 TMP9 --random ##--assignmentSequence
echo ======= With optimization =======
./truffle-optimization-setting.sh on
./run-all-tests.sh TMP9 0 --generated
echo ======= Without optimization =======
./truffle-optimization-setting.sh off
./run-all-tests.sh TMP9 0 --generated
}
echo ======= Normal random contracts ========
doit
rm -rf TMP9
echo ======= "Optimization-friendly (with ganache-cli workarounds) random contracts" ========
export GANACHE_OPTIMIZATION_WORKAROUNDS_ENV_VAR=--ganacheOptimizationWorkarounds
doit
|
import React , {Component} from 'react';
import ItemTemplate from './item_template';
export default function(props) {
let filteredData = {
"sports" : [],
"entertainment" : [],
"news" :[]
};
props.items.map((item) => {
switch (item.category) {
case "Sports":
filteredData.sport.push(item);
break;
case "Entertainment":
filteredData.entertainment.push(item);
break;
case "News":
filteredData.news.push(item);
break;
default :
break;
}
});
//Render each item
function renderItem (data){
<ItemTemplate data ={data} />
}
//Render each row
function renderRow(categoryData){
return (
<div className = "container">
<div className = "row">
{itemList.map(this.renderItem)}
</div>
</div>
)
}
return (
<div>
{filteredData.map(this.renderRow)}
</div>
);
}
|
using System;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Akka.Actor;
using JetBrains.Annotations;
namespace Tauron.Application.Workshop.Mutation
{
[PublicAPI]
public sealed class EventSource<TRespond, TData> : EventSourceBase<TRespond>
{
public EventSource(
WorkspaceSuperviser superviser, Task<IActorRef> mutator, Func<TData, TRespond> transform,
Func<TData, bool>? where, IObservable<TData> handler)
: base(mutator, superviser)
{
if (where == null)
handler.Select(transform).Subscribe(Sender());
else
handler.Where(where).Select(transform).Subscribe(Sender());
}
public EventSource(WorkspaceSuperviser superviser, Task<IActorRef> mutator, IObservable<TRespond> handler)
: base(mutator, superviser)
{
handler.Subscribe(Sender());
}
}
}
|
require 'Bacon_Colored'
require 'escape_escape_escape'
require 'pry'
require "multi_json"
require "escape_escape_escape"
require 'sanitize'
BRACKETS = <<-EOF.split.join(' ')
< %3C < < < < < < <
< < < < < < <
< < < < < < <
< < < < < <
< < < < < < <
< < < < < <
< < < < < < < <
< < < < < <
< < < < < < < <
< < \x3c \x3C \u003c \u003C
EOF
class It_Dsl
class << self
def tests
@tests ||= []
end
def args
@args ||= []
end
def describe str
tests << {:describe => str, :tests=>[]}
end
def it str
args << str
end
def input *o
args << o
end
def << t
if !args.empty?
fail "Unknown values pending for: #{tests.last[:describe]}: #{args.inspect}"
end
t[:it] = if t[:it].strip[/:\z/]
"#{t[:it]} #{t[:input].inspect}"
else
t[:it]
end
tests.last[:tests] << t
end
def stack arr
self << {it: args.shift, input: args.pop, stack: arr}
end
def raises o, m
self << {it: args.shift, input: args.pop, raises: [o, m]}
end
def output o
self << {it: args.shift, input: args.pop, output: o}
end
end # === class << self
end # == class It_Dsl
# =================================================
glob = ENV['RUBY_TEST_FILE'].to_s.strip.empty? ?
"specs/as_ruby/*.rb" :
ENV['RUBY_TEST_FILE']
# =================================================
Dir.glob(glob).sort.each { |f|
contents = File.read f
method_name = File.basename(f).gsub(/\A\d+-|\.rb\z/, '')
It_Dsl.describe method_name.to_sym
It_Dsl.instance_eval contents, f
} # === Dir.glob
It_Dsl.tests.each { |o|
describe o[:describe] do
o[:tests].each { |t|
it t[:it] do
case
when o[:describe] == :==
t[:input].should == [t[:output]]
when t.has_key?(:output)
Escape_Escape_Escape.send(o[:describe], *t[:input])
.should == t[:output]
when !t.has_key?(:output) && t[:raises]
should.raise(t[:raises].first) {
Escape_Escape_Escape.send(o[:describe], *t[:input])
}.message.should.match(t[:raises].last)
when t.has_key?(:stack) && t[:stack].is_a?(Array)
stack = t[:stack]
actual = Escape_Escape_Escape.send(o[:describe], *t[:input])
target = stack.pop
begin
case
when stack[1].is_a?(Array)
meth = stack.shift
args = stack.shift
actual = actual.send(meth, *args)
when stack.first.is_a?(Symbol)
actual = actual.send(stack.shift)
else
fail "Unknown method: #{stack[0].inspect}"
end
end while !stack.empty?
actual.should == target
else
fail "Unknown args for test: #{t.inspect}"
end # === case
end # === it
}
end
} # === It_Dsl
|
# coding=utf-8
from typing import List
import Expr
import Token
class Stmt(object):
def accept(self, visitor):
raise NotImplementedError
def __setattr__(self, attr, value):
if hasattr(self, attr):
raise Exception("Attempting to alter read-only value")
self.__dict__[attr] = value
class Block(Stmt):
def __init__(self, statements: List[Stmt]):
self.statements = statements
def accept(self, visitor):
return visitor.visitBlockStmt(self)
class Expression(Stmt):
def __init__(self, expression: Expr.Expr):
self.expression = expression
def accept(self, visitor):
return visitor.visitExpressionStmt(self)
class Function(Stmt):
def __init__(self, name: Token.Token, params: List[Token.Token], body: List[Stmt]):
self.name = name
self.params = params
self.body = body
def accept(self, visitor):
return visitor.visitFunctionStmt(self)
class Class(Stmt):
def __init__(self, name: Token.Token, superclass: Expr.Variable, methods: List[Function]):
self.name = name
self.superclass = superclass
self.methods = methods
def accept(self, visitor):
return visitor.visitClassStmt(self)
class If(Stmt):
def __init__(self, condition: Expr.Expr, thenBranch: Stmt, elseBranch: Stmt):
self.condition = condition
self.thenBranch = thenBranch
self.elseBranch = elseBranch
def accept(self, visitor):
return visitor.visitIfStmt(self)
class Print(Stmt):
def __init__(self, expression: Expr.Expr):
self.expression = expression
def accept(self, visitor):
return visitor.visitPrintStmt(self)
class Return(Stmt):
def __init__(self, keyword: Token.Token, value: Expr.Expr):
self.keyword = keyword
self.value = value
def accept(self, visitor):
return visitor.visitReturnStmt(self)
class Var(Stmt):
def __init__(self, name: Token.Token, initializer: Expr.Expr):
self.name = name
self.initializer = initializer
def accept(self, visitor):
return visitor.visitVarStmt(self)
class While(Stmt):
def __init__(self, condition: Expr.Expr, body: Stmt):
self.condition = condition
self.body = body
def accept(self, visitor):
return visitor.visitWhileStmt(self)
class Visitor(object):
def visitBlockStmt(self, stmt: Block):
raise NotImplementedError
def visitExpressionStmt(self, stmt: Expression):
raise NotImplementedError
def visitFunctionStmt(self, stmt: Function):
raise NotImplementedError
def visitClassStmt(self, stmt: Class):
raise NotImplementedError
def visitIfStmt(self, stmt: If):
raise NotImplementedError
def visitPrintStmt(self, stmt: Print):
raise NotImplementedError
def visitReturnStmt(self, stmt: Return):
raise NotImplementedError
def visitVarStmt(self, stmt: Var):
raise NotImplementedError
def visitWhileStmt(self, stmt: While):
raise NotImplementedError
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
-- | Heterogeneous lists
--
-- Intended for qualified import
module Ouroboros.Consensus.Util.HList (
-- * Basic definitions
HList(..)
, All
-- * Folding
, foldl
, foldlM
, foldr
, foldMap
, repeatedly
, repeatedlyM
, collapse
-- * Singletons
, SList
, IsList(..)
-- * n-ary functions
, Fn
, applyFn
, afterFn
) where
import Codec.Serialise
import Codec.Serialise.Decoding
import Data.Kind (Constraint)
import Data.Monoid ((<>))
import Data.Proxy
import Prelude hiding (foldMap, foldl, foldr)
{-------------------------------------------------------------------------------
Basic definitions
-------------------------------------------------------------------------------}
data HList :: [*] -> * where
Nil :: HList '[]
(:*) :: a -> HList as -> HList (a ': as)
infixr :*
type family All c as :: Constraint where
All c '[] = ()
All c (a ': as) = (c a, All c as)
instance All Show as => Show (HList as) where
show = show . collapse (Proxy @Show) show
instance (IsList as, All Eq as) => Eq (HList as) where
(==) = eq isList
where
eq :: All Eq bs => SList bs -> HList bs -> HList bs -> Bool
eq SNil _ _ = True
eq (SCons s) (x :* xs) (y :* ys) = x == y && eq s xs ys
instance (IsList as, All Eq as, All Ord as) => Ord (HList as) where
compare = cmp isList
where
cmp :: All Ord bs => SList bs -> HList bs -> HList bs -> Ordering
cmp SNil _ _ = EQ
cmp (SCons s) (x :* xs) (y :* ys) = compare x y <> cmp s xs ys
instance (IsList as, All Serialise as) => Serialise (HList as) where
encode = foldMap (Proxy :: Proxy Serialise) encode
decode = decode' isList
where
decode' :: All Serialise bs => SList bs -> Decoder s (HList bs)
decode' SNil = return Nil
decode' (SCons s) = (:*) <$> decode <*> decode' s
{-------------------------------------------------------------------------------
Folding
-------------------------------------------------------------------------------}
foldl :: forall c as b proxy. All c as
=> proxy c
-> (forall a. c a => b -> a -> b) -> b -> HList as -> b
foldl _ f = go
where
go :: All c as' => b -> HList as' -> b
go !acc Nil = acc
go !acc (a :* as) = go (f acc a) as
foldlM :: forall c as m b proxy. (All c as, Monad m)
=> proxy c
-> (forall a. c a => b -> a -> m b) -> b -> HList as -> m b
foldlM _ f = go
where
go :: All c as' => b -> HList as' -> m b
go !acc Nil = return acc
go !acc (a :* as) = f acc a >>= \acc' -> go acc' as
foldr :: forall c as b proxy. All c as
=> proxy c
-> (forall a. c a => a -> b -> b) -> b -> HList as -> b
foldr _ f e = go
where
go :: All c as' => HList as' -> b
go Nil = e
go (a :* as) = f a (go as)
foldMap :: forall c as b proxy. (All c as, Monoid b)
=> proxy c
-> (forall a. c a => a -> b)
-> HList as
-> b
foldMap p f = foldl p (\b a -> b <> f a) mempty
-- | Apply function repeatedly for all elements of the list
--
-- > repeatedly p = flip . foldl p . flip
repeatedly :: forall c as b proxy. All c as
=> proxy c
-> (forall a. c a => a -> b -> b) -> (HList as -> b -> b)
repeatedly p f as e = foldl p (\b a -> f a b) e as
repeatedlyM :: forall c as b proxy m. (Monad m, All c as)
=> proxy c
-> (forall a. c a => a -> b -> m b) -> (HList as -> b -> m b)
repeatedlyM p f as e = foldlM p (\b a -> f a b) e as
collapse :: forall c as b proxy. All c as
=> proxy c
-> (forall a. c a => a -> b) -> HList as -> [b]
collapse _ f = go
where
go :: All c as' => HList as' -> [b]
go Nil = []
go (a :* as) = f a : go as
{-------------------------------------------------------------------------------
Singleton for HList
-------------------------------------------------------------------------------}
data SList :: [*] -> * where
SNil :: SList '[]
SCons :: SList as -> SList (a ': as)
class IsList (xs :: [*]) where
isList :: SList xs
instance IsList '[] where isList = SNil
instance IsList as => IsList (a ': as) where isList = SCons isList
{-------------------------------------------------------------------------------
n-ary functions
-------------------------------------------------------------------------------}
type family Fn as b where
Fn '[] b = b
Fn (a ': as) b = a -> Fn as b
withArgs :: HList as -> Fn as b -> b
withArgs Nil b = b
withArgs (a :* as) f = withArgs as (f a)
applyFn :: Fn as b -> HList as -> b
applyFn = flip withArgs
afterFn :: SList as -> (b -> c) -> Fn as b -> Fn as c
afterFn SNil g b = g b
afterFn (SCons ss) g f = afterFn ss g . f
|
import styled from 'styled-components';
export const Container = styled.div`
/* margin-bottom: 20px; */
position: relative;
p {
color: #120325;
font-size: 22px;
line-height: 30px;
font-weight: 700;
position: relative;
height: 400px;
width: 500px;
margin: auto;
align-self: center;
text-align: center;
border: 3px solid #120325;
box-shadow: 0 10px 10px 2px #120325;
background: transparent;
blockquote {
margin: 20px;
}
}
i {
background-color: #aaa;
display: block;
height: 24px;
width: 2px;
position: absolute;
left: 50%;
top: -10px;
z-index: 1;
}
i:after {
content: '';
background-color: #c90739;
background-image: radial-gradient(
25% 25%,
circle,
hsla(0, 0%, 100%, 0.3),
hsla(0, 0%, 0%, 0.3)
);
border-radius: 50%;
box-shadow: inset 0 0 0 1px hsla(0, 0%, 0%, 0.1),
inset 3px 3px 3px hsla(0, 0%, 100%, 0.2),
inset -3px -3px 3px hsla(0, 0%, 0%, 0.2),
23px 20px 3px hsla(0, 0%, 0%, 0.15);
height: 12px;
left: -5px;
position: absolute;
top: -10px;
width: 12px;
}
i:before {
content: '';
background-color: hsla(0, 0%, 0%, 0.1);
box-shadow: 0 0 0.25em hsla(0, 0%, 0%, 0.1);
height: 24px;
width: 2px;
left: 0;
position: absolute;
top: 0px;
transform: rotate(57.5deg);
transform-origin: 50% 100%;
}
`;
|
#ifndef _DRV_MBOX_H_
#define _DRV_MBOX_H_
#define HW_ID_OFFSET 7
#include "attrs.h"
/* Hardware Offload Engine ID */
#define M_ENG_CPU 0x00
#define M_ENG_HWHCI 0x01
//#define M_ENG_FRAG 0x02
#define M_ENG_EMPTY 0x02
#define M_ENG_ENCRYPT 0x03
#define M_ENG_MACRX 0x04
#define M_ENG_MIC 0x05
#define M_ENG_TX_EDCA0 0x06
#define M_ENG_TX_EDCA1 0x07
#define M_ENG_TX_EDCA2 0x08
#define M_ENG_TX_EDCA3 0x09
#define M_ENG_TX_MNG 0x0A
#define M_ENG_ENCRYPT_SEC 0x0B
#define M_ENG_MIC_SEC 0x0C
#define M_ENG_RESERVED_1 0x0D
#define M_ENG_RESERVED_2 0x0E
#define M_ENG_TRASH_CAN 0x0F
#define M_ENG_MAX (M_ENG_TRASH_CAN+1)
/* Software Engine ID: */
#define M_CPU_HWENG 0x00
#define M_CPU_TXL34CS 0x01
#define M_CPU_RXL34CS 0x02
#define M_CPU_DEFRAG 0x03
#define M_CPU_EDCATX 0x04
#define M_CPU_RXDATA 0x05
#define M_CPU_RXMGMT 0x06
#define M_CPU_RXCTRL 0x07
#define M_CPU_FRAG 0x08
#define M_CPU_TXTPUT 0x09
/*The queue's depth of HW */
#define M_ENG_CPU_INT 16
#define M_ENG_CPU_OUT 16
#define M_ENG_HWHCI_INT 8
#define M_ENG_HWHCI_OUT 16
#define M_ENG_EMPTY_INT 0
#define M_ENG_EMPTY_OUT 0
#define M_ENG_ENCRYPT_INT 4
#define M_ENG_ENCRYPT_OUT 16
#define M_ENG_MACRX_INT 16
#define M_ENG_MACRX_OUT 0
#define M_ENG_MIC_INT 4
#define M_ENG_MIC_OUT 4
#define M_ENG_TX_EDCA0_INT 4
#define M_ENG_TX_EDCA0_OUT 8
#define M_ENG_TX_EDCA1_INT 4
#define M_ENG_TX_EDCA1_OUT 16
#define M_ENG_TX_EDCA2_INT 4
#define M_ENG_TX_EDCA2_OUT 16
#define M_ENG_TX_EDCA3_INT 4
#define M_ENG_TX_EDCA3_OUT 16
#define M_ENG_TX_MNG_INT 4
#define M_ENG_TX_MNG_OUT 8
#define M_ENG_ENCRYPT_SEC_INT 4
#define M_ENG_ENCRYPT_SEC_OUT 16
#define M_ENG_MIC_SEC_INT 4
#define M_ENG_MIC_SEC_OUT 4
#define M_ENG_RESERVED_1_INT 0
#define M_ENG_RESERVED_1_OUT 0
#define M_ENG_RESERVED_2_INT 0
#define M_ENG_RESERVED_2_OUT 0
#define M_ENG_TRASH_CAN_INT 0
#define M_ENG_TRASH_CAN_OUT 32
#ifndef ID_TRAP_SW_TXTPUT
#define ID_TRAP_SW_TXTPUT 50 //(ID_TRAP_SW_START + M_CPU_TXTPUT - 1)
#endif //ID_TRAP_SW_TXTPUT
inline s32 drv_mailbox_send(u32 hw_number,u32 pktmsg) ATTRIBUTE_SECTION_FAST;
s32 drv_mailbox_cpu_ff(u32 pktmsg, u32 hw_number) ATTRIBUTE_SECTION_FAST;
void dump_mailbox_dbg (int num);
void enable_mailbox_dbg (void);
/**
* The following definitions are only for simulation/emulation platform. These
* definitions are used for simulation of the real chip mailbox behaviors.
*/
#endif /* _DRV_MBOX_H_ */
|
namespace ArdalisRating
{
public abstract class Rater
{
//public readonly RatingEngine _engine;
//public readonly ConsoleLogger _logger;
//public Rater(RatingEngine engine, ConsoleLogger logger)
//{
// _engine = engine;
// _logger = logger;
//}
public readonly IRatingContext _context;
// public readonly ConsoleLogger _logger;
// public readonly ILogger _logger;
public ILogger Logger { get; set; } = new ConsoleLogger();
protected readonly IRatingUpdater _ratingUpdater;
public Rater(IRatingUpdater ratingUpdater)
{
// _context = context;
// _logger = context.Logger;
_ratingUpdater = ratingUpdater;
}
public virtual void Rate(Policy policy)
{ }
}
}
|
---
title: '1979 Dux Litterarum '
date: 1979-11-30T22:02:47.520Z
award: Dux Litterarum
person1_name: Vivienne Wallace
person2_name: Peter Speck
---
|
<?php
namespace Glhd\Gretel\Support;
use Glhd\Gretel\Registry;
use Glhd\Gretel\Resolvers\Resolver;
use Glhd\Gretel\Routing\RouteBreadcrumb;
use Illuminate\Filesystem\Filesystem;
class Cache
{
protected Filesystem $filesystem;
protected string $path;
public function __construct(Filesystem $filesystem, string $path)
{
$this->filesystem = $filesystem;
$this->path = $path;
}
public function path(): string
{
return $this->path;
}
public function exists(): bool
{
return $this->filesystem->exists($this->path);
}
public function load(): bool
{
if ($this->exists()) {
$this->filesystem->getRequire($this->path);
return true;
}
return false;
}
public function clear(): bool
{
if (! $this->exists()) {
return true;
}
return $this->filesystem->delete($this->path);
}
public function write(Registry $registry): bool
{
$contents = $this->generateCacheFile($registry);
return false !== $this->filesystem->put($this->path, $contents);
}
protected function generateCacheFile(Registry $registry)
{
$breadcrumbs = $registry
->map(fn(RouteBreadcrumb $breadcrumb) => $this->exportBreadcrumb($breadcrumb))
->implode(",\n");
$registry_class = Registry::class;
$breadcrumb_class = RouteBreadcrumb::class;
return <<<PHP
<?php
use {$registry_class};
use {$breadcrumb_class};
app(Registry::class)->register(
{$breadcrumbs}
);
PHP;
}
protected function exportBreadcrumb(RouteBreadcrumb $breadcrumb): string
{
$name = var_export($breadcrumb->name, true);
$title = $this->exportResolver($breadcrumb->title);
$parent = $this->exportResolver($breadcrumb->parent);
$url = $this->exportResolver($breadcrumb->url);
return <<<PHP
// '{$breadcrumb->name}'
new RouteBreadcrumb(
$name,
$title,
$parent,
$url
)
PHP;
}
protected function exportResolver(Resolver $resolver): string
{
$fqcn = get_class($resolver);
$callback = var_export($resolver->getSerializedClosure(), true);
return "new \\{$fqcn}({$callback})";
}
}
|
# here is a list of my favorite things
- long walks on the beach
- disco dancing
- OpenSource
- learning Git and GitHub
|
// This file is part of MicropolisJ.
// Copyright (C) 2013 Jason Long
// Portions Copyright (C) 1989-2007 Electronic Arts Inc.
//
// MicropolisJ is free software; you can redistribute it and/or modify
// it under the terms of the GNU GPLv3, with additional terms.
// See the README file, included in this distribution, for details.
package micropolisj.engine;
import static micropolisj.engine.TileConstants.*;
class Bulldozer extends ToolStroke
{
Bulldozer(Micropolis city, int xpos, int ypos)
{
super(city, MicropolisTool.BULLDOZER, xpos, ypos);
}
@Override
protected void applyArea(ToolEffectIfc eff)
{
CityRect b = getBounds();
// scan selection area for rubble, forest, etc...
for (int y = 0; y < b.height; y++) {
for (int x = 0; x < b.width; x++) {
ToolEffectIfc subEff = new TranslatedToolEffect(eff, b.x+x, b.y+y);
if (city.isTileDozeable(subEff)) {
dozeField(subEff);
}
}
}
// scan selection area for zones...
for (int y = 0; y < b.height; y++) {
for (int x = 0; x < b.width; x++) {
if (isZoneCenter(eff.getTile(b.x+x,b.y+y))) {
dozeZone(new TranslatedToolEffect(eff, b.x+x, b.y+y));
}
}
}
}
void dozeZone(ToolEffectIfc eff)
{
int currTile = eff.getTile(0, 0);
// zone center bit is set
assert isZoneCenter(currTile);
CityDimension dim = getZoneSizeFor(currTile);
assert dim != null;
assert dim.width >= 3;
assert dim.height >= 3;
eff.spend(1);
// make explosion sound;
// bigger zones => bigger explosions
if (dim.width * dim.height < 16) {
eff.makeSound(0, 0, Sound.EXPLOSION_HIGH);
}
else if (dim.width * dim.height < 36) {
eff.makeSound(0, 0, Sound.EXPLOSION_LOW);
}
else {
eff.makeSound(0, 0, Sound.EXPLOSION_BOTH);
}
putRubble(new TranslatedToolEffect(eff, -1, -1), dim.width, dim.height);
return;
}
void dozeField(ToolEffectIfc eff)
{
int tile = eff.getTile(0, 0);
if (isOverWater(tile))
{
// dozing over water, replace with water.
eff.setTile(0, 0, RIVER);
}
else
{
// dozing on land, replace with land. Simple, eh?
eff.setTile(0, 0, DIRT);
}
fixZone(eff);
eff.spend(1);
return;
}
void putRubble(ToolEffectIfc eff, int w, int h)
{
for (int yy = 0; yy < h; yy++) {
for (int xx = 0; xx < w; xx++) {
int tile = eff.getTile(xx,yy);
if (tile == CLEAR)
continue;
if (tile != RADTILE && tile != DIRT) {
int z = inPreview ? 0 : city.PRNG.nextInt(3);
int nTile = TINYEXP + z;
eff.setTile(xx, yy, nTile);
}
}
}
fixBorder(eff, w, h);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TRMDataManager.Library.Internal.DataAccess;
using TRMDataManager.Library.Models;
namespace TRMDataManager.Library.DataAccess
{
public class SaleData
{
public void SaveSale(SaleModel saleInfo, string cashierId)
{
// TODO: Make sure this is SOLID/DRY/Better
// Start filling in the sale detail models we will save to the database
List<SaleDetailDBModel> details = new List<SaleDetailDBModel>();
ProductData products = new ProductData();
var taxRate = ConfigHelper.GetTaxRate() / 100;
foreach (var item in saleInfo.SaleDetails)
{
var detail = new SaleDetailDBModel
{
ProductId = item.ProductId,
Quantity = item.Quantity
};
// Get the information about this product
var productInfo = products.GetProductById(detail.ProductId);
if (productInfo == null)
{
throw new Exception($"The product Id of { detail.ProductId } could not be found in the database.");
}
detail.PurchasePrice = (productInfo.RetailPrice * detail.Quantity);
if (productInfo.IsTaxable)
{
detail.Tax = (detail.PurchasePrice * taxRate);
}
details.Add(detail);
}
// Create the sale model
SaleDBModel sale = new SaleDBModel
{
SubTotal = details.Sum(x => x.PurchasePrice),
Tax = details.Sum(x => x.Tax),
CashierId = cashierId
};
sale.Total = sale.SubTotal + sale.Tax;
using (SqlDataAccess sql = new SqlDataAccess())
{
try
{
sql.StartTransaction("TRMData");
// Save the Sale model
sql.SaveDataInTransaction("dbo.spSale_Insert", sale);
// Get the ID from the sale model
sale.Id = sql.LoadDataInTransaction<int, dynamic>("spSale_Lookup", new { sale.CashierId, sale.SaleDate }).FirstOrDefault();
// Finish filling in the sale details models
foreach (var item in details)
{
item.SaleId = sale.Id;
// Save the sale detail models
sql.SaveDataInTransaction("dbo.spSaleDetail_Insert", item);
}
sql.CommitTransaction();
}
catch
{
sql.RollbackTransaction();
throw;
}
}
}
public List<SaleReportModel> GetSaleReport()
{
SqlDataAccess sql = new SqlDataAccess();
var output = sql.LoadData<SaleReportModel, dynamic>("dbo.spSale_SaleReport", new { }, "TRMData");
return output;
}
}
}
|
package reactivecircus.flowbinding.android.widget
import android.view.MenuItem
import android.widget.PopupMenu
import androidx.test.filters.LargeTest
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import reactivecircus.flowbinding.android.fixtures.widget.AndroidWidgetFragment
import reactivecircus.flowbinding.testing.FlowRecorder
import reactivecircus.flowbinding.testing.launchTest
import reactivecircus.flowbinding.testing.recordWith
@LargeTest
class PopupMenuItemClickFlowTest {
@Test
fun popupMenuItemClicks() {
launchTest<AndroidWidgetFragment> {
val recorder = FlowRecorder<MenuItem>(testScope)
val popupMenu = PopupMenu(rootView.context, rootView)
val menu = popupMenu.menu
val item1 = menu.add(0, 1, 0, "menu 1")
val item2 = menu.add(0, 2, 0, "menu 2")
popupMenu.itemClicks().recordWith(recorder)
recorder.assertNoMoreValues()
menu.performIdentifierAction(1, 0)
assertThat(recorder.takeValue())
.isEqualTo(item1)
menu.performIdentifierAction(2, 0)
assertThat(recorder.takeValue())
.isEqualTo(item2)
recorder.assertNoMoreValues()
cancelTestScope()
menu.performIdentifierAction(1, 0)
recorder.assertNoMoreValues()
}
}
}
|
# Improved Fibonacci
# Time Complexity - O(n)
# Space Complexity - O(n)
# Hint, you may want a recursive helper method
def fibonacci(n)
return 1 if n == 1 || n == 2
return 0 if n == 0
raise ArgumentError if n < 0
fibonacci(n - 1) + fibonacci(n - 2)
end
|
export * from './createRequestAndResponseTypes'
export * from './decorateWithHttpMethod'
export * from './HttpMethod'
|
/**
*
*/
package com.github.biticcf.mountain.domain;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.github.biticcf.mountain.core.common.result.WdCallbackResult;
import com.github.biticcf.mountain.domain.support.ConstantContext;
import com.github.biticcf.mountain.model.DemoModel;
import com.github.biticcf.mountain.model.enums.ResultEnum;
/**
* author: DanielCao
* date: 2017年5月9日
* time: 下午5:09:04
*
*/
@Service("demoInsertDomain")
@Scope("prototype")
public class DemoInsertDomain extends AbstractBaseDomain<DemoModel> {
private ConstantContext constantContext;
private DemoModel demoModel;
// 注意:service中的参数通过构造方法传入domain,构造方法第一参数必须是ConstantContext,之后的参数顺序与service方法中的顺序必须一致
public DemoInsertDomain(ConstantContext constantContext, DemoModel demoModel) {
super(constantContext);
this.constantContext = constantContext;
this.demoModel = demoModel;
}
@Override
public WdCallbackResult<DemoModel> executeCheck() {
// 检查参数
return WdCallbackResult.success(ResultEnum.SUCCESS.getCode());
}
@Override
public WdCallbackResult<DemoModel> executeAction() {
// 保存demoModel
int rt = constantContext.getDemoDomainRepository().insert(demoModel);
if (rt <= 0) {
return WdCallbackResult.failure(ResultEnum.SYS_ERROR.getCode(), "保存数据失败");
}
return WdCallbackResult.success(ResultEnum.SUCCESS.getCode(), demoModel);
}
@Override
public void executeAfterSuccess() {
// TODO Auto-generated method stub
}
@Override
public void executeAfterFailure(Throwable e) {
// TODO Auto-generated method stub
}
}
|
# This is intentionally busted
describe "uninitialized constant error" do
it "should error" do
expect(NonExistingClass.true).to be(true)
end
end
|
# Colt
Colt is a proxy generator in python it's the best it works very well (open sources)
I also give you proxies that were generated with colt

|
#!/bin/bash
# login
{
./scripts/vpn-login
} || {
exit 1
}
# $3 is tag which is short name for vpn locations
{
windscribe connect $3
} || {
exit 1
}
|
InvoiceType = GraphQL::ObjectType.define do
name 'Invoice'
description 'An Invoice'
field :id, !types.Int
field :fee_in_cents, types.Int
end
|
# Frontend Introduction
This project is used as an internal project for teaching purposes.
### Installation
This project requires [Node.js](https://nodejs.org/) v4+ and [NPM](https://npmjs.or) to run.
First, clone the project.
```sh
$ git clone git@github.com:chrlvclaudiu/frontend-introduction.git
$ cd frontend-introduction
```
Install the dependencies and devDependencies and start the server.
```sh
$ npm install
$ npm start
```
### Development
Want to contribute? Great!
Author
----
Mihai Vaduva (mihai.vaduva@dreamproduction.com)
License
----
MIT
**Made with ♥ in Timisoara (DP)**
|
require "rails_helper"
RSpec.describe "Submit notifications", :with_stubbed_antivirus, type: :feature do
let(:responsible_person) { create(:responsible_person_with_user, :with_a_contact_person) }
let(:user) { responsible_person.responsible_person_users.first.user }
before do
sign_in_as_member_of_responsible_person(responsible_person, user)
end
scenario "Notification with one nano materials and two items" do
visit "/responsible_persons/#{responsible_person.id}/notifications"
click_on "Add a cosmetic product"
complete_product_wizard(name: "Product no nano two items", items_count: 2, nano_materials_count: 1)
expect_progress(1, 5)
complete_nano_material_wizard("Nano one", nano_material_number: 1)
expect_progress(2, 5)
expect_multi_item_kit_task_not_started
complete_multi_item_kit_wizard
expect_progress(3, 5)
expect_item_task_not_started "Item #1"
expect_item_task_not_started "Item #2"
complete_item_wizard("Cream one", item_number: 1, nanos: ["Nano one"])
expect_progress(3, 5)
expect_item_task_not_started "Item #2"
complete_item_wizard("Cream two", item_number: 2, nanos: [nil])
expect_progress(4, 5)
accept_and_submit_flow
expect_successful_submission
end
end
|
using System;
using System.Threading.Tasks;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using Newtonsoft.Json;
namespace GitHubHook
{
public sealed class LambdaHandler
{
internal const string XGitHubDeliveryHeaderKey = "X-GitHub-Delivery";
internal const string XGitHubEventHeaderKey = "X-GitHub-Event";
private readonly IAuthentication authentication;
private readonly IEventHandlersRegistry eventHandlers;
private readonly IEventPayloadFactory eventPayloadFactory;
public LambdaHandler(
IAuthentication authentication,
IEventHandlersRegistry eventHandlers,
IEventPayloadFactory eventPayloadFactory)
{
this.authentication = authentication;
this.eventHandlers = eventHandlers;
this.eventPayloadFactory = eventPayloadFactory;
}
public async Task<APIGatewayProxyResponse> Handle(APIGatewayProxyRequest request, ILambdaContext context)
{
var authenticationResult = authentication.Authenticate(request);
switch (authenticationResult)
{
case AuthenticationResult.Success:
context.Logger.Log("DEBUG: Request signature validated");
break;
case AuthenticationResult.SignatureNotRequired:
context.Logger.Log("WARNING: Request is not signed");
break;
case AuthenticationResult.HasSignatureButMissingSecretToken:
return new APIGatewayProxyResponse
{
StatusCode = 500,
Body = "ERROR: Secret token not configured"
};
case AuthenticationResult.InvalidSignature:
return new APIGatewayProxyResponse
{
StatusCode = 400,
Body = "ERROR: Invalid signature"
};
case AuthenticationResult.InvalidPayload:
return new APIGatewayProxyResponse
{
StatusCode = 400,
Body = "ERROR: Invalid payload"
};
case AuthenticationResult.MismatchedSignature:
return new APIGatewayProxyResponse
{
StatusCode = 401,
Body = "ERROR: Mismatched signature"
};
default:
throw new NotImplementedException($"Unknown authentication result '{authenticationResult}'");
}
if (!request.Headers.TryGetValue(XGitHubDeliveryHeaderKey, out var deliveryId))
{
return new APIGatewayProxyResponse
{
StatusCode = 400,
Body = $"Missing {XGitHubDeliveryHeaderKey} header"
};
}
if (!request.Headers.TryGetValue(XGitHubEventHeaderKey, out var eventId))
{
return new APIGatewayProxyResponse
{
StatusCode = 400,
Body = $"Missing {XGitHubEventHeaderKey} header"
};
}
context.Logger.Log($"DEBUG: Processing delivery {deliveryId} ({eventId})");
var deliveryResult = new DeliveryResult();
var eventPayload = eventPayloadFactory.CreateEventPayload(eventId, request.Body);
deliveryResult.SetEventPayloadType(eventPayload.GetType());
context.Logger.Log($"DEBUG: Payload deserialized as {eventPayload.GetType().Name}");
var handlers = eventHandlers.GetEventHandlersOrDefault(eventPayload);
foreach (var handler in handlers)
{
var result = await handler.HandleEvent(request, context, deliveryId, eventPayload);
var resultString = $"{handler}: {result}";
deliveryResult.EventHandlerResults.Add(resultString);
context.Logger.Log($"DEBUG: {resultString}");
}
return new APIGatewayProxyResponse
{
StatusCode = 200,
Body = JsonConvert.SerializeObject(deliveryResult, Formatting.Indented)
};
}
}
}
|
use crate::utils::error;
/// bm delete NAME
/// Print help text and exit with non-zero code.
pub fn print_help() {
let help = r#"
NAME
bm - Bookmark Manager
SYNOPSIS
bm [command] [options]
DESCRIPTION
This utility provides shell bookmarks that allows you to save paths and use them.
Bookmarks are kept in file called `store file`. Store file is located/created in
`~/.bm/store.toml` path. Store file is an TOML file.
COMMANDS
add Adds bookmark.
add <name> [options] Adds current directory to bookmarks with given name.
add <name> <path> [options] Adds given directory to bookmarks with given name.
show Show bookmark.
show Show all bookmarks.
show <name> Show bookmark with given name.
delete
delete <name> Delete bookmark with given name
help Prints this help text.
debug Activates debug mode for other commands.
Must be given as the first argument to application.
Example: bm debug add name path --option
OPTIONS
-o, --overwrite Overwrite previous value of bookmark.
-a, --add-anyway Add path even if it does not exist.
-d, --directory-only Add bookmark if it is directory only.
If -f is provided last, -f will be used.
-f, --file-only Add bookmark if it is file only.
If -d is provided last, -d will be used.
-h, --help Prints help text.
RETURN CODES
0 Success.
1 Unrecognized argument.
2 No command argument is provided.
3 User's Home Directoty cannot be accessed.
4 Store file parsing error.
5 Store file serialization error.
6 Unable to write to store file.
7 Command verification error for given options of command.
8 Impossible command error.
9 Add Command: Given bookmark path is not found.
10 Add Command: Given Option/Flag is not recognized.
11 Add Command: Given name already exists and overwrite option not given.
12 Add Command: Given path is not given path type (file or directory).
13 Show Command: Given name not found in store.
14 Delete Command: No name is given.
15 Delete Command: Given name not found in store.
255 Help is printed.
"#;
print!("{}\n",help);
std::process::exit(error::ErrorCode::HelpPrinted as i32);
}
|
push!(LOAD_PATH, "../src")
using CASIM
render_option = Not_Render()
sim_horizon = 5000
num_run = 10
init_num_ac = 100
# spawn_rates = [1000., 2000., 4000., 6000.] ./ 3600
spawn_rates = [250., 500., 1000., 1500., 2000., 4000.] ./ 3600
# spawn_rates = 4000. / 3600
"""
VICAS + Multi
spawn_rates
"""
exp = "SpawnRates_VICAS_10km_init_ac_" * string(init_num_ac) * "/" * VICAS_policyname # to make sub-folder
if !ispath("../simulation_results/SpawnRates_VICAS_10km_init_ac_" * string(init_num_ac))
mkdir("../simulation_results/SpawnRates_VICAS_10km_init_ac_" * string(init_num_ac))
end
cas = VICAS()
cas_ctrl = Uniform_CAS(cas)
sensor = Multi_Threat_Tracker()
sensor_ctrl = Uniform_Sensor(sensor)
# for run in 1:num_run
for run in 7:num_run
for spawn_rate in spawn_rates
scheme = "Multi_sr_" *
string(Int(spawn_rate * 3600)) * "_run_" * string(run)
airspace_ctrl = Constant_Spawn_Rate_Controller(init_num_ac, spawn_rate)
simulate(exp, scheme, sim_horizon, airspace_ctrl, cas_ctrl, sensor_ctrl, render_option)
end
end
|
package sequence_test
import (
"testing"
"github.com/kode4food/ale/data"
"github.com/kode4food/ale/internal/assert"
. "github.com/kode4food/ale/internal/assert/helpers"
"github.com/kode4food/ale/internal/sequence"
)
func TestFilter(t *testing.T) {
as := assert.New(t)
filterTest := data.Applicative(func(args ...data.Value) data.Value {
return B(string(args[0].(data.String)) != "filtered out")
}, 1)
l := L(S("first"), S("filtered out"), S("last"))
w := sequence.Filter(l, filterTest)
v1 := w.First()
as.String("first", v1)
v2 := w.Rest().First()
as.String("last", v2)
r1 := w.Rest().Rest()
as.True(r1.IsEmpty())
p := w.(data.Prepender).Prepend(S("filtered out"))
v4 := p.First()
r2 := p.Rest()
as.String("filtered out", v4)
as.Equal(w.First(), r2.First())
}
func TestFiltered(t *testing.T) {
as := assert.New(t)
l := L(S("first"), S("middle"), S("last"))
fn1 := data.Applicative(func(args ...data.Value) data.Value {
return B(string(args[0].(data.String)) != "middle")
}, 1)
w1 := sequence.Filter(l, fn1)
v1 := w1.First()
as.String("first", v1)
v2 := w1.Rest().First()
as.String("last", v2)
r1 := w1.Rest().Rest()
as.True(r1.IsEmpty())
}
|
//! Functions for creating and sending HTTP requests and receiving responses.
//!
#![no_std]
#![feature(slice_concat_ext)]
#[macro_use] extern crate log;
extern crate alloc;
extern crate smoltcp;
extern crate network_manager;
extern crate hpet;
extern crate httparse;
#[macro_use] extern crate smoltcp_helper;
use core::str;
use alloc::vec::Vec;
use alloc::string::String;
use hpet::get_hpet;
use smoltcp::{
socket::{SocketSet, TcpSocket, SocketHandle},
};
use network_manager::{NetworkInterfaceRef};
use smoltcp_helper::{millis_since, poll_iface};
/// The states that implement the finite state machine for
/// sending and receiving the HTTP request and response, respectively.
#[derive(Debug)]
enum HttpState {
/// The socket is connected, but the HTTP request has not yet been sent.
Requesting,
/// The HTTP request has been sent, but the response has not yet been fully received.
ReceivingResponse,
/// The response has been received in full, including the headers and the entire content.
Responded
}
/// Checks to see if the provided HTTP request can be properly parsed, and returns true if so.
pub fn check_http_request(request_bytes: &[u8]) -> bool {
let mut headers = [httparse::EMPTY_HEADER; 64];
let mut request = httparse::Request::new(&mut headers);
request.parse(request_bytes).is_ok() && request_bytes.ends_with(b"\r\n\r\n")
}
/// TODO: create a proper HttpRequest type with header creation fields and actual verification
pub type HttpRequest = String;
/// An HttpResponse that has been fully received from a remote server.
///
/// TODO: revamp this structure to not store redundant data
pub struct HttpResponse {
/// The actual array of raw bytes received from the server,
/// including all of the headers and body.
pub packet: Vec<u8>,
/// The length of all headers
pub header_length: usize,
/// The status code, e.g., 200, 404
pub status_code: u16,
/// The reason, e.g., "OK", "File not found"
pub reason: String,
}
impl HttpResponse {
pub fn header_bytes(&self) -> &[u8] {
&self.packet[0 .. self.header_length]
}
fn content(&self) -> &[u8] {
&self.packet[self.header_length ..]
}
/// Returns the content of this `HttpResponse` as a `Result`,
/// in which `Ok(content)` is returned if the status code is 200 (Ok),
/// and `Err((status_code, reason))` is returned otherwise.
pub fn as_result(&self) -> Result<&[u8], (u16, &str)> {
if self.status_code == 200 {
Ok(self.content())
} else {
Err((self.status_code, &self.reason))
}
}
/// A convenience function that just returns a standard Err `&str`.
pub fn as_result_err_str(&self) -> Result<&[u8], &'static str> {
self.as_result().map_err(|_e| {
error!("HttpResponse: error code {}, reason {:?}", _e.0, _e.1);
"HttpResponse had an error status code (not Ok 200)"
})
}
}
/// A convenience struct that packages together a connected TCP socket
/// with other elements that are necessary to transceive packets.
pub struct ConnectedTcpSocket<'i, 's, 'sockset_a, 'sockset_b, 'sockset_c> {
iface: &'i NetworkInterfaceRef,
sockets: &'s mut SocketSet<'sockset_a, 'sockset_b, 'sockset_c>,
handle: SocketHandle,
}
impl<'i, 's, 'sockset_a, 'sockset_b, 'sockset_c> ConnectedTcpSocket<'i, 's, 'sockset_a, 'sockset_b, 'sockset_c> {
/// Create a new `ConnectedTcpSocket` with the given necessary items:
/// # Arguments
/// * `iface`: a reference to the `NetworkInterface` that the given TCP socket was created on and uses for transceiving packets.
/// * `sockets`: the set of sockets that includes the given TCP socket (usually just a set with just that one socket).
/// * `tcp_socket_handle`: the handle of the TCP socket, which must be in the given `sockets` set and be already connected to the remote endpoint.
///
/// Returns an `Err` result if the TCP socket isn't connected to the remote endpoint.
///
pub fn new(
iface: &'i NetworkInterfaceRef,
sockets: &'s mut SocketSet<'sockset_a, 'sockset_b, 'sockset_c>,
tcp_socket_handle: SocketHandle,
) -> Result<ConnectedTcpSocket<'i, 's, 'sockset_a, 'sockset_b, 'sockset_c>, &'static str> {
// ensure the socket actually connected to the remote endpoint (i.e., it should be able to send/recv)
{
let socket = sockets.get::<TcpSocket>(tcp_socket_handle);
let connected = socket.may_send() && socket.may_recv();
if !connected {
return Err("http_client: the given TCP socket wasn't connected to the remote endpoint");
}
}
Ok(ConnectedTcpSocket {
iface: iface,
sockets: sockets,
handle: tcp_socket_handle,
})
}
}
/// Sends the given HTTP request over the network via the given `socket` on the given `interface`,
/// waits to receive a full HTTP response from the remote endpoint,
/// and then returns that full response, or an error if the response wasn't fully received properly.
///
/// # Arguments
/// * `request`: the HTTP request to be sent via the connected socket.
/// * `tcp_socket`: the connected TCP socket that will be used to send the HTTP request and receive the response.
/// * `inactivity_timeout_millis`: the timeout in milliseconds that limits how long this function will wait during periods of inactivity.
/// This is not a timeout that bounds the total execution time of this function; the timer is reset when a packet is received.
/// For example, a value of `5000` means that the function will give up if more than 5 seconds elapses without any packets being received.
///
pub fn send_request(
request: HttpRequest,
tcp_socket: &mut ConnectedTcpSocket,
timeout_millis: Option<u64>,
) -> Result<HttpResponse, &'static str> {
// validate the HTTP request
if !check_http_request(request.as_bytes()) {
return Err("http_client: given HTTP request was improperly formatted or incomplete");
}
let ConnectedTcpSocket { iface, sockets, handle } = tcp_socket;
let mut _loop_ctr = 0;
let mut state = HttpState::Requesting;
let mut packet_byte_buffer: Vec<u8> = Vec::new();
let mut packet_header_length: Option<usize> = None;
let mut response_status_code: Option<u16> = None;
let mut response_reason: Option<String> = None;
let startup_time = hpet_ticks!();
let mut latest_packet_timestamp = startup_time;
// in the loop below, we do the actual work of sending the request and receiving the response
loop {
_loop_ctr += 1;
let _packet_io_occurred = poll_iface(&iface, sockets, startup_time)?;
// check if we have timed out
if let Some(t) = timeout_millis {
if millis_since(latest_packet_timestamp)? > t {
error!("http_client: timed out after {} ms, in state {:?}", t, state);
return Err("http_client: timed out");
}
}
let mut socket = sockets.get::<TcpSocket>(*handle);
state = match state {
HttpState::Requesting if socket.can_send() => {
debug!("http_client: sending HTTP request: {:?}", request);
socket.send_slice(request.as_ref()).expect("http_client: cannot send request");
latest_packet_timestamp = hpet_ticks!();
HttpState::ReceivingResponse
}
HttpState::ReceivingResponse if socket.can_recv() => {
// Stay in the receiving state for now; will be changed later if we receive the entire packet.
let mut new_state = HttpState::ReceivingResponse;
let orig_packet_length = packet_byte_buffer.len();
let recv_result = socket.recv(|data| {
// Eagerly append ALL of the received data onto the end of our packet slice,
// which is necessary to attempt to parse it as an HTTP response.
// Later, we can remove bytes towards the end if we ended up appending too many bytes,
// e.g., we received more than enough bytes and some of them were for the next packet.
packet_byte_buffer.extend_from_slice(data);
let bytes_popped_off = {
// Check to see if we've received the full HTTP response:
// First, by checking whether we have received all of the headers (and can properly parse them)
// Second, by getting the content length header and seeing if we've received the full content (in num bytes)
let mut headers = [httparse::EMPTY_HEADER; 64];
let mut response = httparse::Response::new(&mut headers);
match response.parse(&packet_byte_buffer) {
Ok(httparse::Status::Partial) => {
trace!("http_client: received partial HTTP response...");
// we haven't received all of the HTTP header bytes yet,
// so pop off all of the bytes from the recv buffer into our packet
data.len()
}
Ok(httparse::Status::Complete(total_header_len)) => {
packet_header_length = Some(total_header_len);
response_status_code = response.code;
response_reason = response.reason.map(|s| String::from(s));
// Here: we've received all headers, but we may not be done receiving the full response.
// If there is a "Content-Length" header present, we can use that to see if all the bytes are received.
// If there is no such header, then there might be a "Connection: close" header, indicating that the response is complete.
// If neither headers exist, then there has been an unexpected problem, and we should return an error.
if let Some(content_length_header) = response.headers.iter().find(|h| h.name == "Content-Length") {
match str::from_utf8(content_length_header.value)
.map_err(|_e| "failed to read Content-Length header value as UTF-8 string")
.and_then(|s| s.parse::<usize>()
.map_err(|_e| "failed to parse Content-Length header value as usize")
)
{
Ok(content_length) => {
// debug!("http_client: packet_byte_buffer len: {}, content_length: {}, header_len: {} (_loop_ctr: {})",
// packet_byte_buffer.len(), content_length, total_header_len, _loop_ctr
// );
// the total num of bytes that we want is the length of all the headers + the content
let expected_length = total_header_len + content_length;
if packet_byte_buffer.len() < expected_length {
// here: we haven't gotten all of the content bytes yet, so we pop off all of the bytes received so far
data.len()
} else {
// here: we *have* received all of the content, so the full response is ready
new_state = HttpState::Responded;
// we pop off the exact number of bytes that make up the rest of the content,
// leaving the rest on the recv buffer
expected_length - orig_packet_length
}
}
Err(e) => {
error!("http_client: {}", e);
// upon error, return 0, which instructs the recv() method to pop off no bytes from the recv buffer
0
}
}
}
else {
if let Some(_connection_close_header) = response.headers.iter().find(|h| h.name == "Connection" && h.value == b"close") {
// Here: the remote endpoint closed the connection, meaning that the entire response is on the recv buffer.
new_state = HttpState::Responded;
data.len()
}
else {
error!("http_client: couldn't find Content-Length or Connection header, can't determine end of HTTP response");
// upon error, return 0, which instructs the recv() method to pop off no bytes from the recv buffer
0
}
}
}
Err(_e) => {
error!("http_client: Error parsing incoming html: {:?}", _e);
0
}
}
};
// Since we eagerly appended all of the received bytes onto this buffer,
// we need to fix that up based on how many bytes we actually ended up popping off the recv buffer
packet_byte_buffer.truncate(orig_packet_length + bytes_popped_off);
(bytes_popped_off, ())
});
if let Err(_e) = recv_result {
error!("http_client: receive error on socket: {:?}", _e);
return Err("receive error on socket");
}
// if we just received another packet (the packet buffer changed size), then update the timeout deadline
if orig_packet_length != packet_byte_buffer.len() {
latest_packet_timestamp = hpet_ticks!();
}
new_state
}
HttpState::Responded => {
debug!("http_client: received full {}-byte HTTP response (_loop_ctr: {}).", packet_byte_buffer.len(), _loop_ctr);
break;
}
HttpState::ReceivingResponse if !socket.may_recv() => {
error!("http_client: socket was closed prematurely before full reponse was received! (_loop_ctr: {})", _loop_ctr);
return Err("socket was closed prematurely before full reponse was received!");
}
_ => {
// if _loop_ctr % 50000 == 0 {
// warn!("http_client: waiting in state {:?} for socket to send/recv ...", state);
// }
state
}
}
}
// debug!("http_client: exiting HTTP state loop with state: {:?} (_loop_ctr: {})", state, _loop_ctr);
Ok(HttpResponse {
packet: packet_byte_buffer,
header_length: packet_header_length.ok_or("BUG: received full HTTP response but couldn't determine packet header length")?,
status_code: response_status_code.ok_or("BUG: received full HTTP response but couldn't determine its status code")?,
reason: response_reason.ok_or("BUG: received full HTTP response but couldn't determine its reason phrase")?,
})
}
|
#include <cpp_edmi.h>
#include "edm_wrapper_native_interface.h"
#include "EdmDatabase.h"
#include "ifc_model_internals.h"
namespace ifc_interface {
model::model(const char * path) : d_(new internals)
{
try {
IfcInterface::EdmDatabase ^ db = IfcInterface::EdmDatabase::Instance();
d_->m = db->LoadModel(gcnew String(path));
}
catch (cppw::Error & e) { d_->last_error = e.message.data(); }
}
} // namespace ifc_interface
|
namespace TestingSupport.ErrorHandling
{
public class AttemptTracker
{
public int LastAttempt;
}
}
|
# Consolidating the business of round-having.
module HasRound
extend ActiveSupport::Concern
included do
scope :without_round, -> { where('round_id IS NULL OR round_id = ""') }
end
def round
Round.find(round_id) if round_id?
end
def round?
round_id? && !!round
end
def round_type
round.round_type if round?
end
def applications
round.applications if round?
end
def application_count
round.application_count if round?
end
end
|
#!/bin/bash -e
touch /vol/logs/${HOSTNAME}-php-error.log && chown heap:www-data /vol/logs/${HOSTNAME}-php-error.log
touch /vol/logs/${HOSTNAME}-php-slow.log && chown heap:www-data /vol/logs/${HOSTNAME}-php-slow.log
touch /vol/logs/${HOSTNAME}-php-fpm.log && chown heap:www-data /vol/logs/${HOSTNAME}-php-fpm.log
/systpl/systpl.jinja.py /systpl/fpm-php.ini.tmpl > /etc/php/7.2/fpm/php.ini
/systpl/systpl.jinja.py /systpl/php-fpm.conf.tmpl > /etc/php/7.2/fpm/php-fpm.conf
/systpl/systpl.jinja.py /systpl/apc.ini.tmpl > /etc/php/7.2/mods-available/apcu.ini
/systpl/systpl.jinja.py /systpl/opcache.ini.tmpl > /etc/php/7.2/mods-available/opcache.ini
env | awk 'BEGIN { FS="=" } /^VAR_.*=.+/ { print "env[" $1 "]='\''" $2 "'\''" }' > /etc/php/7.2/fpm/env.conf
exec /usr/sbin/php-fpm7.2 -F
|
package Zing::Types;
use 5.014;
use strict;
use warnings;
use Data::Object::Types::Keywords;
use base 'Data::Object::Types::Library';
extends 'Types::Standard';
# VERSION
register {
name => 'App',
parent => 'Object',
validation => is_instance_of('Zing::App'),
};
register {
name => 'Cartridge',
parent => 'Object',
validation => is_instance_of('Zing::Cartridge'),
};
register {
name => 'Channel',
parent => 'Object',
validation => is_instance_of('Zing::Channel'),
};
register {
name => 'Cli',
parent => 'Object',
validation => is_instance_of('Zing::Cli'),
};
register {
name => 'Cursor',
parent => 'Object',
validation => is_instance_of('Zing::Cursor'),
};
register {
name => 'Daemon',
parent => 'Object',
validation => is_instance_of('Zing::Daemon'),
};
register {
name => 'Data',
parent => 'Object',
validation => is_instance_of('Zing::Data'),
};
register {
name => 'Domain',
parent => 'Object',
validation => is_instance_of('Zing::Domain'),
};
register {
name => 'Encoder',
parent => 'Object',
validation => is_instance_of('Zing::Encoder'),
};
register {
name => 'Entity',
parent => 'Object',
validation => is_instance_of('Zing::Entity'),
};
register {
name => 'Env',
parent => 'Object',
validation => is_instance_of('Zing::Env'),
};
register {
name => 'Error',
parent => 'Object',
validation => is_instance_of('Zing::Error'),
};
register {
name => 'Flow',
parent => 'Object',
validation => is_instance_of('Zing::Flow'),
};
register {
name => 'Fork',
parent => 'Object',
validation => is_instance_of('Zing::Fork'),
};
declare 'Interupt',
as Enum([qw(CHLD HUP INT QUIT TERM USR1 USR2)]);
register {
name => 'ID',
parent => 'Object',
validation => is_instance_of('Zing::ID'),
};
register {
name => 'Journal',
parent => 'Object',
validation => is_instance_of('Zing::Journal'),
};
register {
name => 'Kernel',
parent => 'Object',
validation => is_instance_of('Zing::Kernel'),
};
declare 'Key',
as Str(),
where {
$_ =~ qr(^[^\:]+:[^\:]+:[^\:]+:[^\:]+:[^\:]+$)
};
register {
name => 'KeyVal',
parent => 'Object',
validation => is_instance_of('Zing::KeyVal'),
};
register {
name => 'Launcher',
parent => 'Object',
validation => is_instance_of('Zing::Launcher'),
};
register {
name => 'Logic',
parent => 'Object',
validation => is_instance_of('Zing::Logic'),
};
register {
name => 'Lookup',
parent => 'Object',
validation => is_instance_of('Zing::Lookup'),
};
register {
name => 'Loop',
parent => 'Object',
validation => is_instance_of('Zing::Loop'),
};
register {
name => 'Logger',
parent => 'Object',
validation => is_instance_of('FlightRecorder'),
};
register {
name => 'Mailbox',
parent => 'Object',
validation => is_instance_of('Zing::Mailbox'),
};
register {
name => 'Meta',
parent => 'Object',
validation => is_instance_of('Zing::Meta'),
};
declare 'Name',
as Str(),
where {
$_ =~ qr(^[^\:\*]+$)
};
register {
name => 'Poll',
parent => 'Object',
validation => is_instance_of('Zing::Poll'),
};
register {
name => 'Process',
parent => 'Object',
validation => is_instance_of('Zing::Process'),
};
register {
name => 'PubSub',
parent => 'Object',
validation => is_instance_of('Zing::PubSub'),
};
register {
name => 'Queue',
parent => 'Object',
validation => is_instance_of('Zing::Queue'),
};
register {
name => 'Repo',
parent => 'Object',
validation => is_instance_of('Zing::Repo'),
};
register {
name => 'Ring',
parent => 'Object',
validation => is_instance_of('Zing::Ring'),
};
register {
name => 'Scheduler',
parent => 'Object',
validation => is_instance_of('Zing::Scheduler'),
};
register {
name => 'Search',
parent => 'Object',
validation => is_instance_of('Zing::Search'),
};
declare 'Schedule',
as Tuple([Str(), ArrayRef([Str()]), HashRef()]);
declare 'Scheme',
as Tuple([Str(), ArrayRef(), Int()]);
register {
name => 'Savepoint',
parent => 'Object',
validation => is_instance_of('Zing::Savepoint'),
};
register {
name => 'Simple',
parent => 'Object',
validation => is_instance_of('Zing::Simple'),
};
register {
name => 'Single',
parent => 'Object',
validation => is_instance_of('Zing::Single'),
};
register {
name => 'Space',
parent => 'Object',
validation => is_instance_of('Data::Object::Space'),
};
register {
name => 'Spawner',
parent => 'Object',
validation => is_instance_of('Zing::Spawner'),
};
register {
name => 'Store',
parent => 'Object',
validation => is_instance_of('Zing::Store'),
};
register {
name => 'Table',
parent => 'Object',
validation => is_instance_of('Zing::Table'),
};
declare 'TableType',
as Enum([qw(channel domain keyval lookup queue repo table)]);
register {
name => 'Term',
parent => 'Object',
validation => is_instance_of('Zing::Term'),
};
register {
name => 'Timer',
parent => 'Object',
validation => is_instance_of('Zing::Timer'),
};
register {
name => 'Watcher',
parent => 'Object',
validation => is_instance_of('Zing::Watcher'),
};
register {
name => 'Worker',
parent => 'Object',
validation => is_instance_of('Zing::Worker'),
};
register {
name => 'Zing',
parent => 'Object',
validation => is_instance_of('Zing'),
};
1;
|
-- |A structure-recovering parser for malformed documents.
--
-- Copyright 2007-2008 Arjun Guha.
-- Based on HtmlPrag 0.16 Copyright (C) 2003 - 2005 Neil W. Van Dyke.
--
-- This program is Free Software; you can redistribute it and/or modify it under
-- the terms of the GNU Lesser General Public License as published by the Free
-- Software Foundation; either version 2.1 of the License, or (at your option)
-- any later version. This program is distributed in the hope that it will be
-- useful, but without any warranty; without even the implied warranty of
-- merchantability or fitness for a particular purpose. See
-- <http://www.gnu.org/copyleft/lesser.html> for details. For other license
-- options and consulting, contact the author.
module BrownPLT.Html.PermissiveParser
( html
, parseHtmlFromFile
, parseHtmlFromString
-- tokenizer is exported primarily for testing
, tokens
, Token
, Warning (..)
) where
import Control.Monad
import Text.ParserCombinators.Parsec hiding (token,tokens)
import qualified Text.ParserCombinators.Parsec as Parsec
import Data.Char (toLower)
import Data.List (intersperse)
import qualified BrownPLT.Html.Syntax as Html
import BrownPLT.Html.Syntax (HtmlId,Attribute,Script(..))
type ParsedHtml s = Html.Html SourcePos s
type ParsedAttribute s = Html.Attribute SourcePos s
--------------------------------------------------------------------------------
-- Parsers generate warnings
data Warning = StringWarning SourcePos String
instance Show Warning where
show (StringWarning p s) = "Warning parsing HTML: " ++ s
showList [] s = s
showList (x:xs) s = show x ++ ('\n':showList xs s)
warn:: String -> GenParser tok [Warning] ()
warn s = do
p <- getPosition
updateState ((StringWarning p s):)
noWarnings:: [Warning]
noWarnings = []
-- A structure-recovering parser for malformed documents, derived from
-- Neil W. Van Dyke's htmlprag library for PLT Scheme
-- The elements in the list can legally enclose the 1st element of the pair.
parentConstraints:: [(HtmlId,[HtmlId])]
parentConstraints =
[("area",["map"]),
("body",["html"]),
("caption", ["table"]),
("colgroup", ["table"]),
("dd", ["dl"]),
("dt", ["dl"]),
("frame", ["frameset"]),
("head", ["html"]),
("isindex", ["head"]),
("li", ["dir", "menu", "ol", "ul"]),
("meta", ["head"]),
("noframes", ["frameset"]),
("option", ["select"]),
("p", ["body", "td", "th"]),
("param", ["applet"]),
("tbody", ["table"]),
("td", ["tr"]),
("th", ["tr"]),
("thead", ["table"]),
("title", ["head"]),
("tr", ["table", "tbody", "thead"])]
-- |List of HTML elements that are empty.
emptyElements:: [HtmlId]
emptyElements =
["area", "base", "br", "frame", "hr", "img", "input", "isindex", "keygen",
"link", "meta", "object", "param", "spacer", "wbr"]
isLegalChildOf:: HtmlId -> HtmlId -> Bool
isLegalChildOf child parent =
case lookup child parentConstraints of
Nothing -> True
(Just legalParents) -> parent `elem` legalParents
isEmptyElement:: HtmlId -> Bool
isEmptyElement element = element `elem` emptyElements
--}}}
--------------------------------------------------------------------------------
-- Parses an HTML file into a stream of tokens.
-- The auxillary parsing functions return values of this type.
data Script s => Token s
= Text SourcePos String
| EntityToken SourcePos String
| EntityInt SourcePos Int
| Tag SourcePos HtmlId [Attribute SourcePos s] Bool {-closed?-}
| Script SourcePos s
| Inline SourcePos s String
| EndTag SourcePos HtmlId
| Comment SourcePos String
| DoctypeToken SourcePos String String String (Maybe String)
token:: Script s => Bool -> [Attribute SourcePos s]
-> CharParser [Warning] (Token s)
token expectedScript prevAttrs = case expectedScript of
True -> (liftM2 Script getPosition (parseScriptBlock prevAttrs))
<?> "expected a script after a <script> tag"
False -> doctype <|> comment <|> tag <|> endTag <|> inlineScript <|> entity
<|> text
tokens:: Script s => CharParser [Warning] [Token s]
tokens = (eof >> return []) <|> tokens' where
tokens' = do
t <- token False []
case t of
(Tag _ "script" attrs False) -> do s <- token True attrs
ts <- tokens
return (t:s:ts)
_ -> tokens >>= return.(t:)
--------------------------------------------------------------------------------
-- Parsers for various components of HTML
qname:: CharParser st String
qname = do
x <- letter
xs <- many (noneOf "/*=<>\"\' \v\f\t\r\n")
return (x:xs)
-- |We do not permit spaces between the hyphens and the right-angle in the
-- terminating '-->'.
comment:: Script s => CharParser st (Token s)
comment =
let notDoubleHyphen = try (char '-' >> notFollowedBy (char '-') >> return '-')
notHyphen = noneOf "-"
in do try (string "<!--")
pos <- getPosition
msg <- many (notHyphen <|> notDoubleHyphen)
string "-->"
return (Comment pos msg)
endTag:: Script s => CharParser [Warning] (Token s)
endTag = do
pos <- getPosition
string "</"
name <- qname <?> "closing tag\'s name"
junk <- manyTill anyChar (char '>') -- permits junk between tag name and '>'
unless (null junk) (warn $ "extra characters: " ++ junk ++
"; assuming tag name is " ++ name)
return (EndTag pos name)
doctype:: Script s => CharParser [Warning] (Token s)
doctype = do
p <- getPosition
try (string "<!DOCTYPE")
spaces
top <- qname <?> "top-element name"
spaces
avail <- qname <?> "availability"
spaces
regEtc <- quotedString <?> "registration, etc."
spaces
uri <- optionMaybe quotedString
spaces
string ">"
return (DoctypeToken p top avail regEtc uri)
entity:: Script s => CharParser [Warning] (Token s)
entity = do
char '&'
pos <- getPosition
name <- many alphaNum <|> (char '#' >> many1 digit)
when (null name) (warn "no identifer or number after &")
(char ';' >> return ()) <|> (warn "expected semi-colon after entity")
return (EntityToken pos name)
notScript:: CharParser a Char
notScript = try (char '{' >> notFollowedBy (char '!') >> return '{')
-- Parses raw text, upto an opening angle-bracket ('<').
text:: Script s => CharParser st (Token s)
text = do
pos <- getPosition
cs <- many1 (noneOf "<{" <|> notScript) -- Doesn't consume the terminating angle bracket.
return (Text pos cs)
-- Strings that are either double-quoted or single-quoted. Note that HTML
-- strings contain no escape sequences.
quotedString:: CharParser a String
quotedString =
(char '"' >> manyTill anyChar (char '"')) <|>
(char '\'' >> manyTill anyChar (char '\'')) <?>
"quoted string (double-quotes or single quotes)"
-- Parses text to the right of a triple-stick in an inline expression. We have
-- to ensure that if we read a `!,' it isn't immediately followed by `}.'
initText =
let notEnd = try (char '!' >> notFollowedBy (char '}') >> return '!')
in many1 (notEnd <|> noneOf "!")
scriptValue:: Script s => CharParser a (s,String)
scriptValue =
case parseAttributeScript of
Nothing -> fail "attribute-script parser not defined"
(Just parser) -> do string "{!"
script <- parser
init <- (string "!}" >> return "") <|>
(string "|||" >> initText >>=
(\s -> string "!}" >> return s))
return (script,init)
number:: CharParser a String
number = many1 digit
--
nonquotedAttribute:: CharParser [Warning] String
nonquotedAttribute = do
x <- alphaNum <|> oneOf "_"
xs <- many (noneOf "/*=<>\"\' \v\f\t\r\n")
warn $ "non-quoted attribute value: " ++ (x:xs)
return (x:xs)
attribute:: Script s => CharParser [Warning] (Html.Attribute SourcePos s)
attribute = do
pos <- getPosition
name <- qname <?> "attribute name"
spaces
value <- (do char '='
spaces
(liftM Right scriptValue)
<|> (liftM Left (quotedString <|> nonquotedAttribute))
<?> "attribute value")
<|> (return $ Left "") -- Unspecified values are empty values.
case value of
(Left v) -> return $ Html.Attribute name v pos
(Right (s,d)) -> return $ Html.AttributeExpr pos name s d
-- Takes the name of the immediately-enclosing parent tag as an argument.
tag:: Script s => CharParser [Warning] (Token s)
tag = do
try (char '<' >> notFollowedBy (char '/'))
pos <- getPosition
name <- qname <?> "opening tag\'s name"
spaces
attributes <- (attribute `sepEndBy` spaces)
(char '>' >> return (Tag pos name attributes False))
<|> (string "/>" >> return (Tag pos name attributes True))
<?> "end of tag (i.e. \">\")"
-- Parses an inline (curly-banged) script, if an inline-script parser has been
-- specified (i.e. not Nothing). Two-character lookahead for the ``{!,'' after
-- which control is passed to the inline script parser. Once control returns,
-- the parser expects to see the closing ``!}.''
inlineScript:: Script s => CharParser a (Token s)
inlineScript =
case parseInlineScript of
Nothing -> fail "no inline script parser specified." -- TODO: appropriate?
(Just parser) -> do string "{!" <?> "{! script !}"
pos <- getPosition
script <- parser
spaces
init <- (string "!}" >> return "") <|>
(string "|||" >> initText >>=
(\s -> string "!}" >> return s))
return $ Inline pos script init
-- Parses a stream of tokens, with a script parser, s and returns values of
-- type a.
type TokenParser s a = GenParser (Token s) [Warning] a
instance Script s => Show (Token s) where
show = tokenShow
tokenShow token = case token of
(Text _ s) -> s
(EntityToken _ s) -> "&" ++ s ++ ";"
(EntityInt _ n) -> "&#" ++ show n ++ ";"
(Tag _ id attrs closed) ->
"<" ++ id ++ " ... " ++ closing where
closing = if closed then "/>" else ">"
(Script _ s) -> "/* script body omitted */"
(Inline _ s _)-> "{! /* script */ !}"
(EndTag _ id) -> "</" ++ show id ++ ">"
(Comment _ s) -> "<!-- " ++ show s ++ " -->"
(DoctypeToken _ top avail desc Nothing) ->
"<!DOCTYPE " ++ top ++ " " ++ avail ++ " " ++ show desc ++ ">"
(DoctypeToken _ top avail desc (Just uri)) ->
"<!DOCTYPE " ++ top ++ " " ++ avail ++ " " ++ show desc ++ " "
++ show uri ++ ">"
tokenPos tok = case tok of
(Text p _) -> p
(EntityToken p _) -> p
(EntityInt p _) -> p
(Tag p _ _ _) -> p
(Script p _) -> p
(Inline p _ _) -> p
(EndTag p _) -> p
(Comment p _) -> p
(DoctypeToken p _ _ _ _) -> p
textToken :: Script s => TokenParser s (ParsedHtml s)
textToken = Parsec.token tokenShow tokenPos $ \t -> case t of
Text _ s -> Just (Html.Text s (tokenPos t))
otherwise -> Nothing
entityToken :: Script s => TokenParser s (ParsedHtml s)
entityToken =
Parsec.token tokenShow tokenPos
(\t -> case t of
(EntityToken p s) -> Just (Html.Text ("&" ++ s ++ ";") p)
(EntityInt p n) -> Just (Html.Text ("&#" ++ show n ++ ";") p)
otherwise -> Nothing)
commentToken :: Script s => TokenParser s (ParsedHtml s)
commentToken =
Parsec.token tokenShow tokenPos
(\t -> case t of
(Comment _ s) -> Just (Html.Comment s (tokenPos t))
otherwise -> Nothing)
scriptToken :: Script s => TokenParser s (ParsedHtml s)
scriptToken =
Parsec.token tokenShow tokenPos
(\t -> case t of
(Script p s) -> Just (Html.Script s p)
otherwise -> Nothing)
inlineToken :: Script s => TokenParser s (ParsedHtml s)
inlineToken =
Parsec.token tokenShow tokenPos
(\t -> case t of
(Inline p s d) -> Just (Html.InlineScript s p d)
otherwise -> Nothing)
endToken :: Script s => TokenParser s HtmlId
endToken =
Parsec.token tokenShow tokenPos
(\t -> case t of
(EndTag p s) -> Just s
otherwise -> Nothing)
tagToken :: Script s => TokenParser s (Token s)
tagToken =
Parsec.token tokenShow tokenPos
(\t -> case t of
(Tag p id attrs closed) -> Just t
otherwise -> Nothing)
doctypeToken :: Script s => TokenParser s (Token s)
doctypeToken = Parsec.token tokenShow tokenPos $ \t -> case t of
DoctypeToken _ _ _ _ _ -> Just t
otherwise -> Nothing
--------------------------------------------------------------------------------
-- HTML fragments
-- |An HTML fragment represents an HTML element with a sequence of children.
data HtmlFragment s = Fragment {
fragmentPosition :: SourcePos,
fragmentName :: HtmlId,
fragmentAttributes :: [ParsedAttribute s],
fragmentChildren :: [ParsedHtml s]
}
closeFragment:: HtmlFragment s -> ParsedHtml s
closeFragment (Fragment p htmlId attrs children) =
Html.Element htmlId attrs (reverse children) p
appendChildToFragment child fragment =
fragment { fragmentChildren = child : (fragmentChildren fragment) }
atomic :: Script s => TokenParser s (ParsedHtml s)
atomic =
textToken <|> commentToken <|> scriptToken <|> inlineToken <|> entityToken
maybeClose :: Script s => [HtmlFragment s] -> TokenParser s [HtmlFragment s]
maybeClose es = do
htmlId <- endToken
let close [] = do
warn $ "unmatched closing tag \"" ++ htmlId ++ "\"; ignoring"
return es
close (e:e2:es) | fragmentName e == htmlId = do
return $ (appendChildToFragment (closeFragment e) e2) : es
close (e:e2:es) | otherwise =
let e2' = appendChildToFragment (closeFragment e) e2
in close (e2':es)
close [e] | fragmentName e == htmlId = do
return [e]
close [e] | otherwise = do
warn $ "unmatched closing tag \"" ++ htmlId ++ "\"; ignoring"
return [e]
in close es
open :: Script s => [HtmlFragment s] -> TokenParser s [HtmlFragment s]
open [] = fail "PermissiveParser.open: invalid state (1)"
open (e:es) = do
(Tag p id attrs isClosed) <- tagToken
case isClosed of
True -> return $ (appendChildToFragment (Html.Element id attrs [] p) e) : es
False ->
case isEmptyElement id of
True -> do warn $ "empty-element, \"" ++ id
++ "\" was not immediately closed"
return $ (appendChildToFragment (Html.Element id attrs [] p)
e) : es
False -> do
let fragment = Fragment p id attrs []
-- If we reach the root, simply make 'fragment' a child.
let insert [root] = [fragment,root]
-- The <html> element is the only child of the root. This
-- catches all other elements and makes them children of <html>.
insert [html,root] = [fragment,html,root]
insert (e1:e2:es) | id `isLegalChildOf` (fragmentName e1) =
fragment:e1:e2:es
insert (e1:e2:es) | otherwise =
insert $ (appendChildToFragment (closeFragment e1) e2):es
insert [] = fail "PermissiveParser.open: invalid state (2)"
return $ insert (e:es)
structured es = do
maybeClose es <|> open es
html' :: Script s => [HtmlFragment s] -> TokenParser s [HtmlFragment s]
html' [] = fail "PermissiveParser.html': invalid state (1)"
html' (e:es) =
(do a <- atomic
html' $ (appendChildToFragment a e):es) <|>
(structured (e:es) >>= html') <|>
(return (e:es))
parseRoot = Fragment (error "parseRoot: position is meaningless")
"DOCROOT" (error "parseRoot: attributes are meaningless")
[]
html :: Script s => CharParser [Warning] (Html.Html SourcePos s)
html = do
let parser = do
-- optional doctypeToken -- ignored
fragments <- html' [parseRoot]
case fragments of
[fragment] -> case closeFragment fragment of
Html.Element _ _ (c:_) _ -> do
ws <- getState
return (ws,head [c])
otherwise -> fail "root element not found"
otherwise -> fail "no root / multiple roots"
toks <- tokens -- a stream of HTML entities
pos <- Parsec.getPosition
warnings <- Parsec.getState
case Parsec.runParser parser warnings (Parsec.sourceName pos) toks of
Left e -> fail $ "unparsable HTML: " ++ (show e)
Right (ws,html) -> Parsec.setState ws >> return html
htmlWithWarnings :: Script s
=> CharParser [Warning] (Html.Html SourcePos s,[Warning])
htmlWithWarnings = do
spaces
h <- html
ws <- getState
return (h,ws)
parseHtmlFromString :: Script s => String -> String -> Either Parsec.ParseError (Html.Html SourcePos s,[Warning])
parseHtmlFromString sourceName sourceText =
case Parsec.runParser htmlWithWarnings noWarnings sourceName sourceText of
Left err -> Left err
Right (html,ws) -> Right (html,ws)
parseHtmlFromFile :: Script s
=> String
-> IO (Either Parsec.ParseError
(Html.Html SourcePos s,[Warning]))
parseHtmlFromFile filename = do
chars <- readFile filename
case Parsec.runParser htmlWithWarnings noWarnings filename chars of
Left err -> return (Left err)
Right (html,ws) -> return $ Right (html,ws)
|
# Portal Chess
Trabalho desenvolvido em Introdução à Computação, PUC-Rio, Novembro e Dezembro de 2018.
// a inserir slides
|
// Copyright (C) 2014, Panagiotis Christopoulos Charitos.
// All rights reserved.
// Code licensed under the BSD License.
// http://www.anki3d.org/LICENSE
#include "anki/math/Functions.h"
#include "anki/Config.h"
namespace anki {
//==============================================================================
template<typename Scalar>
static Scalar polynomialSinQuadrant(const Scalar a)
{
return a * (1.0 + a * a * (-0.16666 + a * a *
(0.0083143 - a * a * 0.00018542)));
}
//==============================================================================
template<typename Scalar>
static void sinCosInternal(const Scalar a_, Scalar& sina, Scalar& cosa)
{
#if ANKI_DEBUG
sina = sin(a_);
cosa = cos(a_);
#else
Bool negative = false;
Scalar a = a_;
if(a < 0.0)
{
a = -a;
negative = true;
}
const Scalar TWO_OVER_PI = 1.0 / (getPi<Scalar>() / 2.0);
Scalar floatA = TWO_OVER_PI * a;
I intA = (int)floatA;
const Scalar RATIONAL_HALF_PI = 201 / 128.0;
const Scalar REMAINDER_HALF_PI = 4.8382679e-4;
floatA = (a - RATIONAL_HALF_PI * intA) - REMAINDER_HALF_PI * intA;
Scalar floatAMinusHalfPi = (floatA - RATIONAL_HALF_PI) - REMAINDER_HALF_PI;
switch(intA & 3)
{
case 0: // 0 - Pi/2
sina = polynomialSinQuadrant(floatA);
cosa = polynomialSinQuadrant(-floatAMinusHalfPi);
break;
case 1: // Pi/2 - Pi
sina = polynomialSinQuadrant(-floatAMinusHalfPi);
cosa = polynomialSinQuadrant(-floatA);
break;
case 2: // Pi - 3Pi/2
sina = polynomialSinQuadrant(-floatA);
cosa = polynomialSinQuadrant(floatAMinusHalfPi);
break;
case 3: // 3Pi/2 - 2Pi
sina = polynomialSinQuadrant(floatAMinusHalfPi);
cosa = polynomialSinQuadrant(floatA);
break;
};
if(negative)
{
sina = -sina;
}
#endif
}
//==============================================================================
void sinCos(const F32 a, F32& sina, F32& cosa)
{
sinCosInternal(a, sina, cosa);
}
//==============================================================================
void sinCos(const F64 a, F64& sina, F64& cosa)
{
sinCosInternal(a, sina, cosa);
}
} // end namespace anki
|
<?php
namespace Boarrd;
use Boarrd\Framework\Tiles\AbstractTile;
use Facades\Boarrd\Twitter\Helpers\TweetHistory;
class Twitter extends AbstractTile
{
public function __construct(string $position)
{
parent::__construct($position);
$this->requireAttributes('initial-tweets');
}
protected function getInitialTweetsAttribute()
{
return e(json_encode(TweetHistory::getTweets()));
}
public function getElement()
{
return parent::getElement()->setVueAttribute('initial-tweets');
}
}
|
import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:todolist/bloc/home/home_event.dart';
import 'package:todolist/bloc/home/home_state.dart';
import 'package:todolist/bloc/schedule/bloc.dart';
import 'package:todolist/model/task.dart';
import 'package:todolist/repository/home_repository.dart';
class HomeBloc extends Bloc<HomeEvent, HomeState> {
final homeRepo = HomeRepo();
final now = DateTime.now();
StreamSubscription _subscription;
ScheduleBloc _scheduleBloc;
HomeBloc(HomeState initialState, ScheduleBloc scheduleBloc)
: super(initialState) {
_scheduleBloc = scheduleBloc;
}
@override
Future<void> close() {
_subscription?.cancel();
return super.close();
}
@override
Stream<HomeState> mapEventToState(HomeEvent event) async* {
final current = state;
try {
if (event is FirstOpen) {
final itemTask = await homeRepo.getTask();
yield HomeLists(itemTask, false);
}
if (event is ListEvent && !_isHasMax(current)) {
if (current is HomeLists) {
final lastItem = current.items.last;
final itemResult = await homeRepo.fetchingPaginate('id', lastItem.id);
if (itemResult.isNotEmpty) {
yield current.copyWith(
newitem: current.items + itemResult, isMax: false);
} else {
yield current.copyWith(isMax: true);
}
}
}
if (event is TaskDoneEvent) {
await homeRepo.isDoneChecklist(
Task.checkUpdate(event.isDone), event.docName);
}
if (event is DeleteTask) {
if(current is HomeLists){
await homeRepo.deleteTask(event.task.docId);
current.items.remove(event.task);
yield current.copyWith(newitem: List<Task>.from(current.items));
}
}
} catch (e) {
print(e);
yield HomeError(e.toString());
}
}
bool _isHasMax(HomeState stateitem) =>
stateitem is HomeLists && stateitem.isMax;
}
|
<?php
namespace app\models;
use Yii;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\web\UploadedFile;
use app\custom\FileStorage;
/**
* This is the model class for table "materials".
*
* @property int $id ИД
* @property int $ref Номер САП
* @property string $name Наименование
* @property float|null $min_qty Крит. низкое кол-во
* @property float|null $max_qty Макс. кол-во
* @property int $unit Ед. измерения
* @property string|null $type Тип
* @property string|null $group Группа
* @property string|null $created_at Дата добавления
* @property string|null $updated_at Дата изменения
* @property int|null $created_by Кто добавил
* @property int|null $updated_by Кто отредактировал
* @property UploadedFile $photo Фото
*
* @property MaterialStock[] $materialsStocks
* @property Stock[] $stocks
* @property float $quantity Текущее кол-во
* @property array $unitsList
* @property string $unitName
* @property User $creator
* @property User $editor
* @property string $photoPath
* @property array $stockAliases
* @property string $shortName
* @property array $groupsList
* @property array $typesList
*/
class Material extends \yii\db\ActiveRecord
{
const PHOTOS_PATH = '@app/web/images/materials/';
const PHOTOS_EXTENSIONS = ['jpg', 'png', 'jpeg'];
const GROUPS_LIST_STORAGE = 'material_groups_list';
const TYPES_LIST_STORAGE = 'material_types_list';
const SHORT_NAME_LENGTH = 37;
const UNIT_UNDEFINED = 0;
const UNIT_PCS = 1;
const UNIT_METERS = 2;
const UNIT_PAIRS = 3;
const UNIT_KG = 4;
public $photo;
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%materials}}';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['ref', 'name'], 'required'],
[['ref', 'unit', 'created_by', 'updated_by'], 'integer'],
[['min_qty', 'max_qty'], 'number', 'min' => 0],
['max_qty', 'compare', 'compareAttribute' => 'min_qty', 'operator' => '>=', 'type' => 'number'],
['min_qty', 'compare', 'compareAttribute' => 'max_qty', 'operator' => '<=', 'type' => 'number'],
[['created_at', 'updated_at'], 'safe'],
[['name'], 'string', 'max' => 128],
[['type', 'group'], 'string', 'max' => 32],
[['ref'], 'unique'],
[['photo'], 'file', 'extensions' => implode(',', self::PHOTOS_EXTENSIONS), 'maxSize' => 1024*1024]
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'ref' => Yii::t('app', 'Ref'),
'name' => Yii::t('app', 'Material name'),
'quantity' => Yii::t('app', 'Qty'),
'min_qty' => Yii::t('app', 'Min qty'),
'max_qty' => Yii::t('app', 'Max qty'),
'unit' => Yii::t('app', 'Unit'),
'type' => Yii::t('app', 'Type'),
'group' => Yii::t('app', 'Group'),
'created_at' => Yii::t('app', 'Created at'),
'updated_at' => Yii::t('app', 'Updated at'),
'created_by' => Yii::t('app', 'Created by'),
'updated_by' => Yii::t('app', 'Updated by'),
'photo' => Yii::t('app', 'Photo'),
'stockAliases' => Yii::t('app', 'Stock places')
];
}
/**
* @inheritDoc
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'value' => Yii::$app->formatter->asDatetime(time()),
],
BlameableBehavior::class
];
}
/**
* @inheritDoc
*/
public function afterSave($insert, $changedAttributes)
{
if ($this->photo = UploadedFile::getInstance($this, 'photo')) {
$this->deletePhoto();
$this->photo->saveAs($this::PHOTOS_PATH . $this->ref . '.' . $this->photo->extension);
}
}
/**
* @return \yii\db\ActiveQuery
*/
public function getMaterialsStocks()
{
return $this->hasMany(MaterialStock::class, ['material_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getStocks()
{
return $this->hasMany(Stock::class, ['id' => 'stock_id'])
->via('materialsStocks');
}
/**
* @param integer $stockId
* @return int|float
*/
public function getQuantity($stockId = 0)
{
$query = $this->getMaterialsStocks()->select('SUM(qty)');
if ($stockId !== 0) {
$query->where(['stock_id' => $stockId]);
}
return !is_null($query->scalar()) ? $query->scalar() + 0 : 0;
}
/**
* @inheritDoc
*/
public function afterDelete()
{
$this->deletePhoto();
}
/**
* Администратор, добавивший данный материал
* @return \yii\db\ActiveQuery
*/
public function getCreator ()
{
return $this->hasOne(User::class, ['id' => 'created_by']);
}
/**
* Администратор, редактировавший данный материал последним
* @return \yii\db\ActiveQuery
*/
public function getEditor ()
{
return $this->hasOne(User::class, ['id' => 'updated_by']);
}
/**
* List of units
* @return array
*/
public function getUnitsList ()
{
return [
self::UNIT_UNDEFINED => Yii::t('app', '?'),
self::UNIT_PCS => Yii::t('app', 'Pcs'),
self::UNIT_METERS => Yii::t('app', 'Meters'),
self::UNIT_PAIRS => Yii::t('app', 'Pairs'),
self::UNIT_KG => Yii::t('app', 'Kg'),
];
}
/**
* Measurement unit name
* @return string
*/
public function getUnitName ()
{
return !empty($this->unitsList[$this->unit]) ?
$this->unitsList[$this->unit] :
$this->unitsList[0];
}
/**
* @return array|null
*/
public function getGroupsList()
{
$fileStorage = new FileStorage();
return $fileStorage->getContent(self::GROUPS_LIST_STORAGE);
}
/**
* @return array|null
*/
public function getTypesList()
{
$fileStorage = new FileStorage();
return $fileStorage->getContent(self::TYPES_LIST_STORAGE);
}
/**
* Путь для отображения фото
* @return string
*/
public function getPhotoPath ()
{
foreach (self::PHOTOS_EXTENSIONS as $extension) {
$path = Yii::getAlias(self::PHOTOS_PATH) . $this->ref . '.' . $extension;
if(is_file($path)) {
return '@web/images/materials/' . $this->ref . '.' . $extension;
}
}
return '';
}
/**
* @return string
*/
public function getEditorName()
{
return $this->editor instanceof User ? $this->editor->fullName : 'not set';
}
/**
* @return string
*/
public function getCreatorName()
{
return $this->creator instanceof User ? $this->creator->fullName : 'not set';
}
/**
* @param string $attr
* @return float|int
*/
public function getExcelTimestamp($attr)
{
$timestamp = (int) Yii::$app->formatter->asTimestamp($this->{$attr});
return 25569 + (($timestamp + Yii::$app->params['timeZoneShift']) / 86400);
}
/**
* @return array
*/
public function getStockAliases ()
{
$aliases = [];
if (!empty($this->stocks) && is_array($this->stocks)) {
$aliases = array_column($this->stocks, 'alias', 'id');
}
return $aliases;
}
/**
* Cut too long material names
* @return string|null
*/
public function getShortName ()
{
$re = '/<[^>]*>/';
$shortText = preg_replace($re, ' ', $this->name);
if (strlen($shortText) < self::SHORT_NAME_LENGTH) {
return $shortText;
}
$shortText = substr($shortText, 0, self::SHORT_NAME_LENGTH);
$end = strlen(strrchr($shortText, ' '));
return substr($shortText, 0, -$end);
}
/**
* Удаление фото материала
*/
private function deletePhoto ()
{
foreach (self::PHOTOS_EXTENSIONS as $extension) {
$path = Yii::getAlias(self::PHOTOS_PATH) . $this->ref . '.' . $extension;
if(is_file($path)) {
unlink($path);
}
}
}
}
|
<?php
namespace App\Exports;
use App\Models\icom;
use App\Models\inc11s;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
class icomExport implements FromCollection,WithHeadings,WithMapping
{
public function headings(): array
{
return[
'Record_Type',
'CardNo',
'Processing_Code',
'txn_amt',
'settle_amt',
'sett_rate',
'system_trace',
'txn_time',
'txn_date',
'settle_date',
'MCC',
'Acq_institution_code',
'Issuer_bank_code',
'beneficiary_bank_code',
'Forward_institution_code',
'auth_no',
'RRN',
'Card_Acceptor_Terminal',
'txn_curr_code',
'settle_curr_code',
'from_acc',
'to_acc',
'msg_type_identifier',
'res_code',
'receivable_fee',
'payable_fee',
'interchange_fee',
'POS_mode',
'system_traceno',
'POS_condition',
'card_acceptor_code',
'accept_amt',
'cardholder_fee',
'txn_tramsmission',
];
}
public function map($icom): array
{
return [
$icom->recordtype,
"'".$icom->CardNo,
$icom->process_code,
$icom->txn_amt,
$icom->settle_amt,
$icom->sett_rate,
$icom->system_trace,
$icom->txn_time,
$icom->txn_date,
$icom->settle_date,
$icom->MCC,
$icom->Acq_institution_code,
$icom->Issuer_bank_code,
$icom->beneficiary_bank_code,
$icom->Forward_institution_code,
$icom->auth_no,
$icom->RRN,
$icom->Card_Acceptor_Terminal,
$icom->txn_curr_code,
$icom->settle_curr_code,
$icom->from_acc,
$icom->to_acc,
$icom->msg_type_identifier,
$icom->res_code,
$icom->receivable_fee,
$icom->payable_fee,
$icom->interchange_fee,
$icom->POS_mode,
$icom->system_traceno,
$icom->POS_condition,
$icom->card_acceptor_code,
$icom->accept_amt,
$icom->cardholder_fee,
$icom->txn_tramsmission,
];
}
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return collect(icom::ICOM());;
}
}
|
'use strict'
import React, {useEffect, useState, useRef} from 'react';
import Compose from '../Compose';
import Toolbar from '../Toolbar';
import ToolbarButton from '../ToolbarButton';
import Message from '../Message';
import moment from 'moment';
import { gql, useQuery, useSubscription } from '@apollo/client';
import './MessageList.css';
import {getChannelMessages} from '../../apis/GraphqlApi'
const SUBSCRIPTION_CHANNEL = gql`
subscription onSubscriptionMessage($channelId: String!) {
channel(channelId: $channelId){
channel {
id
title
description
}
message{
id
payload
userId
createdAt
}
createdAt
}
}
`
export default function ChatBox(props) {
const {sessionInfo } = props
const messageRef = useRef();
const [list, setList] = useState([])
const { channelId } = props
//console.log('MessageList sessionInfo', JSON.stringify(sessionInfo))
useEffect(()=>{
scrollToBottom()
}, []);
getChannelMessages(channelId).then((data)=>{
console.log("get channel messages", data);
const messageList = removeDuplicatedObject([...data.getChannelMessages])
setList(messageList.map((current, idx, messages)=>{
const data = {
id: current.id,
author: current.userId,
message: current.payload,
timestamp: new Date(current.createdAt).getTime()
}
const previous = messages[idx-1]
const next = messages[idx+1]
console.log(current, previous)
const diff = new Date(current.createdAt).getTime() - previous?new Date(previous.createdAt).getTime():0;
const isMine = sessionInfo.user.userId === current.userId?true:false
const startsSequence = previous?false:true
const endsSequence = next?false:true
const showTimestamp = diff>(1000*60*1)?true:false//endsSequence?true:false
return {
id: it.id,
message: current.payload,
end: next? true:false
}
}))
}).catch((err)=>{
console.error(err)
})
return(
<div >
<ChatBot steps={steps} />
</div>
);
}
|
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
namespace Cassandra
{
internal class Hosts
{
private readonly ConcurrentDictionary<IPAddress, Host> _hosts = new ConcurrentDictionary<IPAddress, Host>();
private readonly IReconnectionPolicy _rp;
public Hosts(IReconnectionPolicy rp)
{
_rp = rp;
}
public bool TryGet(IPAddress endpoint, out Host host)
{
return _hosts.TryGetValue(endpoint, out host);
}
public ICollection<Host> ToCollection()
{
return new List<Host>(_hosts.Values);
}
public bool AddIfNotExistsOrBringUpIfDown(IPAddress ep)
{
if (!_hosts.ContainsKey(ep))
if (_hosts.TryAdd(ep, new Host(ep, _rp)))
return true;
Host host;
if (_hosts.TryGetValue(ep, out host))
return host.BringUpIfDown();
return false;
}
public bool SetDownIfExists(IPAddress ep)
{
Host host;
if (_hosts.TryGetValue(ep, out host))
return host.SetDown();
return false;
}
public void RemoveIfExists(IPAddress ep)
{
Host host;
_hosts.TryRemove(ep, out host);
}
public IEnumerable<IPAddress> AllEndPointsToCollection()
{
return new List<IPAddress>(_hosts.Keys);
}
}
}
|
import { TLPerformanceMode, Utils } from '@tldraw/core'
import { Vec } from '@tldraw/vec'
import { SessionType, TldrawCommand, TldrawPatch, TDShape, TDStatus } from '~types'
import { TLDR } from '~state/TLDR'
import { BaseSession } from '../BaseSession'
import type { TldrawApp } from '../../internal'
export class RotateSession extends BaseSession {
type = SessionType.Rotate
status = TDStatus.Transforming
performanceMode = undefined
delta = [0, 0]
commonBoundsCenter: number[]
initialAngle: number
initialShapes: {
shape: TDShape
center: number[]
}[]
changes: Record<string, Partial<TDShape>> = {}
constructor(app: TldrawApp) {
super(app)
const {
app: { currentPageId, pageState, originPoint },
} = this
const initialShapes = TLDR.getSelectedBranchSnapshot(app.state, currentPageId).filter(
(shape) => !shape.isLocked
)
if (initialShapes.length === 0) {
throw Error('No selected shapes!')
}
if (app.rotationInfo.selectedIds === pageState.selectedIds) {
if (app.rotationInfo.center === undefined) {
throw Error('We should have a center for rotation!')
}
this.commonBoundsCenter = app.rotationInfo.center
} else {
this.commonBoundsCenter = Utils.getBoundsCenter(
Utils.getCommonBounds(initialShapes.map(TLDR.getBounds))
)
app.rotationInfo.selectedIds = pageState.selectedIds
app.rotationInfo.center = this.commonBoundsCenter
}
this.initialShapes = initialShapes
.filter((shape) => shape.children === undefined)
.map((shape) => {
return {
shape,
center: this.app.getShapeUtil(shape).getCenter(shape),
}
})
this.initialAngle = Vec.angle(this.commonBoundsCenter, originPoint)
}
start = (): TldrawPatch | undefined => void null
update = (): TldrawPatch | undefined => {
const {
commonBoundsCenter,
initialShapes,
app: { currentPageId, currentPoint, shiftKey },
} = this
const shapes: Record<string, Partial<TDShape>> = {}
let directionDelta = Vec.angle(commonBoundsCenter, currentPoint) - this.initialAngle
if (shiftKey) {
directionDelta = Utils.snapAngleToSegments(directionDelta, 24) // 15 degrees
}
// Update the shapes
initialShapes.forEach(({ center, shape }) => {
const { rotation = 0 } = shape
let shapeDelta = 0
if (shiftKey) {
const snappedRotation = Utils.snapAngleToSegments(rotation, 24)
shapeDelta = snappedRotation - rotation
}
const change = TLDR.getRotatedShapeMutation(
shape,
center,
commonBoundsCenter,
shiftKey ? directionDelta + shapeDelta : directionDelta
)
if (change) {
shapes[shape.id] = change
}
})
this.changes = shapes
return {
document: {
pages: {
[currentPageId]: {
shapes,
},
},
},
}
}
cancel = (): TldrawPatch | undefined => {
const {
initialShapes,
app: { currentPageId },
} = this
const shapes: Record<string, TDShape> = {}
initialShapes.forEach(({ shape }) => (shapes[shape.id] = shape))
return {
document: {
pages: {
[currentPageId]: {
shapes,
},
},
},
}
}
complete = (): TldrawPatch | TldrawCommand | undefined => {
const {
initialShapes,
app: { currentPageId },
} = this
const beforeShapes = {} as Record<string, Partial<TDShape>>
const afterShapes = this.changes
initialShapes.forEach(({ shape: { id, point, rotation, handles } }) => {
beforeShapes[id] = { point, rotation, handles }
})
return {
id: 'rotate',
before: {
document: {
pages: {
[currentPageId]: {
shapes: beforeShapes,
},
},
},
},
after: {
document: {
pages: {
[currentPageId]: {
shapes: afterShapes,
},
},
},
},
}
}
}
|
// Copyright (c) 2018 Joseph R. Quinn <quinn.josephr@protonmail.com>
// SPDX-License-Identifier: ISC
// 3rd party crates
extern crate clap;
#[macro_use]
extern crate slog;
extern crate slog_term;
fn main() {}
|
export function setup(Models, app){
let { Position, Person } = Models;
app.get('/api/positions', (req, res) => {
Position.findAll({
order: [
[ "type", "ASC" ],
[ "order", "ASC" ],
]
}).then(data => {
res.send(data);
}).error(error => {
res.status(500).send("Error getting positions: " + error);
});
});
app.get('/api/position/:id', (req, res) => {
const id = req.params.id;
Position.findById(id, {
include: [{
model: Person,
include: [ Position ],
order: [[ "order", "ASC" ], [ "lastName", "ASC" ]],
attributes: {
exclude: [ "photo" ]
}
}]
}).then(data => {
res.send(data);
}).error(error => {
res.status(500).send("Error getting position: " + error);
});
});
app.delete('/api/position/:id', (req, res) => {
const id = req.params.id;
Position.destroy({
where: {
id: id
}
}).then(() => {
res.send("OK");
}).error(error => {
res.status(500).send("Error deleting position: " + error);
});
});
app.post('/api/position/:id', (req, res) => {
const id = req.params.id;
Position.findById(id).then(per => {
Object.assign(per, req.body);
return per.save().then((p) => {
res.send(p);
});
}).error(error => {
res.status(500).send("Error saving position: " + error);
});
});
app.put('/api/position', (req, res) => {
Position.create(req.body).then(p => {
res.send(p);
}).error(error => {
res.status(500).send("Error creating position: " + error);
});
});
}
|
import {$} from '../dom'
import {ActiveRoute} from './ActiveRoute'
import {Loader} from '../../components/Loader'
export class Router {
constructor(selector, routes) {
if (!selector) {
throw new Error('Selector is not provided in Router')
}
this.$placeholder = $(selector)
this.routes = routes
this.loader = new Loader()
this.page = null
this.changePageHandler = this.changePageHandler.bind(this)
this.init()
}
init() {
window.addEventListener('hashchange', this.changePageHandler)
this.changePageHandler()
}
async changePageHandler() {
if (this.page) {
this.page.destroy()
}
this.$placeholder.clear().append(this.loader)
const Page = ActiveRoute.path.includes('excel')
? this.routes.excel
: this.routes.dashboard
this.page = new Page(ActiveRoute.param)
const root = await this.page.getRoot()
this.$placeholder.clear().append(root)
this.page.afterRender()
}
destroy() {
window.removeEventListener('hashchange', this.changePageHandler)
}
}
|
set :required_gems, []
set :deb_dependency, []
set :git_submodules, false
set :control_scripts, ['postinst', 'postrm', 'preinst', 'prerm']
# package building tool
set :builder, 'fpm'
set :sct, 'git'
set :owner, 'www-data'
set :group, 'www-data'
set :log_dir, '/var/log'
set :restart_service, true
set :keep_releases, 1
set :rsync_exclude, [ '.git', '*.deb' ]
|
using System.Collections.Generic;
using System.Text;
namespace CSPDC
{
public partial class ByteManager
{
public string ReadBytescstring(Encoding Encoder = null, int MaxLength = 65535)
{
if (Encoder == null) Encoder = Encoding.UTF8;
int length = 0;
byte read;
List<byte> result = new List<byte>();
do
{
read = ReadByte();
result.Add(read);
length++;
if (length > MaxLength)
throw new FieldOverflowException("cstring over MaxLength");
} while (read != 0x00);
result.RemoveAt(length - 1); //remove the null byte
byte[] data = result.ToArray();
return Encoder.GetString(data);
}
public void WriteBytescstring(string Value, Encoding Encoder = null, int MaxLength = 65535)
{
if (Encoder == null) Encoder = Encoding.UTF8;
byte[] data = Encoder.GetBytes(Value);
if(data.Length > MaxLength)
throw new FieldOverflowException("cstring over MaxLength");
WriteBytes(data);
WriteByte(0x00);
}
}
}
|
---
layout: post
title: "Waiting for Network Calls with Watir"
subtitle: "a gist for setting an explicit wait against a network call"
date: 2015-08-22
author: "carldmitch"
keywords: Ruby, Watir, Webdriver, Automation, Selenium, Links, Ajax, Javascript, Performance
categories: gist
header-img: "img/04.jpg"
---
This [gist](https://gist.github.com/watirus/31f81c8e08f90de34596){:target="\_blank"},
will go to the requested url and wait beyond the default selenium page load time
until the specific network call is completed.
This is especially useful if you have elements loaded via javascript/ajax
{% highlight ruby %}
def sc_wait_for_js
begin
status = Timeout::timeout(15) {
until @browser.execute_script("return window.performance.getEntries()").to_s.match(/1\/JS/) do
show_wait_cursor(1)
end
}
rescue
puts($!, $@)
end
end
{% endhighlight %}
|
package org.jesperancinha.smtd.furniture.repository
import org.jesperancinha.smtd.furniture.model.Chair
import org.springframework.data.jpa.repository.JpaRepository
interface ChairRepository : JpaRepository<Chair, Long>
|
require 'integration_test_helper'
class PageIntegrationTest < ActionDispatch::CapybaraIntegrationTest
test "should get home page if not logged in" do
visit root_path()
assert !has_css?("p.flash.error")
assert_equal root_path, current_path
end
site_editors.each do |cu|
test "should create new page with #{cu} login" do
login_as send(cu)
visit new_page_path
fill_in "page[path]", :with => "/MyNewPath"
fill_in "page[menu_en]", :with => "MyNewMenu"
fill_in "page[title_en]", :with => "MyNewTitle"
fill_in "page[body_en]", :with => "MyNewBody"
assert_difference('Page.count',1) {
click_button "Create"
wait_until { has_css?("p.flash.notice") }
}
assert has_css?("p.flash.notice") # success
assert_match /\/pages\/\d+/, current_path
end
test "should edit a page with #{cu} login" do
assert Page.count > 0
p = Page.first # DO NOT USE 'page' as it is part of capybara
login_as send(cu)
visit edit_page_path(p)
assert_equal edit_page_path(p), current_path
end
test "should edit and update a page with #{cu} login" do
assert Page.count > 0
p = Page.first # DO NOT USE 'page' as it is part of capybara
login_as send(cu)
visit edit_page_path(p)
fill_in "page[menu_en]", :with => "MyNewMenu"
click_button "Update"
assert has_css?("p.flash.notice")
assert_equal current_path, page_path(p)
end
# How to drag the rows to change the order and test this?
# changing order should enable save_order button
#var initial_page_order;
#jQuery(function(){
# jQuery('#pages').sortable({
# axis:'y',
# dropOnEmpty:false,
# handle:'img.handle',
# update:function(event,ui){compare_page_order()},
# items:'tr.page.row'
# });
#
# jQuery('#save_order').disable();
#
# initial_page_order = page_order();
#
# jQuery('form#order_pages').submit(function(){
# if( initial_page_order == page_order() ) {
# /*
# Shouldn't get here as button should
# be disabled if not different!
# */
# alert("Page order hasn't changed. Nothing to save.");
# return false
# } else {
# new_action = jQuery(this).attr('action');
# if( (/\?/).test(new_action) ){
# new_action += '&';
# } else {
# new_action += '?';
# }
# new_action += page_order();
# jQuery(this).attr('action',new_action);
# }
# })
#
#});
#
#function page_order() {
# return jQuery('#pages').sortable('serialize',{key:'pages[]'});
#}
#
#function compare_page_order(){
# if( initial_page_order == page_order() ) {
# jQuery('#save_order').disable();
# } else {
# jQuery('#save_order').highlight(4000);
# jQuery('#save_order').enable();
# }
#}
end
end
|
<?php
/*
* This file is part of the Silverstripe Bugsnag Logger.
*
* (c) Evolution 7 <http://www.evolution7.com.au>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Interface for ReleaseStage objects for use with the BugsnagLogger
*/
interface ReleaseStageInterface
{
/**
* @return string Textual description of the current release stage
*/
public function get();
}
|
package com.puddlealley.splash
import com.puddlealley.splash.Dispatcher
import com.puddlealley.splash.Payload
import com.puddlealley.splash.PayloadCallback
import io.kotlintest.TestCase
import io.kotlintest.shouldThrow
import io.kotlintest.specs.DescribeSpec
import io.mockk.mockk
import io.mockk.spyk
import io.mockk.verify
import java.util.*
class TestDispatcher : DescribeSpec() {
private var dispatcher = Dispatcher()
private var callbackA = mockk<PayloadCallback>(relaxed = true)
private var callbackB = mockk<PayloadCallback>(relaxed = true)
override fun beforeTest(testCase: TestCase) {
super.beforeTest(testCase)
dispatcher = Dispatcher()
callbackA = mockk<PayloadCallback>(relaxed = true)
callbackB = mockk<PayloadCallback>(relaxed = true)
}
init {
describe("FluxStore") {
it("should execute all subscriber callbacks"){
dispatcher.register(callbackA)
dispatcher.register(callbackB)
class DemoPayload : Payload
val demoPayload = DemoPayload()
dispatcher.dispatch(demoPayload)
verify(exactly = 1) { callbackA.invoke(demoPayload) }
verify(exactly = 1) { callbackB.invoke(demoPayload) }
dispatcher.dispatch(demoPayload)
verify(exactly = 2) { callbackA.invoke(demoPayload) }
verify(exactly = 2) { callbackB.invoke(demoPayload) }
}
it("should wait for callbacks registered earlier") {
val tokenA = dispatcher.register(callbackA)
val demoPayload = object : Payload {}
dispatcher.register { payload ->
dispatcher.waitFor(tokenA)
verify(exactly = 1) { callbackA.invoke(demoPayload) }
callbackB(payload)
}
dispatcher.dispatch(demoPayload)
verify(exactly = 1) { callbackA.invoke(demoPayload) }
verify(exactly = 1) { callbackB.invoke(demoPayload) }
}
it("should wait for callbacks registered later") {
var tokenB : UUID? = null
val demoPayload = object : Payload {}
dispatcher.register{ payload ->
dispatcher.waitFor(tokenB!!)
verify(exactly = 1) { callbackB.invoke(demoPayload) }
callbackA(payload)
}
tokenB = dispatcher.register(callbackB)
dispatcher.dispatch(demoPayload)
verify(exactly = 1) { callbackA.invoke(demoPayload) }
verify(exactly = 1) { callbackB.invoke(demoPayload) }
}
it("should throw if dispatch() while dispatching") {
val demoPayload = object : Payload {}
dispatcher.register{ payload ->
dispatcher.dispatch(payload)
callbackA(demoPayload)
}
shouldThrow<IllegalStateException> {
dispatcher.dispatch(demoPayload)
}
verify(exactly = 0) { callbackA.invoke(demoPayload) }
}
it("should throw if waitFor() while not dispatching") {
val tokenA = dispatcher.register(callbackA)
shouldThrow<IllegalStateException> {
dispatcher.waitFor(tokenA)
}
verify(exactly = 0) { callbackA.invoke(any()) }
}
it("should throw if waitFor() with invalid token"){
var invalidToken = UUID.randomUUID()
val demoPayload = object : Payload {}
dispatcher.register{ dispatcher.waitFor(invalidToken) }
shouldThrow<IllegalStateException> {
dispatcher.dispatch(demoPayload)
}
}
it("should throw on self-circular dependencies") {
var tokenA : UUID? = null
val demoPayload = object : Payload {}
tokenA = dispatcher.register {
dispatcher.waitFor(tokenA!!)
callbackA(demoPayload)
}
shouldThrow<IllegalStateException> {
dispatcher.dispatch(demoPayload)
}
verify(exactly = 0) { callbackA.invoke(any()) }
}
it("should throw on multi-circular dependencies") {
val demoPayload = object : Payload {}
var tokenB : UUID? = null
var tokenA : UUID? = null
tokenA = dispatcher.register {
dispatcher.waitFor(tokenB!!)
callbackA(demoPayload)
}
tokenB = dispatcher.register{
dispatcher.waitFor(tokenA!!)
callbackB(demoPayload)
}
shouldThrow<IllegalStateException> {
dispatcher.dispatch(demoPayload)
}
verify(exactly = 0) { callbackA.invoke(any()) }
verify(exactly = 0) { callbackB.invoke(any()) }
}
it("should remain in a consistent state after a failed dispatch") {
class ShouldThrow(val shouldThrow: Boolean): Payload
dispatcher.register(callbackA)
dispatcher.register { payload ->
if (payload is ShouldThrow && payload.shouldThrow) {
throw IllegalStateException()
}
callbackB(payload)
}
shouldThrow<IllegalStateException> {
dispatcher.dispatch(ShouldThrow(true))
}
// Cannot make assumptions about a failed dispatch.
dispatcher.dispatch(ShouldThrow(false))
verify(exactly = 2) { callbackA.invoke(any()) }
verify(exactly = 1) { callbackB.invoke(any()) }
}
it("should properly unregister callbacks") {
dispatcher.register(callbackA)
val tokenB = dispatcher.register(callbackB)
val demoPayload = object : Payload {}
val demoPayload2 = object : Payload {}
dispatcher.dispatch(demoPayload)
verify(exactly = 1) { callbackA.invoke(demoPayload) }
verify(exactly = 1) { callbackB.invoke(demoPayload) }
dispatcher.unregister(tokenB)
dispatcher.dispatch(demoPayload)
verify(exactly = 2) { callbackA.invoke(any()) }
verify(exactly = 1) { callbackB.invoke(demoPayload) }
}
}
}
}
|
import React from 'react';
import PropTypes from 'prop-types';
import AWS from 'aws-sdk';
import {
Avatar,
Card,
CardContent,
CardHeader,
Divider,
} from '@material-ui/core';
import ChatBubbleRoundedIcon from '@material-ui/icons/ChatBubbleRounded';
import KeyboardArrowDownIcon from '@material-ui/icons/KeyboardArrowDown';
import './styles/chatbot.css';
class LexChat extends React.Component {
static showRequest(daText) {
const conversationDiv = document.getElementById('conversation');
const requestPara = document.createElement('P');
requestPara.className = 'userRequest';
requestPara.appendChild(document.createTextNode(daText));
conversationDiv.appendChild(requestPara);
conversationDiv.scrollTop = conversationDiv.scrollHeight;
}
static showError(daText) {
const conversationDiv = document.getElementById('conversation');
const errorPara = document.createElement('P');
errorPara.className = 'lexError';
errorPara.appendChild(document.createTextNode(daText));
conversationDiv.appendChild(errorPara);
conversationDiv.scrollTop = conversationDiv.scrollHeight;
}
constructor(props) {
super(props);
this.state = {
data: '',
lexUserId: `chatbot-demo${Date.now()}`,
sessionAttributes: {},
visible: 'closed'
};
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
this.showResponse = this.showResponse.bind(this);
}
componentDidMount() {
const { region, IdentityPoolId } = this.props;
document.getElementById('inputField').focus();
AWS.config.region = region || 'us-west-2';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId
});
const lexruntime = new AWS.LexRuntime();
this.lexruntime = lexruntime;
}
handleClick() {
const { visible } = this.state;
this.setState({
visible: visible === 'open' ? 'closed' : 'open'
});
console.log(this.state);
}
handleChange(event) {
event.preventDefault();
this.setState({ data: event.target.value });
}
showResponse(lexResponse) {
const conversationDiv = document.getElementById('conversation');
const responsePara = document.createElement('P');
responsePara.className = 'lexResponse';
if (lexResponse.message) {
responsePara.appendChild(document.createTextNode(lexResponse.message));
responsePara.appendChild(document.createElement('br'));
}
if (lexResponse.dialogState === 'Fulfilled') {
responsePara.appendChild(document.createElement('br'));
Object.entries(lexResponse.slots).forEach(([key, value]) => {
responsePara.appendChild(document.createTextNode(`${key}: ${value}`));
responsePara.appendChild(document.createElement('br'));
});
const { handlePortfolioChange } = this.props;
const { riskLevel } = lexResponse.slots;
if (riskLevel >= 0 && riskLevel < 5) {
handlePortfolioChange('Conservative');
} else if (riskLevel >= 5 && riskLevel < 8) {
handlePortfolioChange('Moderate');
} else if (riskLevel >= 8 && riskLevel < 11) {
handlePortfolioChange('Aggressive');
}
} else {
responsePara.appendChild(document.createTextNode(''));
}
conversationDiv.appendChild(responsePara);
conversationDiv.scrollTop = conversationDiv.scrollHeight;
}
pushChat(event) {
const { botName } = this.props;
const { lexUserId, sessionAttributes } = this.state;
event.preventDefault();
const inputFieldText = document.getElementById('inputField');
if (
inputFieldText
&& inputFieldText.value
&& inputFieldText.value.trim().length > 0
) {
// disable input to show we're sending it
const inputField = inputFieldText.value.trim();
inputFieldText.value = '...';
inputFieldText.locked = true;
// send it to the Lex runtime
const params = {
botAlias: '$LATEST',
botName,
inputText: inputField,
userId: lexUserId,
sessionAttributes
};
LexChat.showRequest(inputField);
const a = function a(err, data) {
if (err) {
console.log(err, err.stack);
LexChat.showError(`Error: ${err.message} (see console for details)`);
}
if (data) {
// capture the sessionAttributes for the next cycle
this.setState({ sessionAttributes: data.sessionAttributes });
// sessionAttributes = data.sessionAttributes;
// show response and/or error/dialog status
this.showResponse(data);
}
// re-enable input
inputFieldText.value = '';
inputFieldText.locked = false;
};
this.lexruntime.postText(params, a.bind(this));
}
// we always cancel form submission
return false;
}
render() {
const {
height,
backgroundColor,
placeholder,
headerText
} = this.props;
const { visible, data } = this.state;
const inputStyle = {
padding: '4px',
fontSize: 24,
width: '388px',
height: '40px',
borderRadius: '1px',
border: '10px'
};
const conversationStyle = {
width: '400px',
height,
border: 'px solid #ccc',
backgroundColor,
padding: '4px',
overflow: 'scroll',
borderBottom: 'thin ridge #bfbfbf'
};
const headerRectStyle = {
backgroundColor: '#5664d2',
width: '408px',
height: '40px',
textAlign: 'center',
paddingTop: 12,
paddingBottom: -12,
color: '#FFFFFF',
fontSize: '24px'
};
const chatcontainerStyle = {
backgroundColor: '#FFFFFF',
width: 408,
bottom: 20
};
const chatFormStyle = {
margin: '1px',
padding: '2px'
};
return (
<div>
<Card
className={visible}
sx={{
bottom: 80,
fontSize: 12,
right: 24,
position: 'fixed',
width: 400
}}
>
<div
id="chatcontainer"
className={visible}
style={chatcontainerStyle}
>
<CardHeader style={headerRectStyle} title={headerText} />
<CardContent id="conversation" style={conversationStyle} />
<Divider />
<form
id="chatform"
style={chatFormStyle}
onSubmit={this.pushChat.bind(this)}
>
<input
type="text"
id="inputField"
autoComplete="off"
size="40"
value={data}
placeholder={placeholder}
onChange={this.handleChange.bind(this)}
style={inputStyle}
/>
</form>
</div>
</Card>
<Avatar
onClick={this.handleClick}
sx={{
position: 'absolute',
backgroundColor: '#5664d2',
height: 56,
width: 56,
bottom: 10,
right: 24
}}
>
{visible === 'open' ? (
<KeyboardArrowDownIcon />
) : (
<ChatBubbleRoundedIcon />
)}
</Avatar>
</div>
);
}
}
LexChat.propTypes = {
botName: PropTypes.string,
IdentityPoolId: PropTypes.string.isRequired,
placeholder: PropTypes.string.isRequired,
region: PropTypes.string.isRequired,
backgroundColor: PropTypes.string,
height: PropTypes.number,
headerText: PropTypes.string,
handlePortfolioChange: PropTypes.func
};
export default LexChat;
|
package com.bakdata.conquery.io.xodus;
import java.io.File;
import javax.validation.Validator;
import com.bakdata.conquery.models.concepts.StructureNode;
import com.bakdata.conquery.models.config.StorageConfig;
import com.bakdata.conquery.models.exceptions.JSONException;
import com.bakdata.conquery.models.identifiable.mapping.PersistentIdMap;
import jetbrains.exodus.env.Environment;
import jetbrains.exodus.env.Environments;
import lombok.NonNull;
public interface NamespaceStorage extends NamespacedStorage {
public static NamespaceStorage tryLoad(Validator validator, StorageConfig config, File directory) {
Environment env = Environments.newInstance(directory, config.getXodus().createConfig());
boolean exists = env.computeInTransaction(t->env.storeExists(StoreInfo.DATASET.getXodusName(), t));
env.close();
if(!exists) {
return null;
}
NamespaceStorage storage = new NamespaceStorageImpl(validator, config, directory);
storage.loadData();
return storage;
}
MasterMetaStorage getMetaStorage();
void setMetaStorage(@NonNull MasterMetaStorage storage);
StructureNode[] getStructure();
void updateStructure(StructureNode[] structure) throws JSONException;
PersistentIdMap getIdMapping();
void updateIdMapping(PersistentIdMap idMap) throws JSONException;
}
|
import zxcvbnOptions from '../../Options'
import { MatchEstimated } from '../../types'
export default (match: MatchEstimated) => {
if (match.regexName === 'recentYear') {
return {
warning: zxcvbnOptions.translations.warnings.recentYears,
suggestions: [
zxcvbnOptions.translations.suggestions.recentYears,
zxcvbnOptions.translations.suggestions.associatedYears,
],
}
}
return {
warning: '',
suggestions: [],
}
}
|
/********************* */
/*! \file floatingpoint.h.in
** \verbatim
** Top contributors (to current version):
** Martin Brain, Tim King, Andres Noetzli
** Copyright (c) 2013 University of Oxford
** This file is part of the CVC4 project.
** Copyright (c) 2009-2018 by the authors listed in the file AUTHORS
** in the top-level source directory) and their institutional affiliations.
** All rights reserved. See the file COPYING in the top-level source
** directory for licensing information.\endverbatim
**
** \brief [[ Utility functions for working with floating point theories. ]]
**
** [[ This file contains the data structures used by the constant and
** parametric types of the floating point theory. ]]
**/
#include <cvc4/cvc4_public.h>
#ifndef __CVC4__FLOATINGPOINT_H
#define __CVC4__FLOATINGPOINT_H
#include <cvc4/util/bitvector.h>
#include <cvc4/util/rational.h>
#include <fenv.h>
#if 0
#include <symfpu/core/unpackedFloat.h>
#endif /* 0 */
namespace CVC4 {
// Inline these!
inline bool CVC4_PUBLIC validExponentSize (unsigned e) { return e >= 2; }
inline bool CVC4_PUBLIC validSignificandSize (unsigned s) { return s >= 2; }
/**
* Floating point sorts are parameterised by two non-zero constants
* giving the width (in bits) of the exponent and significand
* (including the hidden bit).
*/
class CVC4_PUBLIC FloatingPointSize {
/*
Class invariants:
* VALIDEXPONENTSIZE(e)
* VALIDSIGNIFCANDSIZE(s)
*/
private :
unsigned e;
unsigned s;
public :
FloatingPointSize (unsigned _e, unsigned _s);
FloatingPointSize (const FloatingPointSize &old);
inline unsigned exponent (void) const {
return this->e;
}
inline unsigned significand (void) const {
return this->s;
}
bool operator ==(const FloatingPointSize& fps) const {
return (e == fps.e) && (s == fps.s);
}
// Implement the interface that symfpu uses for floating-point formats.
inline unsigned exponentWidth(void) const { return this->exponent(); }
inline unsigned significandWidth(void) const { return this->significand(); }
inline unsigned packedWidth(void) const
{
return this->exponentWidth() + this->significandWidth();
}
inline unsigned packedExponentWidth(void) const
{
return this->exponentWidth();
}
inline unsigned packedSignificandWidth(void) const
{
return this->significandWidth() - 1;
}
}; /* class FloatingPointSize */
struct CVC4_PUBLIC FloatingPointSizeHashFunction {
static inline size_t ROLL(size_t X, size_t N) {
return (((X) << (N)) | ((X) >> (8*sizeof((X)) - (N)) ));
}
inline size_t operator() (const FloatingPointSize& fpt) const {
return size_t(ROLL(fpt.exponent(), 4*sizeof(unsigned)) |
fpt.significand());
}
}; /* struct FloatingPointSizeHashFunction */
/**
* A concrete instance of the rounding mode sort
*/
enum CVC4_PUBLIC RoundingMode {
roundNearestTiesToEven = FE_TONEAREST,
roundTowardPositive = FE_UPWARD,
roundTowardNegative = FE_DOWNWARD,
roundTowardZero = FE_TOWARDZERO,
// Initializes this to the diagonalization of the 4 other values.
roundNearestTiesToAway = (((~FE_TONEAREST) & 0x1) | ((~FE_UPWARD) & 0x2) |
((~FE_DOWNWARD) & 0x4) | ((~FE_TOWARDZERO) & 0x8))
}; /* enum RoundingMode */
struct CVC4_PUBLIC RoundingModeHashFunction {
inline size_t operator() (const RoundingMode& rm) const {
return size_t(rm);
}
}; /* struct RoundingModeHashFunction */
/**
* This is a symfpu literal "back-end". It allows the library to be used as
* an arbitrary precision floating-point implementation. This is effectively
* the glue between symfpu's notion of "signed bit-vector" and CVC4's
* BitVector.
*/
namespace symfpuLiteral {
// Forward declaration of wrapper so that traits can be defined early and so
// used in the implementation of wrappedBitVector.
template <bool T>
class wrappedBitVector;
// This is the template parameter for symfpu's templates.
class traits
{
public:
// The six key types that symfpu uses.
typedef unsigned bwt;
typedef bool prop;
typedef ::CVC4::RoundingMode rm;
typedef ::CVC4::FloatingPointSize fpt;
typedef wrappedBitVector<true> sbv;
typedef wrappedBitVector<false> ubv;
// Give concrete instances of each rounding mode, mainly for comparisons.
static rm RNE(void);
static rm RNA(void);
static rm RTP(void);
static rm RTN(void);
static rm RTZ(void);
// The sympfu properties.
static void precondition(const prop &p);
static void postcondition(const prop &p);
static void invariant(const prop &p);
};
// Use the same type names as symfpu.
typedef traits::bwt bwt;
typedef traits::prop prop;
typedef traits::rm rm;
typedef traits::fpt fpt;
typedef traits::ubv ubv;
typedef traits::sbv sbv;
// Type function for mapping between types
template <bool T>
struct signedToLiteralType;
template <>
struct signedToLiteralType<true>
{
typedef int literalType;
};
template <>
struct signedToLiteralType<false>
{
typedef unsigned int literalType;
};
// This is an additional interface for CVC4::BitVector.
// The template parameter distinguishes signed and unsigned bit-vectors, a
// distinction symfpu uses.
template <bool isSigned>
class wrappedBitVector : public BitVector
{
protected:
typedef typename signedToLiteralType<isSigned>::literalType literalType;
friend wrappedBitVector<!isSigned>; // To allow conversion between the
// types
#if 0
friend ::symfpu::ite<prop, wrappedBitVector<isSigned> >; // For ITE
#endif /* 0 */
public:
wrappedBitVector(const bwt w, const unsigned v) : BitVector(w, v) {}
wrappedBitVector(const prop &p) : BitVector(1, p ? 1U : 0U) {}
wrappedBitVector(const wrappedBitVector<isSigned> &old) : BitVector(old) {}
wrappedBitVector(const BitVector &old) : BitVector(old) {}
bwt getWidth(void) const { return getSize(); }
/*** Constant creation and test ***/
static wrappedBitVector<isSigned> one(const bwt &w);
static wrappedBitVector<isSigned> zero(const bwt &w);
static wrappedBitVector<isSigned> allOnes(const bwt &w);
prop isAllOnes() const;
prop isAllZeros() const;
static wrappedBitVector<isSigned> maxValue(const bwt &w);
static wrappedBitVector<isSigned> minValue(const bwt &w);
/*** Operators ***/
wrappedBitVector<isSigned> operator<<(
const wrappedBitVector<isSigned> &op) const;
wrappedBitVector<isSigned> operator>>(
const wrappedBitVector<isSigned> &op) const;
/* Inherited but ...
* *sigh* if we use the inherited version then it will return a
* CVC4::BitVector which can be converted back to a
* wrappedBitVector<isSigned> but isn't done automatically when working
* out types for templates instantiation. ITE is a particular
* problem as expressions and constants no longer derive the
* same type. There aren't any good solutions in C++, we could
* use CRTP but Liana wouldn't appreciate that, so the following
* pointless wrapping functions are needed.
*/
wrappedBitVector<isSigned> operator|(
const wrappedBitVector<isSigned> &op) const;
wrappedBitVector<isSigned> operator&(
const wrappedBitVector<isSigned> &op) const;
wrappedBitVector<isSigned> operator+(
const wrappedBitVector<isSigned> &op) const;
wrappedBitVector<isSigned> operator-(
const wrappedBitVector<isSigned> &op) const;
wrappedBitVector<isSigned> operator*(
const wrappedBitVector<isSigned> &op) const;
wrappedBitVector<isSigned> operator/(
const wrappedBitVector<isSigned> &op) const;
wrappedBitVector<isSigned> operator%(
const wrappedBitVector<isSigned> &op) const;
wrappedBitVector<isSigned> operator-(void) const;
wrappedBitVector<isSigned> operator~(void)const;
wrappedBitVector<isSigned> increment() const;
wrappedBitVector<isSigned> decrement() const;
wrappedBitVector<isSigned> signExtendRightShift(
const wrappedBitVector<isSigned> &op) const;
/*** Modular opertaions ***/
// No overflow checking so these are the same as other operations
wrappedBitVector<isSigned> modularLeftShift(
const wrappedBitVector<isSigned> &op) const;
wrappedBitVector<isSigned> modularRightShift(
const wrappedBitVector<isSigned> &op) const;
wrappedBitVector<isSigned> modularIncrement() const;
wrappedBitVector<isSigned> modularDecrement() const;
wrappedBitVector<isSigned> modularAdd(
const wrappedBitVector<isSigned> &op) const;
wrappedBitVector<isSigned> modularNegate() const;
/*** Comparisons ***/
// Inherited ... ish ...
prop operator==(const wrappedBitVector<isSigned> &op) const;
prop operator<=(const wrappedBitVector<isSigned> &op) const;
prop operator>=(const wrappedBitVector<isSigned> &op) const;
prop operator<(const wrappedBitVector<isSigned> &op) const;
prop operator>(const wrappedBitVector<isSigned> &op) const;
/*** Type conversion ***/
wrappedBitVector<true> toSigned(void) const;
wrappedBitVector<false> toUnsigned(void) const;
/*** Bit hacks ***/
wrappedBitVector<isSigned> extend(bwt extension) const;
wrappedBitVector<isSigned> contract(bwt reduction) const;
wrappedBitVector<isSigned> resize(bwt newSize) const;
wrappedBitVector<isSigned> matchWidth(
const wrappedBitVector<isSigned> &op) const;
wrappedBitVector<isSigned> append(
const wrappedBitVector<isSigned> &op) const;
// Inclusive of end points, thus if the same, extracts just one bit
wrappedBitVector<isSigned> extract(bwt upper, bwt lower) const;
};
}
/**
* A concrete floating point number
*/
#if 0
typedef ::symfpu::unpackedFloat<symfpuLiteral::traits> FloatingPointLiteral;
#else
class CVC4_PUBLIC FloatingPointLiteral {
public :
// This intentional left unfinished as the choice of literal
// representation is solver specific.
void unfinished (void) const;
FloatingPointLiteral(unsigned, unsigned, double) { unfinished(); }
FloatingPointLiteral(unsigned, unsigned, const std::string &) { unfinished(); }
FloatingPointLiteral(const FloatingPointLiteral &) { unfinished(); }
bool operator == (const FloatingPointLiteral &op) const {
unfinished();
return false;
}
size_t hash (void) const {
unfinished();
return 23;
}
};
#endif /* 0 */
class CVC4_PUBLIC FloatingPoint {
protected :
FloatingPointLiteral fpl;
public :
FloatingPointSize t;
FloatingPoint (unsigned e, unsigned s, const BitVector &bv);
FloatingPoint (const FloatingPointSize &oldt, const FloatingPointLiteral &oldfpl) : fpl(oldfpl), t(oldt) {}
FloatingPoint (const FloatingPoint &fp) : fpl(fp.fpl), t(fp.t) {}
FloatingPoint (const FloatingPointSize &ct, const RoundingMode &rm, const BitVector &bv, bool signedBV);
FloatingPoint (const FloatingPointSize &ct, const RoundingMode &rm, const Rational &r);
static FloatingPoint makeNaN (const FloatingPointSize &t);
static FloatingPoint makeInf (const FloatingPointSize &t, bool sign);
static FloatingPoint makeZero (const FloatingPointSize &t, bool sign);
const FloatingPointLiteral & getLiteral (void) const {
return this->fpl;
}
// Gives the corresponding IEEE-754 transfer format
BitVector pack (void) const;
FloatingPoint absolute (void) const;
FloatingPoint negate (void) const;
FloatingPoint plus (const RoundingMode &rm, const FloatingPoint &arg) const;
FloatingPoint sub (const RoundingMode &rm, const FloatingPoint &arg) const;
FloatingPoint mult (const RoundingMode &rm, const FloatingPoint &arg) const;
FloatingPoint div (const RoundingMode &rm, const FloatingPoint &arg) const;
FloatingPoint fma (const RoundingMode &rm, const FloatingPoint &arg1, const FloatingPoint &arg2) const;
FloatingPoint sqrt (const RoundingMode &rm) const;
FloatingPoint rti (const RoundingMode &rm) const;
FloatingPoint rem (const FloatingPoint &arg) const;
// zeroCase is whether the left or right is returned in the case of min/max(-0,+0) or (+0,-0)
FloatingPoint maxTotal (const FloatingPoint &arg, bool zeroCaseLeft) const;
FloatingPoint minTotal (const FloatingPoint &arg, bool zeroCaseLeft) const;
// These detect when the answer is defined
typedef std::pair<FloatingPoint, bool> PartialFloatingPoint;
PartialFloatingPoint max (const FloatingPoint &arg) const;
PartialFloatingPoint min (const FloatingPoint &arg) const;
bool operator ==(const FloatingPoint& fp) const;
bool operator <= (const FloatingPoint &arg) const;
bool operator < (const FloatingPoint &arg) const;
bool isNormal (void) const;
bool isSubnormal (void) const;
bool isZero (void) const;
bool isInfinite (void) const;
bool isNaN (void) const;
bool isNegative (void) const;
bool isPositive (void) const;
FloatingPoint convert (const FloatingPointSize &target, const RoundingMode &rm) const;
// These require a value to return in the undefined case
BitVector convertToBVTotal (BitVectorSize width, const RoundingMode &rm,
bool signedBV, BitVector undefinedCase) const;
Rational convertToRationalTotal (Rational undefinedCase) const;
// These detect when the answer is defined
typedef std::pair<BitVector, bool> PartialBitVector;
typedef std::pair<Rational, bool> PartialRational;
PartialBitVector convertToBV (BitVectorSize width, const RoundingMode &rm,
bool signedBV) const;
PartialRational convertToRational (void) const;
}; /* class FloatingPoint */
struct CVC4_PUBLIC FloatingPointHashFunction {
size_t operator() (const FloatingPoint& fp) const {
FloatingPointSizeHashFunction fpshf;
BitVectorHashFunction bvhf;
return fpshf(fp.t) ^ bvhf(fp.pack());
}
}; /* struct FloatingPointHashFunction */
/**
* The parameter type for the conversions to floating point.
*/
class CVC4_PUBLIC FloatingPointConvertSort {
public :
FloatingPointSize t;
FloatingPointConvertSort (unsigned _e, unsigned _s)
: t(_e,_s) {}
FloatingPointConvertSort (const FloatingPointSize &fps)
: t(fps) {}
bool operator ==(const FloatingPointConvertSort& fpcs) const {
return t == fpcs.t;
}
};
/**
* As different conversions are different parameterised kinds, there
* is a need for different (C++) types for each one.
*/
class CVC4_PUBLIC FloatingPointToFPIEEEBitVector : public FloatingPointConvertSort {
public :
FloatingPointToFPIEEEBitVector (unsigned _e, unsigned _s) : FloatingPointConvertSort(_e,_s) {}
FloatingPointToFPIEEEBitVector (const FloatingPointConvertSort &old) : FloatingPointConvertSort(old) {}
};
class CVC4_PUBLIC FloatingPointToFPFloatingPoint : public FloatingPointConvertSort {
public :
FloatingPointToFPFloatingPoint (unsigned _e, unsigned _s) : FloatingPointConvertSort(_e,_s) {}
FloatingPointToFPFloatingPoint (const FloatingPointConvertSort &old) : FloatingPointConvertSort(old) {}
};
class CVC4_PUBLIC FloatingPointToFPReal : public FloatingPointConvertSort {
public :
FloatingPointToFPReal (unsigned _e, unsigned _s) : FloatingPointConvertSort(_e,_s) {}
FloatingPointToFPReal (const FloatingPointConvertSort &old) : FloatingPointConvertSort(old) {}
};
class CVC4_PUBLIC FloatingPointToFPSignedBitVector : public FloatingPointConvertSort {
public :
FloatingPointToFPSignedBitVector (unsigned _e, unsigned _s) : FloatingPointConvertSort(_e,_s) {}
FloatingPointToFPSignedBitVector (const FloatingPointConvertSort &old) : FloatingPointConvertSort(old) {}
};
class CVC4_PUBLIC FloatingPointToFPUnsignedBitVector : public FloatingPointConvertSort {
public :
FloatingPointToFPUnsignedBitVector (unsigned _e, unsigned _s) : FloatingPointConvertSort(_e,_s) {}
FloatingPointToFPUnsignedBitVector (const FloatingPointConvertSort &old) : FloatingPointConvertSort(old) {}
};
class CVC4_PUBLIC FloatingPointToFPGeneric : public FloatingPointConvertSort {
public :
FloatingPointToFPGeneric (unsigned _e, unsigned _s) : FloatingPointConvertSort(_e,_s) {}
FloatingPointToFPGeneric (const FloatingPointConvertSort &old) : FloatingPointConvertSort(old) {}
};
template <unsigned key>
struct CVC4_PUBLIC FloatingPointConvertSortHashFunction {
inline size_t operator() (const FloatingPointConvertSort& fpcs) const {
FloatingPointSizeHashFunction f;
return f(fpcs.t) ^ (0x00005300 | (key << 24));
}
}; /* struct FloatingPointConvertSortHashFunction */
/**
* The parameter type for the conversion to bit vector.
*/
class CVC4_PUBLIC FloatingPointToBV {
public :
BitVectorSize bvs;
FloatingPointToBV (unsigned s)
: bvs(s) {}
FloatingPointToBV (const FloatingPointToBV &old) : bvs(old.bvs) {}
FloatingPointToBV (const BitVectorSize &old) : bvs(old) {}
operator unsigned () const { return bvs; }
};
class CVC4_PUBLIC FloatingPointToUBV : public FloatingPointToBV {
public : FloatingPointToUBV (unsigned _s) : FloatingPointToBV(_s) {}
FloatingPointToUBV (const FloatingPointToBV &old) : FloatingPointToBV(old) {}
};
class CVC4_PUBLIC FloatingPointToSBV : public FloatingPointToBV {
public : FloatingPointToSBV (unsigned _s) : FloatingPointToBV(_s) {}
FloatingPointToSBV (const FloatingPointToBV &old) : FloatingPointToBV(old) {}
};
class CVC4_PUBLIC FloatingPointToUBVTotal : public FloatingPointToBV {
public : FloatingPointToUBVTotal (unsigned _s) : FloatingPointToBV(_s) {}
FloatingPointToUBVTotal (const FloatingPointToBV &old) : FloatingPointToBV(old) {}
};
class CVC4_PUBLIC FloatingPointToSBVTotal : public FloatingPointToBV {
public : FloatingPointToSBVTotal (unsigned _s) : FloatingPointToBV(_s) {}
FloatingPointToSBVTotal (const FloatingPointToBV &old) : FloatingPointToBV(old) {}
};
template <unsigned key>
struct CVC4_PUBLIC FloatingPointToBVHashFunction {
inline size_t operator() (const FloatingPointToBV& fptbv) const {
UnsignedHashFunction< ::CVC4::BitVectorSize > f;
return (key ^ 0x46504256) ^ f(fptbv.bvs);
}
}; /* struct FloatingPointToBVHashFunction */
// It is not possible to pack a number without a size to pack to,
// thus it is difficult to implement this in a sensible way. Use
// FloatingPoint instead...
/*
inline std::ostream& operator <<(std::ostream& os, const FloatingPointLiteral& fp) CVC4_PUBLIC;
inline std::ostream& operator <<(std::ostream& os, const FloatingPointLiteral& fp) {
return os << "FloatingPointLiteral";
}
*/
inline std::ostream& operator <<(std::ostream& os, const FloatingPoint& fp) CVC4_PUBLIC;
inline std::ostream& operator <<(std::ostream& os, const FloatingPoint& fp) {
BitVector bv(fp.pack());
unsigned largestSignificandBit = fp.t.significand() - 2; // -1 for -inclusive, -1 for hidden
unsigned largestExponentBit = (fp.t.exponent() - 1) + (largestSignificandBit + 1);
return os
<< "(fp #b" << bv.extract(largestExponentBit + 1, largestExponentBit + 1)
<< " #b" << bv.extract(largestExponentBit, largestSignificandBit + 1)
<< " #b" << bv.extract(largestSignificandBit, 0)
<< ")";
}
inline std::ostream& operator <<(std::ostream& os, const FloatingPointSize& fps) CVC4_PUBLIC;
inline std::ostream& operator <<(std::ostream& os, const FloatingPointSize& fps) {
return os << "(_ FloatingPoint " << fps.exponent() << " " << fps.significand() << ")";
}
inline std::ostream& operator <<(std::ostream& os, const FloatingPointConvertSort& fpcs) CVC4_PUBLIC;
inline std::ostream& operator <<(std::ostream& os, const FloatingPointConvertSort& fpcs) {
return os << "(_ to_fp " << fpcs.t.exponent() << " " << fpcs.t.significand() << ")";
}
}/* CVC4 namespace */
#endif /* __CVC4__FLOATINGPOINT_H */
|
$myDir = [IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Definition)
$rootDir = [IO.Path]::GetDirectoryName($myDir)
$scriptsDir = Resolve-Path "$rootDir\auto\lib"
. "$scriptsDir\bench.lib.ps1"
$benchEnv = New-Object Mastersign.Bench.BenchEnvironment ($global:BenchConfig)
$benchEnv.Load()
$appLibsDevDir = Safe-Dir "$rootDir\applibs"
$appLibsDir = Empty-Dir $(Get-ConfigValue "AppLibsInstallDir")
pushd $appLibsDevDir
$appLibs = @()
Get-Content "$myDir\applibs.txt" | % {
$parts = $_.Split("=", 2)
$appLibs += @{ "id"=$parts[0]; "url"=$parts[1] }
}
foreach ($lib in $appLibs)
{
$id = $lib.id
$p = "$appLibsDevDir\$id"
if (!(Test-Path $p))
{
echo "App library '$id' is not cloned."
continue
}
echo "Loading app library '$id' ..."
robocopy "$appLibsDevDir\$id" "$appLibsDir\$id" /MIR /XD .git /NJH /NJS
echo ""
}
echo "Finished loading app libraries."
popd
|
using System;
class AppearanceCount
{
static int GetAppearanceCountOfNumInArr(int num, int[] arr)
{
int count = 0;
for (int i = 0; i < arr.Length; i++)
{
if (num == arr[i])
{
count++;
}
}
return count;
}
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
string input = Console.ReadLine();
int[] nums = new int[n];
for (int i = 0; i < n; i++)
{
nums[i] = int.Parse(input.Split(' ')[i]);
}
int x = int.Parse(Console.ReadLine());
Console.WriteLine(GetAppearanceCountOfNumInArr(x, nums));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.