Documentation @versionBadge(explicit = true)
This page explains each component in more details.
Field Constructors
Vertical forms
Horizontal forms
Inline forms
Clear field constructor
Specific field constructors
Arguments (args
)
@bsExampleWithCode {
@b3.text( fooForm("foo"), Symbol("_label") -> "Constraints", Symbol("_showConstraints") -> true, Symbol("placeholder") -> "A simple text showing its constraints..." )
}{
@@b3.text( fooForm("foo"), Symbol("_label") -> "Constraints", Symbol("_showConstraints") -> true, Symbol("placeholder") -> "A simple text showing its constraints..." )
}
Special arguments (the underscored ones)
Validation arguments
@bsExampleWithCode {Optional arguments
Boolean arguments
Arguments with dashes (e.g. data-*
attributes)
ARIA attributes
Forms @@(action: Call, args: (Symbol, Any)*)(body: => Html)(implicit fc: B3FieldConstructor)
Forms with a specific B3FieldConstructor
Forms with CSRF token
Input helpers
About disabled
and readonly
attributes
Validation states & feedback icons
@bsExampleWithCode { @b3.text( fooForm("foo"), Symbol("_label") -> "Success", Symbol("_success") -> true, Symbol("placeholder") -> "Success text..." ) @b3.text( fooForm("foo"), Symbol("_label") -> "Warning", Symbol("_warning") -> "Be carefull with this...", Symbol("placeholder") -> "Warning text..." ) @b3.text( fooForm("foo"), Symbol("_label") -> "Error", Symbol("_error") -> "An error occurred!", Symbol("placeholder") -> "Error text..." ) }{ @@b3.text( fooForm("foo"), Symbol("_label") -> "Success", Symbol("_success") -> true, Symbol("placeholder") -> "Success text..." ) @@b3.text( fooForm("foo"), Symbol("_label") -> "Warning", Symbol("_warning") -> "Be carefull with this...", Symbol("placeholder") -> "Warning text..." ) @@b3.text( fooForm("foo"), Symbol("_label") -> "Error", Symbol("_error") -> "An error occurred!", Symbol("placeholder") -> "Error text..." ) } @bsExampleWithCode { @b3.text( fooForm("foo"), Symbol("_label") -> "Success", Symbol("_showIconValid") -> true, Symbol("placeholder") -> "Success text..." ) @b3.text( fooForm("foo"), Symbol("_label") -> "Warning", Symbol("_warning") -> "Be carefull with this...", Symbol("_showIconWarning") -> true, Symbol("placeholder") -> "Warning text..." ) @b3.text( fooForm("foo"), Symbol("_label") -> "Error", Symbol("_showIconOnError") -> true, Symbol("_error") -> "An error occurred!", Symbol("placeholder") -> "Error text..." ) }{ @@b3.text( fooForm("foo"), Symbol("_label") -> "Success", Symbol("_showIconValid") -> true, Symbol("placeholder") -> "Success text..." ) @@b3.text( fooForm("foo"), Symbol("_label") -> "Warning", Symbol("_warning") -> "Be carefull with this...", Symbol("_showIconWarning") -> true, Symbol("placeholder") -> "Warning text..." ) @@b3.text( fooForm("foo"), Symbol("_label") -> "Error", Symbol("_showIconOnError") -> true, Symbol("_error") -> "An error occurred!", Symbol("placeholder") -> "Error text..." ) }b3.inputType
@@(inputType: String, field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It renders a simple input with a specific type attribute and it adds class="form-control"
by default, but you can add an extra class with Symbol("class") -> "extra_class"
.
b3.text
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It is a short version of b3.inputType
for type="text"
.
b3.password
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It is a short version of b3.inputType
for type="password"
.
For security reasons, this helper doesn't display the possible value the field could have (for example when the form is reloaded after a validation failure).
@bsExampleWithCode { @b3.password( fooForm("password"), Symbol("_label") -> "Password", Symbol("_help") -> "With at least 8 characters" ) }{ @@b3.password( fooForm("password"), Symbol("_label") -> "Password", Symbol("_help") -> "With at least 8 characters" ) }b3.file
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It is a short version of b3.inputType
for type="file"
.
b3.textarea
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It renders a textarea and it adds class="form-control"
by default.
b3.checkbox
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It renders a checkbox. It has the attribute value
set to true by default,
but you can use another one using the 'value
argument.
The special '_text
argument lets you put a text after the checkbox.
Regarding to the checked
attribute, if you want to set it to true as default, use Symbol("_default") -> true
.
And if you need to force its value use directly the 'checked
argument.
It supports readonly
attribute adding an additional disabled
one and a
<input type="hidden">
.
Note you can use any value for the _text
argument.
b3.radio
@@(field: Field, options: Seq[(String, Any)], args: (Symbol, Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It renders a radio. It supports readonly
attribute adding an additional disabled
one and a <input type="hidden">
.
It has an additional special _inline
argument to make it an inline radio (for vertical and horizontal forms).
Note you can use any value for the options
argument.
b3.radio
@@(field: Field, args: (Symbol, Any)*)(content: Tuple6[Boolean, Boolean, String, String, Option[String], Map[Symbol, Any]] => Html)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
b3.radioOption
@@(inputValue: Any, label: Any, args: (Symbol, Any)*)(implicit extraInfo: (Boolean, Boolean, String, String, Option[String], Map[Symbol,Any]))
If you need more versatility you can fully customize your radio options:
@bsExampleWithCode { @b3.radio( fooForm("foo_radio3"), Symbol("_label") -> "Ok, now that we're alone, what do you really prefer?" ) { implicit extraInfo => @b3.radioOption("B", Html("""Beer """)) @b3.radioOption("B", Html("""Coffee """), Symbol("disabled") -> true) } }{ @@b3.radio( fooForm("foo3"), Symbol("_label") -> "Ok, now that we're alone, what do you really prefer?" ) { implicit extraInfo => @@b3.radioOption("B", Html("Beer ")) @@b3.radioOption("B", Html("Coffee "), Symbol("disabled") -> true) } }b3.select
@@(field: Field, options: Seq[(String,String)], args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It renders a select. It supports readonly
attribute adding an additional disabled
one and a <input type="hidden">
.
You can add a default first value using the argument '_default
with a string.
It will add a first option to the select with an empty string value. So you could add a
required constraint to the field to force the user to select one
other option. In addition, this default option is always disable to avoid the user to select it,
and if any other option is selected this default one will not appear at all.
For a multiple select
you only need to add the 'multiple
argument.
In that case, the '_default
argument will be ignored.
b3.select
@@(field: Field, args: (Symbol,Any)*)(content: Set[String] => Html)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
b3.selectOption
@@(value: Any, name: Any, args: (Symbol, Any)*)(implicit values: Set[String])
If you need more versatility you can fully customize your select options:
@bsExampleWithCode { @b3.select( fooForm("foo"), Symbol("_label") -> "Grouped select" ) { implicit values => } @b3.select( fooForm("foo"), Symbol("_label") -> "Fruits select (lemon preselected)" ) { implicit values => } }{ @@b3.select( fooForm("foo"), Symbol("_label") -> "Grouped select" ) { implicit values => } class Fruit (id: Long, name: String, isCitrus: Boolean) @@fruitsWithCitrus = @@{ Seq( Fruit(1L, "Apple", false), Fruit(2L, "Orange", true), Fruit(3L, "Pear", false), Fruit(4L, "Lemon", true), Fruit(5L, "Banana", false) )} @@b3.select( fooForm("foo"), Symbol("_label") -> "Fruits select (lemon preselected)" ) { implicit values => } }b3.hidden
@@(name: String, value: Any, args: (Symbol, Any)*)
It simply renders a hidden input.
@code { @@b3.hidden("fooName", "fooValue", Symbol("fooAttr") -> "fooAttrValue") }Renders to:
@code { }b3.hidden
@@(field: Field, args: (Symbol, Any)*)
You can also render a hidden input directly with a Field
as you could do with a b3.text
helper, for example.
It lets you be able to simply change a b3.text
for a b3.hidden
to hide it.
It will automatically take the name of the Field
and it's value if present. You can set a default value using the argument
'value
. Finally, take into account that every "underscored" argument (with "_" as preffix) will be removed.
Renders to:
@code { }b3.hiddens
@@(namesAndValues: (Any, Any)*)
Render a list of hidden inputs.
@code { @@b3.hiddens("fooId" -> 1L, "barId" -> 2L) }Renders to:
@code { }New HTML5 helpers
Important note: the new HTML5 input types are not fully supported for web browsers. Those not supported by old web browsers, will behave as input type text.
b3.color
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It is a short version of b3.inputType
for type="color"
.
b3.date
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It is a short version of b3.inputType
for type="date"
.
b3.datetime
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It is a short version of b3.inputType
for type="datetime"
.
b3.datetimeLocal
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It is a short version of b3.inputType
for type="datetime-local"
.
b3.email
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It is a short version of b3.inputType
for type="email"
.
b3.month
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It is a short version of b3.inputType
for type="month"
.
b3.number
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It is a short version of b3.inputType
for type="number"
.
b3.range
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It is a short version of b3.inputType
for type="range"
.
b3.search
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It is a short version of b3.inputType
for type="search"
.
b3.tel
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It is a short version of b3.inputType
for type="tel"
.
b3.time
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It is a short version of b3.inputType
for type="time"
.
b3.url
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It is a short version of b3.inputType
for type="url"
.
b3.week
@@(field: Field, args: (Symbol,Any)*)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
It is a short version of b3.inputType
for type="week"
.
More helpers
The following helpers use an auxiliar helper that creates a form-group
without a field.
Here are the special arguments they use:
_id
: the id for the form-group._class
: the class for the form-group (theform-group
class is always added)._label
: the text for the label._help
: a help text below the input.
b3.static
@@(label: String, args: (Symbol,Any)*)(text: => Html)(implicit fc: B3FieldConstructor)
It renders a static control to place within your form. It takes a HTML
as parameter, so you can
render whatever you want. Actually, it is like a wrapper for a static HTML
.
There are two equivalent more versions of b3.static
helper: one for labels with HTML
, and another one to omit the label. Note that you can also have a hidden label using '_hideLabel'
argument.
b3.buttonType
@@(buttonType: String, args: (Symbol,Any)*)(text: => Html)(implicit fc: b3.B3FieldConstructor)
It renders a simple button to place within your form. It takes a HTML
as parameter, so you can
render whatever you want.
b3.submit
@@(args: (Symbol,Any)*)(text: => Html)(implicit fc: B3FieldConstructor)
It is a short version of b3.buttonType for type="submit".
@bsExampleWithCode { @b3.submit(Symbol("class") -> "btn btn-primary"){ Sign in } }{ @@b3.submit(Symbol("class") -> "btn btn-primary"){ Sign in } }b3.reset
@@(args: (Symbol,Any)*)(text: => Html)(implicit fc: B3FieldConstructor)
It is a short version of b3.buttonType for type="reset".
@bsExampleWithCode { @b3.reset(Symbol("class") -> "btn btn-danger"){ Reset } }{ @@b3.reset(Symbol("class") -> "btn btn-danger"){ Reset } }b3.button
@@(args: (Symbol,Any)*)(text: => Html)(implicit fc: B3FieldConstructor)
It is a short version of b3.buttonType for type="button".
@bsExampleWithCode { @b3.button(Symbol("class") -> "btn btn-default"){ Favorite } }{ @@b3.button(Symbol("class") -> "btn btn-default"){ Favorite } }b3.free
@@(args: (Symbol,Any)*)(content: => Html)(implicit fc: B3FieldConstructor)
It renders whatever you want within a form-group
div.
Your own custom helpers
The purpose of these helpers is to be a tool for creating your own helpers. Please see more about creating new helpers here.
b3.inputWrapped
@@(inputType: String, field: Field, args: (Symbol,Any)*)(inputGroup: Html => Html)(implicit handler: B3FieldConstructor, @BSVersion.msgsArg)
This is the same as b3.inputType
but specifying a custom wrapper for the input tag.
It is useful for input groups and inputs with validation states and feedback icons.
b3.multifield
@@(fields: Field*)(args: (Symbol,Any)*)(inputsHtml: (B3FieldConstructor, @BSVersion.msgsClass) => Html)(implicit fc: B3FieldConstructor, @BSVersion.msgsArg)
Sometimes you may need two or more fields within the same line in a horizontal or vertical form (for a set of checkboxes, a date range, ...).
The helper b3.multifield
tries to:
- Manage a set of fields and group them within the same
form-group
. - Manage all of their errors, infos and constraints at the end of the
form-group
as if they were only one. - Take advantage of the helpers that are already implemented.
- Be a tool to create your custom multifield helpers.
To know how it works and how to use it go the the Multifield section.
}


Enter your email address below and we'll send you an email with instructions on how to change your password.


Today
{% include "wagtail_extensions/partials/opening_time.html" with time=today %}
{% endif %}
{% for group in times %}
{% if group|length == 1 %}
{% with first=group|first %}
{% include "wagtail_extensions/partials/opening_time_label.html" with time=first %}
{% include "wagtail_extensions/partials/opening_time.html" with time=first %}
{% include "wagtail_extensions/partials/opening_time_label.html" with time=first %}
-
{% include "wagtail_extensions/partials/opening_time_label.html" with time=last %}
{% include "wagtail_extensions/partials/opening_time.html" with time=first %}


LetterAvatarKit
LetterAvatarKit is an UIImage
extension that generates letter-based avatars. Here are some images showing what LetterAvatarKit does:
Requirements
- iOS 8 and later
- Swift 4.0 and later
Installation
CocoaPods
To install LetterAvatarKit using CocoaPods, add this line to your Podfile:
pod "LetterAvatarKit", "1.1.4"
Usage
You can configure the following properties of LetterAvatarBuilderConfiguration:
/// The size of an avatar image.
open var size: CGSize = CGSize(width: 80, height: 80)
/// The username.
open var username: String?
/// The flag that indicates of using single letter instead of two lettters.
open var singleLetter: Bool = false
/// The letters font.
open var lettersFont: UIFont = UIFont.systemFont(ofSize: 16.0)
/// The letters colors
open var lettersColor: UIColor = LAKUIColorByRGB(red: 236, green: 240, blue: 241)
/// The background colors of an image.
open var backgroundColors: [UIColor] = UIColor.colors
Swift
Using a configuration:
let configuration = LetterAvatarBuilderConfiguration()
configuration.username = "Letter Avatar"
avatarImageView?.image = UIImage.makeLetterAvatar(withConfiguration: configuration)
or
avatarImageView?.image = UIImage.makeLetterAvatar(withUsername: "Letter Avatar")
Objective-C
Using a configuration:
LAKLetterAvatarBuilderCongiguration *configuration = [[LAKLetterAvatarBuilderCongiguration alloc] init];
configuration.username = @"Letter Avatar";
self.avatarImageView.image = [UIImage lak_makeLetterAvatarWithConfiguration:configuration];
or
self.avatarImageView.image = [UIImage lak_makeLetterAvatarWithUsername:@"Letter Avatar"];
Community
Questions, comments, issues, and pull requests are always welcome!
Contacts
License
Distributed under the MIT license. See LICENSE for more information.


Toggle navigation
Mesh Stock Checker
by
@R8T3D
source code
Product
Store
Footpatrol
size?
JD Sports
Add


×
Random Artist-Random Song
Your browser does not support the audio element.
Search results:
Playlist:
Clear


array wincache_rplist_fileinfo ([ bool $summaryonly = false ] )
Retrieves information about cached mappings between relative file paths and corresponding absolute file paths.
Array of meta data about the resolve file path cache or FALSE on failure The array returned by this function contains the following elements: total_file_count - total number of file path mappings stored in the cache rplist_entries - an array that contains the information about all the cached file paths: resolve_path - path to a file subkey_data - corresponding absolute path to a file


Placement Papers of different Companies from July 2001
AMDOCS
ANALOG DEVICES
CADANCE
CISCO
DESHAW
HELLOSOFT
HCL
HONEYWELL
HUGHES
INFOSYS
INFOTECH
IFLEX
IKOS
INTERA
INTEGRAPH
ITTIAM SYSTEMS
JUNO
GEOMETRIC SOFTWARE
L & T Software
MBT
MOTOROLA
ORACLE
ORANGE
PATNI COMPUTERS
SAMSUNG
SAMTEL
SATYAM
SATYAM-GE
ST Microeclectronics
TRIAD
TCS
TI
TATA INFOTECH LTD
WILCO
INFOSYS @ VJTI
INFOSYS at REC Trichy
INFOSYS at REC Trichy (Another)
INFOSYS at IITK
INFOSYS at IITK(Part II)
INFOSYS at Roorkee
AMDOCS (Sample)
AMDOCS (in DOC format)
Analog Devices
CADANCE @ BIT Mesra
CISCO (Last Year)
Details of CISCO Papers
Old (but Useful) CISCO Paper
DESHAW
DESHAW @ IITG
HCL @ Jadhavpur Univ.
HCL @ Jadhavpur Univ. (II)
HCL
HCL Infosystems
HONEYWELL @ Hyderabad Univ.
HUGHES @ Unknown
HUGHES @ IITK.


EVAL简介
EVAL 和 EVALSHA 命令是从 Redis 2.6.0 版本开始的，使用内置的 Lua 解释器，可以对 Lua 脚本进行求值。
EVAL的第一个参数是一段 Lua 5.1 脚本程序。 这段Lua脚本不需要（也不应该）定义函数。它运行在 Redis 服务器中。
EVAL的第二个参数是参数的个数，后面的参数（从第三个参数），表示在脚本中所用到的那些 Redis 键(key)，这些键名参数可以在 Lua 中通过全局变量 KEYS 数组，用 1 为基址的形式访问( KEYS[1]
， KEYS[2]
，以此类推)。
在命令的最后，那些不是键名参数的附加参数 arg [arg ...] ，可以在 Lua 中通过全局变量 ARGV
数组访问，访问的形式和 KEYS 变量类似( ARGV[1]
、 ARGV[2]
，诸如此类)。
举例说明：
> eval "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}" 2 key1 key2 first second
1) "key1"
2) "key2"
3) "first"
4) "second"
注：返回结果是Redis multi bulk replies的Lua数组，这是一个Redis的返回类型，您的客户端库可能会将他们转换成数组类型。
这是从一个Lua脚本中使用两个不同的Lua函数来调用Redis的命令的例子：
redis.call()
redis.pcall()
redis.call()
与 redis.pcall()
很类似, 他们唯一的区别是当redis命令执行结果返回错误时，
redis.call()
将返回给调用者一个错误，而redis.pcall()
会将捕获的错误以Lua表的形式返回
redis.call()
和 redis.pcall()
两个函数的参数可以是任意的 Redis 命令：
> eval "return redis.call('set','foo','bar')" 0
OK
需要注意的是，上面这段脚本的确实现了将键 foo
的值设为 bar 的目的，但是，它违反了 EVAL 命令的语义，因为脚本里使用的所有键都应该由 KEYS 数组来传递，就像这样：
> eval "return redis.call('set',KEYS[1],'bar')" 1 foo
OK
要求使用正确的形式来传递键(key)是有原因的，因为不仅仅是 EVAL 这个命令，所有的 Redis 命令，在执行之前都会被分析，籍此来确定命令会对哪些键进行操作。
因此，对于 EVAL 命令来说，必须使用正确的形式来传递键，才能确保分析工作正确地执行。 除此之外，使用正确的形式来传递键还有很多其他好处，它的一个特别重要的用途就是确保 Redis 集群可以将你的请求发送到正确的集群节点。 (对 Redis 集群的工作还在进行当中，但是脚本功能被设计成可以与集群功能保持兼容。)不过，这条规矩并不是强制性的， 从而使得用户有机会滥用(abuse) Redis 单实例配置(single instance configuration)，代价是这样写出的脚本不能被 Redis 集群所兼容。
Lua 脚本能返回一个值，这个值能按照一组转换规则从Lua转换成redis的返回类型。
Lua 数据类型和 Redis 数据类型之间转换
当 Lua 通过 call() 或 pcall() 函数执行 Redis 命令的时候，命令的返回值会被转换成 Lua 数据结构。 同样地，当 Lua 脚本在 Redis 内置的解释器里运行时，Lua 脚本的返回值也会被转换成 Redis 协议(protocol)，然后由 EVAL 将值返回给客户端。
数据类型之间的转换遵循这样一个设计原则：如果将一个 Redis 值转换成 Lua 值，之后再将转换所得的 Lua 值转换回 Redis 值，那么这个转换所得的 Redis 值应该和最初时的 Redis 值一样。
换句话说， Lua 类型和 Redis 类型之间存在着一一对应的转换关系。
Redis 到 Lua 的转换表。
- Redis integer reply -> Lua number
- Redis bulk reply -> Lua string
- Redis multi bulk reply -> Lua table (may have other Redis data types nested)
- Redis status reply -> Lua table with a single
ok
field containing the status - Redis error reply -> Lua table with a single
err
field containing the error - Redis Nil bulk reply and Nil multi bulk reply -> Lua false boolean type
Lua 到 Redis 的转换表。
- Lua number -> Redis integer reply (the number is converted into an integer)
- Lua string -> Redis bulk reply
- Lua table (array) -> Redis multi bulk reply (truncated to the first nil inside the Lua array if any)
- Lua table with a single
ok
field -> Redis status reply - Lua table with a single
err
field -> Redis error reply - Lua boolean false -> Redis Nil bulk reply.
从 Lua 转换到 Redis 有一条额外的规则，这条规则没有和它对应的从 Redis 转换到 Lua 的规则：
- Lua boolean true -> Redis integer reply with value of 1.
还有下面两点需要重点注意：
- lua中整数和浮点数之间没有什么区别。因此，我们始终Lua的数字转换成整数的回复，这样将舍去小数部分。如果你想从Lua返回一个浮点数，你应该将它作为一个字符串（见比如ZSCORE命令）。
- There is no simple way to have nils inside Lua arrays, this is a result of Lua table semantics, so when Redis converts a Lua array into Redis protocol the conversion is stopped if a nil is encountered.
以下是几个类型转换的例子：
> eval "return 10" 0
(integer) 10
> eval "return {1,2,{3,'Hello World!'}}" 0
1) (integer) 1
2) (integer) 2
3) 1) (integer) 3
2) "Hello World!"
> eval "return redis.call('get','foo')" 0
"bar"
最后一个例子展示如果是Lua直接命令调用它是如何可以从redis.call()
或redis.pcall()
接收到准确的返回值。
下面的例子我们可以看到浮点数和nil将怎么样处理：
> eval "return {1,2,3.3333,'foo',nil,'bar'}" 0
1) (integer) 1
2) (integer) 2
3) (integer) 3
4) "foo"
正如你看到的 3.333 被转换成了3，并且 nil后面的字符串bar没有被返回回来。
返回redis类型的辅助函数
有两个辅助函数从Lua返回Redis的类型。
redis.error_reply(error_string)
returns an error reply. This function simply returns the single field table with theerr
field set to the specified string for you.redis.status_reply(status_string)
returns a status reply. This function simply returns the single field table with theok
field set to the specified string for you.
There is no difference between using the helper functions or directly returning the table with the specified format, so the following two forms are equivalent:
return {err="My Error"}
return redis.error_reply("My Error")
脚本的原子性
Redis 使用单个 Lua 解释器去运行所有脚本，并且， Redis 也保证脚本会以原子性(atomic)的方式执行： 当某个脚本正在运行的时候，不会有其他脚本或 Redis 命令被执行。 这和使用 MULTI / EXEC 包围的事务很类似。 在其他别的客户端看来，脚本的效果(effect)要么是不可见的(not visible)，要么就是已完成的(already completed)。
另一方面，这也意味着，执行一个运行缓慢的脚本并不是一个好主意。写一个跑得很快很顺溜的脚本并不难， 因为脚本的运行开销(overhead)非常少，但是当你不得不使用一些跑得比较慢的脚本时，请小心， 因为当这些蜗牛脚本在慢吞吞地运行的时候，其他客户端会因为服务器正忙而无法执行命令。
错误处理
As already stated, calls to redis.call()
resulting in a Redis command error
will stop the execution of the script and will return the error, in a way that
makes it obvious that the error was generated by a script:
> del foo
(integer) 1
> lpush foo a
(integer) 1
> eval "return redis.call('get','foo')" 0
(error) ERR Error running script (call to f_6b1bf486c81ceb7edf3c093f4c48582e38c0e791): ERR Operation against a key holding the wrong kind of value
Using the redis.pcall()
command no error is raised, but an error object is
returned in the format specified above (as a Lua table with an err
field).
The script can pass the exact error to the user by returning the error object
returned by redis.pcall()
.
Bandwidth and EVALSHA
The EVAL command forces you to send the script body again and again. Redis does not need to recompile the script every time as it uses an internal caching mechanism, however paying the cost of the additional bandwidth may not be optimal in many contexts.
On the other hand, defining commands using a special command or via redis.conf
would be a problem for a few reasons:
Different instances may have different versions of a command implementation.
Deployment is hard if there is to make sure all the instances contain a given command, especially in a distributed environment.
Reading an application code the full semantic could not be clear since the application would call commands defined server side.
In order to avoid these problems while avoiding the bandwidth penalty, Redis implements the EVALSHA command.
EVALSHA works exactly like EVAL, but instead of having a script as the first argument it has the SHA1 digest of a script. The behavior is the following:
If the server still remembers a script with a matching SHA1 digest, the script is executed.
If the server does not remember a script with this SHA1 digest, a special error is returned telling the client to use EVAL instead.
Example:
> set foo bar
OK
> eval "return redis.call('get','foo')" 0
"bar"
> evalsha 6b1bf486c81ceb7edf3c093f4c48582e38c0e791 0
"bar"
> evalsha ffffffffffffffffffffffffffffffffffffffff 0
(error) `NOSCRIPT` No matching script. Please use [EVAL](/commands/eval.html).
The client library implementation can always optimistically send EVALSHA under
the hood even when the client actually calls EVAL, in the hope the script was
already seen by the server.
If the NOSCRIPT
error is returned EVAL will be used instead.
Passing keys and arguments as additional EVAL arguments is also very useful in this context as the script string remains constant and can be efficiently cached by Redis.
Script cache semantics
Executed scripts are guaranteed to be in the script cache forever. This means that if an EVAL is performed against a Redis instance all the subsequent EVALSHA calls will succeed.
The only way to flush the script cache is by explicitly calling the SCRIPT FLUSH command, which will completely flush the scripts cache removing all the scripts executed so far. This is usually needed only when the instance is going to be instantiated for another customer or application in a cloud environment.
The reason why scripts can be cached for long time is that it is unlikely for a well written application to have enough different scripts to cause memory problems. Every script is conceptually like the implementation of a new command, and even a large application will likely have just a few hundred of them. Even if the application is modified many times and scripts will change, the memory used is negligible.
The fact that the user can count on Redis not removing scripts is semantically a very good thing. For instance an application with a persistent connection to Redis can be sure that if a script was sent once it is still in memory, so EVALSHA can be used against those scripts in a pipeline without the chance of an error being generated due to an unknown script (we'll see this problem in detail later).
The SCRIPT command
Redis offers a SCRIPT command that can be used in order to control the scripting subsystem. SCRIPT currently accepts three different commands:
SCRIPT FLUSH. This command is the only way to force Redis to flush the scripts cache. It is most useful in a cloud environment where the same instance can be reassigned to a different user. It is also useful for testing client libraries' implementations of the scripting feature.
SCRIPT EXISTS sha1 sha2... shaN. Given a list of SHA1 digests as arguments this command returns an array of 1 or 0, where 1 means the specific SHA1 is recognized as a script already present in the scripting cache, while 0 means that a script with this SHA1 was never seen before (or at least never seen after the latest SCRIPT FLUSH command).
SCRIPT LOAD script. This command registers the specified script in the Redis script cache. The command is useful in all the contexts where we want to make sure that EVALSHA will not fail (for instance during a pipeline or MULTI/EXEC operation), without the need to actually execute the script.
SCRIPT KILL. This command is the only way to interrupt a long-running script that reaches the configured maximum execution time for scripts. The SCRIPT KILL command can only be used with scripts that did not modify the dataset during their execution (since stopping a read-only script does not violate the scripting engine's guaranteed atomicity). See the next sections for more information about long running scripts.
Scripts as pure functions
A very important part of scripting is writing scripts that are pure functions. Scripts executed in a Redis instance are replicated on slaves by sending the script -- not the resulting commands. The same happens for the Append Only File. The reason is that sending a script to another Redis instance is much faster than sending the multiple commands the script generates, so if the client is sending many scripts to the master, converting the scripts into individual commands for the slave / AOF would result in too much bandwidth for the replication link or the Append Only File (and also too much CPU since dispatching a command received via network is a lot more work for Redis compared to dispatching a command invoked by Lua scripts).
The only drawback with this approach is that scripts are required to have the following property:
- The script always evaluates the same Redis write commands with the same arguments given the same input data set. Operations performed by the script cannot depend on any hidden (non-explicit) information or state that may change as script execution proceeds or between different executions of the script, nor can it depend on any external input from I/O devices.
Things like using the system time, calling Redis random commands like RANDOMKEY, or using Lua random number generator, could result into scripts that will not always evaluate in the same way.
In order to enforce this behavior in scripts Redis does the following:
Lua does not export commands to access the system time or other external state.
Redis will block the script with an error if a script calls a Redis command able to alter the data set after a Redis random command like RANDOMKEY, SRANDMEMBER, TIME. This means that if a script is read-only and does not modify the data set it is free to call those commands. Note that a random command does not necessarily mean a command that uses random numbers: any non-deterministic command is considered a random command (the best example in this regard is the TIME command).
Redis commands that may return elements in random order, like SMEMBERS (because Redis Sets are unordered) have a different behavior when called from Lua, and undergo a silent lexicographical sorting filter before returning data to Lua scripts. So
redis.call("smembers",KEYS[1])
will always return the Set elements in the same order, while the same command invoked from normal clients may return different results even if the key contains exactly the same elements.Lua pseudo random number generation functions
math.random
andmath.randomseed
are modified in order to always have the same seed every time a new script is executed. This means that callingmath.random
will always generate the same sequence of numbers every time a script is executed ifmath.randomseed
is not used.
However the user is still able to write commands with random behavior using the following simple trick. Imagine I want to write a Redis script that will populate a list with N random integers.
I can start with this small Ruby program:
require 'rubygems'
require 'redis'
r = Redis.new
RandomPushScript = <<EOF
local i = tonumber(ARGV[1])
local res
while (i > 0) do
res = redis.call('lpush',KEYS[1],math.random())
i = i-1
end
return res
EOF
r.del(:mylist)
puts r.eval(RandomPushScript,[:mylist],[10,rand(2**32)])
Every time this script executed the resulting list will have exactly the following elements:
> lrange mylist 0 -1
1) "0.74509509873814"
2) "0.87390407681181"
3) "0.36876626981831"
4) "0.6921941534114"
5) "0.7857992587545"
6) "0.57730350670279"
7) "0.87046522734243"
8) "0.09637165539729"
9) "0.74990198051087"
10) "0.17082803611217"
In order to make it a pure function, but still be sure that every invocation of the script will result in different random elements, we can simply add an additional argument to the script that will be used in order to seed the Lua pseudo-random number generator. The new script is as follows:
RandomPushScript = <<EOF
local i = tonumber(ARGV[1])
local res
math.randomseed(tonumber(ARGV[2]))
while (i > 0) do
res = redis.call('lpush',KEYS[1],math.random())
i = i-1
end
return res
EOF
r.del(:mylist)
puts r.eval(RandomPushScript,1,:mylist,10,rand(2**32))
What we are doing here is sending the seed of the PRNG as one of the arguments. This way the script output will be the same given the same arguments, but we are changing one of the arguments in every invocation, generating the random seed client-side. The seed will be propagated as one of the arguments both in the replication link and in the Append Only File, guaranteeing that the same changes will be generated when the AOF is reloaded or when the slave processes the script.
Note: an important part of this behavior is that the PRNG that Redis implements
as math.random
and math.randomseed
is guaranteed to have the same output
regardless of the architecture of the system running Redis.
32-bit, 64-bit, big-endian and little-endian systems will all produce the same
output.
Global variables protection
Redis scripts are not allowed to create global variables, in order to avoid leaking data into the Lua state. If a script needs to maintain state between calls (a pretty uncommon need) it should use Redis keys instead.
When global variable access is attempted the script is terminated and EVAL returns with an error:
redis <IP_ADDRESS>:6379> eval 'a=10' 0
(error) ERR Error running script (call to f_933044db579a2f8fd45d8065f04a8d0249383e57): user_script:1: Script attempted to create global variable 'a'
Accessing a non existing global variable generates a similar error.
Using Lua debugging functionality or other approaches like altering the meta table used to implement global protections in order to circumvent globals protection is not hard. However it is difficult to do it accidentally. If the user messes with the Lua global state, the consistency of AOF and replication is not guaranteed: don't do it.
Note for Lua newbies: in order to avoid using global variables in your scripts simply declare every variable you are going to use using the local keyword.
Available libraries
The Redis Lua interpreter loads the following Lua libraries:
- base lib.
- table lib.
- string lib.
- math lib.
- debug lib.
- cjson lib.
- cmsgpack lib.
Every Redis instance is guaranteed to have all the above libraries so you can be sure that the environment for your Redis scripts is always the same.
The CJSON library provides extremely fast JSON maniplation within Lua. All the other libraries are standard Lua libraries.
Emitting Redis logs from scripts
It is possible to write to the Redis log file from Lua scripts using the
redis.log
function.
redis.log(loglevel,message)
loglevel
is one of:
redis.LOG_DEBUG
redis.LOG_VERBOSE
redis.LOG_NOTICE
redis.LOG_WARNING
They correspond directly to the normal Redis log levels. Only logs emitted by scripting using a log level that is equal or greater than the currently configured Redis instance log level will be emitted.
The message
argument is simply a string.
Example:
redis.log(redis.LOG_WARNING,"Something is wrong with this script.")
Will generate the following:
[32343] 22 Mar 15:21:39 # Something is wrong with this script.
Sandbox and maximum execution time
Scripts should never try to access the external system, like the file system or any other system call. A script should only operate on Redis data and passed arguments.
Scripts are also subject to a maximum execution time (five seconds by default). This default timeout is huge since a script should usually run in under a millisecond. The limit is mostly to handle accidental infinite loops created during development.
It is possible to modify the maximum time a script can be executed with
millisecond precision, either via redis.conf
or using the CONFIG GET / CONFIG
SET command.
The configuration parameter affecting max execution time is called
lua-time-limit
.
When a script reaches the timeout it is not automatically terminated by Redis since this violates the contract Redis has with the scripting engine to ensure that scripts are atomic. Interrupting a script means potentially leaving the dataset with half-written data. For this reasons when a script executes for more than the specified time the following happens:
- Redis logs that a script is running too long.
- It starts accepting commands again from other clients, but will reply with a
BUSY error to all the clients sending normal commands.
The only allowed commands in this status are
SCRIPT KILL
andSHUTDOWN NOSAVE
. - It is possible to terminate a script that executes only read-only commands
using the
SCRIPT KILL
command. This does not violate the scripting semantic as no data was yet written to the dataset by the script. - If the script already called write commands the only allowed command becomes
SHUTDOWN NOSAVE
that stops the server without saving the current data set on disk (basically the server is aborted).
EVALSHA in the context of pipelining
Care should be taken when executing EVALSHA in the context of a pipelined
request, since even in a pipeline the order of execution of commands must be
guaranteed.
If EVALSHA will return a NOSCRIPT
error the command can not be reissued
later otherwise the order of execution is violated.
The client library implementation should take one of the following approaches:
Always use plain EVAL when in the context of a pipeline.
Accumulate all the commands to send into the pipeline, then check for EVAL commands and use the
SCRIPT EXISTS
command to check if all the scripts are already defined. If not, addSCRIPT LOAD
commands on top of the pipeline as required, and use EVALSHA for all the EVAL calls.


patients COVID- SARS-CoV- virus SARS coronavirus outbreak However, respiratory China severe novel Zhang Wang Coronavirus SARS-CoV acute disease treatment {border-style cases human infected study px;} syndrome used #ffffff;} Med epidemic reported Clinical infection Patients symptoms clinical cytokine Infect Lancet caused effective including new pneumonia similar time viral MERS MERS-CoV cells number people protein spread transmission January Wuhan, antibodies patients. severity Thus, Zhou contact immune individuals mortality recovered (%) Novel Wuhan Yang control diagnosis essential health masks response -nCoV East February Middle associated based blood cause confirmed diseases group high major patients, px; receptor storm {font-family COVID-, Chinese CoVs Dis RNA Respiratory Rev TCM age care considered critical days disease, early especially font-size health-care incubation period prognosis release therapy viruses ACE CoV Engl Sci cell described double; highly host humans inflammatory level lower mainly onset pathology phase plasma potential potentially recent risk support surgical treatments versus COVID-. Chan Characteristics Chen Disease Figure Han Health Huang Infection JAMA Liu Microbiol SARS-CoV, Syndrome Therefore, Transmission Zhao animal antiviral bats border-color border-width cases, causes comparison contain current death develop development disease. dry elderly emerging example, family features findings higher intermediate large long medicine mental multiple patient proposed providers public quarantine radiography required results role solid; vaccines {font-style {font-weight (%), (-) (Fig. (SARS) Age Chest China, Clin DOI:./jama.. Dong Drug Ebola Feng Int Nat Pneumonia R.X. SARS, SARS. Table WHO: Zhu addition, approximately average bold cluster common components corticosteroids cough courier; cytokines damage demographic demonstrated did dramatically efficacy em; entire factors genetic global help history https://doi.org/./... individual infect influenza injury known liver load lung lungs membrane men options origin pathogens produce provide psychological pt;} rapidly rate responses review spike started stay steroids studies suggested therapeutic therapies throat treat use using vaccine ventilation virus, virus. weeks


examples of
@pixiv/three-vrm-materials-hdr-emissive-multiplier
loader-plugin.html
Import VRMC_materials_hdr_emissiveMultiplier from gltf


{% load i18n %}
{% blocktrans %} Your account is now approved. You can {% endblocktrans %} {% trans "log in." %}
{% comment %} **registration/admin_approve_complete_email.html** Used after successful account activation. This template has no context variables of its own, and should simply inform the user that their account is now active. {% endcomment %}


{% extends 'base.html' %} {% block title %}NHL Teams{% endblock %} {% block content %}
Click on a team to view stats and graphs!
{% for division in divisions %}| Team | GP | W | L | OT | P | Streak |
|---|---|---|---|---|---|---|
| {{ team.team.abbreviation }} | {{ team.gamesPlayed }} | {{ team.leagueRecord.wins }} | {{ team.leagueRecord.losses }} | {{ team.leagueRecord.ot }} | {{ team.points }} | {{ team.streak.streakCode }} |


Clustering the Palmer Station penguin data, using PyMC3
Adelie, Chinstrap, Gentoo...
This post will be all about trying to infer the species various observations originated from, without actually having access to the labels. This might sound like a far-fetched example, but it happens more often than you might expect in biology! When studying large animals you can usually find clear differences between species, but when studying nematodes (tiny worms) in a soil sample those differences might be very hard to spot! You can also have a sub-population that slightly differs from the main community, for instance polyploid plants (with extra copies of their genome) might grow in the same field as plants with normal ploidy. These are considered the same species and are similar in most ways, except a bit bigger or stronger or more tolerant, so while making initial measurements these might not stand out. Or indirect measurements, some animals are rare and live in remote places, so biologists might use footprints to study those animals. If multiple species leave similar prints … they might have to resort to using their size, distance between them, … to estimate which exact species a set of prints belongs to. So the solution is to measure as many subjects as possible and (hopefully) figure it out later on.
It is particularly challenging to identify different groups if you don’t know even know how many groups there are. Here the Palmer Station Penguin dataset is used, to show the issue (we’ll hide the species labels from the models), and we’ll try to identify how many species there are in the set, and which subjects belong to the same group using flipper, bill and body mass measurements from each subject.
Notebooks with the data and full code for this post can be found in this GitHub repo. There you’ll also find the code applied to other datasets like the Iris and Fish Market datasets (albeit with less documentation).
Loading the data
The GitHub repo contains the data in a .csv format that can be loaded directly using pandas. We don’t need the
island where the observation was made or the sex of the animal, so these columns are dropped. Rows with remaining
missing values are omitted using .dropna()
. We do keep the species label, so later on we can check if
our clustering is actually working, but it will not be used during the clustering.
%load_ext nb_black
import seaborn as sns
import pymc3 as pm
import pandas as pd
import numpy as np
import arviz as az
import altair as alt
penguin_df = (
pd.read_csv("./data/penguins_size.csv").drop(columns=["island", "sex"]).dropna()
)
penguin_df
The data is best scaled, so the mean of each feature will be zero with a standard deviation of one. StandardScaler
makes this easy.
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaled_penguin_df = scaler.fit_transform(penguin_df.drop(columns=["species"]))
scaled_penguin_df = pd.DataFrame(scaled_penguin_df, columns=penguin_df.columns[1:])
scaled_penguin_df["species"] = list(penguin_df["species"])
scaled_penguin_df
The first model - using a single feature
All models in this post have a pm.Dirichlet
distribution at their core which defines the probabilities of observing
a certain group, in this case species. For now, we’ll define the number of clusters we want using n_clusters
,
we’ll work around this later, don’t worry! Next, we assign categories to all observations based on those probabilities.
Explicitly including categories using pm.Categorical
makes is really straightforward to extract groups later, note
however that there are more efficient ways using pm.NormalMixture
if we would just be interested in fitting a
model.
Here we include a sigma and a mean for each category, and create a likelihood function using those to fit a normal distribution on the body mass observations of each species.
n_clusters = 3
n_observations, n_features = scaled_penguin_df.shape
with pm.Model() as model:
p = pm.Dirichlet("p", a=np.ones(n_clusters))
category = pm.Categorical("category", p=p, shape=n_observations)
bm_sigmas = pm.HalfNormal("bm_sigmas", sigma=1, shape=n_clusters)
bm_means = pm.Normal("bm_means", np.zeros(n_clusters), sd=1, shape=n_clusters)
y_bm = pm.Normal(
"y_bm",
mu=bm_means[category],
sd=bm_sigmas[category],
observed=scaled_penguin_df.body_mass_g,
)
trace = pm.sample(10000)
After sampling, we can pull out the categories from one of the traces and compare this to the actual species to see how well it worked. We’ll add the groups back to the original data, quickly reformat it to get counts, and visualize using Altair.
[2][200]
points to the chain at index two and the trace at index 200, when doing this exercise inspect
multiple to get an impression of the overall performance.
groups = [
f"Group {n+1}"
for n in list(trace.get_values("category", burn=6000, combine=False)[2][20])
]
penguin_df["group"] = groups
plot_df = penguin_df.groupby(["species", "group"]).size().reset_index(name="counts")
alt.Chart(plot_df).mark_bar().encode(
x=alt.X("group", title=None),
y=alt.Y("counts", title="Count"),
color=alt.Color("species", title="Species"),
tooltip=["group", "counts", "species"],
).properties(width=400)
Here you can see that Group 2 contains all Gentoo penguins (these are the largest and heaviest), but adds in a few of the others. The other two groups contain a mix of Adelie and Chinstrap penguins, not particularly impressive as a classifier. Let’s have a look the data we provided to the model before proceeding.
As you can see, there is a ton of overlap between the species, not ideal for such a simple classifier to distinguish. So, we should include more measurements, like the flipper length and culmen (part of the beak) length and depth.
A model that includes all features
The easiest way to expand this model is by simply adding more sigmas, means and likelihoods to it all sharing the categories.
n_clusters = 3
n_observations, n_features = scaled_penguin_df.shape
with pm.Model() as model:
p = pm.Dirichlet("p", a=np.ones(n_clusters))
category = pm.Categorical("category", p=p, shape=n_observations)
cl_sigmas = pm.HalfNormal("cl_sigmas", sigma=1, shape=n_clusters)
cd_sigmas = pm.HalfNormal("cd_sigmas", sigma=1, shape=n_clusters)
fl_sigmas = pm.HalfNormal("fl_sigmas", sigma=1, shape=n_clusters)
bm_sigmas = pm.HalfNormal("bm_sigmas", sigma=1, shape=n_clusters)
cl_means = pm.Normal("cl_means", np.zeros(n_clusters), sd=1, shape=n_clusters)
cd_means = pm.Normal("cd_means", np.zeros(n_clusters), sd=1, shape=n_clusters)
fl_means = pm.Normal("fl_means", np.zeros(n_clusters), sd=1, shape=n_clusters)
bm_means = pm.Normal("bm_means", np.zeros(n_clusters), sd=1, shape=n_clusters)
y_cl = pm.Normal(
"y_cl",
mu=cl_means[category],
sd=cl_sigmas[category],
observed=scaled_penguin_df.culmen_length_mm,
)
y_cd = pm.Normal(
"y_cd",
mu=cd_means[category],
sd=cd_sigmas[category],
observed=scaled_penguin_df.culmen_depth_mm,
)
y_fl = pm.Normal(
"y_fl",
mu=fl_means[category],
sd=fl_sigmas[category],
observed=scaled_penguin_df.flipper_length_mm,
)
y_bm = pm.Normal(
"y_bm",
mu=bm_means[category],
sd=bm_sigmas[category],
observed=scaled_penguin_df.body_mass_g,
)
trace = pm.sample(10000)
This certainly works, though this would benefit from a loop instead of repeating code for each feature. However, is it any better than the previous model. Let’s have a look at a randomly selected chain/trace.
This certainly is a much better classification, which is confirmed by looking at multiple traces. All Gentoos are huddled together in group one, group three contains mostly Adelies, though group two is a bit of a mixed batch.However, this model has a big downside, multiple likelihoods. This makes it very hard to use PyMC3 and Arviz to compare the model with other models. It is not impossible, and in the GitHub repo there is a notebook where some code is included to do this, but this was very convoluted and definitely something to avoid where possible.
Switching to multivariate normal distributions
So to solve the issue with multiple likelihoods, pm.MvNormal
can be used, this is a multivariate normal or
gaussian distribution which takes multiple input values and combines them into a single likelihood. It requires a mean
for each feature in the input and a Cholesky decomposition of covariance matrix… Jikes, I won’t pretend I know the
underlying mathematics, I don’t, but fortunately I found a bit of code that generates the required
matrix using pm.LKJCholeskyCov
. In a nutshell this is required to take correlations between different features
into account.
Apart from that, this makes the code considerably cleaner and more generic than the previous model, so that is a nice free little bonus too.
n_clusters = 3
data = scaled_penguin_df.drop(columns=["species"]).values
n_observations, n_features = data.shape
with pm.Model() as model:
chol, corr, stds = pm.LKJCholeskyCov(
"chol",
n=n_features,
eta=2.0,
sd_dist=pm.Exponential.dist(1.0),
compute_corr=True,
)
cov = pm.Deterministic("cov", chol.dot(chol.T))
mu = pm.Normal(
"mu", 0.0, 1.5, shape=(n_clusters, n_features), testval=data.mean(axis=0)
)
p = pm.Dirichlet("p", a=np.ones(n_clusters))
category = pm.Categorical("category", p=p, shape=n_observations)
y = pm.MvNormal("y", mu[category], chol=chol, observed=data)
trace = pm.sample(8000)
As a multivariate gaussian looks at the likelihood of seeing combinations of features it is also a better suited method for these data. So we are rewarded with a better fitting model too, just look at the classification below, which is nearly perfect!
How to determine the number of clusters
So far we hard, coded the number of clusters we wanted. Which is nice if you know this, but if you have no clue … In this case you need to build a model with 2, 3, 4, 5 … clusters and see which one gives the best fit, without being to complex. We’ll first create a function that create a model with n clusters, samples this and returns the model and traces. Then we’ll run and store this with multiple cluster sizes and use Arviz to compare these.
def run_model(data, n_clusters, samples=4000):
print(f"Building model with {n_clusters} cluster and {samples} samples.")
n_observations, n_features = data.shape
with pm.Model() as model:
chol, corr, stds = pm.LKJCholeskyCov(
"chol",
n=n_features,
eta=2.0,
sd_dist=pm.Exponential.dist(1.0),
compute_corr=True,
)
mu = pm.Normal(
"mu", 0.0, 1.5, shape=(n_clusters, n_features), testval=data.mean(axis=0)
)
p = pm.Dirichlet("p", a=np.ones(n_clusters))
category = pm.Categorical("category", p=p, shape=n_observations)
y = pm.MvNormal("y", mu[category], chol=chol, observed=data)
trace = pm.sample(samples)
return model, trace
This is actually a very generic function that will accept any dataframe or matrix (it should be scaled though), and a
number of clusters, builds and samples a models which it then returns. With a few lines of code we can run this and
capture the output in a dictionary. Then we use az.compare
to compare the models with different numbers of
clusters.
data = scaled_penguin_df.drop(columns=["species"]).values
model_traces = {
f"model_{i}_clusters": run_model(data, i, samples=8000) for i in range(2, 6)
}
comp = az.compare({k: v[1] for k, v in model_traces.items()})
comp
| rank | loo | p_loo | d_loo | weight | se | dse | warning | loo_scale | |
|---|---|---|---|---|---|---|---|---|---|
| model_3_clusters | 0 | -905.740656 | 68.837020 | 0.000000 | 4.808971e-01 | 29.476505 | 0.000000 | True | log |
| model_5_clusters | 1 | -905.837578 | 197.606731 | 0.096921 | 5.191029e-01 | 28.926480 | 11.295538 | True | log |
| model_4_clusters | 2 | -922.262126 | 175.651671 | 16.521469 | 0.000000e+00 | 29.039549 | 10.030136 | True | log |
| model_2_clusters | 3 | -1284.311894 | 156.435489 | 378.571238 | 2.416753e-09 | 28.624421 | 16.756834 | True | log |
Using az.compare
there are a number of metrics applied to see which model is the best fit to our data. This
uses by default Leave-one-out cross-validation, and loo
, p_loo
and d_loo
are the numbers coming out of
that analysis (loo is the metric to check, lower is better, p_loo is the estimated number of parameters and d_loo is
the difference with the best model). The weight can roughly be seen as the probability the model is correct given the
data, here closer to 1 is better. The standard error on the cross-validation, se
in the table, is also included
as well the difference with between the models with the best model, dse
.
We can see that the model with three clusters actually performs the best here. As this isn’t the maximum number of
clusters tested we should accept this. However, often it is not that clear from these numbers which model should be
picked, two models might be very close, … So plotting this out using az.plot_compare
can help us sort this out.
az.plot_compare(comp)
Here you can see the scores for all models, the vertical gray line marks the best score. Though you can probably consider all models where the black bar intersects with this line as equally good (in this case models with 3, 4 and 5 clusters). So in that case pick the one with the least clusters, even if it isn’t the top ranked one.
Conclusion
As I’ve only been working with PyMC3 and Bayesian Statistics for a month or two, some concepts here are beyond what I fully understand. Take everything here with a rather large pinch of salt! However, by going slow and taking one step at the time, it was still possible to build a very performant classifier for this dataset. It also gives me a push towards which theory to study up on (Multivariate Gaussians).
References
- palmerpenguins: Palmer Archipelago (Antarctica) penguin data. Allison Marie Horst and Alison Presmanes Hill and Kristen B Gorman (2020).
Acknowledgements
Header photo by Derek Oyen on Unsplash
Liked this post ? You can buy me a coffee


Package org.bitcoinj.wallet
Interface Protos.KeyOrBuilder
-
- All Superinterfaces:
com.google.protobuf.MessageLiteOrBuilder
,com.google.protobuf.MessageOrBuilder
- All Known Implementing Classes:
Protos.Key
,Protos.Key.Builder
- Enclosing class:
- Protos
public static interface Protos.KeyOrBuilder extends com.google.protobuf.MessageOrBuilder
-
-
Method Summary
All Methods Instance Methods Abstract Methods Modifier and Type Method Description int
getAccountPath(int index)
The path to the root.int
getAccountPathCount()
The path to the root.java.util.List<java.lang.Integer>
getAccountPathList()
The path to the root.long
getCreationTimestamp()
Timestamp stored as millis since epoch.Protos.DeterministicKey
getDeterministicKey()
optional .wallet.DeterministicKey deterministic_key = 7;
Protos.DeterministicKeyOrBuilder
getDeterministicKeyOrBuilder()
optional .wallet.DeterministicKey deterministic_key = 7;
com.google.protobuf.ByteString
getDeterministicSeed()
The seed for a deterministic key hierarchy.Protos.EncryptedData
getEncryptedData()
If the secret data is encrypted, then secret_bytes is missing and this field is set.Protos.EncryptedDataOrBuilder
getEncryptedDataOrBuilder()
If the secret data is encrypted, then secret_bytes is missing and this field is set.Protos.EncryptedData
getEncryptedDeterministicSeed()
Encrypted version of the seedProtos.EncryptedDataOrBuilder
getEncryptedDeterministicSeedOrBuilder()
Encrypted version of the seedjava.lang.String
getLabel()
User-provided label associated with the key.com.google.protobuf.ByteString
getLabelBytes()
User-provided label associated with the key.Protos.Key.OutputScriptType
getOutputScriptType()
Type of addresses (aka output scripts) to generate for receiving.com.google.protobuf.ByteString
getPublicKey()
The public EC key derived from the private key.com.google.protobuf.ByteString
getSecretBytes()
Either the private EC key bytes (without any ASN.1 wrapping), or the deterministic root seed.Protos.Key.Type
getType()
required .wallet.Key.Type type = 1;
boolean
hasCreationTimestamp()
Timestamp stored as millis since epoch.boolean
hasDeterministicKey()
optional .wallet.DeterministicKey deterministic_key = 7;
boolean
hasDeterministicSeed()
The seed for a deterministic key hierarchy.boolean
hasEncryptedData()
If the secret data is encrypted, then secret_bytes is missing and this field is set.boolean
hasEncryptedDeterministicSeed()
Encrypted version of the seedboolean
hasLabel()
User-provided label associated with the key.boolean
hasOutputScriptType()
Type of addresses (aka output scripts) to generate for receiving.boolean
hasPublicKey()
The public EC key derived from the private key.boolean
hasSecretBytes()
Either the private EC key bytes (without any ASN.1 wrapping), or the deterministic root seed.boolean
hasType()
required .wallet.Key.Type type = 1;
-
Methods inherited from interface com.google.protobuf.MessageOrBuilder
findInitializationErrors, getAllFields, getDefaultInstanceForType, getDescriptorForType, getField, getInitializationErrorString, getOneofFieldDescriptor, getRepeatedField, getRepeatedFieldCount, getUnknownFields, hasField, hasOneof
-
-
-
-
Method Detail
-
hasType
boolean hasType()
required .wallet.Key.Type type = 1;
-
getType
Protos.Key.Type getType()
required .wallet.Key.Type type = 1;
-
hasSecretBytes
boolean hasSecretBytes()
Either the private EC key bytes (without any ASN.1 wrapping), or the deterministic root seed. If the secret is encrypted, or this is a "watching entry" then this is missing.
optional bytes secret_bytes = 2;
-
getSecretBytes
com.google.protobuf.ByteString getSecretBytes()
Either the private EC key bytes (without any ASN.1 wrapping), or the deterministic root seed. If the secret is encrypted, or this is a "watching entry" then this is missing.
optional bytes secret_bytes = 2;
-
hasEncryptedData
boolean hasEncryptedData()
If the secret data is encrypted, then secret_bytes is missing and this field is set.
optional .wallet.EncryptedData encrypted_data = 6;
-
getEncryptedData
Protos.EncryptedData getEncryptedData()
If the secret data is encrypted, then secret_bytes is missing and this field is set.
optional .wallet.EncryptedData encrypted_data = 6;
-
getEncryptedDataOrBuilder
Protos.EncryptedDataOrBuilder getEncryptedDataOrBuilder()
If the secret data is encrypted, then secret_bytes is missing and this field is set.
optional .wallet.EncryptedData encrypted_data = 6;
-
hasPublicKey
boolean hasPublicKey()
The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to do lots of slow EC math on startup. For DETERMINISTIC_MNEMONIC entries this is missing.
optional bytes public_key = 3;
-
getPublicKey
com.google.protobuf.ByteString getPublicKey()
The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to do lots of slow EC math on startup. For DETERMINISTIC_MNEMONIC entries this is missing.
optional bytes public_key = 3;
-
hasLabel
boolean hasLabel()
User-provided label associated with the key.
optional string label = 4;
-
getLabel
java.lang.String getLabel()
User-provided label associated with the key.
optional string label = 4;
-
getLabelBytes
com.google.protobuf.ByteString getLabelBytes()
User-provided label associated with the key.
optional string label = 4;
-
hasCreationTimestamp
boolean hasCreationTimestamp()
Timestamp stored as millis since epoch. Useful for skipping block bodies before this point. The reason it's optional is that keys derived from a parent don't have this data.
optional int64 creation_timestamp = 5;
-
getCreationTimestamp
long getCreationTimestamp()
Timestamp stored as millis since epoch. Useful for skipping block bodies before this point. The reason it's optional is that keys derived from a parent don't have this data.
optional int64 creation_timestamp = 5;
-
hasDeterministicKey
boolean hasDeterministicKey()
optional .wallet.DeterministicKey deterministic_key = 7;
-
getDeterministicKey
Protos.DeterministicKey getDeterministicKey()
optional .wallet.DeterministicKey deterministic_key = 7;
-
getDeterministicKeyOrBuilder
Protos.DeterministicKeyOrBuilder getDeterministicKeyOrBuilder()
optional .wallet.DeterministicKey deterministic_key = 7;
-
hasDeterministicSeed
boolean hasDeterministicSeed()
The seed for a deterministic key hierarchy. Derived from the mnemonic, but cached here for quick startup. Only applicable to a DETERMINISTIC_MNEMONIC key entry.
optional bytes deterministic_seed = 8;
-
getDeterministicSeed
com.google.protobuf.ByteString getDeterministicSeed()
The seed for a deterministic key hierarchy. Derived from the mnemonic, but cached here for quick startup. Only applicable to a DETERMINISTIC_MNEMONIC key entry.
optional bytes deterministic_seed = 8;
-
hasEncryptedDeterministicSeed
boolean hasEncryptedDeterministicSeed()
Encrypted version of the seed
optional .wallet.EncryptedData encrypted_deterministic_seed = 9;
-
getEncryptedDeterministicSeed
Protos.EncryptedData getEncryptedDeterministicSeed()
Encrypted version of the seed
optional .wallet.EncryptedData encrypted_deterministic_seed = 9;
-
getEncryptedDeterministicSeedOrBuilder
Protos.EncryptedDataOrBuilder getEncryptedDeterministicSeedOrBuilder()
Encrypted version of the seed
optional .wallet.EncryptedData encrypted_deterministic_seed = 9;
-
getAccountPathList
java.util.List<java.lang.Integer> getAccountPathList()
The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry.
repeated uint32 account_path = 10 [packed = true];
-
getAccountPathCount
int getAccountPathCount()
The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry.
repeated uint32 account_path = 10 [packed = true];
-
getAccountPath
int getAccountPath(int index)
The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry.
repeated uint32 account_path = 10 [packed = true];
-
hasOutputScriptType
boolean hasOutputScriptType()
Type of addresses (aka output scripts) to generate for receiving.
optional .wallet.Key.OutputScriptType output_script_type = 11;
-
getOutputScriptType
Protos.Key.OutputScriptType getOutputScriptType()
Type of addresses (aka output scripts) to generate for receiving.
optional .wallet.Key.OutputScriptType output_script_type = 11;
-
-


Government plans to reduce importation of rice - Minister reveals
Deputy Minister of Agriculture in charge of Horticulture, George Boahen Oduro has outlined plans put in place by the government of Ghana to ensure a reduction in the importation of rice.
Speaking in an interview on Adom FM’s morning show Dwaso Nsem, Friday, the Deputy Minister said his outfit was working on an agreement to enable farmers buy from local millers in about two to three years.
He added that the country ought to reach a level where it could produce the rice needed for local consumption.
Rice producers in the country continue to struggle to break even as the country’s rice import increases annually.
In some parts of the Northern and Upper East Regions, local farmers are losing their investments due to lack of ready-markets for their produce.
The Minister also said the government was currently liaising with Agriculture extension officers and the Agriculture Directorates to assist with rice production in the country, further urging rice producers to contact their local assemblies to access the needed assistance, as it is the official channel through which government is implementing its agriculture initiative.


The distributable, loadable, and executable unit of code in WebAssembly is called a module. At runtime, a module can be instantiated with a set of import values to produce an instance, which is an immutable tuple referencing all the state accessible to the running module. Multiple module instances can access the same shared state which is the basis for dynamic linking in WebAssembly. WebAssembly modules are also designed to integrate with ES6 modules.
A module contains the following sections:
A module also defines several index spaces which are statically indexed by various operators and section fields in the module:
A module can declare a sequence of imports which are provided, at instantiation time, by the host environment. There are several kinds of imports:
call
operator;In the future, other kinds of imports may be added. Imports are designed to allow modules to share code and data while still allowing separate compilation and caching.
All imports include two opaque names: a module name and an export name, which are required to be valid UTF-8. The interpretation of these names is up to the host environment but designed to allow a host environments, like the Web, to support a two-level namespace.
Each specific kind of import defines additional fields:
A function import includes a signature to use for the imported function inside the module. The checking of the signature against the imported function outside the module is defined by the host environment. However, if the imported function is a WebAssembly function, the host environment must raise an instantiation-time error if there is a signature mismatch.
A global variable import includes the value type and mutability of the global variable. These fields have the same meaning as in the Global section. In the MVP, global variable imports must be immutable.
A linear memory import includes the same set of fields defined in the Linear Memory section: initial length and optional maximum length. The host environment must only allow imports of WebAssembly linear memories that have initial length greater-or-equal than the initial length declared in the import and that have maximum length less-or-equal than the maximum length declared in the import. This ensures that separate compilation can assume: memory accesses below the declared initial length are always in-bounds, accesses above the declared maximum length are always out-of-bounds and if initial equals maximum, the length is fixed. In the MVP, every memory is a default memory and thus there may be at most one linear memory import or linear memory definition.
A table import includes the same set of fields defined in the Table section: element type, initial length and optional maximum length. As with the linear memory section, the host environment must ensure only WebAssembly tables are imported with exactly-matching element type, greater-or-equal initial length, and less-or-equal maximum length. In the MVP, every table is a default table and thus there may be at most one table import or table definition.
Since the WebAssembly spec does not define how import names are interpreted:
The open-ended nature of module imports allow them to be used to expose
arbitrary host environment functionality to WebAssembly code, similar to a
native syscall
. For example, a shell environment could define a builtin
stdio
module with an export puts
.
A module can declare a sequence of exports which are returned at instantiation time to the host environment. Each export has three fields: a name, which is required to be valid UTF-8, whose meaning is defined by the host environment, a type, indicating whether the export is a function, global, memory or table, and an index into the type’s corresponding index space.
All definitions are exportable: functions, globals, linear memories and tables. The meaning an exported definition is defined by the host environment. However, if another WebAssembly instance imports the definition, then both instances will share the same definition and the associated state (global variable value, linear memory bytes, table elements) is shared.
Export names must be unique.
In the MVP, only immutable global variables can be exported.
While ES6 defines how to parse, link and execute a module, ES6 does not define when this parsing/linking/execution occurs. An additional extension to the HTML spec is required to say when a script is parsed as a module instead of normal global code. This work is ongoing. Currently, the following entry points for modules are being considered:
<script type="module">
;Worker
constructor;importScripts
Worker API;Additionally, an ES6 module can recursively import other modules via import
statements.
For WebAssembly/ES6 module integration, the idea is that all the above module entry points could also load WebAssembly modules simply by passing the URL of a WebAssembly module. The distinction of whether the module was WebAssembly or ES6 code could be made by namespacing or by content sniffing the first bytes of the fetched resource (which, for WebAssembly, would be a non-ASCII—and thus illegal as JavaScript—magic number). Thus, the whole module-loading pipeline (resolving the name to a URL, fetching the URL, any other loader hooks) would be shared and only the final stage would fork into either the JavaScript parser or the WebAssembly decoder.
Any non-builtin imports from within a WebAssembly module would be treated as
if they were import
statements of an ES6 module. If an ES6 module import
ed
a WebAssembly module, the WebAssembly module’s exports would be linked as if
they were the exports of an ES6 module. Once parsing and linking phases
were complete, a WebAssembly module would have its start function, defined
by the start module option, called in place of executing the ES6 module
top-level script. By default, multiple loads of the same module URL (in
the same realm) reuse the same instance. It may be worthwhile in the future
to consider extensions to allow applications to load/compile/link a module
once and instantiate multiple times (each with a separate linear memory).
This integration strategy should allow WebAssembly modules to be fairly
interchangeable with ES6 modules (ignoring
GC/Web API signature restrictions of the
WebAssembly MVP) and thus it should be natural to compose a single application
from both kinds of code. This goal motivates the
semantic design of giving each WebAssembly
module its own disjoint linear memory. Otherwise, if all modules shared a single
linear memory (all modules with the same realm? origin? window?—even the
scope of “all” is a nuanced question), a single app using multiple
independent libraries would have to hope that all the WebAssembly modules
transitively used by those libraries “played well” together (e.g., explicitly
shared malloc
and coordinated global address ranges). Instead, the
dynamic linking future feature is intended
to allow explicitly sharing state between module instances.
If the module has a start node defined, the function it refers should be called by the loader after the instance is initialized, including its Memory and Table though Data and Element sections, and before the exported functions are callable.
For example, a start node in a module will be:
(start $start_function)
or
(start 42)
In the first example, the environment is expected to call the function $start_function
before calling any other module function. In the second case, the environment is
expected to call the module function indexed 42. This number is the function index starting from 0 (same as for export
).
A module can:
The global section provides an internal definition of zero or more global variables.
Each global variable internal definition declares its type (a value type), mutability (boolean flag) and initializer (an initializer expression).
The linear memory section provides an internal definition of one linear memory. In the MVP, every memory is a default memory and there may be at most one linear memory import or linear memory definition.
Each linear memory section declares an initial memory size
(which may be subsequently increased by grow_memory
) and an
optional maximum memory size.
grow_memory
is guaranteed to fail if attempting to
grow past the declared maximum. When declared, implementations should
(non-normative) attempt to reserve virtual memory up to the maximum size. While
failure to allocate the initial memory size is a runtime error, failure to
reserve up to the maximum is not. When a maximum memory size is not declared,
on architectures with limited virtual address space, engines should allocate
only the initial size and reallocate on demand.
The initial contents of linear memory are zero. The data section contains a
possibly-empty array of data segments which specify the initial contents
of fixed (offset, length)
ranges of a given memory, specified by its
linear memory index. This section is analogous to
the .data
section of native executables. The length
is an integer constant
value (defining the length of the given segment). The offset
is an
initializer expression.
The table section contains zero or more definitions of distinct tables. In the MVP, every table is a default table and there may be at most one table import or table definition.
Each table definition declares an element type, initial length, and optional maximum length.
In the MVP, the only valid element type is "anyfunc"
, but in the
future ,
more element types may be added.
In the MVP, tables can only be resized via host-defined APIs (such as
the JavaScript WebAssembly.Table.prototype.grow
).
A grow_table
may be added in the future .
In either case, table growth is guaranteed to fail if attempting to grow past
the declared maximum. As with linear memory, when a maximum is declared,
implementations should (non-normative) attempt to reserve virtual memory up to
the maximum size. While failure to allocate the initial memory size is a
runtime error, failure to reserve up to the maximum is not. When a maximum
memory size is not declared, on architectures with limited virtual address
space, engines should allocate only the initial size and reallocate on demand.
The intial contents of a tables’ elements are sentinel values (that would trap if called). The elements section allows a module to initialize (at instantiation time) the elements of any imported or internally-defined table with any other definition in the module. This is symmetric to how the Data section allows a module to initialize the bytes of any imported or defined memory.
The elements section contains a possibly-empty array of element segments which
specify the initial contents of fixed (offset, length)
ranges of a given
table, specified by its table index. The length
is an
integer constant value (defining the length of the given segment). The offset
is an initializer expression. Elements are specified
by their index into the corresponding index space.
A single logical function definition is defined in two sections:
This split aids in streaming compilation by putting the function bodies, which constitute most of the byte size of the module, near the end so that all metadata necessary for recursive module loading and parallel compilation is available before compilation begins.
The function index space indexes all imported and internally-defined function definitions, assigning monotonically-increasing indices based on the order of definition in the module (as defined by the binary encoding). Thus, the index space starts at zero with the function imports (if any) followed by the functions defined within the module.
The function index space is used by:
The global index space indexes all imported and internally-defined global definitions, assigning monotonically-increasing indices based on the order of definition in the module (as defined by the binary encoding). Thus, the index space starts at zero with the global imports (if any) followed by the globals defined within the module.
The global index space is used by:
The linear memory index space indexes all imported and internally-defined linear memory definitions, assigning monotonically-increasing indices based on the order of definition in the module (as defined by the binary encoding). Thus, the index space starts at zero with the memory imports (if any) followed by the memories defined within the module.
The linear memory index space is only used by the data section. In the MVP, there is at most one linear memory so this index space is just a placeholder for when there can be multiple memories .
The table index space indexes all imported and internally-defined table definitions, assigning monotonically-increasing indices based on the order of definition in the module (as defined by the binary encoding). Thus, the index space starts at zero with the table imports (if any) followed by the tables defined within the module.
The table index space is only used by the elements section. In the MVP, there is at most one table so this index space is just a placeholder for when there can be multiple tables .
Initializer expressions are evaluated at instantiation time and are currently used to:
An initializer expression is a pure WebAssembly expression that is encoded with the same binary encoding as WebAssembly expressions. Not all WebAssembly operators can or should be supported in initializer expressions; initializer expressions represent a minimal pure subset of WebAssembly expressions.
In the MVP, to keep things simple while still supporting the basic needs of dynamic linking, initializer expressions are restricted to the following nullary operators:
get_global
, where the global index must refer to an immutable import.In the future, operators like i32.add
could be added to allow more expressive
base + offset
load-time calculations.


A library of cross-platform tested terminal/console command strings for doing things like color and cursor positioning. This is a subset of both ansi and vt100. All control codes included work on both Windows & Unix-like OSes, except where noted.
var consoleControl = require('console-control-strings')
console.log(consoleControl.color('blue','bgRed', 'bold') + 'hi there' + consoleControl.color('reset'))
process.stdout.write(consoleControl.goto(75, 10))
There are tons of libraries similar to this one. I wanted one that was:
Returns the escape sequence to move num lines up.
Returns the escape sequence to move num lines down.
Returns the escape sequence to move num lines righ.
Returns the escape sequence to move num lines left.
Returns the escape sequence to move num lines down and to the beginning of the line.
Returns the escape sequence to move num lines up and to the beginning of the line.
Returns the escape sequence to erase everything from the current cursor position to the bottom right of the screen. This is line based, so it erases the remainder of the current line and all following lines.
Returns the escape sequence to erase to the end of the current line.
Returns the escape sequence to move the cursor to the designated position. Note that the origin is 1, 1 not 0, 0.
Returns the escape sequence to move the cursor to the beginning of the
current line. (That is, it returns a carriage return, \r
.)
Returns the escape sequence to cause the termianl to beep. (That is, it
returns unicode character \x0007
, a Control-G.)
Returns the escape sequence to hide the cursor.
Returns the escape sequence to show the cursor.
Returns the escape sequence to set the current terminal display attributes
(mostly colors). Arguments can either be a list of attributes or an array
of attributes. The difference between passing in an array or list of colors
and calling .color
separately for each one, is that in the former case a
single escape sequence will be produced where as in the latter each change
will have its own distinct escape sequence. Each attribute can be one of:


|
Task Description
A simple computer
has been designed to have the following general
registers that are each 16-bits wide: AX, BX, CX, and
DX.
This same
computer has the following simple operations that it can
perform on any of the registers:
-
MOV reg1,
reg2 - moves value of reg2 into reg1.
-
MOV reg1,
<value> - moves numeric value specified into
reg1.
-
ADD reg1,
reg2 - adds value of reg2 to reg1 and
stores the sum in reg1.
-
ADD reg1,
<value> - adds the numeric value specified to
reg1 and stores this sum in reg1.
-
SUB reg2,
reg1 - subtracts the value in reg2 from
the reg1 and stores this in reg1.
-
SUB reg1,
<value> - subtracts the numeric value
specified from reg1 and stores this in reg1.
-
SHOW
reg1 - displays value in reg1 (in
decimal) followed by a CR/LF.
-
HLT
- signifies the end of the program.
Note: regx can
be any of the registers (AX, BX, CX, or DX) and <value>
is any whole decimal number 0 – 65535. Assume that only
a comma separates the destination and source fields.
Your task is to
write a code interpreter that will execute a given
program to completion.
Program Input
Your program will
be given an input file (prob14.in) with one operation
per line. It should execute all instructions until it
reaches a “HLT”, and then exit. A sample input file is
shown below:
MOV AX,3
MOV BX,2000
ADD BX,AX
SHOW AX
SHOW BX
HLT
Program Output
Write the output
to prob14.out as follows:
3
2003
|


Bud Light Platinum
If good intentions pave the road to hell, then I've always thought the asphalt would be made from unintended consequences. Case in point: Bud Light Platinum, one of the latest unfortunate byproducts of the craft beer industry.
Craft beer has bestowed upon the beer-consuming public many and varied wonders, and for those I will be forever grateful. And then there's Bud Light Platinum. When Big Beer isn't busy buying up beloved craft breweries to maintain its market share, it's busy trying to convince people to buy a "premium" Bud Light for same price as a craft beer.
If you like Bud Light, there's a decent chance you will like the Platinum version even more. It tastes like a cleaner Bud Light with less of the unpleasant aftertaste that made me renounce Bud products — formerly my go-to when I could afford "good beer" — in my early 20's.
And the AB InBev brewers outdid themselves somewhere in the brewing process because Bud Light Platinum clocks in at 6.0% alcohol by volume and 137 calories. By comparison Budweiser — aka Bud Heavy — is 5.0% and 145 calories. Generally, there's a strong correlation between ABV and calories. That Platinum somewhat bucks this correlation is a testament to the brewing skill at AB InBev.
If only they used their powers — and make no mistake, despite the usual output Anheuser-Busch employs some the best brewers in the world — for good. Instead, they charge, in my area, around $10 a six-pack for a slightly better Bud Light. That's almost criminal. There are many, many, better craft beers that are cheaper than that. And many more that don't cost much more.
Speaking of criminals involved in a multi-national beer conglomerate, a special tip o' the cap to the editorial team responsible for letting this gem through: "When you grab one of our signature blue bottles, be ready to make it platinum." Incomprehensible syntax may not help pave the road to hell, but it is a signpost that you may already living there.
If, even after reading this, you still feel the need to "make it platinum," just buy the good beer of your choice and put the difference between it and Bud Light Platinum in a savings account. As I write this in late January 2019, actual platinum costs about $26 per gram.


Following examples illustrate how easily StepRouter works with any flavor of steps (HTML/CSS/JS). Whether the steps contain static content, forms, or even AJAX calls. StepRouter simply focuses on navigation among the steps without getting in your way of building the steps.


We are a group of students who are providing a platform that will help in the search of missing persons anywhere.
Student, University of Texas at El Paso
Student, Vanderbilt University
Student, Tecnológico de Monterrey
Student, Arizona State University


Experienced Agile Salesforce Administrator (advanced) and Developer (intermediate). Extremely versed in all out-of-the-box functionality and custom platform development, with experience as a sole administrator and in Agile development environments.
Clients include: Centers for Medicare, State of Oklahoma, State Department
Clients include: Unified Parking Partners, CIEE
- Admin for Experience Cloud sites.
- Building and deploying custom objects with heavy use of validation rules, custom Visualforce pages, workflow rules, and Process Builder.
- Building and deploying custom & standard objects.
- Creating custom JavaScript buttons and validation rules.
- App integration (AppExchange and 3rd-Party software); Integrated 3rd-party auditing and scheduling
software.
- Complex report building and dashboarding.
- Pulling and displaying specific data sets with SOQL.
Focused on C#/.NET enviroment


FitText makes font-sizes flexible. Use this plugin on your responsive design for ratio-based resizing of your headlines.
Here is a simple FitText setup:
```html
```
Your text should now fluidly resize, by default: Font-size = 1/10th of the element’s width.
If your text is resizing poorly, you’ll want to turn tweak up/down “The Compressor”. It works a little like a guitar amp. The default is 1
.
javascript
jQuery("#responsive_headline").fitText(1.2); // Turn the compressor up (resizes more aggressively)
jQuery("#responsive_headline").fitText(0.8); // Turn the compressor down (resizes less aggressively)
This will hopefully give you a level of “control” that might not be pixel perfect, but resizes smoothly & nicely.
FitText now allows you to specify two optional pixel values: minFontSize
and maxFontSize
. Great for situations when you want to preserve hierarchy.
javascript
jQuery("#responsive_headline").fitText(1.2, { minFontSize: '20px', maxFontSize: '40px' });
display: inline
elements don’t have a width. Use display: block
OR display: inline-block
+ a specified width (i.e. width: 100%
).position:absolute
elements need a specified width as well.vw
units instead. Supported in all major browsers.That’s okay. Check out these handy non-jQuery versions maintained by other people.
v 1.2
- Added onorientationchange
eventv 1.1
- FitText now ignores font-size and has minFontSize & maxFontSize optionsv 1.0.1
- Fix for broken font-size.v 1.0
- Initial ReleaseIf you want more exact fitting text, there are plugins for that! We recommend checking out BigText by Zach Leatherman or SlabText by Brian McAllister.
If you think you can make this better, please Download, Fork, & Commit. We’d love to see your ideas.


Sugarchain
one-CPU-one-vote, the world's fastest PoW blockchain
Current height is
loading...
0
(
0
blocks since you open this page)
SPECS
DOWNLOAD
CPUMINER
TEAM
CONTACTS
TRADE


| Properties' Summary |
string
DataSourceName |
is the name of a named datasource to use. |
string
URL |
is the connection URL. Could be used instead of the DataSourceName.
|
string
Command |
is the command which should be executed.
|
long
TransactionIsolation |
indicates the transaction isolation level, which should be used for the
connection. |
::com::sun::star::container::XNameAccess
TypeMap |
is the type map that will be used for the custom mapping of SQL structured types
and distinct types.
|
boolean
EscapeProcessing |
returns if escape processing is on or off.
If escape scanning is on (the default), the driver will do
escape substitution before sending the SQL to the database.
This is only evaluated, if the CommandType is COMMAND.
|
long
QueryTimeOut |
retrieves the number of seconds the driver will wait for a Statement
to execute. If the limit is exceeded, a
SQLException
is thrown.
There is no limitation, if set to zero.
|
long
MaxFieldSize |
returns the maximum number of bytes allowed for any column value.
|
long
MaxRows |
retrieves the maximum number of rows that a ResultSet can contain.
If the limit is exceeded, the excess rows are silently dropped.
There is no limitation, if set to zero.
|
string
User |
determines the user for whom to open the connection.
|
string
Password |
determines the user for whom to open the connection.
|
long
ResultSetType |
determine the result set type.
|
| Properties' Details |
DataSourceName
string DataSourceName;
- Description
- is the name of a named datasource to use.
- See also
|
|
URL
string URL;
- Description
- is the connection URL. Could be used instead of the DataSourceName.
|
|
Command
string Command;
- Description
- is the command which should be executed.
|
|
TransactionIsolation
long TransactionIsolation;
- Description
- indicates the transaction isolation level, which should be used for the
connection.
- See also
- TransactionIsolation
|
|
TypeMap
::com::sun::star::container::XNameAccess TypeMap;
- Description
- is the type map that will be used for the custom mapping of SQL structured types
and distinct types.
|
|
EscapeProcessing
boolean EscapeProcessing;
- Description
- returns if escape processing is on or off.
If escape scanning is on (the default), the driver will do
escape substitution before sending the SQL to the database.
This is only evaluated, if the CommandType is COMMAND.
|
|
QueryTimeOut
long QueryTimeOut;
- Description
- retrieves the number of seconds the driver will wait for a Statement
to execute. If the limit is exceeded, a
SQLException
is thrown.
There is no limitation, if set to zero.
|
|
| MaxFieldSize
|
MaxRows
long MaxRows;
- Description
- retrieves the maximum number of rows that a ResultSet can contain.
If the limit is exceeded, the excess rows are silently dropped.
There is no limitation, if set to zero.
|
|
User
string User;
- Description
- determines the user for whom to open the connection.
|
|
Password
string Password;
- Description
- determines the user for whom to open the connection.
|
|
ResultSetType
long ResultSetType;
- Description
- determine the result set type.
- See also
- ResultSetType
|
|
Copyright © 2013, The Apache Software Foundation, Licensed under the Apache License, Version 2.0. Apache, the Apache feather logo, Apache OpenOffice and OpenOffice.org are trademarks of The Apache Software Foundation. Other names may be trademarks of their respective owners.


Empowering from our point of view not only includes breaking the communication barriers but it also includes inspiring the people to achieve greater ambitions as a result of improved communication.
HastBoli is a free and independent platform which will enable people to learn and practice Indian Sign Language (ISL) from the comfort of their home. We have tried to use the best and latest technology to provide a hassle-free and comfortable learning environment which would prove to be an ideal resource in the future.
We will continually strive to make modifications and advancements in the coming time.


The 16th annual KIDSPORTS Invitational Powered by the Warsaw Sports Marketing Center is a nonprofit 3-on-3 basketball tournament for 5th-8th grade boys and girls held at University of Oregon’s Matthew Knight Arena on Sunday, April 12th. Registration is currently open and accessible at www.kidsports.org/warsaw however spots are limited.
The annual tournament is an event consisting of 80 teams, roughly 400 players, that costs only $15 for a team of up to 5 to register. The KIDSPORTS Invitational provides kids with the unique opportunity for kids to play at one of the premier venues in the country, Matthew Knight Arena, have an all-day fun environment, and interact with University of Oregon student athletes regardless of their financial background. The event is free for all to attend, all community members are encouraged to attend.
The tournament began in 1998 as the James H. Warsaw 3-on-3 Classic. Now in its 16th annual iteration, the KIDSPORTS Invitational is organized, promoted, and executed by student members of the University of Oregon’s Warsaw Sports Business Club. The KIDSPORTS Invitational provides Warsaw Sports Business Club members with valuable experiential learning opportunities in event operations, sponsorship, digital media and communications, and creative.
The fundraising effort will seek to strengthen the KIDSPORTS Emerald Scholarship Fund and the Stephen Dember Memorial Scholarship Fund. The goal is to create a life changing event filled with unique opportunities that is accessible to all regardless of financial restrictions.


Module: StackPath
- Defined in:
- lib/stack_path.rb,
lib/stack_path/client.rb,
lib/stack_path/version.rb
Overview
A package for querying the StackPath API
Defined Under Namespace
Constant Summary
- VERSION =
The current version number of the gem
'0.0.2'.freeze
Class Method Summary collapse
-
.build_client(options = {}) ⇒ Object
Build a new Client with the given options and return it.


Gaze data from the Visual World Paradigm requires significant preprocessing prior to plotting and analyzing the data. This package provides functions for preparing visual world eye-tracking data for statistical analysis and plotting. It can prepare data for linear analyses (e.g., ANOVA, Gaussian-family LMER, Gaussian-family GAMM) as well as logistic analyses (e.g., binomial-family LMER and binomial-family GAMM). Additionally, it contains various plotting functions for creating grand average and conditional average plots. See the vignette for samples of the functionality. Currently, the functions in this package are designed for handling data collected with SR Research Eyelink eye trackers using Sample Reports created in SR Research Data Viewer. While we would like to add functionality for data collected with other systems in the future, the current package is considered to be feature-complete; further updates will mainly entail maintenance and the addition of minor functionality.
| Version: | 1.1.0 |
| Depends: | R (≥ 3.3.0), dplyr (≥ 0.7.0) |
| Imports: | rlang (≥ 0.1.1), ggplot2 (≥ 2.2.0), mgcv (≥ 1.8-16), shiny (≥ 0.14.2), tidyr (≥ 0.6.0), stats (≥ 3.3.2) |
| Suggests: | knitr, rmarkdown, gridExtra, itsadug |
| Published: | 2018-03-20 |
| Author: | Vincent Porretta [aut, cre], Aki-Juhani Kyröläinen [aut], Jacolien van Rij [ctb], Juhani Järvikivi [ctb] |
| Maintainer: | Vincent Porretta <vincentporretta at gmail.com> |
| License: | GPL-2 | GPL-3 [expanded from: GPL (≥ 2)] |
| NeedsCompilation: | no |
| Citation: | VWPre citation info |
| Materials: | README NEWS |
| CRAN checks: | VWPre results |
| Reference manual: | VWPre.pdf |
| Vignettes: |
Basic VWP Preprocessing for SR Eyelink Data Relabeling Interest Areas or Defining New Post-hoc Interest Areas for SR Eyelink Data Aligning Sample Data to a Specific Sample Message in SR Eyelink Data Plotting SR Eyelink Data Processed with VWPre |
| Package source: | VWPre_1.1.0.tar.gz |
| Windows binaries: | r-devel: VWPre_1.1.0.zip, r-release: VWPre_1.1.0.zip, r-oldrel: VWPre_1.1.0.zip |
| OS X binaries: | r-release: VWPre_1.1.0.tgz, r-oldrel: VWPre_1.1.0.tgz |
| Old sources: | VWPre archive |
Please use the canonical form https://CRAN.R-project.org/package=VWPre to link to this page.


Connecting
Have you tried using any of the insight and techniques for growing trust and sincerity? How did it go?
I tried the exorcising insight of basic empathy on the level that every human being is 'similar' in a base way.
In this way, walking past a number of relative stranger in the street the other day, I decided to mentally wish them well. Looking them in the eye if they looked, acknowledge them, and say hello.
The effect was quite amazing I think. The majority of people acknowledged me and responded positively to me.
I did actually have a nice sense of well-being and connection. This was with parents of children who go to my my children's school, most of whom I haven't really met, but have seen around. A great sense of community belonging could be a way of describing it.
Try empathic listening - how did it go?
This was a bit more difficult I think, but the rewards are quite substantial if done sincerely.
Listening empathically to my wife seemed to help clarify both our feelings around a topic. The motivations and personal investment behind our statements became clarified, and mis-interpretations were reduced, while the weight of meaning behind statements was increased.
I would say that I would only feel comfortable doing this with someone I know relatively well, and that they felt safe with me and vice-versa.
How did you find the loving kindness meditation?
This was quite a revelation really. The extending of wishing well-ness to yourself, and then loved ones, to people we don't like and then to all sentient beings, is quite mind blowing if you think about it.
It's like extending your personal boundaries, or sense of self, to the whole world.
Complete the political awareness exercise here in writing.
My Perspective
At a previous workplace, I wanted some extra training informally in a particular skill from an experienced colleague. I approached them, and they were happy to show me some techniques. However, another colleague, who had requested similar training from our manager, got the pip because they had been stalled in receiving training. They complained to our manager, and my 'informal' training was stopped.
I felt hurt and sad that this other colleague couldn't talk with me directly, and had to go through other circuitous means, ultimately undoing a sense of initiative and a process of self improvement.
The other person's perspective
They've been waiting for ages for some specialist training, and have been getting rebuffed for the last year by our manager. Then this guy Uili comes in to the team for six months and gets the training they've been after, informally, just like that. That seems unfair, and it feels like he's jumped the queue.
Reflection
Doing this, I can see my former colleague's POV (point of view now). Being able to do so seems to take away much of the sense of personal malice I felt that person had against me.
My experience of personal pain, or emotional pain, towards the situation, and the colleague, feels reduced. Nice.
Any other musings?
This technique of pre-priming, and post-event evaluating, will be very handy with treating people I work and live with with respect and kindness. Any anxiety about how people may feel towards me feels insubstantial compared to the will to wish them well.


{% extends "com/cardform.html" %} {% block title %}
Instructions to change your password will be sent to the provided email address if it is registered with an account.
{% endblock %} {% block card_action %} {% endblock %} {% block before_card_form %}


At LOKAL, you will be served the finest cuisine from top local chefs. Sit back, relax, and enjoy the best dining experience your city has to offer. A fresh, new chef rotates in every two weeks, so you will never run out of new dishes to try at LOKAL.
While you enjoy your meal, take a look at some of the finest works of art by the most talented up-and-coming artists in your city. You'll even be able to meet the creators themselves as you explore your city's local arts scene.
We bring in the classiest, most talented local musicians to liven up your night. Enjoy as their smooth tunes complement your culinary experience and stimulate your appreciation of the artwork. Stay afterwards and meet the musicians who keep your local scene fresh.