prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>MchBaseResult.java<|end_file_name|><|fim▁begin|>package weixin.popular.bean.paymch;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "xml")
@XmlAccessorType(XmlAccessType.FIELD)
public class MchBaseResult {
protected String return_code;
protected String return_msg;
protected String appid;
protected String mch_id;
protected String nonce_str;
protected String sign;
protected String result_code;
protected String err_code;
protected String err_code_des;
public String getReturn_code() {
return return_code;
}
public void setReturn_code(String return_code) {
this.return_code = return_code;
}
public String getReturn_msg() {
return return_msg;
}
public void setReturn_msg(String return_msg) {
this.return_msg = return_msg;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getMch_id() {
return mch_id;
}
public void setMch_id(String mch_id) {
this.mch_id = mch_id;
}
public String getNonce_str() {
return nonce_str;
}
public void setNonce_str(String nonce_str) {
this.nonce_str = nonce_str;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;<|fim▁hole|>
public String getResult_code() {
return result_code;
}
public void setResult_code(String result_code) {
this.result_code = result_code;
}
public String getErr_code() {
return err_code;
}
public void setErr_code(String err_code) {
this.err_code = err_code;
}
public String getErr_code_des() {
return err_code_des;
}
public void setErr_code_des(String err_code_des) {
this.err_code_des = err_code_des;
}
}<|fim▁end|> | } |
<|file_name|>builder_test.go<|end_file_name|><|fim▁begin|>/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package resource
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"github.com/ghodss/yaml"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api/latest"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api/meta"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api/resource"
"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
"github.com/GoogleCloudPlatform/kubernetes/pkg/util/errors"
"github.com/GoogleCloudPlatform/kubernetes/pkg/watch"
watchjson "github.com/GoogleCloudPlatform/kubernetes/pkg/watch/json"
)
func stringBody(body string) io.ReadCloser {
return ioutil.NopCloser(bytes.NewReader([]byte(body)))
}
func watchBody(events ...watch.Event) string {
buf := &bytes.Buffer{}
enc := watchjson.NewEncoder(buf, latest.Codec)
for _, e := range events {
enc.Encode(&e)
}
return buf.String()
}
func fakeClient() ClientMapper {
return ClientMapperFunc(func(*meta.RESTMapping) (RESTClient, error) {
return &client.FakeRESTClient{}, nil
})
}
func fakeClientWith(t *testing.T, data map[string]string) ClientMapper {
return ClientMapperFunc(func(*meta.RESTMapping) (RESTClient, error) {
return &client.FakeRESTClient{
Codec: latest.Codec,
Client: client.HTTPClientFunc(func(req *http.Request) (*http.Response, error) {
p := req.URL.Path
q := req.URL.RawQuery
if len(q) != 0 {
p = p + "?" + q
}
body, ok := data[p]
if !ok {
t.Fatalf("unexpected request: %s (%s)\n%#v", p, req.URL, req)
}
return &http.Response{
StatusCode: http.StatusOK,
Body: stringBody(body),
}, nil
}),
}, nil
})
}
func testData() (*api.PodList, *api.ServiceList) {
pods := &api.PodList{
ListMeta: api.ListMeta{
ResourceVersion: "15",
},
Items: []api.Pod{
{
ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test", ResourceVersion: "10"},
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicy{Always: &api.RestartPolicyAlways{}},
DNSPolicy: api.DNSClusterFirst,
},
},
{
ObjectMeta: api.ObjectMeta{Name: "bar", Namespace: "test", ResourceVersion: "11"},
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicy{Always: &api.RestartPolicyAlways{}},
DNSPolicy: api.DNSClusterFirst,
},
},
},
}
svc := &api.ServiceList{
ListMeta: api.ListMeta{
ResourceVersion: "16",
},
Items: []api.Service{
{
ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "12"},
},
},
}
return pods, svc
}
func streamTestData() (io.Reader, *api.PodList, *api.ServiceList) {
pods, svc := testData()
r, w := io.Pipe()
go func() {
defer w.Close()
w.Write([]byte(runtime.EncodeOrDie(latest.Codec, pods)))
w.Write([]byte(runtime.EncodeOrDie(latest.Codec, svc)))
}()
return r, pods, svc
}
func JSONToYAMLOrDie(in []byte) []byte {
data, err := yaml.JSONToYAML(in)
if err != nil {
panic(err)
}
return data
}
func streamYAMLTestData() (io.Reader, *api.PodList, *api.ServiceList) {
pods, svc := testData()
r, w := io.Pipe()
go func() {
defer w.Close()
w.Write(JSONToYAMLOrDie([]byte(runtime.EncodeOrDie(latest.Codec, pods))))
w.Write([]byte("\n---\n"))
w.Write(JSONToYAMLOrDie([]byte(runtime.EncodeOrDie(latest.Codec, svc))))
}()
return r, pods, svc
}
type testVisitor struct {
InjectErr error
Infos []*Info
}
func (v *testVisitor) Handle(info *Info) error {
v.Infos = append(v.Infos, info)
return v.InjectErr
}
func (v *testVisitor) Objects() []runtime.Object {
objects := []runtime.Object{}
for i := range v.Infos {
objects = append(objects, v.Infos[i].Object)
}
return objects
}
func TestPathBuilder(t *testing.T) {
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClient()).
FilenameParam("../../../examples/guestbook/redis-master-controller.json")
test := &testVisitor{}
singular := false
err := b.Do().IntoSingular(&singular).Visit(test.Handle)
if err != nil || !singular || len(test.Infos) != 1 {
t.Fatalf("unexpected response: %v %f %#v", err, singular, test.Infos)
}
info := test.Infos[0]
if info.Name != "redis-master-controller" || info.Namespace != "" || info.Object == nil {
t.Errorf("unexpected info: %#v", info)
}
}
func TestNodeBuilder(t *testing.T) {
node := &api.Node{
ObjectMeta: api.ObjectMeta{Name: "node1", Namespace: "should-not-have", ResourceVersion: "10"},
Spec: api.NodeSpec{
Capacity: api.ResourceList{
api.ResourceCPU: resource.MustParse("1000m"),
api.ResourceMemory: resource.MustParse("1Mi"),
},
},
}
r, w := io.Pipe()
go func() {
defer w.Close()
w.Write([]byte(runtime.EncodeOrDie(latest.Codec, node)))
}()
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClient()).
NamespaceParam("test").Stream(r, "STDIN")
test := &testVisitor{}
err := b.Do().Visit(test.Handle)
if err != nil || len(test.Infos) != 1 {
t.Fatalf("unexpected response: %v %#v", err, test.Infos)
}
info := test.Infos[0]
if info.Name != "node1" || info.Namespace != "" || info.Object == nil {
t.Errorf("unexpected info: %#v", info)
}
}
func TestPathBuilderWithMultiple(t *testing.T) {
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClient()).
FilenameParam("../../../examples/guestbook/redis-master-controller.json").
FilenameParam("../../../examples/guestbook/redis-master-controller.json").
NamespaceParam("test").DefaultNamespace()
test := &testVisitor{}
singular := false
err := b.Do().IntoSingular(&singular).Visit(test.Handle)
if err != nil || singular || len(test.Infos) != 2 {
t.Fatalf("unexpected response: %v %f %#v", err, singular, test.Infos)
}
info := test.Infos[1]
if info.Name != "redis-master-controller" || info.Namespace != "test" || info.Object == nil {
t.Errorf("unexpected info: %#v", info)
}
}
func TestDirectoryBuilder(t *testing.T) {
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClient()).
FilenameParam("../../../examples/guestbook").
NamespaceParam("test").DefaultNamespace()
test := &testVisitor{}
singular := false
err := b.Do().IntoSingular(&singular).Visit(test.Handle)
if err != nil || singular || len(test.Infos) < 4 {
t.Fatalf("unexpected response: %v %f %#v", err, singular, test.Infos)
}
found := false
for _, info := range test.Infos {
if info.Name == "redis-master-controller" && info.Namespace == "test" && info.Object != nil {
found = true
}
}
if !found {
t.Errorf("unexpected responses: %#v", test.Infos)
}
}
func TestURLBuilder(t *testing.T) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(runtime.EncodeOrDie(latest.Codec, &api.Pod{ObjectMeta: api.ObjectMeta{Namespace: "foo", Name: "test"}})))
}))
defer s.Close()
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClient()).
FilenameParam(s.URL).
NamespaceParam("test")
test := &testVisitor{}
singular := false
err := b.Do().IntoSingular(&singular).Visit(test.Handle)
if err != nil || !singular || len(test.Infos) != 1 {
t.Fatalf("unexpected response: %v %f %#v", err, singular, test.Infos)
}
info := test.Infos[0]
if info.Name != "test" || info.Namespace != "foo" || info.Object == nil {
t.Errorf("unexpected info: %#v", info)
}
}
func TestURLBuilderRequireNamespace(t *testing.T) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(runtime.EncodeOrDie(latest.Codec, &api.Pod{ObjectMeta: api.ObjectMeta{Namespace: "foo", Name: "test"}})))
}))
defer s.Close()
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClient()).
FilenameParam(s.URL).
NamespaceParam("test").RequireNamespace()
test := &testVisitor{}
singular := false
err := b.Do().IntoSingular(&singular).Visit(test.Handle)
if err == nil || !singular || len(test.Infos) != 0 {
t.Fatalf("unexpected response: %v %f %#v", err, singular, test.Infos)
}
}
func TestResourceByName(t *testing.T) {
pods, _ := testData()
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClientWith(t, map[string]string{
"/namespaces/test/pods/foo": runtime.EncodeOrDie(latest.Codec, &pods.Items[0]),
})).
NamespaceParam("test")
test := &testVisitor{}
singular := false
if b.Do().Err() == nil {
t.Errorf("unexpected non-error")
}
b.ResourceTypeOrNameArgs(true, "pods", "foo")
err := b.Do().IntoSingular(&singular).Visit(test.Handle)
if err != nil || !singular || len(test.Infos) != 1 {
t.Fatalf("unexpected response: %v %f %#v", err, singular, test.Infos)
}
if !reflect.DeepEqual(&pods.Items[0], test.Objects()[0]) {
t.Errorf("unexpected object: %#v", test.Objects())
}
mapping, err := b.Do().ResourceMapping()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if mapping.Resource != "pods" {
t.Errorf("unexpected resource mapping: %#v", mapping)
}
}
func TestResourceByNameAndEmptySelector(t *testing.T) {
pods, _ := testData()
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClientWith(t, map[string]string{
"/namespaces/test/pods/foo": runtime.EncodeOrDie(latest.Codec, &pods.Items[0]),
})).
NamespaceParam("test").
SelectorParam("").
ResourceTypeOrNameArgs(true, "pods", "foo")
singular := false
infos, err := b.Do().IntoSingular(&singular).Infos()
if err != nil || !singular || len(infos) != 1 {
t.Fatalf("unexpected response: %v %f %#v", err, singular, infos)
}
if !reflect.DeepEqual(&pods.Items[0], infos[0].Object) {
t.Errorf("unexpected object: %#v", infos[0])
}
mapping, err := b.Do().ResourceMapping()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if mapping.Resource != "pods" {
t.Errorf("unexpected resource mapping: %#v", mapping)
}
}
func TestSelector(t *testing.T) {
pods, svc := testData()
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClientWith(t, map[string]string{
"/namespaces/test/pods?labels=a%3Db": runtime.EncodeOrDie(latest.Codec, pods),
"/namespaces/test/services?labels=a%3Db": runtime.EncodeOrDie(latest.Codec, svc),
})).
SelectorParam("a=b").
NamespaceParam("test").
Flatten()
test := &testVisitor{}
singular := false
if b.Do().Err() == nil {
t.Errorf("unexpected non-error")
}
b.ResourceTypeOrNameArgs(true, "pods,service")
err := b.Do().IntoSingular(&singular).Visit(test.Handle)
if err != nil || singular || len(test.Infos) != 3 {
t.Fatalf("unexpected response: %v %f %#v", err, singular, test.Infos)
}
if !api.Semantic.DeepDerivative([]runtime.Object{&pods.Items[0], &pods.Items[1], &svc.Items[0]}, test.Objects()) {
t.Errorf("unexpected visited objects: %#v", test.Objects())
}
if _, err := b.Do().ResourceMapping(); err == nil {
t.Errorf("unexpected non-error")
}
}
func TestSelectorRequiresKnownTypes(t *testing.T) {
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClient()).
SelectorParam("a=b").
NamespaceParam("test").
ResourceTypes("unknown")
if b.Do().Err() == nil {
t.Errorf("unexpected non-error")
}
}
func TestSingleResourceType(t *testing.T) {
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClient()).
SelectorParam("a=b").
SingleResourceType().
ResourceTypeOrNameArgs(true, "pods,services")
if b.Do().Err() == nil {
t.Errorf("unexpected non-error")
}
}
func TestStream(t *testing.T) {
r, pods, rc := streamTestData()
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClient()).
NamespaceParam("test").Stream(r, "STDIN").Flatten()
test := &testVisitor{}
singular := false
err := b.Do().IntoSingular(&singular).Visit(test.Handle)
if err != nil || singular || len(test.Infos) != 3 {
t.Fatalf("unexpected response: %v %f %#v", err, singular, test.Infos)
}
if !api.Semantic.DeepDerivative([]runtime.Object{&pods.Items[0], &pods.Items[1], &rc.Items[0]}, test.Objects()) {
t.Errorf("unexpected visited objects: %#v", test.Objects())
}
}
func TestYAMLStream(t *testing.T) {
r, pods, rc := streamYAMLTestData()
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClient()).
NamespaceParam("test").Stream(r, "STDIN").Flatten()
test := &testVisitor{}
singular := false
err := b.Do().IntoSingular(&singular).Visit(test.Handle)
if err != nil || singular || len(test.Infos) != 3 {
t.Fatalf("unexpected response: %v %f %#v", err, singular, test.Infos)
}
if !api.Semantic.DeepDerivative([]runtime.Object{&pods.Items[0], &pods.Items[1], &rc.Items[0]}, test.Objects()) {
t.Errorf("unexpected visited objects: %#v", test.Objects())
}
}
func TestMultipleObject(t *testing.T) {
r, pods, svc := streamTestData()
obj, err := NewBuilder(latest.RESTMapper, api.Scheme, fakeClient()).
NamespaceParam("test").Stream(r, "STDIN").Flatten().
Do().Object()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
expected := &api.List{
Items: []runtime.Object{
&pods.Items[0],
&pods.Items[1],
&svc.Items[0],
},
}
if !api.Semantic.DeepDerivative(expected, obj) {
t.Errorf("unexpected visited objects: %#v", obj)
}
}
func TestSingularObject(t *testing.T) {
obj, err := NewBuilder(latest.RESTMapper, api.Scheme, fakeClient()).
NamespaceParam("test").DefaultNamespace().
FilenameParam("../../../examples/guestbook/redis-master-controller.json").
Flatten().
Do().Object()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
rc, ok := obj.(*api.ReplicationController)
if !ok {
t.Fatalf("unexpected object: %#v", obj)
}
if rc.Name != "redis-master-controller" || rc.Namespace != "test" {
t.Errorf("unexpected controller: %#v", rc)
}
}
func TestListObject(t *testing.T) {
pods, _ := testData()
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClientWith(t, map[string]string{
"/namespaces/test/pods?labels=a%3Db": runtime.EncodeOrDie(latest.Codec, pods),
})).
SelectorParam("a=b").
NamespaceParam("test").
ResourceTypeOrNameArgs(true, "pods").
Flatten()
obj, err := b.Do().Object()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
list, ok := obj.(*api.List)
if !ok {
t.Fatalf("unexpected object: %#v", obj)
}
if list.ResourceVersion != pods.ResourceVersion || len(list.Items) != 2 {
t.Errorf("unexpected list: %#v", list)
}
mapping, err := b.Do().ResourceMapping()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if mapping.Resource != "pods" {
t.Errorf("unexpected resource mapping: %#v", mapping)
}
}
<|fim▁hole|>func TestListObjectWithDifferentVersions(t *testing.T) {
pods, svc := testData()
obj, err := NewBuilder(latest.RESTMapper, api.Scheme, fakeClientWith(t, map[string]string{
"/namespaces/test/pods?labels=a%3Db": runtime.EncodeOrDie(latest.Codec, pods),
"/namespaces/test/services?labels=a%3Db": runtime.EncodeOrDie(latest.Codec, svc),
})).
SelectorParam("a=b").
NamespaceParam("test").
ResourceTypeOrNameArgs(true, "pods,services").
Flatten().
Do().Object()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
list, ok := obj.(*api.List)
if !ok {
t.Fatalf("unexpected object: %#v", obj)
}
// resource version differs between type lists, so it's not possible to get a single version.
if list.ResourceVersion != "" || len(list.Items) != 3 {
t.Errorf("unexpected list: %#v", list)
}
}
func TestWatch(t *testing.T) {
_, svc := testData()
w, err := NewBuilder(latest.RESTMapper, api.Scheme, fakeClientWith(t, map[string]string{
"/watch/namespaces/test/services/redis-master?resourceVersion=12": watchBody(watch.Event{
Type: watch.Added,
Object: &svc.Items[0],
}),
})).
NamespaceParam("test").DefaultNamespace().
FilenameParam("../../../examples/guestbook/redis-master-service.json").Flatten().
Do().Watch("12")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer w.Stop()
ch := w.ResultChan()
select {
case obj := <-ch:
if obj.Type != watch.Added {
t.Fatalf("unexpected watch event", obj)
}
service, ok := obj.Object.(*api.Service)
if !ok {
t.Fatalf("unexpected object: %#v", obj)
}
if service.Name != "baz" || service.ResourceVersion != "12" {
t.Errorf("unexpected service: %#v", service)
}
}
}
func TestWatchMultipleError(t *testing.T) {
_, err := NewBuilder(latest.RESTMapper, api.Scheme, fakeClient()).
NamespaceParam("test").DefaultNamespace().
FilenameParam("../../../examples/guestbook/redis-master-controller.json").Flatten().
FilenameParam("../../../examples/guestbook/redis-master-controller.json").Flatten().
Do().Watch("")
if err == nil {
t.Fatalf("unexpected non-error")
}
}
func TestLatest(t *testing.T) {
r, _, _ := streamTestData()
newPod := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test", ResourceVersion: "13"},
}
newPod2 := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "bar", Namespace: "test", ResourceVersion: "14"},
}
newSvc := &api.Service{
ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "15"},
}
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClientWith(t, map[string]string{
"/namespaces/test/pods/foo": runtime.EncodeOrDie(latest.Codec, newPod),
"/namespaces/test/pods/bar": runtime.EncodeOrDie(latest.Codec, newPod2),
"/namespaces/test/services/baz": runtime.EncodeOrDie(latest.Codec, newSvc),
})).
NamespaceParam("other").Stream(r, "STDIN").Flatten().Latest()
test := &testVisitor{}
singular := false
err := b.Do().IntoSingular(&singular).Visit(test.Handle)
if err != nil || singular || len(test.Infos) != 3 {
t.Fatalf("unexpected response: %v %f %#v", err, singular, test.Infos)
}
if !api.Semantic.DeepDerivative([]runtime.Object{newPod, newPod2, newSvc}, test.Objects()) {
t.Errorf("unexpected visited objects: %#v", test.Objects())
}
}
func TestIgnoreStreamErrors(t *testing.T) {
pods, svc := testData()
r, w := io.Pipe()
go func() {
defer w.Close()
w.Write([]byte(`{}`))
w.Write([]byte(runtime.EncodeOrDie(latest.Codec, &pods.Items[0])))
}()
r2, w2 := io.Pipe()
go func() {
defer w2.Close()
w2.Write([]byte(`{}`))
w2.Write([]byte(runtime.EncodeOrDie(latest.Codec, &svc.Items[0])))
}()
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClient()).
ContinueOnError(). // TODO: order seems bad, but allows clients to determine what they want...
Stream(r, "1").Stream(r2, "2")
test := &testVisitor{}
singular := false
err := b.Do().IntoSingular(&singular).Visit(test.Handle)
if err != nil || singular || len(test.Infos) != 2 {
t.Fatalf("unexpected response: %v %f %#v", err, singular, test.Infos)
}
if !api.Semantic.DeepDerivative([]runtime.Object{&pods.Items[0], &svc.Items[0]}, test.Objects()) {
t.Errorf("unexpected visited objects: %#v", test.Objects())
}
}
func TestReceiveMultipleErrors(t *testing.T) {
pods, svc := testData()
r, w := io.Pipe()
go func() {
defer w.Close()
w.Write([]byte(`{}`))
w.Write([]byte(runtime.EncodeOrDie(latest.Codec, &pods.Items[0])))
}()
r2, w2 := io.Pipe()
go func() {
defer w2.Close()
w2.Write([]byte(`{}`))
w2.Write([]byte(runtime.EncodeOrDie(latest.Codec, &svc.Items[0])))
}()
b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClient()).
Stream(r, "1").Stream(r2, "2").
ContinueOnError()
test := &testVisitor{}
singular := false
err := b.Do().IntoSingular(&singular).Visit(test.Handle)
if err == nil || singular || len(test.Infos) != 0 {
t.Fatalf("unexpected response: %v %f %#v", err, singular, test.Infos)
}
errs, ok := err.(errors.Aggregate)
if !ok {
t.Fatalf("unexpected error: %v", reflect.TypeOf(err))
}
if len(errs.Errors()) != 2 {
t.Errorf("unexpected errors", errs)
}
}<|fim▁end|> | |
<|file_name|>pattern.rs<|end_file_name|><|fim▁begin|>peg::parser!( grammar test() for str {
pub rule alphanumeric() = ['a'..='z' | 'A'..='Z' | '0'..='9']*
pub rule inverted_pat() -> &'input str = "(" s:$([^')']*) ")" {s}
pub rule capture() -> char = ['a'..='z']
pub rule capture2() -> (char, char) = a:['a'..='z'] b:['0'..='9'] { (a, b) }
});<|fim▁hole|>fn main() {
assert!(test::alphanumeric("azAZ09").is_ok());
assert!(test::alphanumeric("@").is_err());
assert_eq!(test::inverted_pat("(asdf)"), Ok("asdf"));
assert_eq!(test::capture("x"), Ok('x'));
assert_eq!(test::capture2("a1"), Ok(('a', '1')));
}<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>__author__ = 'Brian Wickman'
from process_provider_ps import ProcessProvider_PS
from process_provider_procfs import ProcessProvider_Procfs
class ProcessProviderFactory(object):
"""
A factory for producing platform-appropriate ProcessProviders.
Typical use-cases:
Import
>>> from twitter.common.process import ProcessProviderFactory
>>> ps = ProcessProviderFactory.get()
Run a collection of all pids
>>> ps.collect_all()
Get a ProcessHandle to the init process
>>> init = ps.get_handle(1)
>>> init
<twitter.common.process.process_handle_ps.ProcessHandlePs object at 0x1004ad950>
Get stats
>>> init.cpu_time()
7980.0600000000004
>>> init.user()
'root'
>>> init.wall_time()
6485509.0
>>> init.pid()
1
>>> init.ppid()
0
Refresh stats
>>> init.refresh()
>>> init.cpu_time()
7982.9700000000003
Introspect the process tree
>>> list(ps.children_of(init.pid()))
[10, 11, 12, 13, 14, 15, 16, 17, 26, 32, 37, 38, 39, 40, 42, 43, 45,
51, 59, 73, 108, 140, 153, 157, 162, 166, 552, 1712, 1968, 38897,
58862, 63321, 64513, 66458, 68598, 78610, 85633, 91019, 97271]
Aggregations
>>> sum(map(lambda pid: ps.get_handle(pid).cpu_time(), ps.children_of(init.pid())))
228574.40999999995
Collect data from a subset of processes
>>> ps.collect_set(ps.children_of(init.pid()))
Re-evaluate
>>> sum(map(lambda pid: ps.get_handle(pid).cpu_time(), ps.children_of(init.pid())))<|fim▁hole|> PROVIDERS = [
ProcessProvider_Procfs,
ProcessProvider_PS
]
@staticmethod
def get():
"""
Return a platform-specific ProcessProvider.
"""
for provider in ProcessProviderFactory.PROVIDERS:
if provider._platform_compatible():
return provider()<|fim▁end|> | 228642.19999999998
""" |
<|file_name|>autocompleteRenderer.js<|end_file_name|><|fim▁begin|>import {addClass, hasClass, empty} from './../helpers/dom/element';
import {eventManager as eventManagerObject} from './../eventManager';
import {getRenderer, registerRenderer} from './../renderers';
import {WalkontableCellCoords} from './../3rdparty/walkontable/src/cell/coords';
var clonableWRAPPER = document.createElement('DIV');
clonableWRAPPER.className = 'htAutocompleteWrapper';
var clonableARROW = document.createElement('DIV');
clonableARROW.className = 'htAutocompleteArrow';
// workaround for https://github.com/handsontable/handsontable/issues/1946
// this is faster than innerHTML. See: https://github.com/handsontable/handsontable/wiki/JavaScript-&-DOM-performance-tips
clonableARROW.appendChild(document.createTextNode(String.fromCharCode(9660)));
var wrapTdContentWithWrapper = function(TD, WRAPPER) {
WRAPPER.innerHTML = TD.innerHTML;
empty(TD);
TD.appendChild(WRAPPER);
};
/**
* Autocomplete renderer<|fim▁hole|> *
* @private
* @renderer AutocompleteRenderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
function autocompleteRenderer(instance, TD, row, col, prop, value, cellProperties) {
var WRAPPER = clonableWRAPPER.cloneNode(true); //this is faster than createElement
var ARROW = clonableARROW.cloneNode(true); //this is faster than createElement
getRenderer('text')(instance, TD, row, col, prop, value, cellProperties);
TD.appendChild(ARROW);
addClass(TD, 'htAutocomplete');
if (!TD.firstChild) { //http://jsperf.com/empty-node-if-needed
//otherwise empty fields appear borderless in demo/renderers.html (IE)
TD.appendChild(document.createTextNode(String.fromCharCode(160))); // workaround for https://github.com/handsontable/handsontable/issues/1946
//this is faster than innerHTML. See: https://github.com/handsontable/handsontable/wiki/JavaScript-&-DOM-performance-tips
}
if (!instance.acArrowListener) {
var eventManager = eventManagerObject(instance);
//not very elegant but easy and fast
instance.acArrowListener = function(event) {
if (hasClass(event.target, 'htAutocompleteArrow')) {
instance.view.wt.getSetting('onCellDblClick', null, new WalkontableCellCoords(row, col), TD);
}
};
eventManager.addEventListener(instance.rootElement, 'mousedown', instance.acArrowListener);
//We need to unbind the listener after the table has been destroyed
instance.addHookOnce('afterDestroy', function() {
eventManager.destroy();
});
}
}
export {autocompleteRenderer};
registerRenderer('autocomplete', autocompleteRenderer);<|fim▁end|> | |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>//! Sodium is a next generation Vi-like editor.
#![feature(stmt_expr_attributes)]
#![deny(warnings)]
#![deny(missing_docs)]
#[cfg(feature = "orbital")]
extern crate orbclient;
/// Core functionality.
#[macro_use]
pub mod core;
/// Carret primitives.<|fim▁hole|>pub mod caret;
/// Editing.
pub mod edit;
/// Input/Output
pub mod io;
/// State of the editor.
pub mod state;
fn main() {
self::state::editor::Editor::init();
}<|fim▁end|> | |
<|file_name|>json.rs<|end_file_name|><|fim▁begin|>//! Experimental loader which takes a program specification in Json form.
use crate::architecture::*;
use crate::loader::*;
use crate::memory::backing::*;
use crate::memory::MemoryPermissions;
use serde_json::Value;
use std::fs::File;
use std::io::Read;
use std::path::Path;
/// Experimental loader which takes a program specification in Json form.
///
/// See the binary ninja script for an example use.
#[derive(Debug)]
pub struct Json {
function_entries: Vec<FunctionEntry>,
memory: Memory,
architecture: Box<dyn Architecture>,
entry: u64,
}
impl Json {
/// Create a new `Json` loader from the given file.
pub fn from_file(filename: &Path) -> Result<Json> {
let mut file = File::open(filename)?;
let mut buf = Vec::new();
file.read_to_end(&mut buf)?;
let root: Value = serde_json::from_str(&String::from_utf8(buf)?)?;
let architecture = match root["arch"] {
Value::String(ref architecture) => {
if architecture == "x86" {
Box::new(X86::new())
} else {
bail!("unsupported architecture {}", root["arch"])
}
}
_ => bail!("architecture missing"),
};
let entry = match root["entry"] {
Value::Number(ref number) => number.as_u64().unwrap(),
_ => bail!("entry missing"),
};
let mut function_entries = Vec::new();<|fim▁hole|> Value::Number(ref address) => match address.as_u64() {
Some(address) => address,
None => bail!("function address not u64"),
},
_ => bail!("address missing for function"),
};
let name = match function["name"] {
Value::String(ref name) => name.to_string(),
_ => bail!("name missing for function"),
};
function_entries.push(FunctionEntry::new(address, Some(name)));
}
} else {
bail!("functions missing");
}
let mut memory = Memory::new(architecture.endian());
if let Value::Array(ref segments) = root["segments"] {
for segment in segments {
let address = match segment["address"] {
Value::Number(ref address) => match address.as_u64() {
Some(address) => address,
None => bail!("segment address not u64"),
},
_ => bail!("address missing for segment"),
};
let bytes = match segment["bytes"] {
Value::String(ref bytes) => base64::decode(&bytes)?,
_ => bail!("bytes missing for segment"),
};
memory.set_memory(address, bytes, MemoryPermissions::ALL);
}
} else {
bail!("segments missing");
}
Ok(Json {
function_entries,
memory,
architecture,
entry,
})
}
}
impl Loader for Json {
fn memory(&self) -> Result<Memory> {
Ok(self.memory.clone())
}
fn function_entries(&self) -> Result<Vec<FunctionEntry>> {
Ok(self.function_entries.clone())
}
fn program_entry(&self) -> u64 {
self.entry
}
fn architecture(&self) -> &dyn Architecture {
self.architecture.as_ref()
}
fn as_any(&self) -> &dyn Any {
self
}
fn symbols(&self) -> Vec<Symbol> {
Vec::new()
}
}<|fim▁end|> | if let Value::Array(ref functions) = root["functions"] {
for function in functions {
let address = match function["address"] { |
<|file_name|>test_aws_redshift_cluster_sensor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
import unittest
import boto3
from airflow import configuration
from airflow.contrib.sensors.aws_redshift_cluster_sensor import AwsRedshiftClusterSensor
try:
from moto import mock_redshift
except ImportError:
mock_redshift = None
class TestAwsRedshiftClusterSensor(unittest.TestCase):
def setUp(self):
configuration.load_test_config()
def _create_cluster(self):
client = boto3.client('redshift', region_name='us-east-1')
client.create_cluster(
ClusterIdentifier='test_cluster',
NodeType='dc1.large',
MasterUsername='admin',
MasterUserPassword='mock_password'
)
if len(client.describe_clusters()['Clusters']) == 0:
raise ValueError('AWS not properly mocked')
@unittest.skipIf(mock_redshift is None, 'mock_redshift package not present')
@mock_redshift
def test_poke(self):
self._create_cluster()
op = AwsRedshiftClusterSensor(task_id='test_cluster_sensor',
poke_interval=1,
timeout=5,
aws_conn_id='aws_default',
cluster_identifier='test_cluster',
target_status='available')
self.assertTrue(op.poke(None))
@unittest.skipIf(mock_redshift is None, 'mock_redshift package not present')
@mock_redshift
def test_poke_false(self):
self._create_cluster()
op = AwsRedshiftClusterSensor(task_id='test_cluster_sensor',<|fim▁hole|> poke_interval=1,
timeout=5,
aws_conn_id='aws_default',
cluster_identifier='test_cluster_not_found',
target_status='available')
self.assertFalse(op.poke(None))
@unittest.skipIf(mock_redshift is None, 'mock_redshift package not present')
@mock_redshift
def test_poke_cluster_not_found(self):
self._create_cluster()
op = AwsRedshiftClusterSensor(task_id='test_cluster_sensor',
poke_interval=1,
timeout=5,
aws_conn_id='aws_default',
cluster_identifier='test_cluster_not_found',
target_status='cluster_not_found')
self.assertTrue(op.poke(None))
if __name__ == '__main__':
unittest.main()<|fim▁end|> | |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# coding: utf-8
import os
import sys
from distutils.core import setup
from distutils.command.install import install
VERSION_NUMBER = "1.6.3"
class CustomInstall(install):
def run(self):
install.run(self)
for script in self.distribution.scripts:
script_path = os.path.join(self.install_scripts,
os.path.basename(script))
with open(script_path, "rb") as fh:
content = fh.read()
content = content.replace("@ INSTALLED_BASE_DIR @",
self._custom_data_dir)
with open(script_path, "wb") as fh:
fh.write(content)
def finalize_options(self):
install.finalize_options(self)
data_dir = os.path.join(self.prefix, "share", self.distribution.get_name())
if self.root is None:
build_dir = data_dir
else:
build_dir = os.path.join(self.root, data_dir[1:])
self.install_lib = build_dir
self._custom_data_dir = data_dir
def setup_linux():
hosts_dir = "guicavane/Hosts"
hosts = os.listdir(hosts_dir)
hosts = ["guicavane.Hosts." + x for x in hosts if os.path.isdir(
os.path.join(hosts_dir, x))]<|fim▁hole|> translations = []
for trans in os.listdir(translations_dir):
trans_path = os.path.join(translations_dir, trans)
if os.path.isdir(trans_path):
translations.append("Translations/" + trans + "/LC_MESSAGES/*")
setup(
name = "guicavane",
version = VERSION_NUMBER,
license = "GPL-3",
author = "Gonzalo García Berrotarán",
author_email = "[email protected]",
description = "Graphical user interface for www.cuevana.tv",
url = "http://www.github.com/j0hn/guicavane/",
packages = ["guicavane", "guicavane.Downloaders", "guicavane.Utils",
"guicavane.Accounts", "guicavane.Hosts"] + hosts,
package_data = {"guicavane": ["Glade/*.glade", "Images/*.png",
"Images/Downloaders/*.png"] + translations},
scripts = ["bin/guicavane"],
cmdclass = {"install": CustomInstall}
)
def setup_windows():
import py2exe
outdata_win = {
"script": "bin\\guicavane",
"dest_base": "guicavane",
"icon_resources": [(1, "guicavane\\Images\\logo.ico")]
}
outdata_con = outdata_win.copy()
outdata_con['dest_base'] = "guicavane_debug"
opts = {
'py2exe': {
'packages': 'encodings, gtk, guicavane, guicavane.Downloaders',
'includes': 'cairo, pangocairo, pango, atk, gobject, os, urllib,' \
'urllib2, cookielib, guicavane, gettext, gtk.glade, ' \
'gio, unicodedata, webbrowser, ' \
'guicavane.Downloaders, guicavane.Accounts, ' \
'guicavane.Utils',
'excludes': ["pywin", "pywin.debugger", "pywin.debugger.dbgcon",
"pywin.dialogs", "pywin.dialogs.list", "Tkconstants",
"Tkinter", "tcl", "doctest", "macpath", "pdb",
"ftplib", "win32wnet", "getopt",],
'dll_excludes': ["w9xpopen.exe"],
'dist_dir': './windows/build',
}
}
files = []
files.append(("Glade",
["guicavane\\Glade\\" + x for x in os.listdir("guicavane\\Glade")]))
files.append(("Images",
["guicavane\\Images\\" + x for x in os.listdir("guicavane\\Images") if \
not os.path.isdir("guicavane\\Images\\" + x)]))
files.append(("Images\\Downloaders\\",
["guicavane\\Images\\Downloaders\\" + x for x in os.listdir("guicavane\\Images\\Downloaders\\")]))
files.append(("Images\\Sites\\",
["guicavane\\Images\\Sites\\" + x for x in os.listdir("guicavane\\Images\\Sites\\")]))
for translation in os.listdir("guicavane\\Translations\\"):
if not os.path.isdir("guicavane\\Translations\\" + translation):
continue
files.append(("Translations\\" + translation + "\\LC_MESSAGES",
["guicavane\\Translations\\" + translation + "\\LC_MESSAGES\\" + \
x for x in os.listdir("guicavane\\Translations\\" + translation + "\\LC_MESSAGES")]))
hosts_dir = "guicavane\\Hosts"
hosts = os.listdir(hosts_dir)
hosts = [os.path.join(hosts_dir, x) for x in hosts if os.path.isdir(
os.path.join(hosts_dir, x))]
for host in hosts:
cleanhost = host.replace("guicavane\\", "")
files.append((cleanhost, [os.path.join(host, x) for x in os.listdir(host)]))
setup(
name = "Guicavane",
license = "GPL-3",
author = "Gonzalo García Berrotarán",
author_email = "[email protected]",
description = "Graphical user interface for www.cuevana.tv",
version = VERSION_NUMBER,
windows = [outdata_win],
console = [outdata_con],
options = opts,
data_files = files
)
if __name__ == "__main__":
path = os.path.dirname(sys.argv[0])
if path:
os.chdir(path)
if os.name == "nt":
setup_windows()
else:
setup_linux()<|fim▁end|> |
translations_dir = "guicavane/Translations" |
<|file_name|>listenerCollection.js<|end_file_name|><|fim▁begin|>/*!
* Copyright(c) 2014 Jan Blaha
*/
define(["async", "underscore"], function(async, _) {
var ListenerCollection = function () {
this._listeners = [];
};
ListenerCollection.prototype.add = function (context, listener) {
this._listeners.push({
fn: listener || context,
context: listener == null ? this : context
});
};
ListenerCollection.prototype.fire = function () {
var args = Array.prototype.slice.call(arguments, 0);
args.pop();
async.forEachSeries(this._listeners, function (l, next) {<|fim▁hole|> l.fn.apply(l.context, currentArgs);
}, arguments[arguments.length - 1]);
};
return ListenerCollection;
});<|fim▁end|> | var currentArgs = args.slice(0);
currentArgs.push(next); |
<|file_name|>marker.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Primitive traits and marker types representing basic 'kinds' of types.
//!
//! Rust types can be classified in various useful ways according to
//! intrinsic properties of the type. These classifications, often called
//! 'kinds', are represented as traits.
//!
//! They cannot be implemented by user code, but are instead implemented
//! by the compiler automatically for the types to which they apply.
//!
//! Marker types are special types that are used with unsafe code to
//! inform the compiler of special constraints. Marker types should
//! only be needed when you are creating an abstraction that is
//! implemented using unsafe code. In that case, you may want to embed
//! some of the marker types below into your type.
#![stable(feature = "rust1", since = "1.0.0")]
use clone::Clone;
use cmp;
use option::Option;
use hash::Hash;
use hash::Hasher;
/// Types able to be transferred across thread boundaries.
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "send"]
#[rustc_on_unimplemented = "`{Self}` cannot be sent between threads safely"]
pub unsafe trait Send {
// empty.
}
unsafe impl Send for .. { }
impl<T> !Send for *const T { }
impl<T> !Send for *mut T { }
/// Types with a constant size known at compile-time.
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "sized"]
#[rustc_on_unimplemented = "`{Self}` does not have a constant size known at compile-time"]
#[fundamental] // for Default, for example, which requires that `[T]: !Default` be evaluatable
pub trait Sized {
// Empty.
}
/// Types that can be "unsized" to a dynamically sized type.
#[unstable(feature = "unsize")]
#[lang="unsize"]
pub trait Unsize<T> {
// Empty.
}
/// Types that can be copied by simply copying bits (i.e. `memcpy`).
///
/// By default, variable bindings have 'move semantics.' In other
/// words:
///
/// ```
/// #[derive(Debug)]
/// struct Foo;
///
/// let x = Foo;
///
/// let y = x;
///
/// // `x` has moved into `y`, and so cannot be used
///
/// // println!("{:?}", x); // error: use of moved value
/// ```
///
/// However, if a type implements `Copy`, it instead has 'copy semantics':
///
/// ```
/// // we can just derive a `Copy` implementation
/// #[derive(Debug, Copy, Clone)]
/// struct Foo;
///
/// let x = Foo;
///
/// let y = x;
///
/// // `y` is a copy of `x`
///
/// println!("{:?}", x); // A-OK!
/// ```
///
/// It's important to note that in these two examples, the only difference is if you are allowed to
/// access `x` after the assignment: a move is also a bitwise copy under the hood.
///
/// ## When can my type be `Copy`?
///
/// A type can implement `Copy` if all of its components implement `Copy`. For example, this
/// `struct` can be `Copy`:
///
/// ```
/// struct Point {
/// x: i32,
/// y: i32,
/// }
/// ```
///
/// A `struct` can be `Copy`, and `i32` is `Copy`, so therefore, `Point` is eligible to be `Copy`.
///
/// ```
/// # struct Point;
/// struct PointList {
/// points: Vec<Point>,
/// }
/// ```
///
/// The `PointList` `struct` cannot implement `Copy`, because `Vec<T>` is not `Copy`. If we
/// attempt to derive a `Copy` implementation, we'll get an error:
///
/// ```text
/// the trait `Copy` may not be implemented for this type; field `points` does not implement `Copy`
/// ```
///
/// ## How can I implement `Copy`?
///
/// There are two ways to implement `Copy` on your type:
///
/// ```
/// #[derive(Copy, Clone)]
/// struct MyStruct;
/// ```
///
/// and
///
/// ```
/// struct MyStruct;
/// impl Copy for MyStruct {}
/// impl Clone for MyStruct { fn clone(&self) -> MyStruct { *self } }
/// ```
///
/// There is a small difference between the two: the `derive` strategy will also place a `Copy`
/// bound on type parameters, which isn't always desired.
///
/// ## When can my type _not_ be `Copy`?
///
/// Some types can't be copied safely. For example, copying `&mut T` would create an aliased
/// mutable reference, and copying `String` would result in two attempts to free the same buffer.
///<|fim▁hole|>///
/// ## When should my type be `Copy`?
///
/// Generally speaking, if your type _can_ implement `Copy`, it should. There's one important thing
/// to consider though: if you think your type may _not_ be able to implement `Copy` in the future,
/// then it might be prudent to not implement `Copy`. This is because removing `Copy` is a breaking
/// change: that second example would fail to compile if we made `Foo` non-`Copy`.
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "copy"]
pub trait Copy : Clone {
// Empty.
}
/// Types that can be safely shared between threads when aliased.
///
/// The precise definition is: a type `T` is `Sync` if `&T` is
/// thread-safe. In other words, there is no possibility of data races
/// when passing `&T` references between threads.
///
/// As one would expect, primitive types like `u8` and `f64` are all
/// `Sync`, and so are simple aggregate types containing them (like
/// tuples, structs and enums). More instances of basic `Sync` types
/// include "immutable" types like `&T` and those with simple
/// inherited mutability, such as `Box<T>`, `Vec<T>` and most other
/// collection types. (Generic parameters need to be `Sync` for their
/// container to be `Sync`.)
///
/// A somewhat surprising consequence of the definition is `&mut T` is
/// `Sync` (if `T` is `Sync`) even though it seems that it might
/// provide unsynchronised mutation. The trick is a mutable reference
/// stored in an aliasable reference (that is, `& &mut T`) becomes
/// read-only, as if it were a `& &T`, hence there is no risk of a data
/// race.
///
/// Types that are not `Sync` are those that have "interior
/// mutability" in a non-thread-safe way, such as `Cell` and `RefCell`
/// in `std::cell`. These types allow for mutation of their contents
/// even when in an immutable, aliasable slot, e.g. the contents of
/// `&Cell<T>` can be `.set`, and do not ensure data races are
/// impossible, hence they cannot be `Sync`. A higher level example
/// of a non-`Sync` type is the reference counted pointer
/// `std::rc::Rc`, because any reference `&Rc<T>` can clone a new
/// reference, which modifies the reference counts in a non-atomic
/// way.
///
/// For cases when one does need thread-safe interior mutability,
/// types like the atomics in `std::sync` and `Mutex` & `RWLock` in
/// the `sync` crate do ensure that any mutation cannot cause data
/// races. Hence these types are `Sync`.
///
/// Any types with interior mutability must also use the `std::cell::UnsafeCell`
/// wrapper around the value(s) which can be mutated when behind a `&`
/// reference; not doing this is undefined behaviour (for example,
/// `transmute`-ing from `&T` to `&mut T` is illegal).
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "sync"]
#[rustc_on_unimplemented = "`{Self}` cannot be shared between threads safely"]
pub unsafe trait Sync {
// Empty
}
unsafe impl Sync for .. { }
impl<T> !Sync for *const T { }
impl<T> !Sync for *mut T { }
/// A type which is considered "not POD", meaning that it is not
/// implicitly copyable. This is typically embedded in other types to
/// ensure that they are never copied, even if they lack a destructor.
#[unstable(feature = "core",
reason = "likely to change with new variance strategy")]
#[deprecated(since = "1.2.0",
reason = "structs are by default not copyable")]
#[lang = "no_copy_bound"]
#[allow(deprecated)]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct NoCopy;
macro_rules! impls{
($t: ident) => (
impl<T:?Sized> Hash for $t<T> {
#[inline]
fn hash<H: Hasher>(&self, _: &mut H) {
}
}
impl<T:?Sized> cmp::PartialEq for $t<T> {
fn eq(&self, _other: &$t<T>) -> bool {
true
}
}
impl<T:?Sized> cmp::Eq for $t<T> {
}
impl<T:?Sized> cmp::PartialOrd for $t<T> {
fn partial_cmp(&self, _other: &$t<T>) -> Option<cmp::Ordering> {
Option::Some(cmp::Ordering::Equal)
}
}
impl<T:?Sized> cmp::Ord for $t<T> {
fn cmp(&self, _other: &$t<T>) -> cmp::Ordering {
cmp::Ordering::Equal
}
}
impl<T:?Sized> Copy for $t<T> { }
impl<T:?Sized> Clone for $t<T> {
fn clone(&self) -> $t<T> {
$t
}
}
)
}
/// `PhantomData<T>` allows you to describe that a type acts as if it stores a value of type `T`,
/// even though it does not. This allows you to inform the compiler about certain safety properties
/// of your code.
///
/// Though they both have scary names, `PhantomData<T>` and "phantom types" are unrelated. 👻👻👻
///
/// # Examples
///
/// ## Unused lifetime parameter
///
/// Perhaps the most common time that `PhantomData` is required is
/// with a struct that has an unused lifetime parameter, typically as
/// part of some unsafe code. For example, here is a struct `Slice`
/// that has two pointers of type `*const T`, presumably pointing into
/// an array somewhere:
///
/// ```ignore
/// struct Slice<'a, T> {
/// start: *const T,
/// end: *const T,
/// }
/// ```
///
/// The intention is that the underlying data is only valid for the
/// lifetime `'a`, so `Slice` should not outlive `'a`. However, this
/// intent is not expressed in the code, since there are no uses of
/// the lifetime `'a` and hence it is not clear what data it applies
/// to. We can correct this by telling the compiler to act *as if* the
/// `Slice` struct contained a borrowed reference `&'a T`:
///
/// ```
/// use std::marker::PhantomData;
///
/// struct Slice<'a, T:'a> {
/// start: *const T,
/// end: *const T,
/// phantom: PhantomData<&'a T>
/// }
/// ```
///
/// This also in turn requires that we annotate `T:'a`, indicating
/// that `T` is a type that can be borrowed for the lifetime `'a`.
///
/// ## Unused type parameters
///
/// It sometimes happens that there are unused type parameters that
/// indicate what type of data a struct is "tied" to, even though that
/// data is not actually found in the struct itself. Here is an
/// example where this arises when handling external resources over a
/// foreign function interface. `PhantomData<T>` can prevent
/// mismatches by enforcing types in the method implementations:
///
/// ```
/// # trait ResType { fn foo(&self); }
/// # struct ParamType;
/// # mod foreign_lib {
/// # pub fn new(_: usize) -> *mut () { 42 as *mut () }
/// # pub fn do_stuff(_: *mut (), _: usize) {}
/// # }
/// # fn convert_params(_: ParamType) -> usize { 42 }
/// use std::marker::PhantomData;
/// use std::mem;
///
/// struct ExternalResource<R> {
/// resource_handle: *mut (),
/// resource_type: PhantomData<R>,
/// }
///
/// impl<R: ResType> ExternalResource<R> {
/// fn new() -> ExternalResource<R> {
/// let size_of_res = mem::size_of::<R>();
/// ExternalResource {
/// resource_handle: foreign_lib::new(size_of_res),
/// resource_type: PhantomData,
/// }
/// }
///
/// fn do_stuff(&self, param: ParamType) {
/// let foreign_params = convert_params(param);
/// foreign_lib::do_stuff(self.resource_handle, foreign_params);
/// }
/// }
/// ```
///
/// ## Indicating ownership
///
/// Adding a field of type `PhantomData<T>` also indicates that your
/// struct owns data of type `T`. This in turn implies that when your
/// struct is dropped, it may in turn drop one or more instances of
/// the type `T`, though that may not be apparent from the other
/// structure of the type itself. This is commonly necessary if the
/// structure is using a raw pointer like `*mut T` whose referent
/// may be dropped when the type is dropped, as a `*mut T` is
/// otherwise not treated as owned.
///
/// If your struct does not in fact *own* the data of type `T`, it is
/// better to use a reference type, like `PhantomData<&'a T>`
/// (ideally) or `PhantomData<*const T>` (if no lifetime applies), so
/// as not to indicate ownership.
#[lang = "phantom_data"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct PhantomData<T:?Sized>;
impls! { PhantomData }
mod impls {
use super::{Send, Sync, Sized};
unsafe impl<'a, T: Sync + ?Sized> Send for &'a T {}
unsafe impl<'a, T: Send + ?Sized> Send for &'a mut T {}
}
/// A marker trait indicates a type that can be reflected over. This
/// trait is implemented for all types. Its purpose is to ensure that
/// when you write a generic function that will employ reflection,
/// that must be reflected (no pun intended) in the generic bounds of
/// that function. Here is an example:
///
/// ```
/// #![feature(reflect_marker)]
/// use std::marker::Reflect;
/// use std::any::Any;
/// fn foo<T:Reflect+'static>(x: &T) {
/// let any: &Any = x;
/// if any.is::<u32>() { println!("u32"); }
/// }
/// ```
///
/// Without the declaration `T:Reflect`, `foo` would not type check
/// (note: as a matter of style, it would be preferable to to write
/// `T:Any`, because `T:Any` implies `T:Reflect` and `T:'static`, but
/// we use `Reflect` here to show how it works). The `Reflect` bound
/// thus serves to alert `foo`'s caller to the fact that `foo` may
/// behave differently depending on whether `T=u32` or not. In
/// particular, thanks to the `Reflect` bound, callers know that a
/// function declared like `fn bar<T>(...)` will always act in
/// precisely the same way no matter what type `T` is supplied,
/// because there are no bounds declared on `T`. (The ability for a
/// caller to reason about what a function may do based solely on what
/// generic bounds are declared is often called the ["parametricity
/// property"][1].)
///
/// [1]: http://en.wikipedia.org/wiki/Parametricity
#[rustc_reflect_like]
#[unstable(feature = "reflect_marker",
reason = "requires RFC and more experience")]
#[allow(deprecated)]
#[rustc_on_unimplemented = "`{Self}` does not implement `Any`; \
ensure all type parameters are bounded by `Any`"]
pub trait Reflect {}
impl Reflect for .. { }<|fim▁end|> | /// Generalizing the latter case, any type implementing `Drop` can't be `Copy`, because it's
/// managing some resource besides its own `size_of::<T>()` bytes. |
<|file_name|>behaviors.js<|end_file_name|><|fim▁begin|>var sys = require('sys'),
child_process = require('child_process'),
vm = require('vm'),
http = require('http'),
querystring = require('querystring'),
Persistence = require('./persistence/persistence'),
request = require('request'),
xml2jsParser = require('xml2js').parseString;
function msToString(ms) {
var str = "";
if (ms > 3600000) {
var hours = Math.floor(ms/3600000);
str += hours + " hours, ";
ms = ms - (hours*3600000);
}
if (ms > 60000) {
var minutes = Math.floor(ms/60000);
str += minutes + " minutes, ";
ms = ms - (minutes*60000);
}
str += Math.floor(ms/1000) + " seconds";
return str;
}
function addBehaviors(bot, properties) {
var persistence = new Persistence(properties);
var userEval = 1;
// Rate to mix in yahoo answers with stored responses
// 0.75 = 75% Yahoo answers, 25% stored responses
var mix = 0.5;
bot.addMessageListener("logger", function(nick, message) {
// Check to see if this is from a nick we shouldn't log
if (properties.logger.ignoreNicks.filter(function (x) { return nick.indexOf(x) > -1; }).length > 0) {
return true;
}
if (! (/^!/).test(message)) {
persistence.saveMessage(nick, message);
}
return true;
});
var yahooAnswer = function(message) {
var url = 'http://answers.yahoo.com/AnswersService/V1/questionSearch?appid=' + properties.yahooId +
"&query=" + querystring.escape(message) + "&type=resolved&output=json";
sys.log("Calling " + url);
request(url, function(error, response, body) {
try {
var yahooResponse = JSON.parse(body);
if (yahooResponse.all.count > 0) {
var bestAnswer = yahooResponse.all.questions[0].ChosenAnswer;
bestAnswer = bestAnswer.substring(0, 400);
bot.say(bestAnswer);
} else {
persistence.getRandom(bot);
}
} catch (err) {
sys.log(err);
persistence.getRandom(bot);
}
});
};
bot.addMessageListener("listen for name", function (nick, message) {
var re = new RegExp(properties.bot.nick);
if (re.test(message)) {
if (Math.random() < mix && properties.yahooId) {
sys.log("mix = " + mix + ", serving from yahoo answers");
yahooAnswer(message.replace(re, ''));
} else {
sys.log("mix = " + mix + ", serving from mysql");
persistence.getRandom(bot);
}
return false;
} else {
return true;
}
});
bot.addCommandListener("!do [nick]", /!do ([0-9A-Za-z_\-]*)/, "random quote", function(doNick) {
persistence.getQuote(doNick, bot);
});
bot.addCommandListener("!msg [#]", /!msg ([0-9]*)/, "message recall", function(id) {
persistence.getMessage(id, bot);
});
bot.addCommandListener("!about [regex pattern]", /!about (.*)/, "random message with phrase", function(pattern) {
persistence.matchMessage(pattern, bot);
});
bot.addCommandListener("!uds", /!uds/, "random message about uds", function() {
persistence.matchMessage('uds', bot);
});
bot.addCommandListener("!aevans", /!aevans/, "so, message from aevans", function() {
persistence.matchMessageForNick('aevans', '^so(\\s|,)', bot);
});
bot.addCommandListener("!leaders [start index]", /!leaders\s*(\d*)/, "top users by message count", function(index) {
persistence.leaders(index, bot);
});
bot.addCommandListener("!playback start end", /!playback (\d+ \d+)/, "playback a series of messages", function(range) {
var match = range.match(/(\d+) (\d+)/);
if (match) {
var start = match[1];
var end = match[2];
if (end - start >= 10) {
bot.say("playback limited to 10 messages");
} else if (start >= end) {
bot.say("start must be less than end");
} else {
for (var i = start; i <= end; i++) {
persistence.getMessage(i, bot);
}
}
}
});
bot.addCommandListener("!stats nick", /!stats (.*)/, "stats about a user", function(nick) {
persistence.userStats(nick, bot);
});
bot.addCommandListener("!alarm <time> -m <message>", /!alarm (.* -m .*)/, "set an alarm, valid time examples: 5s, 5m, 5h, 10:00, 14:30, 2:30pm", function(timeString, nick) {
var matchInterval = timeString.match(/(\d+)([h|m|s]) -m (.*)/);
var matchTime = timeString.match(/(\d{1,2}):(\d{2})(am|pm){0,1} -m (.*)/);
if (matchInterval) {
var timeNumber = matchInterval[1];
var timeUnit = matchInterval[2];
var sleepTime = timeNumber;
if (timeUnit === 'h') {
sleepTime = sleepTime * 60 * 60 * 1000;
} else if (timeUnit === 'm') {
sleepTime = sleepTime * 60 * 1000;
} else if (timeUnit === 's') {
sleepTime = sleepTime * 1000;
}
if (sleepTime < 2147483647) {
bot.say("Alarm will go off in " + msToString(sleepTime));
setTimeout(function() {
bot.say(nick + ': ' + matchInterval[3]);
}, sleepTime);
} else {
bot.say("Delay exceeds maximum timeout, see: http://stackoverflow.com/questions/3468607/why-does-settimeout-break-for-large-millisecond-delay-values");
}
} else if (matchTime) {
var hour = parseInt(matchTime[1]);
var minute = matchTime[2];
if (matchTime[3] === 'pm' && hour != 12) {
hour = hour + 12;
} else if (matchTime[3] === 'am' && hour === 12) {
hour = 0;
}
var now = new Date();
var sleepTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour, minute, 0, 0) - now;
if (sleepTime < 0) {
sleepTime += 86400000;
}
bot.say("Alarm will go off in " + msToString(sleepTime));
setTimeout(function() {
bot.say(nick + ': ' + matchTime[4]);
}, sleepTime);
} else {
bot.say("Unknown time format!");
}
});
bot.addCommandListener("!uname", /!uname/, "information about host", function() {
child_process.exec('uname -a', function(error, stdout, stderr) {
bot.say(stdout);
});
});
bot.addCommandListener("!version", /!version/, "report node version", function() {
bot.say("Node version = " + process.version);
});
bot.addCommandListener("!help <cmd>", /!help(.*)/, "command help", function(cmd) {
if (cmd) {
bot.helpCommand(cmd);
} else {
bot.listCommands();
}
});
bot.addCommandListener("!quote [symbol]", /!quote (.*)/, "get a stock quote", function(symbol) {
var url = 'https://api.iextrading.com/1.0/stock/' + symbol + '/batch?types=quote';
request(url, function(error, response, body) {
if (error) { console.log(error); }
var result = JSON.parse(body);
if (! error && result.quote && result.quote.latestPrice) {
var mktCap = result.quote.marketCap;
var mktCapString = "";
if (mktCap > 1000000000) {
mktCapString = "$" + ((mktCap/1000000000).toFixed(2)) + "B";
} else if (mktCap > 1000000) {
mktCapString = "$" + ((mktCap/1000000).toFixed(2)) + "M";
}
var changePrefix = (result.quote.change > 0) ? '+' : '';
bot.say(result.quote.companyName + ' ... ' +<|fim▁hole|> changePrefix + String(result.quote.change) + ' ' +
changePrefix + String((result.quote.changePercent * 100).toFixed(2)) + '% ' +
mktCapString);
} else {
bot.say("Unable to get a quote for " + symbol);
}
});
});
bot.addMessageListener("toggle", function(nick, message) {
var check = message.match(/!toggle (.*)/);
if (check) {
var name = check[1];
var result = bot.toggleMessageListener(name);
if (result) {
bot.say("Message listener " + name + " is active");
} else {
bot.say("Message listener " + name + " is inactive");
}
return false;
}
return true;
});
bot.addMessageListener("eval", function(nick, message) {
var check = message.match(/!add (.*)/);
if (check) {
var msg = check[1];
var mlName = "user eval " + userEval++;
bot.addMessageListener(mlName, function(nick, message) {
var sandbox = { output: null, nick: nick, message: message };
vm.runInNewContext(msg, sandbox);
if (sandbox.output) {
bot.say(sandbox.output);
return false;
}
return true;
});
bot.say("Added message listener: " + mlName);
return false;
}
return true;
});
bot.addCommandListener("!define [phrase]", /!define (.*)/, "urban definition of a word or phrase", function(msg) {
var data = "";
var request = require('request');
request("http://api.urbandictionary.com/v0/define?term=" + querystring.escape(msg), function (error, response, body) {
if (!error && response.statusCode == 200) {
var urbanresult = JSON.parse(body);
bot.say(urbanresult.list[0].definition);
}
})
});
bot.addCommandListener("!example [phrase]", /!example (.*)/, "Use of urban definition of a word or phrase in a sentence", function(msg) {
var data = "";
var request = require('request');
request("http://api.urbandictionary.com/v0/define?term=" + querystring.escape(msg), function (error, response, body) {
if (!error && response.statusCode == 200) {
var urbanresult = JSON.parse(body);
bot.say(urbanresult.list[0].example);
}
})
});
bot.addCommandListener("!showerthought", /!showerthought/, "Return a reddit shower thought", function(msg) {
var data = "";
var request = require('request');
request("http://www.reddit.com/r/showerthoughts/.json", function (error, response, body) {
if (!error && response.statusCode == 200) {
//console.log(body) // Print the results
var showerthought = JSON.parse(body);
// There are many returned in the json. Get a count
var showercount=showerthought.data.children.length
var randomthought=Math.floor((Math.random() * showercount) + 1);
console.log("Found " + showercount + " shower thoughts. Randomly returning number " + randomthought);
bot.say(showerthought.data.children[randomthought].data.title);
}
})
});
bot.addCommandListener("!firstworldproblems", /!firstworldproblems/, "Return a reddit first world problem", function(msg) {
var data = "";
var request = require('request');
request("http://www.reddit.com/r/firstworldproblems/.json", function (error, response, body) {
if (!error && response.statusCode == 200) {
//console.log(body) // Print the results
var firstworldproblem = JSON.parse(body);
// There are many returned in the json. Get a count
var problemcount=firstworldproblem.data.children.length
var randomproblem=Math.floor((Math.random() * problemcount) + 1);
console.log("Found " + problemcount + " shower thoughts. Randomly returning number " + randomproblem);
bot.say(firstworldproblem.data.children[randomproblem].data.title);
}
})
});
}
module.exports = addBehaviors;<|fim▁end|> | '$' + String(result.quote.latestPrice) + ' ' + |
<|file_name|>celery_setup.py<|end_file_name|><|fim▁begin|>import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_secretary.settings')
app = Celery('test_secretary')
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')<|fim▁hole|><|fim▁end|> | app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) |
<|file_name|>extension.js<|end_file_name|><|fim▁begin|>(function() {
'use strict';
process.env.debug_sql = true;
var Class = require('ee-class')
, log = require('ee-log')
, assert = require('assert')
, fs = require('fs')
, QueryContext = require('related-query-context')
, ORM = require('related');
var TimeStamps = require('../')
, sqlStatments
, extension
, orm
, db;
// sql for test db
sqlStatments = fs.readFileSync(__dirname+'/db.postgres.sql').toString().split(';').map(function(input){
return input.trim().replace(/\n/gi, ' ').replace(/\s{2,}/g, ' ')
}).filter(function(item){
return item.length;
});
describe('Travis', function(){
it('should have set up the test db', function(done){
var config;
try {
config = require('../config.js').db
} catch(e) {
config = [{
type: 'postgres'
, schema: 'related_timestamps_test'
, database : 'test'
, hosts: [{}]
}];
}
this.timeout(5000);
orm = new ORM(config);
done();
});
it('should be able to drop & create the testing schema ('+sqlStatments.length+' raw SQL queries)', function(done){
orm.getDatabase('related_timestamps_test').getConnection('write').then((connection) => {
return new Promise((resolve, reject) => {
let exec = (index) => {
if (sqlStatments[index]) {
connection.query(new QueryContext({sql:sqlStatments[index]})).then(() => {
exec(index + 1);
}).catch(reject);
}
else resolve();
}
exec(0);
});
}).then(() => {
done();
}).catch(done);
});
});
var expect = function(val, cb){
return function(err, result){
try {
assert.equal(JSON.stringify(result), val);
} catch (err) {
return cb(err);
}
cb();
}
};
describe('The TimeStamps Extension', function() {
var oldDate;
it('should not crash when instatiated', function() {
db = orm.related_timestamps_test;
extension = new TimeStamps();
});
it('should not crash when injected into the orm', function(done) {
orm.use(extension);
orm.load(done);
});
it('should set correct timestamps when inserting a new record', function(done) {
db = orm.related_timestamps_test;
new db.event().save(function(err, evt) {
if (err) done(err);
else {
assert.notEqual(evt.created, null);
assert.notEqual(evt.updated, null);
assert.equal(evt.deleted, null);
oldDate = evt.updated;
done();
}
});
});
it('should set correct timestamps when updating a record', function(done) {
// wait, we nede a new timestamp
setTimeout(function() {
db.event({id:1}, ['*']).findOne(function(err, evt) {
if (err) done(err);
else {
evt.name = 'func with timestamps? no, that ain\'t fun!';
evt.save(function(err){
assert.notEqual(evt.created, null);
assert.notEqual(evt.updated, null);
assert.notEqual(evt.updated.toUTCString(), oldDate.toUTCString());
assert.equal(evt.deleted, null);
done();
});
}
});
}, 1500);
});
it('should set correct timestamps when deleting a record', function(done) {
db.event({id:1}, ['*']).findOne(function(err, evt) {
if (err) done(err);
else {
evt.delete(function(err) {
assert.notEqual(evt.created, null);
assert.notEqual(evt.updated, null);
assert.notEqual(evt.deleted, null);
done();
});
}<|fim▁hole|> it('should not return soft deleted records when not requested', function(done) {
db.event({id:1}, ['*']).findOne(function(err, evt) {
if (err) done(err);
else {
assert.equal(evt, undefined);
done();
}
});
});
it('should return soft deleted records when requested', function(done) {
db.event({id:1}, ['*']).includeSoftDeleted().findOne(function(err, evt) {
if (err) done(err);
else {
assert.equal(evt.id, 1);
done();
}
});
});
it('should hard delete records when requested', function(done) {
db.event({id:1}, ['*']).includeSoftDeleted().findOne(function(err, evt) {
if (err) done(err);
else {
evt.hardDelete(function(err) {
if (err) done(err);
else {
db.event({id:1}, ['*']).findOne(function(err, evt) {
if (err) done(err);
else {
assert.equal(evt, undefined);
done();
}
});
}
});
}
});
});
it('should not load softdeleted references', function(done) {
new db.event({
name: 'so what'
, eventInstance: [new db.eventInstance({startdate: new Date(), deleted: new Date()})]
}).save(function(err, evt) {
if (err) done(err);
else {
db.event(['*'], {id:evt.id}).fetchEventInstance(['*']).findOne(function(err, event) {
if (err) done(err);
else {
assert.equal(event.eventInstance.length, 0);
done();
}
});
}
});
})
it ('should work when using bulk deletes', function(done) {
new db.event({name: 'bulk delete 1'}).save().then(function() {
return new db.event({name: 'bulk delete 2'}).save()
}).then(function() {
return new db.event({name: 'bulk delete 3'}).save()
}).then(function() {
return db.event('id').find();
}).then(function(records) {
if (JSON.stringify(records) !== '[{"id":2},{"id":3},{"id":4},{"id":5}]') return Promise.reject(new Error('Expected «[{"id":2},{"id":3},{"id":4},{"id":5}]», got «'+JSON.stringify(records)+'»!'))
else return db.event({
id: ORM.gt(3)
}).delete();
}).then(function() {
return db.event('id').find();
}).then(function(emptyList) {
if (JSON.stringify(emptyList) !== '[{"id":2},{"id":3}]') return Promise.reject(new Error('Expected «[{"id":2},{"id":3}]», got «'+JSON.stringify(emptyList)+'»!'))
else return db.event('id').includeSoftDeleted().find();
}).then(function(list) {
if (JSON.stringify(list) !== '[{"id":2},{"id":3},{"id":4},{"id":5}]') return Promise.reject(new Error('Expected «[{"id":2},{"id":3},{"id":4},{"id":5}]», got «'+JSON.stringify(list)+'»!'))
done();
}).catch(done);
})
});
})();<|fim▁end|> | });
});
|
<|file_name|>mininet_tests.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
import random
import unittest
import networkx
from mininet.topo import Topo
from clib.mininet_test_watcher import TopologyWatcher
from clib.mininet_test_base_topo import FaucetTopoTestBase
class FaucetFaultToleranceBaseTest(FaucetTopoTestBase):
"""
Generate a topology of the given parameters (using build_net & TopoBaseTest)
and then call network function to test the network and then slowly tear out bits
until the expected host connectivity does not match the real host connectivity.
===============================================================================================
INSTANT_FAIL:
The fault-tolerant tests will continue fail if there is a pair of hosts that can not
establish a connection.
Set to true to allow the test suite to continue testing the connectivity
for a fault to build the full graph for the current fault.
ASSUME_SYMMETRIC_PING:
A simplification can assume that (h1 -> h2) implies (h2 -> h1).
Set to true to assume that host connectivity is symmetric.
INTERVLAN_ONLY:
Set to true to test only the inter-VLAN connectivity; ignore connections between hosts on
the same VLAN. Speed up the inter-VLAN testing by ignoring the intra-VLAN cases for
tests that inherit from a intra-VLAN test. This creates that assumption that inter-VLAN
does not disrupt the intra-VLAN.
===============================================================================================
TODO: Add the following options
PROTECTED_NODES/EDGES: Prevent desired nodes/edges from being destroyed
ASSUME_TRANSITIVE_PING: Assume for (h1 -> h2) & (h2 -> h3) then (h1 -> h3)
IGNORE_SUBGRAPH: Assume for a topology with subgraphs, the subgraphs do not need to be tested
(if they have already been tested)
"""
INSTANT_FAIL = True
ASSUME_SYMMETRIC_PING = True
INTERVLAN_ONLY = False
# Watches the faults and host connectvitiy
topo_watcher = None
# List of fault events
fault_events = None
# Number of faults to occur before recalculating connectivity
num_faults = 1
# Fault-tolerance tests will only work in software
SOFTWARE_ONLY = True
# Randomization variables
seed = 1
rng = None
# Number of VLANs to create, if >= 2 then routing will be applied
NUM_VLANS = None
# Number of DPs in the network
NUM_DPS = None
# Number of links between switches
N_DP_LINKS = None
host_links = None
switch_links = None
routers = None
stack_roots = None
def setUp(self):
pass
def set_up(self, network_graph, stack_roots, host_links=None, host_vlans=None):
"""
Args:
network_graph (networkx.MultiGraph): Network topology for the test
stack_roots (dict): The priority values for the stack roots
host_links (dict): Links for each host to switches
host_vlans (dict): VLAN for each host
"""
super().setUp()
switch_links = list(network_graph.edges()) * self.N_DP_LINKS
link_vlans = {edge: None for edge in switch_links}
if not host_links or not host_vlans:
# Setup normal host links & vlans
host_links = {}
host_vlans = {}
host_n = 0
for dp_i in network_graph.nodes():
for v in range(self.NUM_VLANS):
host_links[host_n] = [dp_i]
host_vlans[host_n] = v
host_n += 1
dp_options = {}
for i in network_graph.nodes():
dp_options.setdefault(i, {
'group_table': self.GROUP_TABLE,
'ofchannel_log': self.debug_log_path + str(i) if self.debug_log_path else None,
'hardware': 'Open vSwitch'
})
if i in stack_roots:
dp_options[i]['stack'] = {'priority': stack_roots[i]}
vlan_options = {}
routers = {}
if self.NUM_VLANS >= 2:
# Setup options for routing
routers = {0: list(range(self.NUM_VLANS))}
for i in range(self.NUM_VLANS):
vlan_options[i] = {
'faucet_mac': self.faucet_mac(i),
'faucet_vips': [self.faucet_vip(i)],
'targeted_gw_resolution': False
}
for i in network_graph.nodes():
dp_options[i]['arp_neighbor_timeout'] = 2
dp_options[i]['max_resolve_backoff_time'] = 2
dp_options[i]['proactive_learn_v4'] = True
self.host_links = host_links
self.switch_links = switch_links
self.routers = routers
self.stack_roots = stack_roots
self.build_net(
host_links=host_links,
host_vlans=host_vlans,
switch_links=switch_links,
link_vlans=link_vlans,
n_vlans=self.NUM_VLANS,
dp_options=dp_options,
vlan_options=vlan_options,
routers=routers
)
self.start_net()
def host_connectivity(self, host, dst):
"""Ping to a destination, return True if the ping was successful"""
try:
self._ip_ping(host, dst, 5, timeout=50, count=5, require_host_learned=False)
except AssertionError:
return False
return True
def calculate_connectivity(self):
"""Ping between each set of host pairs to calculate host connectivity"""
connected_hosts = self.topo_watcher.get_connected_hosts(
two_way=not self.ASSUME_SYMMETRIC_PING, strictly_intervlan=self.INTERVLAN_ONLY)
for src, dsts in connected_hosts.items():
src_host = self.host_information[src]['host']
for dst in dsts:
dst_host = self.host_information[dst]['host']
dst_ip = self.host_information[dst]['ip']
result = self.host_connectivity(src_host, dst_ip.ip)
self.topo_watcher.add_network_info(src_host.name, dst_host.name, result)
self.assertTrue(not self.INSTANT_FAIL or result, 'Pair connection failed')
def create_controller_fault(self, *args):
"""
Set controller down (disconnects all switches from the controller)
Args:
index: The index to the controller to take down
"""
index = args[0]
controller = self.net.controllers[index]
controller.stop()
self.net.controllers.remove(controller)
self.topo_watcher.add_fault('Controller %s DOWN' % controller.name)
def create_random_controller_fault(self, *args):
"""Randomly create a fault for a controller"""
controllers = [c for c in self.net.controllers if c.name != 'gauge']
i = random.randrange(len(controllers))
c_name = controllers[i].name
controller = next((cont for cont in self.net.controllers if cont.name == c_name), None)
if controller is None:
return
self.create_controller_fault(self.net.controllers.index(controller))
def create_switch_fault(self, *args):
"""
Set switch down (Deletes the OVS switch bridge)
Args:
index: Index of the switch dpid to take out
"""
index = args[0]
dpid = self.dpids[index]
switch_name = self.topo.switches_by_id[index]
switch = next((switch for switch in self.net.switches if switch.name == switch_name), None)
if switch is None:
return
self.dump_switch_flows(switch)
name = '%s:%s DOWN' % (self.topo.switches_by_id[index], self.dpids[index])
self.topo_watcher.add_switch_fault(index, name)
switch.stop()
switch.cmd(self.VSCTL, 'del-controller', switch.name, '|| true')
self.assertTrue(
self.wait_for_prometheus_var(
'of_dp_disconnections_total', 1, dpid=dpid), 'DP %s not detected as DOWN' % dpid)
self.net.switches.remove(switch)
def random_switch_fault(self, *args):
"""Randomly take out an available switch"""
dpid_list = self.topo_watcher.get_eligable_switch_events()
if len(self.stack_roots.keys()) <= 1:
# Prevent only root from being destroyed
sorted_roots = dict(sorted(self.stack_roots.items(), key=lambda item: item[1]))
for root_index in sorted_roots.keys():
root_dpid = self.dpids[root_index]
if root_dpid in dpid_list:
dpid_list.remove(root_dpid)
break
if not dpid_list:
return
dpid_item_index = self.rng.randrange(len(dpid_list))
dpid_item = dpid_list[dpid_item_index]
dpid_index = self.dpids.index(dpid_item)
self.create_switch_fault(dpid_index)
def dp_link_fault(self, *args):
"""
Create a fault/tear down the stack link between two switches
Args:
src_dp_index: Index of the source DP of the stack link
dst_dp_index: Index of the destination DP of the stack
"""
src_i = args[0]
dst_i = args[1]
src_dpid = self.dpids[src_i]
dst_dpid = self.dpids[dst_i]
s1_name = self.topo.switches_by_id[src_i]
s2_name = self.topo.switches_by_id[dst_i]
for port, link in self.topo.ports[s1_name].items():
status = self.stack_port_status(src_dpid, s1_name, port)
if link[0] == s2_name and status == 3:
peer_port = link[1]
self.set_port_down(port, src_dpid)
self.set_port_down(peer_port, dst_dpid)
self.wait_for_stack_port_status(src_dpid, s1_name, port, 4)
self.wait_for_stack_port_status(dst_dpid, s2_name, peer_port, 4)
name = 'Link %s[%s]:%s-%s[%s]:%s DOWN' % (
s1_name, src_dpid, port, s2_name, dst_dpid, peer_port)
self.topo_watcher.add_link_fault(src_i, dst_i, name)
return
def random_dp_link_fault(self, *args):
"""Randomly create a fault for a DP link"""
link_list = self.topo_watcher.get_eligable_link_events()
if not link_list:
return
index = self.rng.randrange(len(link_list))
dplink = link_list[index]
srcdp = self.dpids.index(dplink[0])
dstdp = self.dpids.index(dplink[1])
self.dp_link_fault(srcdp, dstdp)
def create_proportional_random_fault_event(self):
"""Create a fault-event randomly based on the number of link and switch events available"""
funcs = []
for _ in self.topo_watcher.get_eligable_link_events():
funcs.append(self.random_dp_link_fault)
for _ in self.topo_watcher.get_eligable_switch_events():
funcs.append(self.random_switch_fault)
i = self.rng.randrange(len(funcs))
funcs[i]()
def create_random_fault_event(self):
"""Randomly choose an event type to fault on"""
funcs = []
if self.topo_watcher.get_eligable_link_events():
funcs.append(self.random_dp_link_fault)
if self.topo_watcher.get_eligable_switch_events():
funcs.append(self.random_switch_fault)
if not funcs:
return
i = self.rng.randrange(len(funcs))
funcs[i]()
def network_function(self, fault_events=None, num_faults=1):
"""
Test the network by slowly tearing it down different ways
Args:
fault_events: (optional) list of tuples of fault event functions and the parameters to
use in the given order; instead of randomly choosing parts of the network to break
num_faults: (optional) number of faults to cause before each evaluation is made<|fim▁hole|> self.num_faults = num_faults
self.rng = random.Random(self.seed)
self.topo_watcher = TopologyWatcher(
self.dpids, self.switch_links, self.host_links,
self.NUM_VLANS, self.host_information, self.routers)
# Calculate stats (before any tear downs)
self.calculate_connectivity()
self.assertTrue(self.topo_watcher.is_connected(), (
'Host connectivity does not match predicted'))
# Start tearing down the network
if self.fault_events:
# Do Specified list of faults (in order) until failure or fault list completed
fault_index = 0
while fault_index < len(self.fault_events):
for _ in range(self.num_faults):
event_func, params = self.fault_events[fault_index]
fault_index += 1
event_func(*params)
self.calculate_connectivity()
self.assertTrue(self.topo_watcher.is_connected(), (
'Host connectivity does not match predicted'))
else:
# Continue creating fault until none are available or expected connectivity does not
# match real connectivity
while self.topo_watcher.continue_faults():
for _ in range(self.num_faults):
self.create_proportional_random_fault_event()
self.calculate_connectivity()
self.assertTrue(self.topo_watcher.is_connected(), (
'Host connectivity does not match predicted'))
def tearDown(self, ignore_oferrors=False):
"""Make sure to dump the watcher information too"""
if self.topo_watcher:
self.topo_watcher.dump_info(self.tmpdir)
super(FaucetFaultToleranceBaseTest, self).tearDown(ignore_oferrors=ignore_oferrors)
class FaucetSingleFaultTolerance2DPTest(FaucetFaultToleranceBaseTest):
"""Run a range of fault-tolerance tests for topologies on 2 DPs"""
NUM_DPS = 2
NUM_HOSTS = 4
NUM_VLANS = 2
N_DP_LINKS = 1
STACK_ROOTS = {0: 1}
ASSUME_SYMMETRIC_PING = False
class FaucetSingleFaultTolerance3DPTest(FaucetFaultToleranceBaseTest):
"""Run a range of fault-tolerance tests for topologies on 3 DPs"""
NUM_DPS = 3
NUM_HOSTS = 6
NUM_VLANS = 2
N_DP_LINKS = 1
STACK_ROOTS = {0: 1}
class FaucetSingleFaultTolerance4DPTest(FaucetFaultToleranceBaseTest):
"""Run a range of fault-tolerance tests for topologies on 4 DPs"""
NUM_DPS = 4
NUM_HOSTS = 4
NUM_VLANS = 1
N_DP_LINKS = 1
STACK_ROOTS = {0: 1}
def test_ftp2_all_random_switch_failures(self):
"""Test fat-tree-pod-2 randomly tearing down only switches"""
fault_events = [(self.random_switch_fault, (None,)) for _ in range(self.NUM_DPS)]
stack_roots = {2*i: 1 for i in range(self.NUM_DPS//2)}
self.set_up(networkx.cycle_graph(self.NUM_DPS), stack_roots)
self.network_function(fault_events=fault_events)
def test_ftp2_all_random_link_failures(self):
"""Test fat-tree-pod-2 randomly tearing down only switch-switch links"""
network_graph = networkx.cycle_graph(self.NUM_DPS)
fault_events = [(self.random_dp_link_fault, (None,)) for _ in range(len(network_graph.edges()))]
stack_roots = {2*i: 1 for i in range(self.NUM_DPS//2)}
self.set_up(network_graph, stack_roots)
self.network_function(fault_events=fault_events)
def test_ftp2_edge_root_link_fault(self):
"""Test breaking a link between a edge switch to the root aggregation switch"""
fault_events = [(self.dp_link_fault, (0, 3))]
stack_roots = {2*i: i+1 for i in range(self.NUM_DPS//2)}
self.set_up(networkx.cycle_graph(self.NUM_DPS), stack_roots)
self.network_function(fault_events=fault_events)
def test_ftp2_destroying_one_of_each_link(self):
"""Test tearing down one of each link for a fat-tree-pod-2 with redundant edges"""
self.N_DP_LINKS = 2
fault_events = []
for i in range(self.NUM_DPS):
j = i+1 if i+1 < self.NUM_DPS else 0
fault_events.append((self.dp_link_fault, (i, j)))
num_faults = len(fault_events)
stack_roots = {2*i: 1 for i in range(self.NUM_DPS//2)}
self.set_up(networkx.cycle_graph(self.NUM_DPS), stack_roots)
self.network_function(fault_events=fault_events, num_faults=num_faults)
self.N_DP_LINKS = 1
class FaucetSingleFaultTolerance5DPTest(FaucetFaultToleranceBaseTest):
"""Run a range of fault-tolerance tests for topologies on 5 DPs"""
NUM_DPS = 5
NUM_HOSTS = 5
NUM_VLANS = 1
N_DP_LINKS = 1
STACK_ROOTS = {0: 1}
@unittest.skip('Too computationally complex')
class FaucetSingleFaultTolerance6DPTest(FaucetFaultToleranceBaseTest):
"""Run a range of fault-tolerance tests for topologies on 5 DPs"""
NUM_DPS = 6
NUM_HOSTS = 6
NUM_VLANS = 1
N_DP_LINKS = 1
STACK_ROOTS = {0: 1}
@unittest.skip('Too computationally complex')
class FaucetSingleFaultTolerance7DPTest(FaucetFaultToleranceBaseTest):
"""Run a range of fault-tolerance tests for topologies on 5 DPs"""
NUM_DPS = 7
NUM_HOSTS = 7
NUM_VLANS = 1
N_DP_LINKS = 1
STACK_ROOTS = {0: 1}
TEST_CLASS_LIST = [
FaucetSingleFaultTolerance2DPTest,
FaucetSingleFaultTolerance3DPTest,
FaucetSingleFaultTolerance4DPTest,
FaucetSingleFaultTolerance5DPTest,
FaucetSingleFaultTolerance6DPTest,
FaucetSingleFaultTolerance7DPTest
]
MIN_NODES = min([c.NUM_DPS for c in TEST_CLASS_LIST])
MAX_NODES = max([c.NUM_DPS for c in TEST_CLASS_LIST])<|fim▁end|> | """
self.verify_stack_up()
self.fault_events = fault_events |
<|file_name|>tables.py<|end_file_name|><|fim▁begin|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.core.exceptions import ValidationError # noqa
from django.core.urlresolvers import reverse<|fim▁hole|>from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy
from openstack_auth import utils as auth_utils
from horizon import exceptions
from horizon import forms
from horizon import tables
from keystoneclient.exceptions import Conflict # noqa
from openstack_dashboard import api
from openstack_dashboard import policy
class RescopeTokenToProject(tables.LinkAction):
name = "rescope"
verbose_name = _("Set as Active Project")
url = "switch_tenants"
def allowed(self, request, project):
# allow rescoping token to any project the user has a role on,
# authorized_tenants, and that they are not currently scoped to
return next((True for proj in request.user.authorized_tenants
if proj.id == project.id and
project.id != request.user.project_id), False)
def get_link_url(self, project):
# redirects to the switch_tenants url which then will redirect
# back to this page
dash_url = reverse("horizon:identity:projects:index")
base_url = reverse(self.url, args=[project.id])
param = urlencode({"next": dash_url})
return "?".join([base_url, param])
class UpdateMembersLink(tables.LinkAction):
name = "users"
verbose_name = _("Manage Members")
url = "horizon:identity:projects:update"
classes = ("ajax-modal",)
icon = "pencil"
policy_rules = (("identity", "identity:list_users"),
("identity", "identity:list_roles"))
def get_link_url(self, project):
step = 'update_members'
base_url = reverse(self.url, args=[project.id])
param = urlencode({"step": step})
return "?".join([base_url, param])
class UpdateGroupsLink(tables.LinkAction):
name = "groups"
verbose_name = _("Modify Groups")
url = "horizon:identity:projects:update"
classes = ("ajax-modal",)
icon = "pencil"
policy_rules = (("identity", "identity:list_groups"),)
def allowed(self, request, project):
return api.keystone.VERSIONS.active >= 3
def get_link_url(self, project):
step = 'update_group_members'
base_url = reverse(self.url, args=[project.id])
param = urlencode({"step": step})
return "?".join([base_url, param])
class UsageLink(tables.LinkAction):
name = "usage"
verbose_name = _("View Usage")
url = "horizon:identity:projects:usage"
icon = "stats"
policy_rules = (("compute", "compute_extension:simple_tenant_usage:show"),)
def allowed(self, request, project):
return request.user.is_superuser
class CreateProject(tables.LinkAction):
name = "create"
verbose_name = _("Create Project")
url = "horizon:identity:projects:create"
classes = ("ajax-modal",)
icon = "plus"
policy_rules = (('identity', 'identity:create_project'),)
def allowed(self, request, project):
return api.keystone.keystone_can_edit_project()
class UpdateProject(tables.LinkAction):
name = "update"
verbose_name = _("Edit Project")
url = "horizon:identity:projects:update"
classes = ("ajax-modal",)
icon = "pencil"
policy_rules = (('identity', 'identity:update_project'),)
def allowed(self, request, project):
return api.keystone.keystone_can_edit_project()
class ModifyQuotas(tables.LinkAction):
name = "quotas"
verbose_name = _("Modify Quotas")
url = "horizon:identity:projects:update"
classes = ("ajax-modal",)
icon = "pencil"
policy_rules = (('compute', "compute_extension:quotas:update"),)
def get_link_url(self, project):
step = 'update_quotas'
base_url = reverse(self.url, args=[project.id])
param = urlencode({"step": step})
return "?".join([base_url, param])
class DeleteTenantsAction(tables.DeleteAction):
@staticmethod
def action_present(count):
return ungettext_lazy(
u"Delete Project",
u"Delete Projects",
count
)
@staticmethod
def action_past(count):
return ungettext_lazy(
u"Deleted Project",
u"Deleted Projects",
count
)
policy_rules = (("identity", "identity:delete_project"),)
def allowed(self, request, project):
return api.keystone.keystone_can_edit_project()
def delete(self, request, obj_id):
api.keystone.tenant_delete(request, obj_id)
def handle(self, table, request, obj_ids):
response = \
super(DeleteTenantsAction, self).handle(table, request, obj_ids)
auth_utils.remove_project_cache(request.user.token.id)
return response
class TenantFilterAction(tables.FilterAction):
def filter(self, table, tenants, filter_string):
"""Really naive case-insensitive search."""
# FIXME(gabriel): This should be smarter. Written for demo purposes.
q = filter_string.lower()
def comp(tenant):
if q in tenant.name.lower():
return True
return False
return filter(comp, tenants)
class UpdateRow(tables.Row):
ajax = True
def get_data(self, request, project_id):
project_info = api.keystone.tenant_get(request, project_id,
admin=True)
return project_info
class UpdateCell(tables.UpdateAction):
def allowed(self, request, project, cell):
policy_rule = (("identity", "identity:update_project"),)
return (
(cell.column.name != 'enabled' or
request.user.token.project['id'] != cell.datum.id) and
api.keystone.keystone_can_edit_project() and
policy.check(policy_rule, request))
def update_cell(self, request, datum, project_id,
cell_name, new_cell_value):
# inline update project info
try:
project_obj = datum
# updating changed value by new value
setattr(project_obj, cell_name, new_cell_value)
api.keystone.tenant_update(
request,
project_id,
name=project_obj.name,
description=project_obj.description,
enabled=project_obj.enabled)
except Conflict:
# Returning a nice error message about name conflict. The message
# from exception is not that clear for the users.
message = _("This name is already taken.")
raise ValidationError(message)
except Exception:
exceptions.handle(request, ignore=True)
return False
return True
class TenantsTable(tables.DataTable):
name = tables.Column('name', verbose_name=_('Name'),
form_field=forms.CharField(max_length=64),
update_action=UpdateCell)
description = tables.Column(lambda obj: getattr(obj, 'description', None),
verbose_name=_('Description'),
form_field=forms.CharField(
widget=forms.Textarea(attrs={'rows': 4}),
required=False),
update_action=UpdateCell)
id = tables.Column('id', verbose_name=_('Project ID'))
enabled = tables.Column('enabled', verbose_name=_('Enabled'), status=True,
form_field=forms.BooleanField(
label=_('Enabled'),
required=False),
update_action=UpdateCell)
class Meta:
name = "tenants"
verbose_name = _("Projects")
row_class = UpdateRow
row_actions = (UpdateMembersLink, UpdateGroupsLink, UpdateProject,
UsageLink, ModifyQuotas, DeleteTenantsAction,
RescopeTokenToProject)
table_actions = (TenantFilterAction, CreateProject,
DeleteTenantsAction)
pagination_param = "tenant_marker"<|fim▁end|> | from django.utils.http import urlencode |
<|file_name|>test_data.py<|end_file_name|><|fim▁begin|>from jupyter_workflow.data import get_fremont_data<|fim▁hole|> data = get_fremont_data()
assert all(data.columns == ['West','East','Total'])
assert isinstance(data.index,pd.DatetimeIndex)<|fim▁end|> | import pandas as pd
def test_fremont_data(): |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>module.exports = middleware;
var states = {
STANDBY: 0,
BUSY: 1<|fim▁hole|> var regio = require('regio'),
tessel = require('tessel'),
camera = require('camera-vc0706').use(tessel.port[options.port]),
app = regio.router(),
hwReady = false,
current;
camera.on('ready', function() {
hwReady = true;
current = states.STANDBY;
});
app.get('/', handler);
function handler(req, res) {
if (hwReady) {
if (current === states.STANDBY) {
current = states.BUSY;
camera.takePicture(function (err, image) {
res.set('Content-Type', 'image/jpeg');
res.set('Content-Length', image.length);
res.status(200).end(image);
current = states.STANDBY;
});
} else {
res.set('Retry-After', 100);
res.status(503).end();
}
} else {
res.status(503).end();
}
}
return app;
}<|fim▁end|> | };
function middleware(options) { |
<|file_name|>kubernetes.go<|end_file_name|><|fim▁begin|>// Copyright 2017 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
<|fim▁hole|>package util
import (
"fmt"
"time"
"github.com/golang/glog"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api/v1"
)
// Test utilities for kubernetes
const (
// PodCheckBudget is the maximum number of retries with 1s delays
PodCheckBudget = 90
)
// CreateNamespace creates a fresh namespace
func CreateNamespace(cl kubernetes.Interface) (string, error) {
ns, err := cl.CoreV1().Namespaces().Create(&v1.Namespace{
ObjectMeta: meta_v1.ObjectMeta{
GenerateName: "istio-test-",
},
})
if err != nil {
return "", err
}
glog.Infof("Created namespace %s", ns.Name)
return ns.Name, nil
}
// DeleteNamespace removes a namespace
func DeleteNamespace(cl kubernetes.Interface, ns string) {
if ns != "" && ns != "default" {
if err := cl.CoreV1().Namespaces().Delete(ns, &meta_v1.DeleteOptions{}); err != nil {
glog.Warningf("Error deleting namespace: %v", err)
}
glog.Infof("Deleted namespace %s", ns)
}
}
// GetPods gets pod names in a namespace
func GetPods(cl kubernetes.Interface, ns string) []string {
out := make([]string, 0)
list, err := cl.CoreV1().Pods(ns).List(meta_v1.ListOptions{})
if err != nil {
return out
}
for _, pod := range list.Items {
out = append(out, pod.Name)
}
return out
}
// GetAppPods awaits till all pods are running in a namespace, and returns a map
// from "app" label value to the pod names.
func GetAppPods(cl kubernetes.Interface, ns string) (map[string][]string, error) {
pods := make(map[string][]string)
var items []v1.Pod
for n := 0; ; n++ {
glog.Info("Checking all pods are running...")
list, err := cl.CoreV1().Pods(ns).List(meta_v1.ListOptions{})
if err != nil {
return pods, err
}
items = list.Items
ready := true
for _, pod := range items {
if pod.Status.Phase != "Running" {
glog.Infof("Pod %s has status %s", pod.Name, pod.Status.Phase)
ready = false
break
}
}
if ready {
break
}
if n > PodCheckBudget {
return pods, fmt.Errorf("exceeded budget for checking pod status")
}
time.Sleep(time.Second)
}
for _, pod := range items {
if app, exists := pod.Labels["app"]; exists {
pods[app] = append(pods[app], pod.Name)
}
}
return pods, nil
}
// FetchLogs for a container in a a pod
func FetchLogs(cl kubernetes.Interface, name, namespace string, container string) string {
glog.V(2).Infof("Fetching log for container %s in %s.%s", container, name, namespace)
raw, err := cl.CoreV1().Pods(namespace).
GetLogs(name, &v1.PodLogOptions{Container: container}).
Do().Raw()
if err != nil {
glog.Infof("Request error %v", err)
return ""
}
return string(raw)
}<|fim▁end|> | |
<|file_name|>perfcountertest.py<|end_file_name|><|fim▁begin|>import time
import find_remove_find5<|fim▁hole|>import walk_through7
def time_find_two_smallest(find_func, lst):
...<|fim▁end|> | import sort_then_find3 |
<|file_name|>test_simple09.py<|end_file_name|><|fim▁begin|>###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, [email protected]
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename('simple09.xlsx')
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
# Test data out of range. These should be ignored.
worksheet.write('A0', 'foo')
worksheet.write(-1, -1, 'foo')
worksheet.write(0, -1, 'foo')
worksheet.write(-1, 0, 'foo')
worksheet.write(1048576, 0, 'foo')
worksheet.write(0, 16384, 'foo')
workbook.close()<|fim▁hole|>
self.assertExcelEqual()<|fim▁end|> | |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, [email protected]
# Gerhard Lausser, [email protected]
# Gregory Starck, [email protected]
# Hartmut Goebel, [email protected]
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
from item import Item, Items
from shinken.util import strip_and_uniq
from shinken.property import BoolProp, IntegerProp, StringProp
from shinken.log import logger, naglog_result
_special_properties = ('service_notification_commands', 'host_notification_commands',
'service_notification_period', 'host_notification_period',
'service_notification_options', 'host_notification_options',
'host_notification_commands', 'contact_name')
_simple_way_parameters = ('service_notification_period', 'host_notification_period',
'service_notification_options', 'host_notification_options',
'service_notification_commands', 'host_notification_commands',
'min_business_impact')
class Contact(Item):
id = 1 # zero is always special in database, so we do not take risk here
my_type = 'contact'
properties = Item.properties.copy()
properties.update({
'contact_name': StringProp(fill_brok=['full_status']),
'alias': StringProp(default='none', fill_brok=['full_status']),
'contactgroups': StringProp(default='', fill_brok=['full_status']),
'host_notifications_enabled': BoolProp(default='1', fill_brok=['full_status']),
'service_notifications_enabled': BoolProp(default='1', fill_brok=['full_status']),
'host_notification_period': StringProp(fill_brok=['full_status']),
'service_notification_period': StringProp(fill_brok=['full_status']),
'host_notification_options': StringProp(fill_brok=['full_status']),
'service_notification_options': StringProp(fill_brok=['full_status']),
'host_notification_commands': StringProp(fill_brok=['full_status']),
'service_notification_commands': StringProp(fill_brok=['full_status']),
'min_business_impact': IntegerProp(default='0', fill_brok=['full_status']),
'email': StringProp(default='none', fill_brok=['full_status']),
'pager': StringProp(default='none', fill_brok=['full_status']),
'address1': StringProp(default='none', fill_brok=['full_status']),
'address2': StringProp(default='none', fill_brok=['full_status']),
'address3': StringProp(default='none', fill_brok=['full_status']),
'address4': StringProp(default='none', fill_brok=['full_status']),
'address5': StringProp(default='none', fill_brok=['full_status']),
'address6': StringProp(default='none', fill_brok=['full_status']),
'can_submit_commands': BoolProp(default='0', fill_brok=['full_status']),
'is_admin': BoolProp(default='0', fill_brok=['full_status']),
'retain_status_information': BoolProp(default='1', fill_brok=['full_status']),
'notificationways': StringProp(default='', fill_brok=['full_status']),
'password': StringProp(default='NOPASSWORDSET', fill_brok=['full_status']),
})
running_properties = Item.running_properties.copy()
running_properties.update({
'modified_attributes': IntegerProp(default=0L, fill_brok=['full_status'], retention=True),
'downtimes': StringProp(default=[], fill_brok=['full_status'], retention=True),
})
# This tab is used to transform old parameters name into new ones
# so from Nagios2 format, to Nagios3 ones.
# Or Shinken deprecated names like criticity
old_properties = {
'min_criticity': 'min_business_impact',
}
macros = {
'CONTACTNAME': 'contact_name',
'CONTACTALIAS': 'alias',
'CONTACTEMAIL': 'email',
'CONTACTPAGER': 'pager',
'CONTACTADDRESS1': 'address1',
'CONTACTADDRESS2': 'address2',
'CONTACTADDRESS3': 'address3',
'CONTACTADDRESS4': 'address4',
'CONTACTADDRESS5': 'address5',
'CONTACTADDRESS6': 'address6',
'CONTACTGROUPNAME': 'get_groupname',
'CONTACTGROUPNAMES': 'get_groupnames'
}
# For debugging purpose only (nice name)
def get_name(self):
try:
return self.contact_name
except AttributeError:
return 'UnnamedContact'
# Search for notification_options with state and if t is
# in service_notification_period
def want_service_notification(self, t, state, type, business_impact, cmd=None):
if not self.service_notifications_enabled:
return False
# If we are in downtime, we do nto want notification
for dt in self.downtimes:
if dt.is_in_effect:
return False
# Now the rest is for sub notificationways. If one is OK, we are ok
# We will filter in another phase
for nw in self.notificationways:
nw_b = nw.want_service_notification(t, state, type, business_impact, cmd)
if nw_b:
return True
# Oh... no one is ok for it? so no, sorry
return False
# Search for notification_options with state and if t is in
# host_notification_period
def want_host_notification(self, t, state, type, business_impact, cmd=None):
if not self.host_notifications_enabled:
return False
# If we are in downtime, we do nto want notification
for dt in self.downtimes:
if dt.is_in_effect:
return False
# Now it's all for sub notificationways. If one is OK, we are OK
# We will filter in another phase
for nw in self.notificationways:
nw_b = nw.want_host_notification(t, state, type, business_impact, cmd)
if nw_b:
return True
# Oh, nobody..so NO :)
return False
# Call to get our commands to launch a Notification
def get_notification_commands(self, type):
r = []
# service_notification_commands for service
notif_commands_prop = type + '_notification_commands'
for nw in self.notificationways:
r.extend(getattr(nw, notif_commands_prop))
return r
# Check is required prop are set:
# contacts OR contactgroups is need
def is_correct(self):
state = True
cls = self.__class__
# All of the above are checks in the notificationways part
for prop, entry in cls.properties.items():
if prop not in _special_properties:
if not hasattr(self, prop) and entry.required:
logger.error("[contact::%s] %s property not set", self.get_name(), prop)
state = False # Bad boy...
# There is a case where there is no nw: when there is not special_prop defined
# at all!!
if self.notificationways == []:
for p in _special_properties:
if not hasattr(self, p):
logger.error("[contact::%s] %s property is missing", self.get_name(), p)
state = False
if hasattr(self, 'contact_name'):
for c in cls.illegal_object_name_chars:
if c in self.contact_name:
logger.error("[contact::%s] %s character not allowed in contact_name", self.get_name(), c)
state = False
else:
if hasattr(self, 'alias'): # take the alias if we miss the contact_name
self.contact_name = self.alias
return state
# Raise a log entry when a downtime begins
# CONTACT DOWNTIME ALERT: test_contact;STARTED; Contact has entered a period of scheduled downtime
def raise_enter_downtime_log_entry(self):
naglog_result('info', "CONTACT DOWNTIME ALERT: %s;STARTED; Contact has "
"entered a period of scheduled downtime"
% self.get_name())
# Raise a log entry when a downtime has finished
# CONTACT DOWNTIME ALERT: test_contact;STOPPED; Contact has exited from a period of scheduled downtime
def raise_exit_downtime_log_entry(self):
naglog_result('info', "CONTACT DOWNTIME ALERT: %s;STOPPED; Contact has "
"exited from a period of scheduled downtime"
% self.get_name())
# Raise a log entry when a downtime prematurely ends
# CONTACT DOWNTIME ALERT: test_contact;CANCELLED; Contact has entered a period of scheduled downtime
def raise_cancel_downtime_log_entry(self):
naglog_result('info', "CONTACT DOWNTIME ALERT: %s;CANCELLED; Scheduled "
"downtime for contact has been cancelled."
% self.get_name())
<|fim▁hole|> def linkify(self, timeperiods, commands, notificationways):
#self.linkify_with_timeperiods(timeperiods, 'service_notification_period')
#self.linkify_with_timeperiods(timeperiods, 'host_notification_period')
#self.linkify_command_list_with_commands(commands, 'service_notification_commands')
#self.linkify_command_list_with_commands(commands, 'host_notification_commands')
self.linkify_with_notificationways(notificationways)
# We've got a notificationways property with , separated contacts names
# and we want have a list of NotificationWay
def linkify_with_notificationways(self, notificationways):
for i in self:
if not hasattr(i, 'notificationways'):
continue
new_notificationways = []
for nw_name in strip_and_uniq(i.notificationways.split(',')):
nw = notificationways.find_by_name(nw_name)
if nw is not None:
new_notificationways.append(nw)
else:
err = "The 'notificationways' of the %s '%s' named '%s' is unknown!" % (i.__class__.my_type, i.get_name(), nw_name)
i.configuration_errors.append(err)
# Get the list, but first make elements uniq
i.notificationways = list(set(new_notificationways))
def late_linkify_c_by_commands(self, commands):
for i in self:
for nw in i.notificationways:
nw.late_linkify_nw_by_commands(commands)
# We look for contacts property in contacts and
def explode(self, contactgroups, notificationways):
# Contactgroups property need to be fullfill for got the informations
self.apply_partial_inheritance('contactgroups')
# _special properties maybe came from a template, so
# import them before grok ourselves
for prop in _special_properties:
if prop == 'contact_name':
continue
self.apply_partial_inheritance(prop)
# Register ourself into the contactsgroups we are in
for c in self:
if c.is_tpl() or not (hasattr(c, 'contact_name') and hasattr(c, 'contactgroups')):
continue
for cg in c.contactgroups.split(','):
contactgroups.add_member(c.contact_name, cg.strip())
# Now create a notification way with the simple parameter of the
# contacts
for c in self:
if not c.is_tpl():
need_notificationway = False
params = {}
for p in _simple_way_parameters:
if hasattr(c, p):
need_notificationway = True
params[p] = getattr(c, p)
else: # put a default text value
# Remove the value and put a default value
setattr(c, p, '')
if need_notificationway:
#print "Create notif way with", params
cname = getattr(c, 'contact_name', getattr(c, 'alias', ''))
nw_name = cname + '_inner_notificationway'
notificationways.new_inner_member(nw_name, params)
if not hasattr(c, 'notificationways'):
c.notificationways = nw_name
else:
c.notificationways = c.notificationways + ',' + nw_name<|fim▁end|> | class Contacts(Items):
name_property = "contact_name"
inner_class = Contact
|
<|file_name|>menu_login.py<|end_file_name|><|fim▁begin|>"""
Menu-driven login system
Contribution - Griatch 2011
This is an alternative login system for Evennia, using the
contrib.menusystem module. As opposed to the default system it doesn't
use emails for authentication and also don't auto-creates a Character
with the same name as the Player (instead assuming some sort of
character-creation to come next).
Install is simple:
To your settings file, add/edit the line:
CMDSET_UNLOGGEDIN = "contrib.menu_login.UnloggedInCmdSet"
That's it. Reload the server and try to log in to see it.
The initial login "graphic" is taken from strings in the module given
by settings.CONNECTION_SCREEN_MODULE. You will want to copy the
template file in game/gamesrc/conf/examples up one level and re-point
the settings file to this custom module. you can then edit the string
in that module (at least comment out the default string that mentions
commands that are not available) and add something more suitable for
the initial splash screen.
"""
import re
import traceback
from django.conf import settings
from ev import managers
from ev import utils, logger, create_player
from ev import Command, CmdSet
from ev import syscmdkeys
from src.server.models import ServerConfig
from contrib.menusystem import MenuNode, MenuTree
CMD_LOGINSTART = syscmdkeys.CMD_LOGINSTART
CMD_NOINPUT = syscmdkeys.CMD_NOINPUT
CMD_NOMATCH = syscmdkeys.CMD_NOMATCH
CONNECTION_SCREEN_MODULE = settings.CONNECTION_SCREEN_MODULE
# Commands run on the unloggedin screen. Note that this is not using
# settings.UNLOGGEDIN_CMDSET but the menu system, which is why some are
# named for the numbers in the menu.
#
# Also note that the menu system will automatically assign all
# commands used in its structure a property "menutree" holding a reference
# back to the menutree. This allows the commands to do direct manipulation
# for example by triggering a conditional jump to another node.
#
# Menu entry 1a - Entering a Username
class CmdBackToStart(Command):
"""
Step back to node0
"""
key = CMD_NOINPUT
locks = "cmd:all()"
def func(self):
"Execute the command"
self.menutree.goto("START")
class CmdUsernameSelect(Command):
"""
Handles the entering of a username and
checks if it exists.
"""
key = CMD_NOMATCH
locks = "cmd:all()"
<|fim▁hole|> self.caller.msg("{rThis account name couldn't be found. Did you create it? If you did, make sure you spelled it right (case doesn't matter).{n")
self.menutree.goto("node1a")
else:
# store the player so next step can find it
self.menutree.player = player
self.caller.msg(echo=False)
self.menutree.goto("node1b")
# Menu entry 1b - Entering a Password
class CmdPasswordSelectBack(Command):
"""
Steps back from the Password selection
"""
key = CMD_NOINPUT
locks = "cmd:all()"
def func(self):
"Execute the command"
self.menutree.goto("node1a")
self.caller.msg(echo=True)
class CmdPasswordSelect(Command):
"""
Handles the entering of a password and logs into the game.
"""
key = CMD_NOMATCH
locks = "cmd:all()"
def func(self):
"Execute the command"
self.caller.msg(echo=True)
if not hasattr(self.menutree, "player"):
self.caller.msg("{rSomething went wrong! The player was not remembered from last step!{n")
self.menutree.goto("node1a")
return
player = self.menutree.player
if not player.check_password(self.args):
self.caller.msg("{rIncorrect password.{n")
self.menutree.goto("node1b")
return
# before going on, check eventual bans
bans = ServerConfig.objects.conf("server_bans")
if bans and (any(tup[0]==player.name.lower() for tup in bans)
or
any(tup[2].match(self.caller.address) for tup in bans if tup[2])):
# this is a banned IP or name!
string = "{rYou have been banned and cannot continue from here."
string += "\nIf you feel this ban is in error, please email an admin.{x"
self.caller.msg(string)
self.caller.sessionhandler.disconnect(self.caller, "Good bye! Disconnecting...")
return
# we are ok, log us in.
self.caller.msg("{gWelcome %s! Logging in ...{n" % player.key)
#self.caller.session_login(player)
self.caller.sessionhandler.login(self.caller, player)
# abort menu, do cleanup.
self.menutree.goto("END")
# we are logged in. Look around.
character = player.character
if character:
character.execute_cmd("look")
else:
# we have no character yet; use player's look, if it exists
player.execute_cmd("look")
# Menu entry 2a - Creating a Username
class CmdUsernameCreate(Command):
"""
Handle the creation of a valid username
"""
key = CMD_NOMATCH
locks = "cmd:all()"
def func(self):
"Execute the command"
playername = self.args
# sanity check on the name
if not re.findall('^[\w. @+-]+$', playername) or not (3 <= len(playername) <= 30):
self.caller.msg("\n\r {rAccount name should be between 3 and 30 characters. Letters, spaces, dig\
its and @/./+/-/_ only.{n") # this echoes the restrictions made by django's auth module.
self.menutree.goto("node2a")
return
if managers.players.get_player_from_name(playername):
self.caller.msg("\n\r {rAccount name %s already exists.{n" % playername)
self.menutree.goto("node2a")
return
# store the name for the next step
self.menutree.playername = playername
self.caller.msg(echo=False)
self.menutree.goto("node2b")
# Menu entry 2b - Creating a Password
class CmdPasswordCreateBack(Command):
"Step back from the password creation"
key = CMD_NOINPUT
locks = "cmd:all()"
def func(self):
"Execute the command"
self.caller.msg(echo=True)
self.menutree.goto("node2a")
class CmdPasswordCreate(Command):
"Handle the creation of a password. This also creates the actual Player/User object."
key = CMD_NOMATCH
locks = "cmd:all()"
def func(self):
"Execute the command"
password = self.args
self.caller.msg(echo=False)
if not hasattr(self.menutree, 'playername'):
self.caller.msg("{rSomething went wrong! Playername not remembered from previous step!{n")
self.menutree.goto("node2a")
return
playername = self.menutree.playername
if len(password) < 3:
# too short password
string = "{rYour password must be at least 3 characters or longer."
string += "\n\rFor best security, make it at least 8 characters "
string += "long, avoid making it a real word and mix numbers "
string += "into it.{n"
self.caller.msg(string)
self.menutree.goto("node2b")
return
# everything's ok. Create the new player account. Don't create
# a Character here.
try:
permissions = settings.PERMISSION_PLAYER_DEFAULT
typeclass = settings.BASE_PLAYER_TYPECLASS
new_player = create_player(playername, None, password,
typeclass=typeclass,
permissions=permissions)
if not new_player:
self.msg("There was an error creating the Player. This error was logged. Contact an admin.")
self.menutree.goto("START")
return
utils.init_new_player(new_player)
# join the new player to the public channel
pchanneldef = settings.CHANNEL_PUBLIC
if pchanneldef:
pchannel = managers.channels.get_channel(pchanneldef[0])
if not pchannel.connect(new_player):
string = "New player '%s' could not connect to public channel!" % new_player.key
logger.log_errmsg(string)
# tell the caller everything went well.
string = "{gA new account '%s' was created. Now go log in from the menu!{n"
self.caller.msg(string % (playername))
self.menutree.goto("START")
except Exception:
# We are in the middle between logged in and -not, so we have
# to handle tracebacks ourselves at this point. If we don't, we
# won't see any errors at all.
string = "%s\nThis is a bug. Please e-mail an admin if the problem persists."
self.caller.msg(string % (traceback.format_exc()))
logger.log_errmsg(traceback.format_exc())
# Menu entry 3 - help screen
LOGIN_SCREEN_HELP = \
"""
Welcome to %s!
To login you need to first create an account. This is easy and
free to do: Choose option {w(1){n in the menu and enter an account
name and password when prompted. Obs- the account name is {wnot{n
the name of the Character you will play in the game!
It's always a good idea (not only here, but everywhere on the net)
to not use a regular word for your password. Make it longer than 3
characters (ideally 6 or more) and mix numbers and capitalization
into it. The password also handles whitespace, so why not make it
a small sentence - easy to remember, hard for a computer to crack.
Once you have an account, use option {w(2){n to log in using the
account name and password you specified.
Use the {whelp{n command once you're logged in to get more
aid. Hope you enjoy your stay!
(return to go back)""" % settings.SERVERNAME
# Menu entry 4
class CmdUnloggedinQuit(Command):
"""
We maintain a different version of the quit command
here for unconnected players for the sake of simplicity. The logged in
version is a bit more complicated.
"""
key = "4"
aliases = ["quit", "qu", "q"]
locks = "cmd:all()"
def func(self):
"Simply close the connection."
self.menutree.goto("END")
self.caller.sessionhandler.disconnect(self.caller, "Good bye! Disconnecting...")
# The login menu tree, using the commands above
START = MenuNode("START", text=utils.random_string_from_module(CONNECTION_SCREEN_MODULE),
links=["node1a", "node2a", "node3", "END"],
linktexts=["Log in with an existing account",
"Create a new account",
"Help",
"Quit"],
selectcmds=[None, None, None, CmdUnloggedinQuit])
node1a = MenuNode("node1a", text="Please enter your account name (empty to abort).",
links=["START", "node1b"],
helptext=["Enter the account name you previously registered with."],
keywords=[CMD_NOINPUT, CMD_NOMATCH],
selectcmds=[CmdBackToStart, CmdUsernameSelect],
nodefaultcmds=True) # if we don't, default help/look will be triggered by names starting with l/h ...
node1b = MenuNode("node1b", text="Please enter your password (empty to go back).",
links=["node1a", "END"],
keywords=[CMD_NOINPUT, CMD_NOMATCH],
selectcmds=[CmdPasswordSelectBack, CmdPasswordSelect],
nodefaultcmds=True)
node2a = MenuNode("node2a", text="Please enter your desired account name (empty to abort).",
links=["START", "node2b"],
helptext="Account name can max be 30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only.",
keywords=[CMD_NOINPUT, CMD_NOMATCH],
selectcmds=[CmdBackToStart, CmdUsernameCreate],
nodefaultcmds=True)
node2b = MenuNode("node2b", text="Please enter your password (empty to go back).",
links=["node2a", "START"],
helptext="Your password cannot contain any characters.",
keywords=[CMD_NOINPUT, CMD_NOMATCH],
selectcmds=[CmdPasswordCreateBack, CmdPasswordCreate],
nodefaultcmds=True)
node3 = MenuNode("node3", text=LOGIN_SCREEN_HELP,
links=["START"],
helptext="",
keywords=[CMD_NOINPUT],
selectcmds=[CmdBackToStart])
# access commands
class UnloggedInCmdSet(CmdSet):
"Cmdset for the unloggedin state"
key = "UnloggedinState"
priority = 0
def at_cmdset_creation(self):
"Called when cmdset is first created"
self.add(CmdUnloggedinLook())
class CmdUnloggedinLook(Command):
"""
An unloggedin version of the look command. This is called by the server
when the player first connects. It sets up the menu before handing off
to the menu's own look command..
"""
key = CMD_LOGINSTART
locks = "cmd:all()"
def func(self):
"Execute the menu"
menu = MenuTree(self.caller, nodes=(START, node1a, node1b,
node2a, node2b, node3),
exec_end=None)
menu.start()<|fim▁end|> | def func(self):
"Execute the command"
player = managers.players.get_player_from_name(self.args)
if not player: |
<|file_name|>CalcRSI.java<|end_file_name|><|fim▁begin|>package com.chariotinstruments.markets;
import java.util.ArrayList;
/**<|fim▁hole|>
private MarketDay marketDay;
private ArrayList<MarketCandle> marketCandles;
private double gainAverage;
private double lossAverage;
public CalcRSI(MarketDay marDay){
this.marketDay = marDay;
marketCandles = new ArrayList<MarketCandle>();
marketCandles = this.marketDay.getMarketCandles();
}
public double getGainAverage(){
return gainAverage;
}
public double getLossAverage(){
return lossAverage;
}
public double getCurrentRSI(){
double RSI = 0.0;
if(marketCandles.size()>1) {
getFirstAverages();
RSI = getRSI(gainAverage, lossAverage);
}
return RSI;
}
public void getFirstAverages(){
double curAmount = 0.0;
double prevAmount = 0.0;
double sum = 0.0;
double lastAmount = 0.0;
for(int i = 1; i < 15; i++) { //start from the beginning to get the first SMA
curAmount = marketCandles.get(i).getClose();
prevAmount = marketCandles.get(i-1).getClose();
sum = curAmount - prevAmount;
if(sum < 0){
lossAverage += (sum * -1);
}else{
gainAverage += sum;
}
}
lossAverage = lossAverage / 14;
gainAverage = gainAverage / 14;
getSmoothAverages(lossAverage, gainAverage);
}
public void getSmoothAverages(double lossAvg, double gainAvg){
double curAmount = 0.0;
double prevAmount = 0.0;
double lastAmount = 0.0;
//loop through the remaining amounts in the marketDay and calc the smoothed avgs
for(int i = 15; i < marketCandles.size(); i++){
curAmount = marketCandles.get(i).getClose();
prevAmount = marketCandles.get(i-1).getClose();
lastAmount = curAmount - prevAmount;
if(lastAmount < 0) {
lossAvg = ((lossAvg * 13) + (lastAmount * -1)) / 14;
gainAvg = ((gainAvg * 13) + 0) / 14;
}else{
lossAvg = ((lossAvg * 13) + 0) / 14;
gainAvg = ((gainAvg * 13) + lastAmount) / 14;
}
}
lossAverage = lossAvg;
gainAverage = gainAvg;
}
private double getRSI(double avgGain, double avgLoss){
double RS = avgGain/avgLoss;
double RSI = 0;
if(avgLoss > 0) {
RSI = (100 - (100 / (1 + RS)));
}else{
RSI = 100;
}
return RSI;
}
public String tester(){
String output = "";
for(int i = 0; i < marketCandles.size(); i++){
output = output + "\n" + Double.toString(marketCandles.get(i).getClose());
}
return output;
}
}<|fim▁end|> | * Created by user on 1/30/16.
*/
public class CalcRSI { |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>fn main() {
let mut numbers = Vec::new();
for arg in std::env::args().skip(1) {
numbers.push(u64::from_str(&arg).expect("error parsing argument"));
}
if numbers.len() == 0 {
writeln!(std::io::stderr(), "Usage: gcd NUMBER ...").unwrap();
std::process::exit(1);
}
let mut d = numbers[0];
for m in &numbers[1..] {
d = gcd(d, *m);
}
println!("The greatest common divisor of {:?} is {}", numbers, d);
}
fn gcd(mut n: u64, mut m: u64) -> u64 {
assert!(n != 0 && m != 0);
while m != 0 {
if m < n {
let t = m;
m = n;
n = t;
}
m = m % n;
}
n
}
#[test]
fn test_gcd() {
assert_eq!(gcd(2 * 3 * 5 * 11 * 17, 3 * 7 * 11 * 13 * 19), 3 * 11);
}<|fim▁end|> | use std::io::Write;
use std::str::FromStr;
|
<|file_name|>win32.py<|end_file_name|><|fim▁begin|>"""SCons.Platform.win32
Platform-specific initialization for Win32 systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "/home/scons/scons/branch.0/baseline/src/engine/SCons/Platform/win32.py 0.96.1.D001 2004/08/23 09:55:29 knight"
import os
import os.path
import string
import sys
import tempfile
from SCons.Platform.posix import exitvalmap
# XXX See note below about why importing SCons.Action should be
# eventually refactored.
import SCons.Action
import SCons.Util
class TempFileMunge:
"""A callable class. You can set an Environment variable to this,
then call it with a string argument, then it will perform temporary
file substitution on it. This is used to circumvent the win32 long command
line limitation.
Example usage:
env["TEMPFILE"] = TempFileMunge
env["LINKCOM"] = "${TEMPFILE('$LINK $TARGET $SOURCES')}"
"""
def __init__(self, cmd):
self.cmd = cmd
def __call__(self, target, source, env, for_signature):
if for_signature:
return self.cmd
cmd = env.subst_list(self.cmd, 0, target, source)[0]
try:
maxline = int(env.subst('$MAXLINELENGTH'))
except ValueError:
maxline = 2048
if (reduce(lambda x, y: x + len(y), cmd, 0) + len(cmd)) <= maxline:
return self.cmd
else:
# We do a normpath because mktemp() has what appears to be
# a bug in Win32 that will use a forward slash as a path
# delimiter. Win32's link mistakes that for a command line
# switch and barfs.
#
# We use the .lnk suffix for the benefit of the Phar Lap
# linkloc linker, which likes to append an .lnk suffix if
# none is given.
tmp = os.path.normpath(tempfile.mktemp('.lnk'))
native_tmp = SCons.Util.get_native_path(tmp)
if env['SHELL'] and env['SHELL'] == 'sh':
# The sh shell will try to escape the backslashes in the
# path, so unescape them.
native_tmp = string.replace(native_tmp, '\\', r'\\\\')
# In Cygwin, we want to use rm to delete the temporary
# file, because del does not exist in the sh shell.
rm = env.Detect('rm') or 'del'
else:
# Don't use 'rm' if the shell is not sh, because rm won't
# work with the win32 shells (cmd.exe or command.com) or
# win32 path names.
rm = 'del'
args = map(SCons.Util.quote_spaces, cmd[1:])
open(tmp, 'w').write(string.join(args, " ") + "\n")
# XXX Using the SCons.Action.print_actions value directly
# like this is bogus, but expedient. This class should
# really be rewritten as an Action that defines the
# __call__() and strfunction() methods and lets the
# normal action-execution logic handle whether or not to
# print/execute the action. The problem, though, is all
# of that is decided before we execute this method as
# part of expanding the $TEMPFILE construction variable.
# Consequently, refactoring this will have to wait until
# we get more flexible with allowing Actions to exist
# independently and get strung together arbitrarily like
# Ant tasks. In the meantime, it's going to be more
# user-friendly to not let obsession with architectural
# purity get in the way of just being helpful, so we'll
# reach into SCons.Action directly.
if SCons.Action.print_actions:
print("Using tempfile "+native_tmp+" for command line:\n"+
str(cmd[0]) + " " + string.join(args," "))
return [ cmd[0], '@' + native_tmp + '\n' + rm, native_tmp ]
# The upshot of all this is that, if you are using Python 1.5.2,
# you had better have cmd or command.com in your PATH when you run
# scons.
def piped_spawn(sh, escape, cmd, args, env, stdout, stderr):
# There is no direct way to do that in python. What we do
# here should work for most cases:
# In case stdout (stderr) is not redirected to a file,
# we redirect it into a temporary file tmpFileStdout
# (tmpFileStderr) and copy the contents of this file
# to stdout (stderr) given in the argument
if not sh:
sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n")
return 127
else:
# one temporary file for stdout and stderr
tmpFileStdout = os.path.normpath(tempfile.mktemp())
tmpFileStderr = os.path.normpath(tempfile.mktemp())
# check if output is redirected
stdoutRedirected = 0
stderrRedirected = 0<|fim▁hole|> stdoutRedirected = 1
# are there more possibilities to redirect stderr ?
if string.find( arg, "2>", 0, 2 ) != -1:
stderrRedirected = 1
# redirect output of non-redirected streams to our tempfiles
if stdoutRedirected == 0:
args.append(">" + str(tmpFileStdout))
if stderrRedirected == 0:
args.append("2>" + str(tmpFileStderr))
# actually do the spawn
try:
args = [sh, '/C', escape(string.join(args)) ]
ret = os.spawnve(os.P_WAIT, sh, args, env)
except OSError, e:
# catch any error
ret = exitvalmap[e[0]]
if stderr != None:
stderr.write("scons: %s: %s\n" % (cmd, e[1]))
# copy child output from tempfiles to our streams
# and do clean up stuff
if stdout != None and stdoutRedirected == 0:
try:
stdout.write(open( tmpFileStdout, "r" ).read())
os.remove( tmpFileStdout )
except (IOError, OSError):
pass
if stderr != None and stderrRedirected == 0:
try:
stderr.write(open( tmpFileStderr, "r" ).read())
os.remove( tmpFileStderr )
except (IOError, OSError):
pass
return ret
def spawn(sh, escape, cmd, args, env):
if not sh:
sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n")
return 127
else:
try:
args = [sh, '/C', escape(string.join(args)) ]
ret = os.spawnve(os.P_WAIT, sh, args, env)
except OSError, e:
ret = exitvalmap[e[0]]
sys.stderr.write("scons: %s: %s\n" % (cmd, e[1]))
return ret
# Windows does not allow special characters in file names anyway, so
# no need for a complex escape function, we will just quote the arg.
escape = lambda x: '"' + x + '"'
# Get the windows system directory name
def get_system_root():
# A resonable default if we can't read the registry
try:
val = os.environ['SYSTEMROOT']
except KeyError:
val = "C:/WINDOWS"
pass
# First see if we can look in the registry...
if SCons.Util.can_read_reg:
try:
# Look for Windows NT system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows NT\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
except SCons.Util.RegError:
try:
# Okay, try the Windows 9x system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
except KeyboardInterrupt:
raise
except:
pass
return val
# Get the location of the program files directory
def get_program_files_dir():
# Now see if we can look in the registry...
val = ''
if SCons.Util.can_read_reg:
try:
# Look for Windows Program Files directory
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'ProgramFilesDir')
except SCons.Util.RegError:
val = ''
pass
if val == '':
# A reasonable default if we can't read the registry
# (Actually, it's pretty reasonable even if we can :-)
val = os.path.join(os.path.dirname(get_system_root()),"Program Files")
return val
def generate(env):
# Attempt to find cmd.exe (for WinNT/2k/XP) or
# command.com for Win9x
cmd_interp = ''
# First see if we can look in the registry...
if SCons.Util.can_read_reg:
try:
# Look for Windows NT system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows NT\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
cmd_interp = os.path.join(val, 'System32\\cmd.exe')
except SCons.Util.RegError:
try:
# Okay, try the Windows 9x system root
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot')
cmd_interp = os.path.join(val, 'command.com')
except KeyboardInterrupt:
raise
except:
pass
# For the special case of not having access to the registry, we
# use a temporary path and pathext to attempt to find the command
# interpreter. If we fail, we try to find the interpreter through
# the env's PATH. The problem with that is that it might not
# contain an ENV and a PATH.
if not cmd_interp:
systemroot = r'C:\Windows'
if os.environ.has_key('SYSTEMROOT'):
systemroot = os.environ['SYSTEMROOT']
tmp_path = systemroot + os.pathsep + \
os.path.join(systemroot,'System32')
tmp_pathext = '.com;.exe;.bat;.cmd'
if os.environ.has_key('PATHEXT'):
tmp_pathext = os.environ['PATHEXT']
cmd_interp = SCons.Util.WhereIs('cmd', tmp_path, tmp_pathext)
if not cmd_interp:
cmd_interp = SCons.Util.WhereIs('command', tmp_path, tmp_pathext)
if not cmd_interp:
cmd_interp = env.Detect('cmd')
if not cmd_interp:
cmd_interp = env.Detect('command')
if not env.has_key('ENV'):
env['ENV'] = {}
# Import things from the external environment to the construction
# environment's ENV. This is a potential slippery slope, because we
# *don't* want to make builds dependent on the user's environment by
# default. We're doing this for SYSTEMROOT, though, because it's
# needed for anything that uses sockets, and seldom changes. Weigh
# the impact carefully before adding other variables to this list.
import_env = [ 'SYSTEMROOT' ]
for var in import_env:
v = os.environ.get(var)
if v:
env['ENV'][var] = v
env['ENV']['PATHEXT'] = '.COM;.EXE;.BAT;.CMD'
env['OBJPREFIX'] = ''
env['OBJSUFFIX'] = '.obj'
env['SHOBJPREFIX'] = '$OBJPREFIX'
env['SHOBJSUFFIX'] = '$OBJSUFFIX'
env['PROGPREFIX'] = ''
env['PROGSUFFIX'] = '.exe'
env['LIBPREFIX'] = ''
env['LIBSUFFIX'] = '.lib'
env['SHLIBPREFIX'] = ''
env['SHLIBSUFFIX'] = '.dll'
env['LIBPREFIXES'] = [ '$LIBPREFIX' ]
env['LIBSUFFIXES'] = [ '$LIBSUFFIX' ]
env['PSPAWN'] = piped_spawn
env['SPAWN'] = spawn
env['SHELL'] = cmd_interp
env['TEMPFILE'] = TempFileMunge
env['MAXLINELENGTH'] = 2048
env['ESCAPE'] = escape<|fim▁end|> | for arg in args:
# are there more possibilities to redirect stdout ?
if (string.find( arg, ">", 0, 1 ) != -1 or
string.find( arg, "1>", 0, 2 ) != -1): |
<|file_name|>TangramToolWindow.cpp<|end_file_name|><|fim▁begin|>/********************************************************************************
* Tangram Library - version 8.0 *
*********************************************************************************
* Copyright (C) 2002-2015 by Tangram Team. All Rights Reserved. *
*
* THIS SOURCE FILE IS THE PROPERTY OF TANGRAM TEAM AND IS NOT TO
* BE RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED
* WRITTEN CONSENT OF TANGRAM TEAM.
*
* THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS
* OUTLINED IN THE GPL LICENSE AGREEMENT.TANGRAM TEAM
* GRANTS TO YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE
* THIS SOFTWARE ON A SINGLE COMPUTER.
*
* CONTACT INFORMATION:
* mailto:[email protected]
* http://www.tangramFX.com
*
*
********************************************************************************/
#include "stdafx.h"
#include "CommonIncludes.h"
<|fim▁hole|>
const GUID& CTangramToolWnd::GetToolWindowGuid() const
{
return CLSID_guidPersistanceSlot;
}
void CTangramToolWnd::PostCreate()
{
CComVariant srpvt;
srpvt.vt = VT_I4;
srpvt.intVal = IDB_IMAGES;
// We don't want to make the window creation fail only becuase we can not set
// the icon, so we will not throw if SetProperty fails.
if (SUCCEEDED(GetIVsWindowFrame()->SetProperty(VSFPROPID_BitmapResource, srpvt)))
{
srpvt.intVal = 1;
GetIVsWindowFrame()->SetProperty(VSFPROPID_BitmapIndex, srpvt);
}
if (theApp.m_pTangramCore&&m_pPane)
{
HWND h = m_pPane->m_hWnd;
//Begin add By Tangram Team: Step 2
theApp.m_pTangramCore->put_ToolWndHandle((LONGLONG)(h));
theApp.m_hVSToolWnd = h;
theApp.m_pTangramCore->CreateTangram((LONGLONG)::GetParent(h), &m_pTangram);
if (m_pTangram)
{
CComBSTR strAppStartFilePath(L"res://StartupPage.dll/start.htm");
//CComBSTR strAppStartFilePath(L"http://tangramcloud.com/static/startup.html");
m_pTangram->put_URL(strAppStartFilePath);
}
}
//End add By Tangram Team!
}<|fim▁end|> | #include "TangramToolWindow.h"
#include "TangramVSIApp.h"
|
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>#[macro_use] extern crate nickel;
extern crate tera;
extern crate postgres;
use postgres::{Connection, SslMode};
use nickel::{Nickel, HttpRouter, StaticFilesHandler, FormBody};
use tera::{Tera, Context};
use std::collections::HashMap;
//use std::str;
fn main() {
//Initialize nickel instance
let mut server: Nickel = Nickel::new();
//Enable static file handling
server.utilize(StaticFilesHandler::new("/var/www/ninetytwo/static/"));
//set tera root
let templates = Tera::new("/var/www/ninetytwo/templates/*");
//DB Models
struct Message{
_id: u32,
body: String,
email: String,
}
macro_rules! page {
($view_name: ident, $context: ident) => (
let html_path = str::replace(stringify!($view_name), "_", "/");
let template_name = html_path.to_string() + ".html";
let html: String = templates.render(template_name.as_str(), $context).unwrap();
if stringify!($view_name) == "index"{
server.get("/", middleware!(html.as_str()));
}
else{
let path = str::replace(stringify!($view_name), "_", "/");
let route = "/".to_string() + path.as_str();
server.get(route, middleware!(html.as_str()));
}
)
}
//Routing
//Home Page
let mut index_data = HashMap::new();<|fim▁hole|> index_data.insert("name", "ninetytwo");
index_data.insert("description", "The source code for this website.");
index_data.insert("langs", "HTML | CSS | JavaScript | Rust");
index_data.insert("link", "https://github.com/ninetytwo/ninetytwo.ml");
let projects = [index_data];
let mut index_context = Context::new();
index_context.add("projects", &projects);
page!(index, index_context);
server.post("/", middleware!{ |req, res|
let form_data = try_with!(res, req.form_body());
let mut _id_num: u32 = 0;
let message = Message{
_id: _id_num,
body: form_data.get("message").unwrap_or("No Text").to_string(),
email: form_data.get("email").unwrap_or("No Email").to_string()
};
_id_num = _id_num + 1;
let ninetytwo_db = Connection::connect("postgres://[email protected]:5432/ninetytwo", SslMode::None).unwrap();
ninetytwo_db.execute("INSERT INTO message (body, email) VALUES ($1, $2);",
&[&message.body, &message.email]).unwrap();
println!("{}\n{}", form_data.get("message").unwrap_or("nonne"), form_data.get("email").unwrap_or("nonne"));
let mut test_context = Context::new();
test_context.add("projects", &projects);
let html: String = templates.render("index.html", test_context).unwrap();
html
});
server.listen("0.0.0.0:3000");
}
#[macro_use] extern crate nickel;
extern crate tera;
extern crate postgres;
use postgres::{Connection, SslMode};
use nickel::{Nickel, HttpRouter, StaticFilesHandler, FormBody};
use tera::{Tera, Context};
use std::collections::HashMap;
//use std::str;
fn main() {
//Initialize nickel instance
let mut server: Nickel = Nickel::new();
//Enable static file handling
server.utilize(StaticFilesHandler::new("/var/www/ninetytwo/static/"));
//set tera root
let templates = Tera::new("/var/www/ninetytwo/templates/*");
//DB Models
struct Message{
_id: u32,
body: String,
email: String,
}
macro_rules! page {
($view_name: ident, $context: ident) => (
let html_path = str::replace(stringify!($view_name), "_", "/");
let template_name = html_path.to_string() + ".html";
let html: String = templates.render(template_name.as_str(), $context).unwrap();
if stringify!($view_name) == "index"{
server.get("/", middleware!(html.as_str()));
}
else{
let path = str::replace(stringify!($view_name), "_", "/");
let route = "/".to_string() + path.as_str();
server.get(route, middleware!(html.as_str()));
}
)
}
//Routing
//Home Page
let mut index_data = HashMap::new();
index_data.insert("name", "ninetytwo");
index_data.insert("description", "The source code for this website.");
index_data.insert("langs", "HTML | CSS | JavaScript | Rust");
index_data.insert("link", "https://github.com/ninetytwo/ninetytwo.ml");
let projects = [index_data];
let mut index_context = Context::new();
index_context.add("projects", &projects);
page!(index, index_context);
server.post("/", middleware!{ |req, res|
let form_data = try_with!(res, req.form_body());
let mut _id_num: u32 = 0;
let message = Message{
_id: _id_num,
body: form_data.get("message").unwrap_or("No Text").to_string(),
email: form_data.get("email").unwrap_or("No Email").to_string()
};
_id_num = _id_num + 1;
let ninetytwo_db = Connection::connect("postgres://[email protected]:5432/ninetytwo", SslMode::None).unwrap();
ninetytwo_db.execute("INSERT INTO message (body, email) VALUES ($1, $2);",
&[&message.body, &message.email]).unwrap();
println!("{}\n{}", form_data.get("message").unwrap_or("nonne"), form_data.get("email").unwrap_or("nonne"));
let mut test_context = Context::new();
test_context.add("projects", &projects);
let html: String = templates.render("index.html", test_context).unwrap();
html
});
server.listen("0.0.0.0:3000");
}<|fim▁end|> | |
<|file_name|>role.doc.js<|end_file_name|><|fim▁begin|>/**
* getRoles - get all roles
*
* @api {get} /roles Get all roles
* @apiName GetRoles
* @apiGroup Role
*
*
* @apiSuccess {Array[Role]} raw Return table of roles
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* [
* {
* "id": 1,
* "name": "Administrator",
* "slug": "administrator"
* }
* ]
*
* @apiUse InternalServerError
*/
/**
* createRole - create new role
*
* @api {post} /roles Create a role
* @apiName CreateRole
* @apiGroup Role
* @apiPermission admin
*
* @apiParam {String} name Name of new role
* @apiParam {String} slug Slug from name of new role
*
* @apiSuccess (Created 201) {Number} id Id of new role
* @apiSuccess (Created 201) {String} name Name of new role
* @apiSuccess (Created 201) {String} slug Slug of new role
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 201 Created
* {
* "id": 3,
* "name": "Custom",
* "slug": "custom"
* }
*
* @apiUse BadRequest
* @apiUse InternalServerError
*/
/**
* getRole - get role by id
*
* @api {get} /roles/:id Get role by id
* @apiName GetRole
* @apiGroup Role
*
* @apiSuccess {Number} id Id of role
* @apiSuccess {String} name Name of role
* @apiSuccess {String} slug Slug of role
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "id": 2,
* "name": "User",
* "slug": "user"
* }
*
* @apiUse NotFound
* @apiUse InternalServerError
*/
/**
* updateRole - update role
*
* @api {put} /roles/:id Update role from id
* @apiName UpdateRole
* @apiGroup Role
* @apiPermission admin
*
*
* @apiParam {String} name New role name
* @apiParam {String} slug New role slug
*
* @apiSuccess {Number} id Id of role
* @apiSuccess {String} name Name of role
* @apiSuccess {String} slug Slug of role<|fim▁hole|> * @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "id": 3,
* "name": "Customer",
* "slug": "customer"
* }
*
* @apiUse NotFound
* @apiUse BadRequest
* @apiUse InternalServerError
*/
/**
* deleteRole - delete role
*
* @api {delete} /roles/:id Delete role from id
* @apiName DeleteRole
* @apiGroup Role
* @apiPermission admin
*
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 204 No Content
*
* @apiUse NotFound
* @apiUse BadRequest
* @apiUse InternalServerError
*/<|fim▁end|> | |
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.db.models import Q
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.utils.timezone import now
from django.conf import settings
from django import template # import Template,Context
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.utils.deconstruct import deconstructible
from email import message_from_string
from celery.result import AsyncResult
from bs4 import BeautifulSoup as Soup
import traceback
import re
from utils import (
create_auto_secret,
create_auto_short_secret,
expire,
get_template_source,
)
import json
import logging
logger = logging.getLogger('paloma')
DEFAULT_RETURN_PATH_RE = r"bcmsg-(?P<message_id>\d+)@(?P<domain>.+)"
DEFAULT_RETURN_PATH_FORMAT = "bcmsg-%(message_id)s@%(domain)s"
RETURN_PATH_RE = r"^(?P<commnad>.+)-(?P<message_id>\d+)@(?P<domain>.+)"
RETURN_PATH_FORMAT = "%(command)s-%(message_id)s@%(domain)s"
def return_path_from_address(address):
return re.search(
DEFAULT_RETURN_PATH_RE,
address).groupdict()
def default_return_path(param):
return DEFAULT_RETURN_PATH_FORMAT % param
def read_return_path(address):
return re.search(
RETURN_PATH_RE,
address).groupdict()
def make_return_path(param):
return RETURN_PATH_FORMAT % param
def MDT(t=None):
return (t or now()).strftime('%m%d%H%M%S')
@deconstructible
class Domain(models.Model):
''' Domain
- virtual_transport_maps.cf
'''
domain = models.CharField(
_(u'Domain'),
unique=True, max_length=100, db_index=True, )
''' Domain
- key for virtual_transport_maps.cf
- key and return value for virtual_domains_maps.cf
'''
description = models.CharField(
_(u'Description'),
max_length=200, default='')
maxquota = models.BigIntegerField(null=True, blank=True, default=None)
quota = models.BigIntegerField(null=True, blank=True, default=None)
transport = models.CharField(max_length=765)
'''
- virtual_transport_maps.cf looks this for specified **domain**.
'''
backupmx = models.IntegerField(null=True, blank=True, default=None)
active = models.BooleanField(default=True)
class Meta:
verbose_name = _(u'Domain')
verbose_name_plural = _(u'Domains')
@deconstructible
class Alias(models.Model):
''' Alias
- local user - maildir
- remote user - alias
- for virtual_alias_maps.cf
'''
address = models.CharField(
_('Alias Address'), max_length=100)
'''
- key for virtual_alias_maps.cf
'''
alias = models.CharField(
_('Alias Forward'), max_length=100)
'''
- value for virtual_alias_maps.cf
'''
mailbox = models.CharField(
_(u'Mailbox'),
max_length=100, null=True, default=None, blank=True,
help_text=u'specify Maildir path if address is local user ')
'''
- for local usr
- value for virtual_alias_maps.cf
'''
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _('Alias')
verbose_name_plural = _('Alias')
unique_together = (('address', 'alias', ), )
##
class AbstractProfile(models.Model):
''' Profile meta class'''
def target_context(self, member):
""" override this to return context dict for template rendering """
raise NotImplementedError
@classmethod
def target(cls, obj, *args, **kwargs):
context = {}
subclasses = cls.__subclasses__()
for ref in obj._meta.get_all_related_objects():
if ref.model in subclasses:
try:
context.update(
getattr(obj, ref.var_name
).target_context(*args, **kwargs)
)
except Exception:
pass
return context
class Meta:
abstract = True
@deconstructible
class Site(models.Model):
''' Site
'''
name = models.CharField(
_(u'Owner Site Name'), help_text=_(u'Owner Site Name'),
max_length=100, db_index=True, unique=True)
''' Site Name '''
domain = models.CharField(
_(u'@Domain'), help_text=_(u'@Domain'),
max_length=100, default='localhost',
db_index=True, unique=True, null=False, blank=False, )
''' @Domain'''
url = models.CharField(
_(u'URL'), help_text=_(u'URL'),
max_length=150, db_index=True, unique=True, default="/",)
''' URL path '''
operators = models.ManyToManyField(
User, help_text=_('User'), verbose_name=_(u'Site Operators'))
''' Site Operators '''
class Meta:
verbose_name = _('Site')
verbose_name_plural = _('Site')
unique_together = (('name', 'domain'), )
@property
def authority_address(self):
return "{0}@{1}".format(self.name, self.domain)
@property
def default_circle(self):
try:
return self.circle_set.get(is_default=True,)
except:
#: if no, get default:
name = getattr(settings, 'PALOMA_NAME', 'all')
return self.circle_set.get_or_create(
site=self, name=name, symbol=name,)[0]
def __unicode__(self):
return self.domain
@classmethod
def app_site(cls):
name = getattr(settings, 'PALOMA_NAME', 'paloma')
domain = getattr(settings, 'PALOMA_DEFAULT_DOMAIN', 'example.com')
return Site.objects.get_or_create(name=name, domain=domain)[0]
# Mesage Tempalte
class TemplateManager(models.Manager):
def get_template(self, name, site=None):
site = site or Site.app_site()
ret, created = self.get_or_create(site=site, name=name)
if created or not ret.subject or not ret.text:
try:
path = 'paloma/mails/default_%s.html' % name.lower()
source = Soup(get_template_source(path))
ret.subject = source.select('subject')[0].text
ret.subject = ret.subject.replace('\n', '').replace('\r', '')
ret.text = source.select('text')[0].text
ret.save()
except Exception:
logger.debug(traceback.format_exc())
return ret
@deconstructible
class Template(models.Model):
''' Site Notice Text '''
site = models.ForeignKey(Site, verbose_name=_(u'Owner Site'))
''' Owner Site'''
name = models.CharField(
_(u'Template Name'),
max_length=200, db_index=True,)
''' Notice Name'''
subject = models.CharField(
_(u'Template Subject'),
max_length=100, default='',)
''' Subject '''
text = models.TextField(
_(u'Template Text'), default='',)
''' Text '''
objects = TemplateManager()
@classmethod
def get_default_template(cls, name='DEFAULT_TEMPLATE', site=None):
site = site or Site.app_site()
return Template.objects.get_or_create(site=site, name=name,)[0]
def render(self, *args, **kwargs):
'''
:param kwargs: Context dictionary
'''
return tuple([template.Template(t).render(template.Context(kwargs))
for t in [self.subject, self.text]])
def __unicode__(self):
return self.name
class Meta:
unique_together = (('site', 'name'),)
verbose_name = _(u'Template')
verbose_name_plural = _(u'Templates')
@deconstructible
class Targetting(models.Model):
''' '''
site = models.ForeignKey(Site, verbose_name=_(u'Owner Site'))
''' Owner Site'''
targetter_content_type = models.ForeignKey(
ContentType,
related_name="targetter")
''' targetter model class'''
targetter_object_id = models.PositiveIntegerField()
''' tragetter object id '''
targetter = generic.GenericForeignKey(
'targetter_content_type',
'targetter_object_id')
''' targgetter instance '''
mediator_content_type = models.ForeignKey(
ContentType,
related_name="mediator")
''' mediator model class'''
mediator_object_id = models.PositiveIntegerField()
''' mediator object id '''
mediator = generic.GenericForeignKey('mediator_content_type',
'mediator_object_id')
''' mediator instance '''
def __unicode__(self):
return self.targetter.__unicode__()
class CircleManager(models.Manager):
def find_for_domain(self, domain, symbol=None):
q = {'site__domain': domain}
if symbol is None or symbol == '':
q['is_default'] = True
else:
q['symbol'] = symbol
return self.get(**q)
def accessible_list(self, user):
return self.filter(
Q(membership__member__user=user) | Q(is_secret=False)
).distinct()
def of_user(self, user):
return self.filter(membership__member__user=user)
def of_user_exclusive(self, user):
return self.exclude(membership__member__user=user)
def of_admin(self, user):
return self.filter(membership__member__user=user,
membership__is_admin=True)
@deconstructible
class Circle(models.Model):
''' Circle
'''
site = models.ForeignKey(
Site, verbose_name=_(u'Owner Site'))
''' Owner Site'''
name = models.CharField(
_(u'Circle Name'), max_length=100, db_index=True)
''' Circle Name '''
description = models.TextField(
_(u'Circle Description'), null=True, default=None, blank=True)
symbol = models.CharField(
_(u'Circle Symbol'), max_length=100, db_index=True,
help_text=_(u'Circle Symbol Help Text'), )
''' Symbol '''
is_default = models.BooleanField(
_(u'Is Default Circle'), default=False,
help_text=_('Is Default Circle Help'),)
''' Site's Default Circle or not '''
is_moderated = models.BooleanField(
_(u'Is Moderated Circle'),
default=True, help_text=_('Is Moderated Circle Help'), )
''' True: Only operators(Membership.is_admin True)
can circulate their message.'''
is_secret = models.BooleanField(
_(u'Is Secret Circle'),
default=False, help_text=_('Is Secret Circle Help'), )
''' True: only membership users know its existence '''
objects = CircleManager()
def __unicode__(self):
return "%s of %s" % (self.name, self.site.__unicode__())
@property
def main_address(self):
return "%s@%s" % (self.symbol, self.site.domain)
@property
def domain(self):
return self.site.domain
def save(self, **kwargs):
if self.is_default:
self.site.circle_set.update(is_default=False)
else:
query = () if self.id is None else (~Q(id=self.id), )
if self.site.circle_set.filter(
is_default=True, *query).count() < 1:
self.is_default = True
super(Circle, self).save(**kwargs)
def is_admin_user(self, user):
return user.is_superuser or self.membership_set.filter(
member__user=user, is_admin=True).exists()
def is_admin(self, user):
return user.is_superuser or self.membership_set.filter(
member__user=user, is_admin=True).exists()
def is_operator(self, user):
return user.is_superuser or self.membership_set.filter(
member__user=user, is_admin=True).exists()
def is_member(self, user):
return self.membership_set.filter(
member__user=user, is_admitted=True).exists()
@property
def memberships(self):
return self.membership_set.all()
def membership_for_user(self, user):
try:
return self.membership_set.get(member__user=user)
except:
return None
@property
def memberships_unadmitted(self):
return self.membership_set.filter(is_admitted=False)
def are_member(self, users):
''' all users are member of this Circle '''
return all(
map(lambda u: self.membership_set.filter(member__user=u).exists(),
users))
pass
def any_admin(self):
try:
admin_list = self.membership_set.filter(is_admin=True)
if admin_list.count() > 0:
return admin_list[0]
return User.objects.filter(is_superuser=True)[0]
except Exception:
logger.debug(traceback.format_exc())
return None
def add_member(self, member, is_admin=False, is_admitted=False):
membership, created = Membership.objects.get_or_create(circle=self,
member=member)
membership.is_admin = is_admin
membership.is_admitted = is_admitted
membership.save()
return membership
class Meta:
unique_together = (
('site', 'name'),
('site', 'symbol'),)
verbose_name = _(u'Circle')
verbose_name_plural = _(u'Circles')
@deconstructible
class Member(models.Model):
''' Member
- a system user can have multiple personality
'''
user = models.ForeignKey(User, verbose_name=_(u'System User'))
''' System User '''
address = models.CharField(_(u'Forward address'),
max_length=100, unique=True)
''' Email Address
'''
is_active = models.BooleanField(_(u'Actaive status'), default=False)
''' Active Status '''
bounces = models.IntegerField(_(u'Bounce counts'), default=0)
''' Bounce count'''
circles = models.ManyToManyField(Circle,
through='Membership',
verbose_name=_(u'Opt-in Circle'))
''' Opt-In Circles'''
def __unicode__(self):
return "%s(%s)" % (
self.user.__unicode__() if self.user else "unbound user",
self.address if self.address else "not registered",
)
def reset_password(self, active=False):
''' reset password '''
newpass = User.objects.make_random_password()
self.user.set_password(newpass)
self.user.is_active = active
self.user.save()
return newpass
def get_absolute_url(self):
''' Django API '''
return None
# return self.user.get_absolute_url() if self.user else None
class Meta:
verbose_name = _(u'Member')
verbose_name_plural = _(u'Members')
@deconstructible
class Membership(models.Model):
member = models.ForeignKey(Member, verbose_name=_(u'Member'))
''' Member ( :ref:`paloma.models.Member` ) '''
circle = models.ForeignKey(Circle, verbose_name=_(u'Circle'))
''' Circle ( :ref:`paloma.models.Circle` )'''
is_admin = models.BooleanField(_(u'Is Circle Admin'), default=False)
is_admitted = models.BooleanField(
_(u'Is Membership Admitted'),
default=False,
help_text=_(u'Is Membership Admitted Help'))
''' Member must be admitted by a Circle Admin to has a Membership '''
def is_member_active(self):
return self.member.is_active
is_member_active.short_description = _(u"Is Member Active")
def is_user_active(self):
return self.member.user.is_active
is_user_active.short_description = _(u"Is User Active")
def user(self):
return self.member.user
def __unicode__(self):
return "%s -> %s(%s)" % (
self.member.__unicode__() if self.member else "N/A",
self.circle.__unicode__() if self.circle else "N/A",
_(u"Circle Admin") if self.is_admin else _(u"General Member"),)
def get_absolute_url(self):
''' Django API '''
# if self.member and self.member.user:
# return self.member.user.get_absolute_url()
return None
class Meta:
unique_together = (('member', 'circle', ), )
verbose_name = _(u'Membership')
verbose_name_plural = _(u'Memberships')
PUBLISH_STATUS = (
('pending', _('Pending')),
('scheduled', _('Scheduled')),
('active', _('Active')),
('finished', _('Finished')),
('canceled', _('Canceled')),)
@deconstructible
class Publish(models.Model):
''' Message Delivery Publish'''
site = models.ForeignKey(Site, verbose_name=_(u'Site'),)
''' Site '''
publisher = models.ForeignKey(User, verbose_name=_(u'Publisher'))
''' publisher '''
messages = models.ManyToManyField('Message',
through="Publication",
verbose_name=_("Messages"),
related_name="message_set",)
subject = models.CharField(_(u'Subject'), max_length=101,)
''' Subject '''
text = models.TextField(_(u'Text'), )
''' Text '''
circles = models.ManyToManyField(Circle, verbose_name=_(u'Target Circles'))
''' Circle'''
task_id = models.CharField(_(u'Task ID'),
max_length=40, default=None,
null=True, blank=True,)
''' Task ID '''
status = models.CharField(_(u"Publish Status"), max_length=24,
db_index=True,
help_text=_('Publish Status Help'),
default="pending", choices=PUBLISH_STATUS)
dt_start = models.DateTimeField(
_(u'Time to Send'),
help_text=_(u'Time to Send Help'),
null=True, blank=True, default=now)
''' Stat datetime to send'''
activated_at = models.DateTimeField(
_(u'Task Activated Time'),
help_text=_(u'Task Activated Time Help'),
null=True, blank=True, default=None)
''' Task Activated Time '''
forward_to = models.CharField(
_(u'Forward address'),
max_length=100, default=None, null=True, blank=True)
''' Forward address for incomming email '''
targettings = generic.GenericRelation(
Targetting,
verbose_name=_('Optional Targetting'),
object_id_field="mediator_object_id",
content_type_field="mediator_content_type")
def __unicode__(self):
if self.dt_start:
return self.subject + self.dt_start.strftime(
"(%Y-%m-%d %H:%M:%S) by " + self.publisher.__unicode__())
else:
return self.subject + "(now)"
def get_context(self, circle, user):
context = {}
for ref in self._meta.get_all_related_objects():
if ref.model in AbstractProfile.__subclasses__():
try:
context.update(
getattr(self,
ref.var_name).target_context(circle, user)
)
except Exception:
pass
return context
def target_members_for_user(self, user):
return Member.objects.filter(
membership__circle__in=self.circles.all(),
user=user)
@property
def is_timeup(self):
return self.dt_start is None or self.dt_start <= now()
@property
def task(self):
try:
return AsyncResult(self.task_id)
except:
return None
class Meta:
verbose_name = _(u'Publish')
verbose_name_plural = _(u'Publish')
####
class JournalManager(models.Manager):
''' Message Manager'''
def handle_incomming_mail(self, sender, is_jailed, recipient, mssage):
'''
:param mesage: :py:class:`email.Message`
'''
pass
@deconstructible
class Journal(models.Model):
''' Raw Message
'''
dt_created = models.DateTimeField(
_(u'Journaled Datetime'),
help_text=_(u'Journaled datetime'), auto_now_add=True)
''' Journaled Datetime '''
sender = models.CharField(u'Sender', max_length=100)
''' sender '''
recipient = models.CharField(u'Receipient', max_length=100)
''' recipient '''
text = models.TextField(
_(u'Message Text'), default=None, blank=True, null=True)
''' Message text '''
is_jailed = models.BooleanField(_(u'Jailed Message'), default=False)
''' Jailed(Reciepient missing emails have been journaled) if true '''
def mailobject(self):
''' return mail object
:rtype: email.message.Message
'''
# print ">>>>> type", type(self.text)
return message_from_string(self.text.encode('utf8'))
class Meta:
verbose_name = _(u'Journal')
verbose_name_plural = _(u'Journals')
def forwards(self):
return Alias.objects.filter(address=self.recipient)
def forward_from(self):
return "jfwd-{0}@{1}".format(
self.id,
self.recipient.split('@')[1],
)
try:
from rsyslog import Systemevents, Systemeventsproperties
Systemevents()
Systemeventsproperties()
except:
pass
@deconstructible
class MessageManager(models.Manager):
def create_from_template(self,
member_or_recepient,
template_name,
params={},
message_id=None,
circle=None):
''' Create Message from specified Template '''
template_name = template_name.lower()
msg = {
'circle': circle,
}
member = None
recipient = None
if type(member_or_recepient) == Member:
member = member_or_recepient
elif type(member_or_recepient) == Membership:
member = member_or_recepient.member
circle = member_or_recepient.circle
else: # str
recipient = member_or_recepient
site = msg['circle'].site if msg['circle'] else Site.app_site()
# load tempalte from storage
template = Template.objects.get_template(site=site,
name=template_name)<|fim▁hole|> try:
mail, created = self.get_or_create(mail_message_id=message_id)
mail.cirlce = circle
mail.template = template
mail.member = member
mail.recipient = recipient
mail.render(**params)
mail.save()
return mail
except Exception, e:
for err in traceback.format_exc().split('\n'):
logger.debug('send_template_mail:error:%s:%s' % (str(e), err))
return None
@deconstructible
class Message(models.Model):
''' Message '''
mail_message_id = models.CharField(u'Message ID', max_length=100,
db_index=True, unique=True)
''' Mesage-ID header - 'Message-ID: <local-part "@" domain>' '''
template = models.ForeignKey(Template, verbose_name=u'Template',
null=True, on_delete=models.SET_NULL)
''' Message Template '''
member = models.ForeignKey(Member, verbose_name=u'Member',
null=True, default=None, blank=True,
on_delete=models.SET_NULL)
''' Recipient Member (member.circle is Sender)'''
circle = models.ForeignKey(Circle, verbose_name=u'Circle',
null=True, default=None, blank=True,
on_delete=models.SET_NULL)
''' Target Circle ( if None, Site's default circle is used.)'''
recipient = models.EmailField(u'recipient', max_length=50,
default=None, blank=True, null=True)
''' Recipient (for non-Member )'''
subject = models.TextField(u'Message Subject', default=None,
blank=True, null=True)
''' Message Subject '''
text = models.TextField(_(u'Message Text'), default=None,
blank=True, null=True)
''' Message text '''
status = models.CharField(u'Status', max_length=50,
default=None, blank=True, null=True)
''' SMTP Status '''
task_id = models.CharField(u'Task ID', max_length=40,
default=None, null=True, blank=True, )
''' Task ID '''
checked = models.BooleanField(_(u'Mail Checked'), default=False, )
created = models.DateTimeField(_(u'Created'), auto_now_add=True)
updated = models.DateTimeField(_(u'Updated'), auto_now=True)
smtped = models.DateTimeField(_(u'SMTP Time'),
default=None, blank=True, null=True)
parameters = models.TextField(blank=True, null=True, )
''' extra parameters '''
_context_cache = None
''' Base Text'''
objects = MessageManager()
def __init__(self, *args, **kwargs):
super(Message, self).__init__(*args, **kwargs)
if self.template is None:
self.template = Template.get_default_template()
def __unicode__(self):
try:
return self.template.__unicode__() + str(self.recipients)
except:
return unicode(self.id)
@property
def task(self):
try:
return AsyncResult(self.task_id)
except:
return None
@property
def recipients(self): # plural!!!!
return [self.recipient] if self.recipient else [self.member.address]
def context(self, **kwargs):
''' "text" and "subject" are rendered with this context
- member : paloma.models.Member
- template : paloma.models.Template
- kwargs : extra parameters
- [any] : JSON serialized dict save in "parameters"
'''
ret = {"member": self.member, "template": self.template, }
ret.update(kwargs)
try:
ret.update(json.loads(self.parameters))
except:
pass
return ret
def render(self, do_save=True, **kwargs):
''' render for member in circle'''
if self.template:
self.text = template.Template(
self.template.text
).render(template.Context(self.context(**kwargs)))
self.subject = template.Template(
self.template.subject
).render(template.Context(self.context(**kwargs)))
if do_save:
self.save()
@property
def from_address(self):
circle = self.circle or self.template.site.default_circle
return circle.main_address
@property
def return_path(self):
''' default return path '''
return make_return_path({"command": "msg", "message_id": self.id,
"domain": self.template.site.domain})
def set_status(self, status=None, smtped=None, do_save=True):
self.smtped = smtped
self.status = status
if do_save:
self.save()
@classmethod
def update_status(cls, msg, **kwargs):
for m in cls.objects.filter(
mail_message_id=kwargs.get('message_id', '')):
m.set_status(msg, now())
class Meta:
verbose_name = _(u'Message')
verbose_name_plural = _(u'Messages')
@deconstructible
class Provision(models.Model):
''' Account Provision management
'''
member = models.OneToOneField(Member, verbose_name=_(u'Member'),
on_delete=models.SET_NULL,
null=True, default=None, blank=True)
''' Member'''
status = models.CharField(_(u"Provision Status"),
max_length=24, db_index=True,)
''' Provisioning Status'''
circle = models.ForeignKey(Circle, verbose_name=_(u'Circle'),
null=True, default=None, blank=True,
on_delete=models.SET_NULL)
''' Circle'''
inviter = models.ForeignKey(User, verbose_name=_(u'Inviter'),
null=True, default=None, blank=True,
on_delete=models.SET_NULL)
''' Inviter'''
prospect = models.CharField(_(u'Provision Prospect'),
max_length=100, default=None,
null=True, blank=True)
''' Prospect Email Address'''
secret = models.CharField(
_(u'Provision Secret'),
max_length=100,
default='',
unique=True)
''' Secret
'''
short_secret = models.CharField(
_(u'Provision Short Secret'),
max_length=10, unique=True,
default='')
''' Short Secret
'''
url = models.CharField(_(u'URL for Notice'),
max_length=200, default=None, null=True, blank=True)
''' URL for notice '''
dt_expire = models.DateTimeField(
_(u'Provision Secret Expired'),
null=True, blank=True,
default=None,
help_text=u'Secrete Expired', )
''' Secrete Expired'''
dt_try = models.DateTimeField(_(u'Provision Try Datetime'),
null=True, blank=True, default=None,
help_text=u'Try Datetime', )
''' Try Datetime'''
dt_commit = models.DateTimeField(_(u'Commit Datetime'),
null=True, blank=True, default=None,
help_text=u'Commit Datetime', )
''' Commit Datetime'''
def __init__(self, *args, **kwargs):
super(Provision, self).__init__(*args, **kwargs)
self.dt_expire = self.dt_expire or expire()
self.secret = self.secret or create_auto_secret()
self.short_secret = self.short_secret or create_auto_short_secret()
def is_open(self, dt_now=None):
''' check if this is open status or not
'''
dt_now = dt_now if dt_now else now()
return (self.dt_commit is None) and \
(self.dt_expire > dt_now) and \
(self.mailbox is not None) and \
(self.group is not None)
def close(self):
''' close this enroll management
'''
self.dt_commit = now()
self.save()
def provided(self, user, address, is_active=True):
self.member = Member.objects.get_or_create(
user=user, address=address)[0]
self.member.is_active = is_active
self.member.save()
if self.circle:
membership, created = Membership.objects.get_or_create(
circle=self.circle, member=self.member)
membership.is_admitted = is_active
membership.save()
self.dt_commit = now()
self.save()
return membership
def reset(self, save=False):
self.secret = create_auto_secret()
self.short_secret = create_auto_short_secret()
self.dt_commit = None
self.dt_expire = expire()
if save:
self.save()
def send_response(self):
''' send response mail
'''
from paloma.tasks import send_templated_message
mail_message_id = u"%s-up-%d@%s" % (self.circle.symbol,
self.id,
self.circle.site.domain)
name = "provision_%s" % self.status
recipient = self.member and self.member.address or self.prospect
send_templated_message(
recipient,
name,
params={'provision': self},
message_id=mail_message_id,
)
logger.debug(_('Provision %(provision)s is sent for %(to)s') % {
"provision": name,
"to": str(recipient)})
class Meta:
verbose_name = _('Provision')
verbose_name_plural = _('Provisions')
class PublicationManager(models.Manager):
def publish(self, publish, circle, member, signature='pub'):
assert all([publish, circle, member])
msgid = "<%s-%d-%d-%d@%s>" % (
signature, publish.id,
circle.id, member.id, circle.domain)
ret, created = self.get_or_create(
publish=publish,
message=Message.objects.get_or_create(
mail_message_id=msgid,
template=Template.get_default_template('PUBLICATION'),
circle=circle,
member=member,)[0] # (object,created )
)
ret.render()
ret.save()
return ret
@deconstructible
class Publication(models.Model):
''' Each Published Item
'''
publish = models.ForeignKey(Publish, verbose_name=_(u'Publish'))
''' Mail Schedule'''
message = models.ForeignKey(Message, verbose_name=_(u'Mail Message'))
''' Message '''
objects = PublicationManager()
def context(self, **kwargs):
ret = self.message.context(**kwargs)
ret['publish'] = self.publish
#: Circle & Member Targetting
ret.update(
AbstractProfile.target(self.message.circle, self.message.member)
)
#:AdHoc Targetting
for t in self.publish.targettings.all():
try:
ret.update(t.target(self))
except:
pass
return ret
def render(self, **kwargs):
''' render for member in circle'''
self.message.text = template.Template(
self.publish.text
).render(template.Context(self.context(**kwargs)))
self.message.subject = template.Template(
self.publish.subject
).render(template.Context(self.context(**kwargs)))
self.message.save()<|fim▁end|> | message_id = message_id or \
"msg-%s-%s@%s" % (template_name, MDT(), site.domain)
# create |
<|file_name|>Ask_For_Record_Details_Confirmation.py<|end_file_name|><|fim▁begin|>## This file is part of Invenio.
## Copyright (C) 2008, 2010, 2011 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## Invenio is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Display the details of a record on which some operation is to be carried
out and prompt for the user's confirmation that it is the correct record.
Upon the clicking of the confirmation button, augment step by one.
"""
__revision__ = "$Id$"
import cgi
from invenio.config import CFG_SITE_ADMIN_EMAIL
from invenio.websubmit_config import \
InvenioWebSubmitFunctionStop, \
InvenioWebSubmitFunctionError
from invenio.search_engine import print_record, record_exists
## Details of record to display to the user for confirmation:
CFG_DOCUMENT_DETAILS_MESSAGE = """
<div>
We're about to process your request for the following document:<br /><br />
<table border="0">
<tr>
<td>Report Number(s):</td><td>%(report-numbers)s</td>
</tr>
<tr>
<td>Title:</td><td>%(title)s</td>
</tr>
<tr>
<td>Author(s):</td><td>%(author)s</td>
</tr>
</table>
<br />
If this is correct, please CONFIRM it:<br />
<br />
<input type="submit" width="350" height="50"
name="CONFIRM" value="CONFIRM"
onClick="document.forms[0].step.value=%(newstep)s;">
<br />
If you think that there is a problem, please contact
<a href="mailto:%(admin-email)s">%(admin-email)s</a>.<br />
</div>
"""
def Ask_For_Record_Details_Confirmation(parameters, \
curdir, \
form, \
user_info=None):
"""
Display the details of a record on which some operation is to be carried
out and prompt for the user's confirmation that it is the correct record.
Upon the clicking of the confirmation button, augment step by one.
Given the "recid" (001) of a record, retrieve the basic metadata
(title, report-number(s) and author(s)) and display them in the
user's browser along with a prompt asking them to confirm that
it is indeed the record that they expected to see.
The function depends upon the presence of the "sysno" global and the
presence of the "step" field in the "form" parameter.
When the user clicks on the "confirm" button, step will be augmented by
1 and the form will be submitted.
@parameters: None.
@return: None.
@Exceptions raise: InvenioWebSubmitFunctionError if problems are
encountered;
InvenioWebSubmitFunctionStop in order to display the details of the
record and the confirmation message.
"""
global sysno
## Make sure that we know the current step:
try:
current_step = int(form['step'])
except TypeError:
## Can't determine step.
msg = "Unable to determine submission step. Cannot continue."
raise InvenioWebSubmitFunctionError(msg)
else:
newstep = current_step + 1
## Make sure that the sysno is valid:
try:
working_recid = int(sysno)
except TypeError:
## Unable to find the details of this record - cannot query the database
msg = "Unable to retrieve details of record - record id was invalid."
raise InvenioWebSubmitFunctionError(msg)
if not record_exists(working_recid):
## Record doesn't exist.
msg = "Unable to retrieve details of record [%s] - record does not " \
"exist." % working_recid
raise InvenioWebSubmitFunctionError(msg)
## Retrieve the details to be displayed:
##
## Author(s):
rec_authors = ""
rec_first_author = print_record(int(sysno), 'tm', "100__a")
rec_other_authors = print_record(int(sysno), 'tm', "700__a")
if rec_first_author != "":
rec_authors += "".join(["%s<br />\n" % cgi.escape(author.strip()) for \
author in rec_first_author.split("\n")])
if rec_other_authors != "":
rec_authors += "".join(["%s<br />\n" % cgi.escape(author.strip()) for \
author in rec_other_authors.split("\n")])
## Title:<|fim▁hole|> print_record(int(sysno), 'tm', "245__a").split("\n")])
## Report numbers:
rec_reportnums = ""
rec_reportnum = print_record(int(sysno), 'tm', "037__a")
rec_other_reportnums = print_record(int(sysno), 'tm', "088__a")
if rec_reportnum != "":
rec_reportnums += "".join(["%s<br />\n" % cgi.escape(repnum.strip()) \
for repnum in rec_reportnum.split("\n")])
if rec_other_reportnums != "":
rec_reportnums += "".join(["%s<br />\n" % cgi.escape(repnum.strip()) \
for repnum in \
rec_other_reportnums.split("\n")])
raise InvenioWebSubmitFunctionStop(CFG_DOCUMENT_DETAILS_MESSAGE % \
{ 'report-numbers' : rec_reportnums, \
'title' : rec_title, \
'author' : rec_authors, \
'newstep' : newstep, \
'admin-email' : CFG_SITE_ADMIN_EMAIL, \
} )<|fim▁end|> | rec_title = "".join(["%s<br />\n" % cgi.escape(title.strip()) for title in \ |
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ConservationFeature'
db.create_table('seak_conservationfeature', (
('name', self.gf('django.db.models.fields.CharField')(max_length=99)),
('level1', self.gf('django.db.models.fields.CharField')(max_length=99)),
('level2', self.gf('django.db.models.fields.CharField')(max_length=99, null=True, blank=True)),
('level3', self.gf('django.db.models.fields.CharField')(max_length=99, null=True, blank=True)),
('level4', self.gf('django.db.models.fields.CharField')(max_length=99, null=True, blank=True)),
('level5', self.gf('django.db.models.fields.CharField')(max_length=99, null=True, blank=True)),
('dbf_fieldname', self.gf('django.db.models.fields.CharField')(max_length=15, null=True, blank=True)),
('units', self.gf('django.db.models.fields.CharField')(max_length=90, null=True, blank=True)),
('uid', self.gf('django.db.models.fields.IntegerField')(primary_key=True)),
))
db.send_create_signal('seak', ['ConservationFeature'])
# Adding model 'Cost'
db.create_table('seak_cost', (
('name', self.gf('django.db.models.fields.CharField')(max_length=99)),
('uid', self.gf('django.db.models.fields.IntegerField')(primary_key=True)),
('dbf_fieldname', self.gf('django.db.models.fields.CharField')(max_length=15, null=True, blank=True)),
('units', self.gf('django.db.models.fields.CharField')(max_length=16, null=True, blank=True)),
('desc', self.gf('django.db.models.fields.TextField')()),
))
db.send_create_signal('seak', ['Cost'])
# Adding model 'PlanningUnit'
db.create_table('seak_planningunit', (
('fid', self.gf('django.db.models.fields.IntegerField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=99)),
('geometry', self.gf('django.contrib.gis.db.models.fields.MultiPolygonField')(srid=3857, null=True, blank=True)),
('date_modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
))
db.send_create_signal('seak', ['PlanningUnit'])
# Adding model 'PuVsCf'
db.create_table('seak_puvscf', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('pu', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['seak.PlanningUnit'])),
('cf', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['seak.ConservationFeature'])),
('amount', self.gf('django.db.models.fields.FloatField')(null=True, blank=True)),
))
db.send_create_signal('seak', ['PuVsCf'])
# Adding unique constraint on 'PuVsCf', fields ['pu', 'cf']
db.create_unique('seak_puvscf', ['pu_id', 'cf_id'])
# Adding model 'PuVsCost'
db.create_table('seak_puvscost', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('pu', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['seak.PlanningUnit'])),
('cost', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['seak.Cost'])),
('amount', self.gf('django.db.models.fields.FloatField')(null=True, blank=True)),
))
db.send_create_signal('seak', ['PuVsCost'])
# Adding unique constraint on 'PuVsCost', fields ['pu', 'cost']
db.create_unique('seak_puvscost', ['pu_id', 'cost_id'])
# Adding model 'Scenario'
db.create_table('seak_scenario', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='seak_scenario_related', to=orm['auth.User'])),
('name', self.gf('django.db.models.fields.CharField')(max_length='255')),
('date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
('date_modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
('content_type', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='seak_scenario_related', null=True, to=orm['contenttypes.ContentType'])),
('object_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True)),
('input_targets', self.gf('seak.models.JSONField')()),
('input_penalties', self.gf('seak.models.JSONField')()),
('input_relativecosts', self.gf('seak.models.JSONField')()),
('input_geography', self.gf('seak.models.JSONField')()),
('input_scalefactor', self.gf('django.db.models.fields.FloatField')(default=0.0)),
('description', self.gf('django.db.models.fields.TextField')(default='', null=True, blank=True)),
('output_best', self.gf('seak.models.JSONField')(null=True, blank=True)),
('output_pu_count', self.gf('seak.models.JSONField')(null=True, blank=True)),
))
db.send_create_signal('seak', ['Scenario'])
# Adding M2M table for field sharing_groups on 'Scenario'
db.create_table('seak_scenario_sharing_groups', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('scenario', models.ForeignKey(orm['seak.scenario'], null=False)),
('group', models.ForeignKey(orm['auth.group'], null=False))
))
db.create_unique('seak_scenario_sharing_groups', ['scenario_id', 'group_id'])
# Adding model 'Folder'
db.create_table('seak_folder', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='seak_folder_related', to=orm['auth.User'])),
('name', self.gf('django.db.models.fields.CharField')(max_length='255')),
('date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
('date_modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
('content_type', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='seak_folder_related', null=True, to=orm['contenttypes.ContentType'])),
('object_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True)),
('description', self.gf('django.db.models.fields.TextField')(default='', null=True, blank=True)),
))
db.send_create_signal('seak', ['Folder'])
# Adding M2M table for field sharing_groups on 'Folder'
db.create_table('seak_folder_sharing_groups', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('folder', models.ForeignKey(orm['seak.folder'], null=False)),
('group', models.ForeignKey(orm['auth.group'], null=False))
))
db.create_unique('seak_folder_sharing_groups', ['folder_id', 'group_id'])
# Adding model 'PlanningUnitShapes'
db.create_table('seak_planningunitshapes', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('pu', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['seak.PlanningUnit'])),
('stamp', self.gf('django.db.models.fields.FloatField')()),
('bests', self.gf('django.db.models.fields.IntegerField')(default=0)),
('hits', self.gf('django.db.models.fields.IntegerField')(default=0)),
('fid', self.gf('django.db.models.fields.IntegerField')(null=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=99, null=True)),
('geometry', self.gf('django.contrib.gis.db.models.fields.MultiPolygonField')(srid=3857, null=True, blank=True)),
))
db.send_create_signal('seak', ['PlanningUnitShapes'])
def backwards(self, orm):
# Removing unique constraint on 'PuVsCost', fields ['pu', 'cost']
db.delete_unique('seak_puvscost', ['pu_id', 'cost_id'])
# Removing unique constraint on 'PuVsCf', fields ['pu', 'cf']
db.delete_unique('seak_puvscf', ['pu_id', 'cf_id'])
# Deleting model 'ConservationFeature'
db.delete_table('seak_conservationfeature')
# Deleting model 'Cost'
db.delete_table('seak_cost')
# Deleting model 'PlanningUnit'
db.delete_table('seak_planningunit')
# Deleting model 'PuVsCf'
db.delete_table('seak_puvscf')
# Deleting model 'PuVsCost'
db.delete_table('seak_puvscost')
# Deleting model 'Scenario'
db.delete_table('seak_scenario')
# Removing M2M table for field sharing_groups on 'Scenario'
db.delete_table('seak_scenario_sharing_groups')
# Deleting model 'Folder'
db.delete_table('seak_folder')
# Removing M2M table for field sharing_groups on 'Folder'
db.delete_table('seak_folder_sharing_groups')
# Deleting model 'PlanningUnitShapes'
db.delete_table('seak_planningunitshapes')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 7, 18, 8, 47, 45, 101970)'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 7, 18, 8, 47, 45, 101877)'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'seak.conservationfeature': {<|fim▁hole|> 'level2': ('django.db.models.fields.CharField', [], {'max_length': '99', 'null': 'True', 'blank': 'True'}),
'level3': ('django.db.models.fields.CharField', [], {'max_length': '99', 'null': 'True', 'blank': 'True'}),
'level4': ('django.db.models.fields.CharField', [], {'max_length': '99', 'null': 'True', 'blank': 'True'}),
'level5': ('django.db.models.fields.CharField', [], {'max_length': '99', 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '99'}),
'uid': ('django.db.models.fields.IntegerField', [], {'primary_key': 'True'}),
'units': ('django.db.models.fields.CharField', [], {'max_length': '90', 'null': 'True', 'blank': 'True'})
},
'seak.cost': {
'Meta': {'object_name': 'Cost'},
'dbf_fieldname': ('django.db.models.fields.CharField', [], {'max_length': '15', 'null': 'True', 'blank': 'True'}),
'desc': ('django.db.models.fields.TextField', [], {}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '99'}),
'uid': ('django.db.models.fields.IntegerField', [], {'primary_key': 'True'}),
'units': ('django.db.models.fields.CharField', [], {'max_length': '16', 'null': 'True', 'blank': 'True'})
},
'seak.folder': {
'Meta': {'object_name': 'Folder'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'seak_folder_related'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'default': "''", 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': "'255'"}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'sharing_groups': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'seak_folder_related'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['auth.Group']"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'seak_folder_related'", 'to': "orm['auth.User']"})
},
'seak.planningunit': {
'Meta': {'object_name': 'PlanningUnit'},
'date_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'fid': ('django.db.models.fields.IntegerField', [], {'primary_key': 'True'}),
'geometry': ('django.contrib.gis.db.models.fields.MultiPolygonField', [], {'srid': '3857', 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '99'})
},
'seak.planningunitshapes': {
'Meta': {'object_name': 'PlanningUnitShapes'},
'bests': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'fid': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'geometry': ('django.contrib.gis.db.models.fields.MultiPolygonField', [], {'srid': '3857', 'null': 'True', 'blank': 'True'}),
'hits': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '99', 'null': 'True'}),
'pu': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['seak.PlanningUnit']"}),
'stamp': ('django.db.models.fields.FloatField', [], {})
},
'seak.puvscf': {
'Meta': {'unique_together': "(('pu', 'cf'),)", 'object_name': 'PuVsCf'},
'amount': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'cf': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['seak.ConservationFeature']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'pu': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['seak.PlanningUnit']"})
},
'seak.puvscost': {
'Meta': {'unique_together': "(('pu', 'cost'),)", 'object_name': 'PuVsCost'},
'amount': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'cost': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['seak.Cost']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'pu': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['seak.PlanningUnit']"})
},
'seak.scenario': {
'Meta': {'object_name': 'Scenario'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'seak_scenario_related'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'default': "''", 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'input_geography': ('seak.models.JSONField', [], {}),
'input_penalties': ('seak.models.JSONField', [], {}),
'input_relativecosts': ('seak.models.JSONField', [], {}),
'input_scalefactor': ('django.db.models.fields.FloatField', [], {'default': '0.0'}),
'input_targets': ('seak.models.JSONField', [], {}),
'name': ('django.db.models.fields.CharField', [], {'max_length': "'255'"}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'output_best': ('seak.models.JSONField', [], {'null': 'True', 'blank': 'True'}),
'output_pu_count': ('seak.models.JSONField', [], {'null': 'True', 'blank': 'True'}),
'sharing_groups': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'seak_scenario_related'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['auth.Group']"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'seak_scenario_related'", 'to': "orm['auth.User']"})
}
}
complete_apps = ['seak']<|fim▁end|> | 'Meta': {'object_name': 'ConservationFeature'},
'dbf_fieldname': ('django.db.models.fields.CharField', [], {'max_length': '15', 'null': 'True', 'blank': 'True'}),
'level1': ('django.db.models.fields.CharField', [], {'max_length': '99'}), |
<|file_name|>rename_resources.py<|end_file_name|><|fim▁begin|>import os
import sys
import fnmatch
directory = os.path.dirname(os.path.realpath(sys.argv[0])) #get the directory of your script
for subdir, dirs, files in os.walk(directory):
print(files)<|fim▁hole|> newFilePath = filePath.replace("mpsdk_","px_") #create the new name
os.rename(filePath, newFilePath) #rename your file<|fim▁end|> | for filename in files:
if fnmatch.fnmatch(filename,'mpsdk_*') > 0:
subdirectoryPath = os.path.relpath(subdir, directory) #get the path to your subdirectory
filePath = os.path.join(subdirectoryPath, filename) #get the path to your file |
<|file_name|>ntil.js<|end_file_name|><|fim▁begin|>/**
* Copyright (c) 2015, Legendum Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of ntil nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* ntil - create a handler to call a function until the result is good.
*
* This package provides a single method "ntil()" which is called thus:
*
* ntil(performer, success, failure, opts)
*
* checker - a function to check a result and return true or false
* performer - a function to call to perform a task which may succeed or fail
* success - an optional function to process the result of a successful call
* failure - an optional function to process the result of a failed call
* opts - an optional hash of options (see below)
*
* ntil() will return a handler that may be called with any number of arguments.
* The performer function will receive these arguments, with a final "next" arg
* appended to the argument list, such that it should be called on completion,
* passing the result (as a single argument *or* multiple arguments) thus:
*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*
* var ntil = require('ntil');
* var handler = ntil(
* function(result) { return result === 3 }, // the checker
* function myFunc(a, b, next) { next(a + b) }, // the performer
* function(result) { console.log('success! ' + result) }, // on success
* function(result) { console.log('failure! ' + result) }, // on failure
* {logger: console} // options
* );
*
* handler(1, 1); // this will fail after 7 attempts (taking about a minute)
* handler(1, 2); // this will succeed immediately
*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*
* ...and here's the equivalent code in a syntax more similar to promises:
*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*
* var ntil = require('./ntil');
* var handler = ntil(
* function(result) { return result === 3 }
* ).exec(
* function myFunc(a, b, next) { next(a + b) }
* ).done(
* function(result) { console.log('success! ' + result) }
* ).fail(
* function(result) { console.log('failure! ' + result) }
* }.opts(
* {logger: console}
* ).func();
*
* handler(1, 1); // this will fail after 7 attempts (taking about a minute)
* handler(1, 2); // this will succeed immediately
*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*
* Note that the logger includes "myFunc" in log messages, because the function
* is named. An alternative is to use the "name" option (see below).
*
* The "checker" function checks that the result is 3, causing the first handler
* to fail (it has a result of 2, not 3) and the second handler to succeed.
*
* The output from both these examples is:
*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*
* perform: 1 failure - trying again in 1 seconds
* perform: success
* success! 3
* perform: 2 failures - trying again in 2 seconds
* perform: 3 failures - trying again in 4 seconds
* perform: 4 failures - trying again in 8 seconds
* perform: 5 failures - trying again in 16 seconds
* perform: 6 failures - trying again in 32 seconds
* perform: too many failures (7)
* failure! 2
*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*
*
* The options may optionally include:
* name: The name of the "performer" function we're calling, e.g. "getData"
* logger: A logger object that responds to "info" and "warn" method calls
* waitSecs: The initial duration in seconds to wait before retrying
* waitMult: The factor by which to multiply the wait duration upon each retry
* maxCalls: The maximum number of calls to make before failing
*
* Note that "waitSecs" defaults to 1, "waitMult" defaults to 2, and "maxCalls" * defaults to 7.
*
* Ideas for improvement? Email [email protected]
*/
(function() {
"use strict";
var sig = "Check params: function ntil(checker, performer, success, failure, opts)";
function chain(checker, opts) {
this.opts = function(options) { opts = options; return this }
this.exec = function(perform) { this.perform = perform; return this };
this.done = function(success) { this.success = success; return this };
this.fail = function(failure) { this.failure = failure; return this };
this.func = function() {
return ntil(checker, this.perform, this.success, this.failure, opts);
};
}
function ntil(checker, performer, success, failure, opts) {
opts = opts || {};
if (typeof checker !== 'function') throw sig;
if (typeof performer !== 'function') return new chain(checker, performer);
var name = opts.name || performer.name || 'anonymous function',
logger = opts.logger,
waitSecs = opts.waitSecs || 1,
waitMult = opts.waitMult || 2,
maxCalls = opts.maxCalls || 7; // it takes about a minute for 7 attempts
return function() {
var args = Array.prototype.slice.call(arguments, 0),<|fim▁hole|> var result = Array.prototype.slice.call(arguments, 0);
if (checker.apply(checker, result) === true) {
if (logger) logger.info(name + ': success');
if (typeof success === 'function') success.apply(success, result);
} else {
calls++;
if (calls < maxCalls) {
if (logger) logger.warn(name + ': ' + calls + ' failure' + (calls === 1 ? '' : 's') + ' - trying again in ' + wait + ' seconds');
setTimeout(function() {
invoke();
}, wait * 1000);
wait *= waitMult;
} else {
if (logger) logger.warn(name + ': too many failures (' + calls + ')');
if (typeof failure === 'function') failure.apply(failure, result);
}
}
}
function invoke() {
try {
performer.apply(performer, args);
} catch (e) {
if (logger) logger.warn(name + ': exception "' + e + '"');
next();
}
}
args.push(next);
invoke();
}
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = ntil;
} else { // browser?
this.ntil = ntil;
}
}).call(this);<|fim▁end|> | wait = waitSecs,
calls = 0;
function next() { |
<|file_name|>shader_test.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
'''Tests rendering using shader objects from core GL or extensions
Uses the:
Lighthouse 3D Tutorial toon shader
http://www.lighthouse3d.com/opengl/glsl/index.php?toon2
By way of:
http://www.pygame.org/wiki/GLSLExample
'''
import OpenGL
OpenGL.ERROR_ON_COPY = True
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *<|fim▁hole|># PyOpenGL 3.0.1 introduces this convenience module...
from OpenGL.GL.shaders import *
import time, sys
program = None
# A general OpenGL initialization function. Sets all of the initial parameters.
def InitGL(Width, Height): # We call this right after our OpenGL window is created.
glClearColor(0.0, 0.0, 0.0, 0.0) # This Will Clear The Background Color To Black
glClearDepth(1.0) # Enables Clearing Of The Depth Buffer
glDepthFunc(GL_LESS) # The Type Of Depth Test To Do
glEnable(GL_DEPTH_TEST) # Enables Depth Testing
glShadeModel(GL_SMOOTH) # Enables Smooth Color Shading
glMatrixMode(GL_PROJECTION)
glLoadIdentity() # Reset The Projection Matrix
# Calculate The Aspect Ratio Of The Window
gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)
glMatrixMode(GL_MODELVIEW)
if not glUseProgram:
print 'Missing Shader Objects!'
sys.exit(1)
global program
program = compileProgram(
compileShader('''
varying vec3 normal;
void main() {
normal = gl_NormalMatrix * gl_Normal;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
''',GL_VERTEX_SHADER),
compileShader('''
varying vec3 normal;
void main() {
float intensity;
vec4 color;
vec3 n = normalize(normal);
vec3 l = normalize(gl_LightSource[0].position).xyz;
// quantize to 5 steps (0, .25, .5, .75 and 1)
intensity = (floor(dot(l, n) * 4.0) + 1.0)/4.0;
color = vec4(intensity*1.0, intensity*0.5, intensity*0.5,
intensity*1.0);
gl_FragColor = color;
}
''',GL_FRAGMENT_SHADER),)
# The function called when our window is resized (which shouldn't happen if you enable fullscreen, below)
def ReSizeGLScene(Width, Height):
if Height == 0: # Prevent A Divide By Zero If The Window Is Too Small
Height = 1
glViewport(0, 0, Width, Height) # Reset The Current Viewport And Perspective Transformation
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)
glMatrixMode(GL_MODELVIEW)
# The main drawing function.
def DrawGLScene():
# Clear The Screen And The Depth Buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity() # Reset The View
# Move Left 1.5 units and into the screen 6.0 units.
glTranslatef(-1.5, 0.0, -6.0)
if program:
glUseProgram(program)
glutSolidSphere(1.0,32,32)
glTranslate( 1,0,2 )
glutSolidCube( 1.0 )
# since this is double buffered, swap the buffers to display what just got drawn.
glutSwapBuffers()
# The function called whenever a key is pressed. Note the use of Python tuples to pass in: (key, x, y)
def keyPressed(*args):
# If escape is pressed, kill everything.
if args[0] == '\x1b':
sys.exit()
def main():
global window
# For now we just pass glutInit one empty argument. I wasn't sure what should or could be passed in (tuple, list, ...)
# Once I find out the right stuff based on reading the PyOpenGL source, I'll address this.
glutInit(sys.argv)
# Select type of Display mode:
# Double buffer
# RGBA color
# Alpha components supported
# Depth buffer
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
# get a 640 x 480 window
glutInitWindowSize(640, 480)
# the window starts at the upper left corner of the screen
glutInitWindowPosition(0, 0)
# Okay, like the C version we retain the window id to use when closing, but for those of you new
# to Python (like myself), remember this assignment would make the variable local and not global
# if it weren't for the global declaration at the start of main.
window = glutCreateWindow("Jeff Molofee's GL Code Tutorial ... NeHe '99")
# Register the drawing function with glut, BUT in Python land, at least using PyOpenGL, we need to
# set the function pointer and invoke a function to actually register the callback, otherwise it
# would be very much like the C version of the code.
glutDisplayFunc(DrawGLScene)
# Uncomment this line to get full screen.
#glutFullScreen()
# When we are doing nothing, redraw the scene.
glutIdleFunc(DrawGLScene)
# Register the function called when our window is resized.
glutReshapeFunc(ReSizeGLScene)
# Register the function called when the keyboard is pressed.
glutKeyboardFunc(keyPressed)
# Initialize our window.
InitGL(640, 480)
# Start Event Processing Engine
glutMainLoop()
# Print message to console, and kick off the main to get it rolling.
if __name__ == "__main__":
print "Hit ESC key to quit."
main()<|fim▁end|> | |
<|file_name|>news_item.py<|end_file_name|><|fim▁begin|>import re
import string
import nltk
from bs4 import BeautifulSoup
__author__ = 'nolram'
class NewsItem:
def __init__(self, news, stop_words):
self.all_words = []
self.stop_words = stop_words
self.regex = re.compile('[%s]' % re.escape(string.punctuation))
if "titulo" in news and "categoria" in news:
self.add_words(news["titulo"])
self.title = news["titulo"]
if "subcategoria" in news:
self.category = news["subcategoria"].lower()
else:
self.category = news["categoria"].lower()
if "texto" in news:
self.add_words(" ".join(news["texto"]))
self.url = news["url"]
def normalized_words(self, s):
words = []
oneline = s.replace('\n', ' ')
soup = BeautifulSoup(oneline.strip(), 'html.parser')
cleaned = soup.get_text()
toks1 = cleaned.split()
for t1 in toks1:
translated = self.regex.sub('', t1)
toks2 = translated.split()
for t2 in toks2:
t2s = t2.strip()
if len(t2s) > 1:
words.append(t2s.lower())
return words
def word_count(self):
return len(self.all_words)
def word_freq_dist(self):
freqs = nltk.FreqDist() # class nltk.probability.FreqDist
for w in self.all_words:
freqs.inc(w, 1)
return freqs
def add_words(self, s):
words = self.normalized_words(s)
for w in words:
if w not in self.stop_words:
self.all_words.append(w)
def features(self, top_words):
word_set = set(self.all_words)
features = {}
features['url'] = self.url
for w in top_words:
features["w_%s" % w] = (w in word_set)
return features
def normalized_frequency_power(self, word, freqs, largest_count):
n = self.normalized_frequency_value(word, freqs, largest_count)
return pow(n, 2)
def normalized_frequency_value(self, word, freqs, largest_count):
count = freqs.get(word)
n = 0
if count is None:
n = float(0)
else:
n = ((float(count) * float(largest_count)) / float(freqs.N())) * 100.0
return n
def normalized_boolean_value(self, word, freqs, largest_count):
count = freqs.get(word)
if count is None:
return float(0)
else:
return float(1)
def knn_data(self, top_words):
data_array = []
freqs = self.word_freq_dist()
largest_count = freqs.values()[0]
features = {}
features['url'] = self.url
for w in top_words:
data_array.append(self.normalized_boolean_value(w, freqs, largest_count))
print "knn_data: %s" % data_array
return data_array
def as_debug_array(self, guess):
l = []
l.append('---')
#l.append('lookup_key: %s' % (self.lookup_key()))
l.append('Categoria: %s' % (self.category))
l.append('Palpite: %s' % (guess))
l.append('URL: %s' % (self.url))
l.append('Titulos: %s' % (self.title))
l.append('')
l.append('Todas as palavras por contagem')
freqs = nltk.FreqDist([w.lower() for w in self.all_words])<|fim▁hole|> l.append('')
l.append('all_words, sequentially:')
for w in self.all_words:
l.append(w)
return l<|fim▁end|> | for w in freqs.keys():
l.append("%-20s %d" % (w, freqs.get(w))) |
<|file_name|>frameRedirect.ts<|end_file_name|><|fim▁begin|>import * as angular from 'angular';
import appConfig from './config/app.config';
import adalConfig from './config/app.config.adal';
import routeConfig from './config/app.config.routes';
import '@uirouter/core';
import '@uirouter/angularjs';
import 'adal-angular/lib/adal'; // adal library
import 'adal-angular/lib/adal-angular'; // adal-angular library
import * as adal from 'adal-angular'; // @types library
angular
.module('app', [
'AdalAngular',
'ui.router'
])
.constant('appConfig', appConfig)<|fim▁hole|> .config(adalConfig)
.config(routeConfig);<|fim▁end|> | |
<|file_name|>logging-enabled.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
<|fim▁hole|>
fn main() {
if log_enabled!(logging::DEBUG) {
fail!("what?! debugging?");
}
if !log_enabled!(logging::INFO) {
fail!("what?! no info?");
}
}<|fim▁end|> | // xfail-fast
// exec-env:RUST_LOG=logging-enabled=info
use std::logging; |
<|file_name|>aivdmDecode.js<|end_file_name|><|fim▁begin|>var _ = require('underscore');
var colors = require('colors');
var sprintf = require('sprintf-js').sprintf;
/**
* used to decode AIS messages.
* Currently decodes types 1,2,3,4,5,9,18,19,21,24,27
* Currently does not decode 6,7,8,10,11,12,13,14,15,16,17,20,22,23,25,26
* Currently does not support the USCG Extended AIVDM messages
*
* Normal usage:
* var decoder = new aivdmDecode.aivdmDecode(options)
* then
* decoder.decode(aivdm);
* var msgData = decoder.getData();
*
* aisData will return with an object that contains the message fields.
* The object returned will also include the sentence(s) that were decoded. This is to make it easy to
* use the decoder to filter based on in-message criteria but then forward the undecoded packets.
*
* The decoded data object uses field naming conventions in the same way that GPSD does.
*
* @param {object} options:
* returnJson: If true then json is returned instead of a javascript object (default false)
* aivdmPassthrough If true then the aivdm messages that were decoded are included with the returned object
* default false
*/
/**
* String.lpad: Used to pad mmsi's to 9 digits and imo's to 7 digits
* Converts number to string, then lpads it with padString to length
* @param {string} padString The character to use when padding
* @param desiredLength The desired length after padding<|fim▁hole|> */
Number.prototype.lpad = function (padString, desiredLength) {
var str = '' + this;
while (str.length < desiredLength)
str = padString + str;
return str;
};
var aivdmDecode = function (options) {
if (options) {
// returnJson: If true, returns json instead of an object
this.returnJson = options.returnJson || false;
// aivdmPassthrough: If true then the original aivdm sentences are embedded in the returned object
this.aivdmPassthrough = options.aivdmPassthrough || true;
// includeMID: If true then the mid (nationality) of the vessels is included in the returned object
this.includeMID = options.includeMID || true;
// accept_related. Passed as true to decoder when you wish static packets with accepted MMSI passed to output
//this.accept_related = options.accept_related || true;
// isDebug. If true, prints debug messages
this.isDebug = options.isDebug || false;
} else {
this.returnJson = false;
this.aivdmPassthrough = true;
this.includeMID = true;
this.isDebug = false;
}
this.AIVDM = '';
this.splitParts = []; // Contains aivdm's of multi part messages
this.splitPart1Sequence = null;
this.splitPart1Type = null;
this.splitLines = []; // contains untrimmed lines of multi part messages
this.numFragments = null;
this.fragmentNum = null;
this.seqMsgId = '';
this.binString = '';
this.partNo = null;
this.channel = null;
this.msgType = null;
this.supportedTypes = [1,2,3,4,5,9,18,19,21,24,27];
this.char_table = [
/*
4th line would normally be:
'[', '\\', ']', '^', '_', ' ', '!', '"', '#', '$', '%', '&', '\\', '(', ')', '*', '+', ',', '-','.', '/',
but has been customized to eliminate most punctuation characters
Last line would normally be:
':', ';', '<', '=', '>', '?'
but has been customized to eliminate most punctuation characters
*/
'@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '-', '-', '-', '-', '_', ' ', '-', '-', '-', '-', '-', '-',
'-', '(', ')', '-', '-', '-', '-', '.', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '-', '<',
'-', '>', '-'
];
this.posGroups = {
1: {'lat': {'start': 89, 'length': 27, 'divisor': 600000.0},
'lon': {'start': 61, 'length': 28, 'divisor': 600000.0}},
2: {'lat': {'start': 89, 'length': 27, 'divisor': 600000.0},
'lon': {'start': 61, 'length': 28, 'divisor': 600000.0}},
3: {'lat': {'start': 89, 'length': 27, 'divisor': 600000.0},
'lon': {'start': 61, 'length': 28, 'divisor': 600000.0}},
4: {'lat': {'start': 107, 'length': 27, 'divisor': 600000.0},
'lon': {'start': 79, 'length': 28, 'divisor': 600000.0}},
9: {'lat': {'start': 89, 'length': 27, 'divisor': 600000.0},
'lon': {'start': 61, 'length': 28, 'divisor': 600000.0}},
18: {'lat': {'start': 85, 'length': 27, 'divisor': 600000.0},
'lon': {'start': 57, 'length': 28, 'divisor': 600000.0}},
19: {'lat': {'start': 85, 'length': 27, 'divisor': 600000.0},
'lon': {'start': 57, 'length': 28, 'divisor': 600000.0}},
21: {'lat': {'start': 192, 'length': 27, 'divisor': 600000.0},
'lon': {'start': 164, 'length': 28, 'divisor': 600000.0}},
27: {'lat': {'start': 62, 'length': 17, 'divisor': 600.0},
'lon': {'start': 44, 'length': 18, 'divisor': 600.0}}
};
this.speedGroups = {
1: {'start': 50, 'length': 10, 'divisor': 10},
2: {'start': 50, 'length': 10, 'divisor': 10},
3: {'start': 50, 'length': 10, 'divisor': 10},
9: {'start': 50, 'length': 10, 'divisor': 1},
18: {'start': 46, 'length': 10, 'divisor': 10},
19: {'start': 46, 'length': 10, 'divisor': 10},
27: {'start': 79, 'length': 6, 'divisor': 1}
};
this.navStatusText = [
'Under way using engine',
'At anchor',
'Not under command',
'Restricted manoeuverability',
'Constrained by her draught',
'Moored',
'Aground',
'Engaged in Fishing',
'Under way sailing',
'Reserved for future amendment of Navigational Status for HSC',
'Reserved for future amendment of Navigational Status for WIG',
'Reserved for future use',
'Reserved for future use',
'Reserved for future use',
'AIS-SART is active',
'Not defined'
];
this.maneuverText = [
'Not available',
'No special maneuver',
'Special maneuver (such as regional passing arrangement'
];
this.epfdText = [
'Undefined',
'GPS',
'GLONASS',
'Combined GPS/GLONASS',
'Loran-C',
'Chayka',
'Integrated navigation system',
'Surveyed',
'Galileo'
];
this.shiptypeText = [
"Not available",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Reserved for future use",
"Wing in ground (WIG) - all ships of this type",
"Wing in ground (WIG) - Hazardous category A",
"Wing in ground (WIG) - Hazardous category B",
"Wing in ground (WIG) - Hazardous category C",
"Wing in ground (WIG) - Hazardous category D",
"Wing in ground (WIG) - Reserved for future use",
"Wing in ground (WIG) - Reserved for future use",
"Wing in ground (WIG) - Reserved for future use",
"Wing in ground (WIG) - Reserved for future use",
"Wing in ground (WIG) - Reserved for future use",
"Fishing",
"Towing",
"Towing: length exceeds 200m or breadth exceeds 25m",
"Dredging or underwater ops",
"Diving ops",
"Military ops",
"Sailing",
"Pleasure Craft",
"Reserved",
"Reserved",
"High speed craft (HSC) - all ships of this type",
"High speed craft (HSC) - Hazardous category A",
"High speed craft (HSC) - Hazardous category B",
"High speed craft (HSC) - Hazardous category C",
"High speed craft (HSC) - Hazardous category D",
"High speed craft (HSC) - Reserved for future use",
"High speed craft (HSC) - Reserved for future use",
"High speed craft (HSC) - Reserved for future use",
"High speed craft (HSC) - Reserved for future use",
"High speed craft (HSC) - No additional information",
"Pilot Vessel1",
"Search and Rescue vessel",
"Tug",
"Port Tender",
"Anti-pollution equipment",
"Law Enforcement",
"Spare - Local Vessel",
"Spare - Local Vessel",
"Medical Transport",
"Ship according to RR Resolution No. 18",
"Passenger - all ships of this type",
"Passenger - Hazardous category A",
"Passenger - Hazardous category B",
"Passenger - Hazardous category C",
"Passenger - Hazardous category D",
"Passenger - Reserved for future use",
"Passenger - Reserved for future use",
"Passenger - Reserved for future use",
"Passenger - Reserved for future use",
"Passenger - No additional information",
"Cargo - all ships of this type",
"Cargo - Hazardous category A",
"Cargo - Hazardous category B",
"Cargo - Hazardous category C",
"Cargo - Hazardous category D",
"Cargo - Reserved for future use",
"Cargo - Reserved for future use",
"Cargo - Reserved for future use",
"Cargo - Reserved for future use",
"Cargo - No additional information",
"Tanker - all ships of this type",
"Tanker - Hazardous category A",
"Tanker - Hazardous category B1",
"Tanker - Hazardous category C1",
"Tanker - Hazardous category D1",
"Tanker - Reserved for future use",
"Tanker - Reserved for future use",
"Tanker - Reserved for future use",
"Tanker - Reserved for future use",
"Tanker - No additional information",
"Other Type - all ships of this type",
"Other Type - Hazardous category A",
"Other Type - Hazardous category B",
"Other Type - Hazardous category C",
"Other Type - Hazardous category D",
"Other Type - Reserved for future use",
"Other Type - Reserved for future use",
"Other Type - Reserved for future use",
"Other Type - Reserved for future use",
"Other Type - no additional information"
];
this.midTable = {
202: "Andorra (Principality of)",
203: "Austria",
204: "Azores - Portugal",
205: "Belgium",
206: "Belarus (Republic of)",
207: "Bulgaria (Republic of)",
208: "Vatican City State",
209: "Cyprus (Republic of)",
210: "Cyprus (Republic of)",
211: "Germany (Federal Republic of)",
212: "Cyprus (Republic of)",
213: "Georgia",
214: "Moldova (Republic of)",
215: "Malta",
216: "Armenia (Republic of)",
218: "Germany (Federal Republic of)",
219: "Denmark",
220: "Denmark",
224: "Spain",
225: "Spain",
226: "France",
227: "France",
228: "France",
229: "Malta",
230: "Finland",
231: "Faroe Islands - Denmark",
232: "United Kingdom of Great Britain and Northern Ireland",
233: "United Kingdom of Great Britain and Northern Ireland",
234: "United Kingdom of Great Britain and Northern Ireland",
235: "United Kingdom of Great Britain and Northern Ireland",
236: "Gibraltar - United Kingdom of Great Britain and Northern Ireland",
237: "Greece",
238: "Croatia (Republic of)",
239: "Greece",
240: "Greece",
241: "Greece",
242: "Morocco (Kingdom of)",
243: "Hungary",
244: "Netherlands (Kingdom of the)",
245: "Netherlands (Kingdom of the)",
246: "Netherlands (Kingdom of the)",
247: "Italy",
248: "Malta",
249: "Malta",
250: "Ireland",
251: "Iceland",
252: "Liechtenstein (Principality of)",
253: "Luxembourg",
254: "Monaco (Principality of)",
255: "Madeira - Portugal",
256: "Malta",
257: "Norway",
258: "Norway",
259: "Norway",
261: "Poland (Republic of)",
262: "Montenegro",
263: "Portugal",
264: "Romania",
265: "Sweden",
266: "Sweden",
267: "Slovak Republic",
268: "San Marino (Republic of)",
269: "Switzerland (Confederation of)",
270: "Czech Republic",
271: "Turkey",
272: "Ukraine",
273: "Russian Federation",
274: "The Former Yugoslav Republic of Macedonia",
275: "Latvia (Republic of)",
276: "Estonia (Republic of)",
277: "Lithuania (Republic of)",
278: "Slovenia (Republic of)",
279: "Serbia (Republic of)",
301: "Anguilla - United Kingdom of Great Britain and Northern Ireland",
303: "Alaska (State of) - United States of America",
304: "Antigua and Barbuda",
305: "Antigua and Barbuda",
306: "Dutch West Indies",
//306: "Curaçao - Netherlands (Kingdom of the)",
//306: "Sint Maarten (Dutch part) - Netherlands (Kingdom of the)",
//306: "Bonaire, Sint Eustatius and Saba - Netherlands (Kingdom of the)",
307: "Aruba - Netherlands (Kingdom of the)",
308: "Bahamas (Commonwealth of the)",
309: "Bahamas (Commonwealth of the)",
310: "Bermuda - United Kingdom of Great Britain and Northern Ireland",
311: "Bahamas (Commonwealth of the)",
312: "Belize",
314: "Barbados",
316: "Canada",
319: "Cayman Islands - United Kingdom of Great Britain and Northern Ireland",
321: "Costa Rica",
323: "Cuba",
325: "Dominica (Commonwealth of)",
327: "Dominican Republic",
329: "Guadeloupe (French Department of) - France",
330: "Grenada",
331: "Greenland - Denmark",
332: "Guatemala (Republic of)",
334: "Honduras (Republic of)",
336: "Haiti (Republic of)",
338: "United States of America",
339: "Jamaica",
341: "Saint Kitts and Nevis (Federation of)",
343: "Saint Lucia",
345: "Mexico",
347: "Martinique (French Department of) - France",
348: "Montserrat - United Kingdom of Great Britain and Northern Ireland",
350: "Nicaragua",
351: "Panama (Republic of)",
352: "Panama (Republic of)",
353: "Panama (Republic of)",
354: "Panama (Republic of)",
355: "unassigned",
356: "unassigned",
357: "unassigned",
358: "Puerto Rico - United States of America",
359: "El Salvador (Republic of)",
361: "Saint Pierre and Miquelon (Territorial Collectivity of) - France",
362: "Trinidad and Tobago",
364: "Turks and Caicos Islands - United Kingdom of Great Britain and Northern Ireland",
366: "United States of America",
367: "United States of America",
368: "United States of America",
369: "United States of America",
370: "Panama (Republic of)",
371: "Panama (Republic of)",
372: "Panama (Republic of)",
373: "Panama (Republic of)",
375: "Saint Vincent and the Grenadines",
376: "Saint Vincent and the Grenadines",
377: "Saint Vincent and the Grenadines",
378: "British Virgin Islands - United Kingdom of Great Britain and Northern Ireland",
379: "United States Virgin Islands - United States of America",
401: "Afghanistan",
403: "Saudi Arabia (Kingdom of)",
405: "Bangladesh (People's Republic of)",
408: "Bahrain (Kingdom of)",
410: "Bhutan (Kingdom of)",
412: "China (People's Republic of)",
413: "China (People's Republic of)",
414: "China (People's Republic of)",
416: "Taiwan (Province of China) - China (People's Republic of)",
417: "Sri Lanka (Democratic Socialist Republic of)",
419: "India (Republic of)",
422: "Iran (Islamic Republic of)",
423: "Azerbaijan (Republic of)",
425: "Iraq (Republic of)",
428: "Israel (State of)",
431: "Japan",
432: "Japan",
434: "Turkmenistan",
436: "Kazakhstan (Republic of)",
437: "Uzbekistan (Republic of)",
438: "Jordan (Hashemite Kingdom of)",
440: "Korea (Republic of)",
441: "Korea (Republic of)",
443: "State of Palestine (In accordance with Resolution 99 Rev. Guadalajara, 2010)",
445: "Democratic People's Republic of Korea",
447: "Kuwait (State of)",
450: "Lebanon",
451: "Kyrgyz Republic",
453: "Macao (Special Administrative Region of China) - China (People's Republic of)",
455: "Maldives (Republic of)",
457: "Mongolia",
459: "Nepal (Federal Democratic Republic of)",
461: "Oman (Sultanate of)",
463: "Pakistan (Islamic Republic of)",
466: "Qatar (State of)",
468: "Syrian Arab Republic",
470: "United Arab Emirates",
472: "Tajikistan (Republic of)",
473: "Yemen (Republic of)",
475: "Yemen (Republic of)",
477: "Hong Kong (Special Administrative Region of China) - China (People's Republic of)",
478: "Bosnia and Herzegovina",
501: "Adelie Land - France",
503: "Australia",
506: "Myanmar (Union of)",
508: "Brunei Darussalam",
510: "Micronesia (Federated States of)",
511: "Palau (Republic of)",
512: "New Zealand",
514: "Cambodia (Kingdom of)",
515: "Cambodia (Kingdom of)",
516: "Christmas Island (Indian Ocean) - Australia",
518: "Cook Islands - New Zealand",
520: "Fiji (Republic of)",
523: "Cocos (Keeling) Islands - Australia",
525: "Indonesia (Republic of)",
529: "Kiribati (Republic of)",
531: "Lao People's Democratic Republic",
533: "Malaysia",
536: "Northern Mariana Islands (Commonwealth of the) - United States of America",
538: "Marshall Islands (Republic of the)",
540: "New Caledonia - France",
542: "Niue - New Zealand",
544: "Nauru (Republic of)",
546: "French Polynesia - France",
548: "Philippines (Republic of the)",
553: "Papua New Guinea",
555: "Pitcairn Island - United Kingdom of Great Britain and Northern Ireland",
557: "Solomon Islands",
559: "American Samoa - United States of America",
561: "Samoa (Independent State of)",
563: "Singapore (Republic of)",
564: "Singapore (Republic of)",
565: "Singapore (Republic of)",
566: "Singapore (Republic of)",
567: "Thailand",
570: "Tonga (Kingdom of)",
572: "Tuvalu",
574: "Viet Nam (Socialist Republic of)",
576: "Vanuatu (Republic of)",
577: "Vanuatu (Republic of)",
578: "Wallis and Futuna Islands - France",
601: "South Africa (Republic of)",
603: "Angola (Republic of)",
605: "Algeria (People's Democratic Republic of)",
607: "Saint Paul and Amsterdam Islands - France",
608: "Ascension Island - United Kingdom of Great Britain and Northern Ireland",
609: "Burundi (Republic of)",
610: "Benin (Republic of)",
611: "Botswana (Republic of)",
612: "Central African Republic",
613: "Cameroon (Republic of)",
615: "Congo (Republic of the)",
616: "Comoros (Union of the)",
617: "Cabo Verde (Republic of)",
618: "Crozet Archipelago - France",
619: "Côte d'Ivoire (Republic of)",
620: "Comoros (Union of the)",
621: "Djibouti (Republic of)",
622: "Egypt (Arab Republic of)",
624: "Ethiopia (Federal Democratic Republic of)",
625: "Eritrea",
626: "Gabonese Republic",
627: "Ghana",
629: "Gambia (Republic of the)",
630: "Guinea-Bissau (Republic of)",
631: "Equatorial Guinea (Republic of)",
632: "Guinea (Republic of)",
633: "Burkina Faso",
634: "Kenya (Republic of)",
635: "Kerguelen Islands - France",
636: "Liberia (Republic of)",
637: "Liberia (Republic of)",
638: "South Sudan (Republic of)",
642: "Libya",
644: "Lesotho (Kingdom of)",
645: "Mauritius (Republic of)",
647: "Madagascar (Republic of)",
649: "Mali (Republic of)",
650: "Mozambique (Republic of)",
654: "Mauritania (Islamic Republic of)",
655: "Malawi",
656: "Niger (Republic of the)",
657: "Nigeria (Federal Republic of)",
659: "Namibia (Republic of)",
660: "Reunion (French Department of) - France",
661: "Rwanda (Republic of)",
662: "Sudan (Republic of the)",
663: "Senegal (Republic of)",
664: "Seychelles (Republic of)",
665: "Saint Helena - United Kingdom of Great Britain and Northern Ireland",
666: "Somalia (Federal Republic of)",
667: "Sierra Leone",
668: "Sao Tome and Principe (Democratic Republic of)",
669: "Swaziland (Kingdom of)",
670: "Chad (Republic of)",
671: "Togolese Republic",
672: "Tunisia",
674: "Tanzania (United Republic of)",
675: "Uganda (Republic of)",
676: "Democratic Republic of the Congo",
677: "Tanzania (United Republic of)",
678: "Zambia (Republic of)",
679: "Zimbabwe (Republic of)",
701: "Argentine Republic",
710: "Brazil (Federative Republic of)",
720: "Bolivia (Plurinational State of)",
725: "Chile",
730: "Colombia (Republic of)",
735: "Ecuador",
740: "Falkland Islands (Malvinas) - United Kingdom of Great Britain and Northern Ireland",
745: "Guiana (French Department of) - France",
750: "Guyana",
755: "Paraguay (Republic of)",
760: "Peru",
765: "Suriname (Republic of)",
770: "Uruguay (Eastern Republic of)",
775: "Venezuela (Bolivarian Republic of)"
};
this.functionMap = {
"accuracy": "getAccuracy",
"aid_type": "getAidType",
"alt": "getAlt",
"assigned": "getAssigned",
"callsign": "getCallsign",
"course": "getCourse",
"day": "getDay",
"destination": "getDestination",
"dimensions": "getDimensions",
"draught": "getDraught",
"dte": "getDte",
"epfd": "getEpfd",
"fragmentNum": "getFragmentNum",
"heading": "getHeading",
"hour": "getHour",
"imo": "getIMO",
"latLon": "getLatLon",
"maneuver": "getManeuver",
"mid": "getMid",
"mmsi": "getMMSI",
"minute": "getMinute",
"month": "getMonth",
"name": "getName",
"nameExtension": "getNameExtension",
"numFragments": "getNumFragments",
"off_position": "getOffPosition",
"part": "getPartno",
"radio": "getRadio",
"raim": "getRaim",
"second": "getSecond",
"seqMsgId": "getSeqMsgId",
"shiptype": "getShiptype",
"speed": "getSpeed",
"status": "getStatus",
"turn": "getTurn",
"type": "getType",
"vendorInfo": "getVendorInfo",
"virtual_aid": "getVirtualAid",
"year": "getYear"
};
/**
* Type 6 and 8 (Binary addressed message and Binary broadcast message) contain lat/lon in some of their subtypes.
* These messages are evidently only used in the St Lawrence seaway, the USG PAWSS system and the Port Authority of
* london and aren't implemented in this code
*
* Type 17 is the Differential correction message type and is not implemented in this code
* Type 22 is a channel management message and is not implemented in this code
* Type 23 is a Group assignment message and is not implemented in this code
*/
};
/** Loads required attributes from AIVDM message for retrieval by other methods
[0]=!AIVDM, [1]=Number of fragments, [2]=Fragment num, [3]=Seq msg ID, [4]=channel, [5]=payload,
Fetch the AIVDM part of the line, from !AIVDM to the end of the line
Split the line into fragments, delimited by commas
fetch numFragments, fragmentNum and SeqMsgId (SeqMsgId may be empty)
convert to a binary 6 bit string
: param (string) line. The received message within which we hope an AIVDM statement exists
:returns True if message is a single packet msg (1,2,3,9,18,27 etc) or part 1 of a multi_part message
False if !AIVDM not in the line or exception during decode process
*/
aivdmDecode.prototype = {
/**
* getData(aivdm)
* Decodes message, then returns an object containing extracted data
* If the message is received in two parts (i.e. type 5 and 19) then
* the return for the first of the messages is null. When the second part has been received then it
* is combined with the first and decoded.
* Whether a single or two part message, the return will contain the original message(s) in an array called 'aivdm'
*/
getData: function (line) {
var lineData = {
numFragments: this.numFragments,
fragmentNum: this.fragmentNum,
type: this.getType(),
mmsi: this.getMMSI(),
mid: this.getMid(),
seqMsgId: this.getSeqMsgId(),
aivdm: this.splitLines
};
return this.msgTypeSwitcher(line, lineData);
},
/**
* msgTypeSwitcher
* Used only by getData
* Fills fields relevant to the message type
* @param line The !AIVD string
* @param lineData The partially filled lineData object
* @returns {*} lineData object or false (if lineData is not filled
*/
msgTypeSwitcher: function (line, lineData) {
switch (this.getType()) {
// Implemented message types
case 1:
case 2:
case 3:
lineData = this.fill_1_2_3(line, lineData);
break;
case 4:
lineData = this.fill_4(line, lineData);
break;
case 5:
lineData = this.fill_5(line, lineData);
break;
case 9:
lineData = this.fill_9(line, lineData);
break;
case 18:
lineData = this.fill_18(line, lineData);
break;
case 19:
lineData = this.fill_19(line, lineData);
break;
case 21:
lineData = this.fill_21(line, lineData);
break;
case 24:
lineData.partno = this.getPartno();
if (lineData.partno === 'A') {
lineData = this.fill_24_0(line, lineData);
} else if (lineData.partno === 'B') {
lineData = this.fill_24_1(line, lineData);
}
break;
case 27:
lineData = this.fill_27(line, lineData);
break;
// unimplemented message types
case 6:
case 7:
case 8:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 20:
case 22:
case 23:
case 25:
case 26:
if (module.parent && module.parent.exports.isDebug) {
//if (swu.hasProp(module, 'parent.exports.isDebug')) {
console.log('Message type (switch) %d', parseInt(this.binString.substr(0, 6), 2));
console.log(line);
console.log('-------------------------------------------------------');
}
lineData = false;
break;
default:
if (module.parent && module.parent.exports.isDebug) {
//if (swu.hasProp(module, 'prent.exports.isDebug')) {
console.log('Message type ????? %d ?????', parseInt(this.binString.substr(0, 6), 2));
}
lineData = false;
}
if (lineData) {
if (this.returnJson) {
return JSON.stringify(lineData);
} else {
return lineData;
}
} else {
return false;
}
},
fill_1_2_3: function (line, lineData) {
var latLon = this.getLatLon();
var status = this.getStatus();
var maneuver = this.getManeuver();
if (this.aivdmPassthrough) { lineData.aivdm = [line]; }
lineData.status = status.status_num;
lineData.status_text = status.status_text;
lineData.turn = this.getTurn();
lineData.speed = this.getSpeed();
lineData.accuracy = this.getAccuracy();
lineData.lon = latLon.lon;
lineData.lat = latLon.lat;
lineData.course = this.getCourse();
lineData.heading = this.getHeading();
lineData.second = this.getSecond();
lineData.maneuver = maneuver.maneuver;
lineData.maneuver_text = maneuver.maneuver_text;
lineData.raim = this.getRaim();
lineData.radio = this.getRadio();
return lineData;
},
fill_4: function (line, lineData) {
var latLon = this.getLatLon();
var epfd = this.getEpfd();
if (this.aivdmPassthrough) { lineData.aivdm = [line]; }
lineData.year = this.getYear();
lineData.month = this.getMonth();
lineData.day = this.getDay();
lineData.hour = this.getHour();
lineData.minute = this.getMinute();
lineData.second = this.getSecond();
lineData.accuracy = this.getAccuracy();
lineData.lon = latLon.lon;
lineData.lat = latLon.lat;
lineData.epfd = epfd.epfd;
lineData.epfd_text = epfd.epfd_text;
lineData.raim = this.getRaim();
lineData.radio = this.getRadio();
return lineData;
},
fill_5: function (line, lineData) {
var dimensions = this.getDimensions();
var epfd = this.getEpfd();
var shiptype = this.getShiptype();
var eta = sprintf(
'%s-%sT%s:%sZ',
this.getMonth().lpad('0', 2),
this.getDay().lpad('0', 2),
this.getHour().lpad('0', 2),
this.getMinute().lpad('0', 2)
);
//if (this.aivdmPassthrough) { lineData.aivdm = this.splitLines; }
//if (this.aivdmPassthrough) { lineData.aivdm = this.splitParts; }
lineData.imo = this.getIMO();
lineData.callsign = this.getCallsign();
lineData.shipname = this.getName();
lineData.shiptype = shiptype.shiptype;
lineData.shiptype_text = shiptype.shiptype_text;
lineData.to_bow = dimensions.to_bow;
lineData.to_stern = dimensions.to_stern;
lineData.to_port = dimensions.to_port;
lineData.to_starboard = dimensions.to_starboard;
lineData.epfd = epfd.epfd;
lineData.eta = eta;
lineData.epfd_text = epfd.epfd.text;
lineData.month = this.getMonth();
lineData.day = this.getDay();
lineData.hour = this.getHour();
lineData.minute = this.getMinute();
lineData.draught = this.getDraught();
lineData.destination = this.getDestination();
lineData.dte = this.getDte();
return lineData;
},
fill_9: function (line, lineData) {
var latLon = this.getLatLon();
if (this.aivdmPassthrough) { lineData.aivdm = [line]; }
lineData.alt = this.getAlt();
lineData.speed = this.getSpeed();
lineData.accuracy = this.getAccuracy();
lineData.lon = latLon.lon;
lineData.lat = latLon.lat;
lineData.course = this.getCourse();
lineData.second = this.getSecond();
lineData.assigned = this.getAssigned();
lineData.raim = this.getRaim();
lineData.radio = this.getRadio();
return lineData;
},
fill_18: function (line, lineData) {
var latLon = this.getLatLon();
if (this.aivdmPassthrough) { lineData.aivdm = [line]; }
lineData.speed = this.getSpeed();
lineData.accuracy = this.getAccuracy();
lineData.lon = latLon.lon;
lineData.lat = latLon.lat;
lineData.course = this.getCourse();
lineData.heading = this.getHeading();
lineData.second = this.getSecond();
lineData.raim = this.getRaim();
lineData.radio = this.getRadio();
return lineData;
},
fill_19: function (line, lineData) {
var latLon = this.getLatLon();
var dimensions = this.getDimensions();
var epfd = this.getEpfd();
var shiptype = this.getShiptype();
if (this.aivdmPassthrough) { lineData.aivdm = [line]; }
lineData.speed = this.getSpeed();
lineData.accuracy = this.getAccuracy();
lineData.lon = latLon.lon;
lineData.lat = latLon.lat;
lineData.course = this.getCourse();
lineData.heading = this.getHeading();
lineData.second = this.getSecond();
lineData.shipname = this.getName();
lineData.shiptype = shiptype.shiptype;
lineData.shiptype_text = shiptype.shiptype_text;
lineData.to_bow = dimensions.to_bow;
lineData.to_stern = dimensions.to_stern;
lineData.to_port = dimensions.to_port;
lineData.to_starboard = dimensions.to_starboard;
lineData.epfd = epfd.epfd;
lineData.epfd_text = epfd.epfd_text;
lineData.raim = this.getRaim();
return lineData;
},
fill_21: function (line, lineData) {
var latLon = this.getLatLon();
var dimensions = this.getDimensions();
var epfd = this.getEpfd();
if (this.aivdmPassthrough) { lineData.aivdm = [line]; }
lineData.aid_type = this.getAidType();
lineData.name = this.getName();
lineData.accuracy = this.getAccuracy();
lineData.lon = latLon.lon;
lineData.lat = latLon.lat;
lineData.to_bow = dimensions.to_bow;
lineData.to_stern = dimensions.to_stern;
lineData.to_port = dimensions.to_port;
lineData.to_starboard = dimensions.to_starboard;
lineData.epfd = epfd.epfd;
lineData.epfd_text = epfd.epfd_text;
lineData.second = this.getSecond();
lineData.off_position = this.getOffPosition();
lineData.raim = this.getRaim();
lineData.virtual_aid = this.getVirtualAid();
lineData.assigned = this.getAssigned();
lineData.name += this.getNameExtension();
return lineData;
},
fill_24_0: function (line, lineData) {
if (this.aivdmPassthrough) { lineData.aivdm = [line]; }
lineData.part = this.getPartno();
lineData.shipname = this.getName();
return lineData;
},
fill_24_1: function (line, lineData) {
var dimensions;
var vendorInfo = this.getVendorInfo();
var shiptype = this.getShiptype();
if (this.aivdmPassthrough) { lineData.aivdm = [line]; }
lineData.part = this.getPartno();
lineData.shiptype = shiptype.shiptype;
lineData.shiptype_text = shiptype.shiptype_text;
lineData.callsign = this.getCallsign();
if (lineData.mmsi.toString().substr(0, 2) === '98') { // Then this is an auxiliary craft (see AIVDM Docs)
lineData.mothership_mmsi = this.getBits(132, 30);
dimensions = {to_bow: null, to_stern: null, to_port: null, to_starboard: null};
} else {
lineData.mothership_mmsi = null;
dimensions = this.getDimensions();
}
lineData.vendorid = vendorInfo.vendorString;
lineData.model = vendorInfo.model;
lineData.serial = vendorInfo.serial;
lineData.to_bow = dimensions.to_bow;
lineData.to_stern = dimensions.to_stern;
lineData.to_port = dimensions.to_port;
lineData.to_starboard = dimensions.to_starboard;
return lineData;
},
fill_27: function (line, lineData) {
var latLon = this.getLatLon();
var status = this.getStatus();
if (this.aivdmPassthrough) { lineData.aivdm = [line]; }
lineData.accuracy = this.getAccuracy();
lineData.raim = this.getRaim();
lineData.status = status.status_num;
lineData.status_text = status.status_text;
lineData.lon = latLon.lon;
lineData.lat = latLon.lat;
lineData.speed = this.getSpeed();
lineData.course = this.getCourse();
return lineData;
},
// -------------------------------
/**
* getAccuracy()
* @returns {boolean} false if 0, else true - to synchronise with how gpsd handles it
*/
getAccuracy: function () {
switch (this.msgType) {
case 1:
case 2:
case 3:
case 9:
return this.getBits(60, 1) !== 0;
case 18:
case 19:
return this.getBits(56, 1) !== 0;
case 21:
return this.getBits(163, 1) !== 0;
case 27:
return this.getBits(38, 1) !== 0;
default:
return false;
}
},
getAidType: function () {
return this.getBits(38,5);
},
getAlt: function () {
return this.getBits(38, 12);
},
getAssigned: function () {
switch (this.msgType) {
case 9:
return this.getBits(146, 1);
case 21:
return this.getBits(270, 1);
default:
return false;
}
},
getCallsign: function () {
var callsignField;
switch (this.msgType) {
case 5:
callsignField = this.binString.substr(70, 42);
break;
case 24:
if (this.partNo == 1) {
callsignField = this.binString.substr(90, 42);
} else {
callsignField = null;
}
break;
default:
callsignField = null
}
if (callsignField) {
var callsignArray = callsignField.match(/.{1,6}/g);
var callsign = '';
var self = this;
_.each(callsignArray, function (binChar, index) {
callsign += self.char_table[parseInt(binChar, 2)];
});
return callsign.replace(/@/g, '').trim();
} else {
return false;
}
},
getCourse: function () {
switch (this.msgType) {
case 1:
case 2:
case 3:
case 9:
return this.getBits(116, 12) / 10;
break;
case 18:
case 19:
return this.getBits(112, 12) / 10;
break;
case 27:
return this.getBits(85, 9);
break;
default:
return false;
}
},
getDay: function () {
switch (this.msgType) {
case 4:
return this.getBits(56, 5);
case 5:
return this.getBits(278, 5);
default:
return false;
}
},
getDestination: function () {
var destField = null;
switch (this.msgType) {
case 5:
destField = this.binString.substr(302, 120);
break;
default:
destField = null
}
if (destField) {
var destArray = destField.match(/.{1,6}/g);
var destination = '';
var self = this;
_.each(destArray, function (binChar, index) {
destination += self.char_table[parseInt(binChar, 2)];
});
return destination.replace(/@/g, '').trim();
} else {
return false;
}
},
getDimensions: function () {
var dimensions = {to_bow: null, to_stern: null, to_port: null, to_starboard: null};
switch (this.msgType) {
case 5:
dimensions.to_bow = this.getBits(240, 9);
dimensions.to_stern = this.getBits(249, 9);
dimensions.to_port = this.getBits(258, 6);
dimensions.to_starboard = this.getBits(264, 6);
break;
case 19:
dimensions.to_bow = this.getBits(271, 9);
dimensions.to_stern = this.getBits(280, 9);
dimensions.to_port = this.getBits(289, 6);
dimensions.to_starboard = this.getBits(295, 6);
break;
case 21:
dimensions.to_bow = this.getBits(219, 9);
dimensions.to_stern = this.getBits(228, 9);
dimensions.to_port = this.getBits(237, 6);
dimensions.to_starboard = this.getBits(243, 6);
break;
case 24:
dimensions.to_bow = this.getBits(132, 9);
dimensions.to_stern = this.getBits(141, 9);
dimensions.to_port = this.getBits(150, 6);
dimensions.to_starboard = this.getBits(156, 6);
break;
}
return dimensions;
},
getDraught: function () {
switch (this.msgType) {
case 5:
return this.getBits(294, 8) / 10;
default:
return 0;
}
},
getDte: function () {
switch (this.msgType) {
case 5:
return this.getBits(423, 1);
default:
return 0;
}
},
getETA: function () {
},
getEpfd: function () {
var epfd;
switch (this.msgType) {
case 4:
epfd = this.getBits(134, 4);
break;
case 5:
epfd = this.getBits(270, 4);
break;
case 19:
epfd = this.getBits(310, 4);
break;
case 21:
epfd = this.getBits(249, 4);
break;
default:
epfd = 0;
}
if (epfd < 0 || epfd > 8) { epfd = 0; }
return {epfd: epfd, epfd_text: this.epfdText[epfd]}
},
getFragmentNum: function getFragmentNum () {
return this.fragmentNum;
},
getHeading: function () {
switch (this.msgType) {
case 1:
case 2:
case 3:
return this.getBits(128, 9);
case 18:
case 19:
return this.getBits(124, 9);
default:
return false;
}
},
getHour: function () {
switch (this.msgType) {
case 4:
return this.getBits(61, 5);
case 5:
return this.getBits(283, 5);
default:
return false;
}
},
getIMO: function () {
switch (this.msgType) {
case 5:
return this.getBits(40, 30);
default:
return false;
}
},
getLatLon: function () {
// Does this message contain position info?
var msgType = this.getType();
if (msgType in this.posGroups) {
var latGroup = this.posGroups[msgType]['lat'];
var lonGroup = this.posGroups[msgType]['lon'];
// fetch the relevant bits
var latString = this.binString.substr(latGroup['start'], latGroup['length']);
var lonString = this.binString.substr(lonGroup['start'], lonGroup['length']);
// convert them
var lat = this.toTwosComplement(parseInt(latString, 2), latString.length) / latGroup['divisor'];
var lon = this.toTwosComplement(parseInt(lonString, 2), lonString.length) / lonGroup['divisor'];
return {"lat": parseFloat(lat.toFixed(4)), "lon": parseFloat(lon.toFixed(4))};
} else { // Not a message type that contains a position
return {'lat': null, 'lon': null};
}
},
getManeuver: function () {
var man, maneuver_text;
switch (this.msgType) {
case 1:
case 2:
case 3:
man = this.getBits(143, 2);
break;
default:
man = 0;
}
if (man < 1 || man > 2) { man = 0; }
maneuver_text = this.maneuverText[man];
return {maneuver: man, maneuver_text: maneuver_text};
},
/**
* getMid() Fetched 3 digit MID number that is embedded in MMSI
* The mid usually occupies chars 0,1 and 2 of the MMSI string
* For some special cases it may be at another location (see below).
* Uses this.midTable to look up nationality.
* Returns "" unless the option 'includeMID' is set true in the aivdmDecode constructor options
* @returns {string} mid - a string containing 3 numeric digits.
*/
getMid: function () {
// See info in http://catb.org/gpsd/AIVDM.html
if (this.includeMID) {
var mid;
var mmsi = this.getMMSI();
var nationality;
if (mmsi !== null && mmsi.length === 9) {
// Coastal station
if (mmsi.substr(0, 2) == "00") {
mid = mmsi.substr(2, 3);
}
// Group of ships (i.e. coast guard is 0369
else if (mmsi.substr(0, 1) === "0") {
mid = mmsi.substr(1, 3);
}
// SAR Aircraft
else if (mmsi.substr(0, 3) === "111") {
mid = mmsi.substr(3, 3);
}
// Aus craft associated with a parent ship
else if (mmsi.substr(0, 2) === "98" || mmsi.substr(0, 2) === "99") {
mid = mmsi.substr(2, 3);
}
// AIS SART
else if (mmsi.substr(0, 3) === "970") {
mid = mmsi.substr(3, 3);
}
// MOB device (972) or EPIRB (974). Neither of these have a MID
else if (mmsi.substr(0, 3) === "972" || mmsi.substr(0, 3) === "974") {
mid = "";
}
// Normal ship transponder
else {
mid = mmsi.substr(0, 3);
}
if (mid !== "") {
nationality = this.midTable[mid];
if (nationality !== undefined) {
if (typeof(nationality) !== 'string') {
nationality = "";
}
} else {
nationality = "";
}
} else {
nationality = "";
}
} else {
nationality = "";
}
} else {
nationality = "";
}
return nationality;
},
getMMSI: function (/* onlyValidMid */) {
//TODO: onlyValidMid to be implemented later
return this.getBits(8, 30);
},
getMinute: function () {
switch (this.msgType) {
case 4:
return this.getBits(66, 6);
case 5:
return this.getBits(288, 6);
default:
return false;
}
},
getMonth: function () {
switch (this.msgType) {
case 4:
return this.getBits(53, 4);
case 5:
return this.getBits(274, 4);
default:
return false;
}
},
getName: function () {
var msgType = this.getType();
var nameField = null;
switch (msgType) {
case 5:
nameField = this.binString.substr(112, 120);
break;
case 19:
nameField = this.binString.substr(143, 120);
break;
case 21:
nameField = this.binString.substr(43, 120);
break;
case 24:
nameField = this.binString.substr(40, 120);
break;
default:
nameField = null
}
if (nameField) {
var nameArray = nameField.match(/.{1,6}/g);
var name = '';
var self = this;
_.each(nameArray, function (binChar, index) {
name += self.char_table[parseInt(binChar, 2)];
});
return name.replace(/@/g, '').trim();
} else {
return false;
}
},
getNameExtension: function () {
switch (this.msgType) {
case 21:
if (this.binString.length >= 272) {
var nameBits = this.binString.substring(272, this.binString.length -1);
var nameArray = nameBits.match(/.{1,6}/g);
var name = '';
var self = this;
_.each(nameArray, function (binChar, index) {
name += self.char_table[parseInt(binChar, 2)];
});
return name.replace(/@/g, '').trim();
} else {
return '';
}
break;
default:
return false;
}
},
getNumFragments: function getNumFragments () {
return this.numFragments;
},
getOffPosition: function () {
return this.getBits(259, 1);
},
getPartno: function () {
switch (this.msgType) {
case 24:
var partRaw = parseInt(this.getBits(38, 2), 2);
var partNo = partRaw === 0 ? 'A' : 'B';
return partNo;
default:
return '';
}
},
getRadio: function () {
switch (this.msgType) {
case 1:
case 2:
case 3:
return this.getBits(149, 19);
case 9:
case 18:
return this.getBits(148, 19);
default:
return false;
}
},
getRaim: function () {
switch (this.msgType) {
case 1:
case 2:
case 3:
return this.getBits(148, 1) !== 0;
case 9:
case 18:
return this.getBits(147, 1) !== 0;
case 19:
return this.getBits(305, 1) !== 0;
case 21:
return this.getBits(268, 1) !== 0;
case 27:
return this.getBits(39, 1) !== 0;
default:
return false;
}
},
getSecond: function () {
switch (this.msgType) {
case 1:
case 2:
case 3:
return this.getBits(137, 6);
case 9:
return this.getBits(128, 6);
case 18:
case 19:
return this.getBits(133, 6);
case 21:
return this.getBits(253, 6);
default:
return false;
}
},
getSeqMsgId: function () {
return this.seqMsgId;
},
getShiptype: function () {
var sType;
switch (this.msgType) {
case 5:
sType = this.getBits(232, 8);
break;
case 19:
sType = this.getBits(263, 8);
break;
case 24:
sType = this.getBits(40, 8);
break;
default:
sType = 0;
}
if (sType < 0 || sType > 99) { sType = 0; }
return {shiptype: sType, shiptype_text: this.shiptypeText[sType]};
},
getSpeed: function () {
if (this.numFragments == 1) {
var msgType = this.getType();
if (msgType in this.speedGroups) {
var group = this.speedGroups[msgType];
var speedString = this.binString.substr(group['start'], group['length']);
return parseInt(speedString, 2) / group['divisor'];
} else {
return false;
}
} else {
return false;
}
},
getStatus: function () {
var statusText = "", statusNum = -1;
switch (this.msgType) {
case 1:
case 2:
case 3:
statusNum = this.getBits(38, 4);
break;
case 27:
statusNum = this.getBits(40, 4);
break;
}
if (statusNum >= 0 && statusNum <= 15) {
statusText = this.navStatusText[statusNum];
}
// status_num coerced to string to match gpsdecode / gpsd
return {status_num: '' + statusNum, status_text: statusText}
},
/**
* getTurn() Called only for types 1,2 and 3
* @returns {null}
*/
getTurn: function () {
var turn = this.getBits(42, 8);
switch (true) {
case turn === 0:
break;
case turn > 0 && turn <= 126:
return '' + (4.733 * Math.sqrt(turn));
case turn === 127:
return 'fastright';
case turn < 0 && turn >= -126:
return '' + (4.733 * Math.sqrt(turn));
case turn === -127:
return 'fastleft';
case turn == 128 || turn == -128:
return "nan";
default:
return "nan";
}
},
getType: function () {
return this.getBits(0,6);
},
getVendorInfo: function () {
var vendorBits, vendorArray, vendorString, model, serial;
switch (this.msgType) {
case 24:
vendorBits = this.binString.substr(48, 38);
vendorArray = vendorBits.match(/.{1,6}/g);
vendorString = '';
var self = this;
_.each(vendorArray, function (binChar, index) {
vendorString += self.char_table[parseInt(binChar, 2)];
});
vendorString = vendorString.replace(/@/g, '').trim();
model = parseInt(this.binString.substr(66, 4), 2);
serial = parseInt(this.binString.substr(70, 20), 2);
return {vendorString: vendorString, model: model, serial: serial};
}
},
/**
* getVendorID not currently implemented
* @returns {*}
*/
getVendorID: function () {
var msgType = this.getType();
var vendorID = null;
switch (msgType) {
case 24:
vendorID = this.binString.substr(48, 18);
break;
default:
vendorID = null
}
if (vendorID) {
var vendorIDArray = vendorID.match(/.{1,6}/g);
var vid = '';
var self = this;
_.each(vendorIDArray, function (binChar, index) {
vid += self.char_table[parseInt(binChar, 2)];
});
return vid.replace(/@/g, '').trim();
} else {
return false;
}
},
getVirtualAid: function () {
return this.getBits(269, 1);
},
getYear: function () {
switch (this.msgType) {
case 4:
return this.getBits(38, 14);
default:
return false;
}
},
// ---------------------------------------
/**
* manageFragments
* makes aivdm sentences ready for data fetching by using buildBinString to convert them to a binary string
* Returns true when a message is ready for data to be fetched.
* For single part messages this is after processing of the aivdm payload
* For multi part messages the payloads are accumulated until all have been received, then the binString
* conversion is done.
* For multi part messages returns false for the first and any intermediate messages
* @param line A string containing an AIVDM or AIVDO sentence. May have a tag block on the front of the msg
* @param payload The payload portion of the AIVD? string
* @returns {boolean} true when this.binString has been set, false when this.binString is not set
*/
manageFragments: function (line, payload) {
// this.splitParts is an array of payloads that are joined to become the binString of multi msgs
// this.splitLines is an array of the received lines including AIVDM's
if (this.numFragments === 1) {
this.splitLines = [line];
this.binString = this.buildBinString(payload);
this.msgType = this.getType();
return true;
}
else if (this.numFragments > 1 && this.fragmentNum === 1) {
this.splitParts = [payload];
this.splitLines = [line];
this.splitPart1Sequence = this.seqMsgId;
this.binString = this.buildBinString(payload);
this.splitPart1Type = this.getType();
this.msgType = this.getType();
return false;
}
else if (this.numFragments > 1 && this.fragmentNum > 1) {
if (this.seqMsgId === this.splitPart1Sequence) {
this.splitParts.push(payload);
this.splitLines.push(line);
}
}
if (this.fragmentNum === this.numFragments) {
var parts = this.splitParts.join('');
this.binString = this.buildBinString(parts);
this.msgType = this.splitPart1Type;
return true;
} else {
return false;
}
},
/**
* decode
* @param line A line containing an !AIVD sentence
* @returns {boolean} true if this.binString has been set (ready for data to be fetched
* false if:
* binString not set,
* line is not an !AIVD
* !AIVD is not a supported type (see this.supportedTypes)
*/
decode: function (bLine) {
var line = bLine.toString('utf8');
var aivdmPos = line.indexOf('!AIVD');
if (aivdmPos !== -1) {
this.AIVDM = line.substr(aivdmPos);
var aivdmFragments = this.AIVDM.split(',');
this.numFragments = parseInt(aivdmFragments[1]);
this.fragmentNum = parseInt(aivdmFragments[2]);
try {
this.seqMsgId = parseInt(aivdmFragments[3]);
if (typeof(this.seqMsgId) !== 'number') { this.seqMsgId = ''; }
} catch (err) {
this.seqMsgId = '';
}
this.channel = aivdmFragments[4];
var payload = aivdmFragments[5];
if (this.manageFragments(line, payload)) {
if (_.contains(this.supportedTypes, this.msgType)) {
this.msgType = this.getType();
if (this.msgType == 24) {
this.partNo = this.getBits(38, 2)
}
return this.getData(bLine);
//return true; // this.binString is ready
} else {
return false;
}
} else { // this.binString is not ready
return false;
}
} else { // no !AIVD on front of line
return false;
}
},
buildBinString: function (payload) {
var binStr = '';
var payloadArr = payload.split("");
_.each(payloadArr, function (value) {
var dec = value.charCodeAt(0);
var bit8 = dec - 48;
if (bit8 > 40) {
bit8 -= 8;
}
var strBin = bit8.toString(2);
strBin = sprintf('%06s', strBin);
binStr += strBin;
});
if (module.parent && module.parent.exports.isDebug) {
//if (swu.hasProp(module, 'parent.exports.isDebug')) {
console.log('binString for type ', parseInt(binStr.substr(0, 6), 2), payload, binStr);
}
return binStr;
},
getBits: function (start, len) {
return parseInt(this.binString.substr(start, len), 2);
},
asciidec_2_8bit: function (dec) {
var newDec = dec - 48;
if (newDec > 40) {
newDec -= 8;
}
return newDec;
},
dec_2_6bit: function (bit8) {
var strBin = bit8.toString(2);
strBin = sprintf('%06s', strBin);
return strBin;
},
toTwosComplement: function (val, bits) {
if ((val & (1 << (bits - 1))) != 0) {
val -= 1 << bits;
}
return val;
}
};
module.exports = { aivdmDecode: aivdmDecode };
if (require.main === module) {
var SW_utilsModule = require('SW_utils');
SW_utils = new SW_utilsModule.SW_Utils('aivdmDecode', false);
/**
* testSet
* An array of objects. Each object contains:
* aivdm: The raw aivdm sentence to be decoded
* gpsd: aivdm as decoded by gpsdecode
* test: The fields within the decoded aivdm to test
* @type {*[]}
*/
var testSet = [
// type 5 first msg
{aivdm: '!AIVDM,2,1,4,A,539cRCP00000@7WSON08:3?V222222222222221@4@=3340Ht50000000000,0*13',
gpsd: ''
},
// type 5 second msg
{aivdm: '!AIVDM,2,2,4,A,00000000000,2*20',
gpsd: {"class":"AIS","device":"stdin","type":5,"repeat":0,"mmsi":211477070,"scaled":true,"imo":0,"ais_version":0,"callsign":"DA9877 ","shipname":"BB 39","shiptype":80,"shiptype_text":"Tanker - all ships of this type","to_bow":34,"to_stern":13,"to_port":3,"to_starboard":3,"epfd":1,"epfd_text":"GPS","eta":"00-00T24:60Z","draught":2.0,"destination":"","dte":0},
test: ['type', 'mmsi', 'imo', 'callsign', 'shipname', 'shiptype', 'shiptype_text', 'to_bow', 'to_stern', 'to_port',
'to_starboard', 'epfd', 'eta', 'draught', 'destination', 'dte']
},
// type 1
{aivdm: '!AIVDM,1,1,,A,144iRPgP001N;PjOb:@F1?vj0PSB,0*47',
gpsd: {"class":"AIS","device":"stdin","type":1,"repeat":0,"mmsi":273441410,"scaled":true,"status":"15","status_text":"Not defined","turn":"nan","speed":0.0,"accuracy":false,"lon":20.5739,"lat":55.3277,"course":154.0,"heading":511,"second":25,"maneuver":0,"raim":false,"radio":133330},
test: ['type', 'mmsi', 'status', 'status_text','turn', 'speed', 'accuracy', 'lon', 'lat', 'course', 'heading', 'second', 'maneuver', 'raim', 'radio']
},
// type 3
{aivdm: '!AIVDM,1,1,,A,33aTCJ0Oh;8>Q>7kW>eKwaf6010P,0*63',
gpsd: {"class":"AIS","device":"stdin","type":3,"repeat":0,"mmsi":244913000,"scaled":true,"status":"0","status_text":"Under way using engine","turn":"fastright","speed":1.1,"accuracy":false,"lon":115.0198,"lat":-21.6479,"course":307.0,"heading":311,"second":3,"maneuver":0,"raim":false,"radio":4128},
test: ['type', 'mmsi', 'status', 'status_text', 'turn', 'speed', 'accuracy', 'lon', 'lat', 'course', 'heading', 'second', 'maneuver', 'raim', 'radio']
},
// type 9
{aivdm: "!AIVDM,1,1,,A,97oordNF>hPppq5af003QHi0S7sE,0*52",
gpsd: {
"class": "AIS",
"device": "stdin",
"type": 9,
"repeat": 0,
"mmsi": 528349873,
"scaled": true,
"alt": 3672,
"speed": 944,
"accuracy": true,
"lon": 12.4276,
"lat": -38.9393,
"course": 90.1,
"second": 35,
"regional": 16,
"dte": 0,
"raim": false,
"radio": 818901
},
test: ['type', 'mmsi', 'speed', 'lon', 'lat']
},
// type 24
{aivdm: '!AIVDM,1,1,,B,H7OeD@QLE=A<D63:22222222220,2*25',
gpsd: {"class":"AIS","device":"stdin","type":24,"repeat":0,"mmsi":503010370,"scaled":true,"part":"A","shipname":"WESTSEA 2"},
test: ['type', 'mmsi', 'part', 'shipname']
},
//type 24 part A
{aivdm: '!AIVDM,1,1,,A,H697GjPhT4t@4qUF3;G;?F22220,2*7E',
gpsd: {"class":"AIS","device":"stdin","type":24,"repeat":0,"mmsi":412211146,"scaled":true,"part":"A","shipname":"LIAODANYU 25235"},
test: ['type', 'mmsi', 'part', 'shipname']
},
// type 24 part B
{aivdm: '!AIVDM,1,1,,B,H3mw=<TT@B?>1F0<7kplk01H1120,0*5D',
gpsd: {"class":"AIS","device":"stdin","type":24,"repeat":0,"mmsi":257936690,"scaled":true,"part":"B","shiptype":36,"shiptype_text":"Sailing","vendorid":"PRONAV","model":3,"serial":529792,"callsign":"LG3843","to_bow":11,"to_stern":1,"to_port":1,"to_starboard":2},
test: ['type', 'mmsi', 'part', 'shiptype', 'shiptype_text', 'vendorid', 'model', 'serial', 'callsign', 'to_bow', 'to_stern', 'to_port', 'to_starboard']
}
];
var aisDecoder = new aivdmDecode({returnJson: false, aivdmPassthrough: true});
_.each(testSet, function (val, index) {
var decoded = aisDecoder.decode(val.aivdm);
if (decoded) {
var testSubject = aisDecoder.getData(val.aivdm);
console.log(colors.cyan('Test subject ' + index));
if (testSubject && testSubject.type) {
//if (swu.hasProp(testSubject, 'type')) {
console.log(colors.cyan('Type: ' + testSubject.type));
}
if (val.gpsd.part) {
console.log(sprintf(colors.cyan('Part %s'), val.gpsd.part));
}
if (val.test) {
_.each(val.test, function (item) {
console.log('Testing: ' + item);
// test for undefined item in testSubject
if (testSubject[item] === undefined) {
console.log(colors.red('Item missing ' + item));
return;
}
// test that both items are the same type
else if (typeof(val.gpsd[item]) !== typeof(testSubject[item])) {
console.log(colors.red('Type mismatch: gpsd: ' + typeof(val.gpsd[item]) + ' me: ' + typeof(testSubject[item])));
return;
}
// if gpsd is int then testSubject should also be int
else if (SW_utils.isInt(val.gpsd[item])) {
if (!SW_utils.isInt(testSubject[item])) {
console.log(colors.red('Type mismatch (gpsd int testsubject float'));
return;
}
// if gpsd is float then testSubject should also be float
} else if (SW_utils.isFloat(val.gpsd[item])) {
if (!SW_utils.isFloat(testSubject[item])) {
console.log(colors.red('Type mismatch (gpsd float testsubject int'));
return
}
}
// finally, test items for equality
if (typeof(val.gpsd[item]) === 'string') {
gItem = val.gpsd[item].trim();
tItem = testSubject[item].trim();
} else {
gItem = val.gpsd[item];
tItem = testSubject[item];
}
if (gItem === tItem) {
console.log(
sprintf(colors.yellow('Test ok gpsd: %s'), gItem) +
sprintf(colors.cyan(' me: %s'), tItem)
);
} else {
console.log(colors.red('Test failed'));
console.log(colors.red('gpsd: ' + val.gpsd[item] + ' me: ' + testSubject[item]))
}
})
}
}
if (this.isDebug) { console.log(colors.magenta('----------------------------------------------------------')); }
});
}<|fim▁end|> | |
<|file_name|>cellGcmSys.cpp<|end_file_name|><|fim▁begin|>#include "stdafx.h"
#include "Emu/SysCalls/SysCalls.h"
#include "Emu/SysCalls/SC_FUNC.h"
#include "Emu/GS/GCM.h"
void cellGcmSys_init();
void cellGcmSys_load();
void cellGcmSys_unload();
Module cellGcmSys(0x0010, cellGcmSys_init, cellGcmSys_load, cellGcmSys_unload);
u32 local_size = 0;
u32 local_addr = 0;
enum
{
CELL_GCM_ERROR_FAILURE = 0x802100ff,
CELL_GCM_ERROR_NO_IO_PAGE_TABLE = 0x80210001,
CELL_GCM_ERROR_INVALID_ENUM = 0x80210002,
CELL_GCM_ERROR_INVALID_VALUE = 0x80210003,
CELL_GCM_ERROR_INVALID_ALIGNMENT = 0x80210004,
CELL_GCM_ERROR_ADDRESS_OVERWRAP = 0x80210005
};
// Function declaration
int cellGcmSetPrepareFlip(mem_ptr_t<CellGcmContextData> ctxt, u32 id);
//----------------------------------------------------------------------------
// Memory Mapping
//----------------------------------------------------------------------------
struct gcm_offset
{
u64 io;
u64 ea;
};
void InitOffsetTable();
int32_t cellGcmAddressToOffset(u64 address, mem32_t offset);
uint32_t cellGcmGetMaxIoMapSize();
void cellGcmGetOffsetTable(mem_ptr_t<gcm_offset> table);
int32_t cellGcmIoOffsetToAddress(u32 ioOffset, u64 address);
int32_t cellGcmMapEaIoAddress(const u32 ea, const u32 io, const u32 size);
int32_t cellGcmMapEaIoAddressWithFlags(const u32 ea, const u32 io, const u32 size, const u32 flags);
int32_t cellGcmMapMainMemory(u64 ea, u32 size, mem32_t offset);
int32_t cellGcmReserveIoMapSize(const u32 size);
int32_t cellGcmUnmapEaIoAddress(u64 ea);
int32_t cellGcmUnmapIoAddress(u64 io);
int32_t cellGcmUnreserveIoMapSize(u32 size);
//----------------------------------------------------------------------------
CellGcmConfig current_config;
CellGcmContextData current_context;
gcmInfo gcm_info;
u32 map_offset_addr = 0;
u32 map_offset_pos = 0;
//----------------------------------------------------------------------------
// Data Retrieval
//----------------------------------------------------------------------------
u32 cellGcmGetLabelAddress(u8 index)
{
cellGcmSys.Log("cellGcmGetLabelAddress(index=%d)", index);
return Memory.RSXCMDMem.GetStartAddr() + 0x10 * index;
}
u32 cellGcmGetReportDataAddressLocation(u8 location, u32 index)
{
ConLog.Warning("cellGcmGetReportDataAddressLocation(location=%d, index=%d)", location, index);
return Emu.GetGSManager().GetRender().m_report_main_addr;
}
u64 cellGcmGetTimeStamp(u32 index)
{
cellGcmSys.Log("cellGcmGetTimeStamp(index=%d)", index);
return Memory.Read64(Memory.RSXFBMem.GetStartAddr() + index * 0x10);
}
//----------------------------------------------------------------------------
// Command Buffer Control
//----------------------------------------------------------------------------
u32 cellGcmGetControlRegister()
{
cellGcmSys.Log("cellGcmGetControlRegister()");
return gcm_info.control_addr;
}
u32 cellGcmGetDefaultCommandWordSize()
{
cellGcmSys.Warning("cellGcmGetDefaultCommandWordSize()");
return 0x400;
}
u32 cellGcmGetDefaultSegmentWordSize()
{
cellGcmSys.Warning("cellGcmGetDefaultSegmentWordSize()");
return 0x100;
}
int cellGcmInitDefaultFifoMode(s32 mode)
{
cellGcmSys.Warning("cellGcmInitDefaultFifoMode(mode=%d)", mode);
return CELL_OK;
}
int cellGcmSetDefaultFifoSize(u32 bufferSize, u32 segmentSize)
{
cellGcmSys.Warning("cellGcmSetDefaultFifoSize(bufferSize=0x%x, segmentSize=0x%x)", bufferSize, segmentSize);
return CELL_OK;
}
//----------------------------------------------------------------------------
// Hardware Resource Management
//----------------------------------------------------------------------------
int cellGcmBindTile(u8 index)
{
cellGcmSys.Warning("cellGcmBindTile(index=%d)", index);
if (index >= RSXThread::m_tiles_count)
{
return CELL_GCM_ERROR_INVALID_VALUE;
}
auto& tile = Emu.GetGSManager().GetRender().m_tiles[index];
tile.m_binded = true;
return CELL_OK;
}
int cellGcmBindZcull(u8 index)
{
cellGcmSys.Warning("TODO: cellGcmBindZcull(index=%d)", index);
return CELL_OK;
}
int cellGcmGetConfiguration(mem_ptr_t<CellGcmConfig> config)
{
cellGcmSys.Log("cellGcmGetConfiguration(config_addr=0x%x)", config.GetAddr());
if (!config.IsGood()) return CELL_EFAULT;
*config = current_config;
return CELL_OK;
}
int cellGcmGetFlipStatus()
{
return Emu.GetGSManager().GetRender().m_flip_status;
}
u32 cellGcmGetTiledPitchSize(u32 size)
{
//TODO
cellGcmSys.Warning("cellGcmGetTiledPitchSize(size=%d)", size);
return size;
}
int cellGcmInit(u32 context_addr, u32 cmdSize, u32 ioSize, u32 ioAddress)
{
cellGcmSys.Warning("cellGcmInit(context_addr=0x%x,cmdSize=0x%x,ioSize=0x%x,ioAddress=0x%x)", context_addr, cmdSize, ioSize, ioAddress);
if(!cellGcmSys.IsLoaded())
cellGcmSys.Load();
if(!local_size && !local_addr)
{
local_size = 0xf900000; //TODO
local_addr = Memory.RSXFBMem.GetStartAddr();
Memory.RSXFBMem.AllocAlign(local_size);
}
cellGcmSys.Warning("*** local memory(addr=0x%x, size=0x%x)", local_addr, local_size);
InitOffsetTable();
Memory.MemoryBlocks.push_back(Memory.RSXIOMem.SetRange(0x50000000, 0x10000000/*256MB*/));//TODO: implement allocateAdressSpace in memoryBase
if(cellGcmMapEaIoAddress(ioAddress, 0, ioSize) != CELL_OK)
{
Memory.MemoryBlocks.pop_back();
return CELL_GCM_ERROR_FAILURE;
}
map_offset_addr = 0;
map_offset_pos = 0;
current_config.ioSize = ioSize;
current_config.ioAddress = ioAddress;
current_config.localSize = local_size;
current_config.localAddress = local_addr;
current_config.memoryFrequency = 650000000;
current_config.coreFrequency = 500000000;
Memory.RSXCMDMem.AllocAlign(cmdSize);
u32 ctx_begin = ioAddress/* + 0x1000*/;
u32 ctx_size = 0x6ffc;
current_context.begin = ctx_begin;
current_context.end = ctx_begin + ctx_size;
current_context.current = current_context.begin;
current_context.callback = Emu.GetRSXCallback() - 4;
gcm_info.context_addr = Memory.MainMem.AllocAlign(0x1000);
gcm_info.control_addr = gcm_info.context_addr + 0x40;
Memory.WriteData(gcm_info.context_addr, current_context);
Memory.Write32(context_addr, gcm_info.context_addr);
CellGcmControl& ctrl = (CellGcmControl&)Memory[gcm_info.control_addr];
ctrl.put = 0;
ctrl.get = 0;
ctrl.ref = -1;
auto& render = Emu.GetGSManager().GetRender();
render.m_ctxt_addr = context_addr;
render.m_gcm_buffers_addr = Memory.Alloc(sizeof(gcmBuffer) * 8, sizeof(gcmBuffer));
render.m_zculls_addr = Memory.Alloc(sizeof(CellGcmZcullInfo) * 8, sizeof(CellGcmZcullInfo));
render.m_tiles_addr = Memory.Alloc(sizeof(CellGcmTileInfo) * 15, sizeof(CellGcmTileInfo));
render.m_gcm_buffers_count = 0;
render.m_gcm_current_buffer = 0;
render.m_main_mem_addr = 0;
render.Init(ctx_begin, ctx_size, gcm_info.control_addr, local_addr);
return CELL_OK;
}
int cellGcmResetFlipStatus()
{
Emu.GetGSManager().GetRender().m_flip_status = 1;
return CELL_OK;
}
int cellGcmSetDebugOutputLevel(int level)
{
cellGcmSys.Warning("cellGcmSetDebugOutputLevel(level=%d)", level);
switch (level)
{
case CELL_GCM_DEBUG_LEVEL0:
case CELL_GCM_DEBUG_LEVEL1:
case CELL_GCM_DEBUG_LEVEL2:
Emu.GetGSManager().GetRender().m_debug_level = level;
break;
default: return CELL_EINVAL;
}
return CELL_OK;
}
int cellGcmSetDisplayBuffer(u32 id, u32 offset, u32 pitch, u32 width, u32 height)
{
cellGcmSys.Warning("cellGcmSetDisplayBuffer(id=0x%x,offset=0x%x,pitch=%d,width=%d,height=%d)",
id, offset, width ? pitch/width : pitch, width, height);
if(id > 7) return CELL_EINVAL;
gcmBuffer* buffers = (gcmBuffer*)Memory.GetMemFromAddr(Emu.GetGSManager().GetRender().m_gcm_buffers_addr);
buffers[id].offset = re(offset);
buffers[id].pitch = re(pitch);
buffers[id].width = re(width);
buffers[id].height = re(height);
if(id + 1 > Emu.GetGSManager().GetRender().m_gcm_buffers_count)
{
Emu.GetGSManager().GetRender().m_gcm_buffers_count = id + 1;
}
return CELL_OK;
}
int cellGcmSetFlip(mem_ptr_t<CellGcmContextData> ctxt, u32 id)
{
cellGcmSys.Log("cellGcmSetFlip(ctx=0x%x, id=0x%x)", ctxt.GetAddr(), id);
int res = cellGcmSetPrepareFlip(ctxt, id);
return res < 0 ? CELL_GCM_ERROR_FAILURE : CELL_OK;
}
int cellGcmSetFlipHandler(u32 handler_addr)
{
cellGcmSys.Warning("cellGcmSetFlipHandler(handler_addr=%d)", handler_addr);
if (handler_addr != 0 && !Memory.IsGoodAddr(handler_addr))
{
return CELL_EFAULT;
}
Emu.GetGSManager().GetRender().m_flip_handler.SetAddr(handler_addr);
return CELL_OK;
}
int cellGcmSetFlipMode(u32 mode)
{
cellGcmSys.Warning("cellGcmSetFlipMode(mode=%d)", mode);
switch (mode)
{
case CELL_GCM_DISPLAY_HSYNC:
case CELL_GCM_DISPLAY_VSYNC:
case CELL_GCM_DISPLAY_HSYNC_WITH_NOISE:
Emu.GetGSManager().GetRender().m_flip_mode = mode;
break;
default:
return CELL_EINVAL;
}
return CELL_OK;
}
void cellGcmSetFlipStatus()
{
cellGcmSys.Warning("cellGcmSetFlipStatus()");
Emu.GetGSManager().GetRender().m_flip_status = 0;
}
int cellGcmSetPrepareFlip(mem_ptr_t<CellGcmContextData> ctxt, u32 id)
{
cellGcmSys.Log("cellGcmSetPrepareFlip(ctx=0x%x, id=0x%x)", ctxt.GetAddr(), id);
if(id >= 8)
{
return CELL_GCM_ERROR_FAILURE;
}
GSLockCurrent gslock(GS_LOCK_WAIT_FLUSH); // could stall on exit
u32 current = ctxt->current;
u32 end = ctxt->end;
if(current + 8 >= end)
{
ConLog.Warning("bad flip!");
//cellGcmCallback(ctxt.GetAddr(), current + 8 - end);
//copied:
CellGcmControl& ctrl = (CellGcmControl&)Memory[gcm_info.control_addr];
const s32 res = ctxt->current - ctxt->begin - ctrl.put;
if(res > 0) Memory.Copy(ctxt->begin, ctxt->current - res, res);
ctxt->current = ctxt->begin + res;
ctrl.put = res;
ctrl.get = 0;
}
current = ctxt->current;
Memory.Write32(current, 0x3fead | (1 << 18));
Memory.Write32(current + 4, id);
ctxt->current += 8;
if(ctxt.GetAddr() == gcm_info.context_addr)
{
CellGcmControl& ctrl = (CellGcmControl&)Memory[gcm_info.control_addr];
ctrl.put += 8;
}
return id;
}
int cellGcmSetSecondVFrequency(u32 freq)
{
cellGcmSys.Warning("cellGcmSetSecondVFrequency(level=%d)", freq);
switch (freq)
{
case CELL_GCM_DISPLAY_FREQUENCY_59_94HZ:
case CELL_GCM_DISPLAY_FREQUENCY_SCANOUT:
case CELL_GCM_DISPLAY_FREQUENCY_DISABLE:
Emu.GetGSManager().GetRender().m_frequency_mode = freq;
break;
default: return CELL_EINVAL;
}
return CELL_OK;
}
int cellGcmSetTileInfo(u8 index, u8 location, u32 offset, u32 size, u32 pitch, u8 comp, u16 base, u8 bank)
{
cellGcmSys.Warning("cellGcmSetTileInfo(index=%d, location=%d, offset=%d, size=%d, pitch=%d, comp=%d, base=%d, bank=%d)",
index, location, offset, size, pitch, comp, base, bank);
if (index >= RSXThread::m_tiles_count || base >= 800 || bank >= 4)<|fim▁hole|> if (offset & 0xffff || size & 0xffff || pitch & 0xf)
{
return CELL_GCM_ERROR_INVALID_ALIGNMENT;
}
if (location >= 2 || (comp != 0 && (comp < 7 || comp > 12)))
{
return CELL_GCM_ERROR_INVALID_ENUM;
}
if (comp)
{
cellGcmSys.Error("cellGcmSetTileInfo: bad comp! (%d)", comp);
}
auto& tile = Emu.GetGSManager().GetRender().m_tiles[index];
tile.m_location = location;
tile.m_offset = offset;
tile.m_size = size;
tile.m_pitch = pitch;
tile.m_comp = comp;
tile.m_base = base;
tile.m_bank = bank;
Memory.WriteData(Emu.GetGSManager().GetRender().m_tiles_addr + sizeof(CellGcmTileInfo)* index, tile.Pack());
return CELL_OK;
}
u32 cellGcmSetUserHandler(u32 handler)
{
cellGcmSys.Warning("cellGcmSetUserHandler(handler=0x%x)", handler);
return handler;
}
int cellGcmSetVBlankHandler()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetWaitFlip(mem_ptr_t<CellGcmContextData> ctxt)
{
cellGcmSys.Log("cellGcmSetWaitFlip(ctx=0x%x)", ctxt.GetAddr());
GSLockCurrent lock(GS_LOCK_WAIT_FLIP);
return CELL_OK;
}
int cellGcmSetZcull(u8 index, u32 offset, u32 width, u32 height, u32 cullStart, u32 zFormat, u32 aaFormat, u32 zCullDir, u32 zCullFormat, u32 sFunc, u32 sRef, u32 sMask)
{
cellGcmSys.Warning("TODO: cellGcmSetZcull(index=%d, offset=0x%x, width=%d, height=%d, cullStart=0x%x, zFormat=0x%x, aaFormat=0x%x, zCullDir=0x%x, zCullFormat=0x%x, sFunc=0x%x, sRef=0x%x, sMask=0x%x)",
index, offset, width, height, cullStart, zFormat, aaFormat, zCullDir, zCullFormat, sFunc, sRef, sMask);
return CELL_OK;
}
int cellGcmUnbindTile(u8 index)
{
cellGcmSys.Warning("cellGcmUnbindTile(index=%d)", index);
if (index >= RSXThread::m_tiles_count)
{
return CELL_GCM_ERROR_INVALID_VALUE;
}
auto& tile = Emu.GetGSManager().GetRender().m_tiles[index];
tile.m_binded = false;
return CELL_OK;
}
int cellGcmUnbindZcull(u8 index)
{
cellGcmSys.Warning("cellGcmUnbindZcull(index=%d)", index);
if (index >= 8)
return CELL_EINVAL;
return CELL_OK;
}
u32 cellGcmGetTileInfo()
{
cellGcmSys.Warning("cellGcmGetTileInfo()");
return Emu.GetGSManager().GetRender().m_tiles_addr;
}
u32 cellGcmGetZcullInfo()
{
cellGcmSys.Warning("cellGcmGetZcullInfo()");
return Emu.GetGSManager().GetRender().m_zculls_addr;
}
u32 cellGcmGetDisplayInfo()
{
cellGcmSys.Warning("cellGcmGetDisplayInfo() = 0x%x", Emu.GetGSManager().GetRender().m_gcm_buffers_addr);
return Emu.GetGSManager().GetRender().m_gcm_buffers_addr;
}
int cellGcmGetCurrentDisplayBufferId(u32 id_addr)
{
cellGcmSys.Warning("cellGcmGetCurrentDisplayBufferId(id_addr=0x%x)", id_addr);
if (!Memory.IsGoodAddr(id_addr))
{
return CELL_EFAULT;
}
Memory.Write32(id_addr, Emu.GetGSManager().GetRender().m_gcm_current_buffer);
return CELL_OK;
}
//----------------------------------------------------------------------------
// Memory Mapping
//----------------------------------------------------------------------------
gcm_offset offsetTable = { 0, 0 };
void InitOffsetTable()
{
offsetTable.io = Memory.Alloc(3072 * sizeof(u16), 1);
for (int i = 0; i<3072; i++)
{
Memory.Write16(offsetTable.io + sizeof(u16)*i, 0xFFFF);
}
offsetTable.ea = Memory.Alloc(256 * sizeof(u16), 1);//TODO: check flags
for (int i = 0; i<256; i++)
{
Memory.Write16(offsetTable.ea + sizeof(u16)*i, 0xFFFF);
}
}
int32_t cellGcmAddressToOffset(u64 address, mem32_t offset)
{
cellGcmSys.Log("cellGcmAddressToOffset(address=0x%x,offset_addr=0x%x)", address, offset.GetAddr());
if (address >= 0xD0000000/*not on main memory or local*/)
return CELL_GCM_ERROR_FAILURE;
u32 result;
// If address is in range of local memory
if (Memory.RSXFBMem.IsInMyRange(address))
{
result = address - Memory.RSXFBMem.GetStartAddr();
}
// else check if the adress (main memory) is mapped in IO
else
{
u16 upper12Bits = Memory.Read16(offsetTable.io + sizeof(u16)*(address >> 20));
if (upper12Bits != 0xFFFF)
{
result = (((u64)upper12Bits << 20) | (address & (0xFFFFF)));
}
// address is not mapped in IO
else
{
return CELL_GCM_ERROR_FAILURE;
}
}
offset = result;
return CELL_OK;
}
uint32_t cellGcmGetMaxIoMapSize()
{
return Memory.RSXIOMem.GetEndAddr() - Memory.RSXIOMem.GetStartAddr() - Memory.RSXIOMem.GetReservedAmount();
}
void cellGcmGetOffsetTable(mem_ptr_t<gcm_offset> table)
{
table->io = re(offsetTable.io);
table->ea = re(offsetTable.ea);
}
int32_t cellGcmIoOffsetToAddress(u32 ioOffset, u64 address)
{
u64 realAddr;
realAddr = Memory.RSXIOMem.getRealAddr(Memory.RSXIOMem.GetStartAddr() + ioOffset);
if (!realAddr)
return CELL_GCM_ERROR_FAILURE;
Memory.Write64(address, realAddr);
return CELL_OK;
}
int32_t cellGcmMapEaIoAddress(const u32 ea, const u32 io, const u32 size)
{
cellGcmSys.Warning("cellGcmMapEaIoAddress(ea=0x%x, io=0x%x, size=0x%x)", ea, io, size);
if ((ea & 0xFFFFF) || (io & 0xFFFFF) || (size & 0xFFFFF)) return CELL_GCM_ERROR_FAILURE;
//check if the mapping was successfull
if (Memory.RSXIOMem.Map(ea, size, Memory.RSXIOMem.GetStartAddr() + io))
{
//fill the offset table
for (u32 i = 0; i<(size >> 20); i++)
{
Memory.Write16(offsetTable.io + ((ea >> 20) + i)*sizeof(u16), (io >> 20) + i);
Memory.Write16(offsetTable.ea + ((io >> 20) + i)*sizeof(u16), (ea >> 20) + i);
}
}
else
{
return CELL_GCM_ERROR_FAILURE;
}
return CELL_OK;
}
int32_t cellGcmMapEaIoAddressWithFlags(const u32 ea, const u32 io, const u32 size, const u32 flags)
{
cellGcmSys.Warning("cellGcmMapEaIoAddressWithFlags(ea=0x%x, io=0x%x, size=0x%x, flags=0x%x)", ea, io, size, flags);
return cellGcmMapEaIoAddress(ea, io, size); // TODO: strict ordering
}
int32_t cellGcmMapLocalMemory(u64 address, u64 size)
{
if (!local_size && !local_addr)
{
local_size = 0xf900000; //TODO
local_addr = Memory.RSXFBMem.GetStartAddr();
Memory.RSXFBMem.AllocAlign(local_size);
Memory.Write32(address, local_addr);
Memory.Write32(size, local_size);
}
else
{
cellGcmSys.Error("RSX local memory already mapped");
return CELL_GCM_ERROR_FAILURE;
}
return CELL_OK;
}
int32_t cellGcmMapMainMemory(u64 ea, u32 size, mem32_t offset)
{
cellGcmSys.Warning("cellGcmMapMainMemory(ea=0x%x,size=0x%x,offset_addr=0x%x)", ea, size, offset.GetAddr());
u64 io;
if ((ea & 0xFFFFF) || (size & 0xFFFFF)) return CELL_GCM_ERROR_FAILURE;
//check if the mapping was successfull
if (io = Memory.RSXIOMem.Map(ea, size, 0))
{
// convert to offset
io = io - Memory.RSXIOMem.GetStartAddr();
//fill the offset table
for (u32 i = 0; i<(size >> 20); i++)
{
Memory.Write16(offsetTable.io + ((ea >> 20) + i)*sizeof(u16), (io >> 20) + i);
Memory.Write16(offsetTable.ea + ((io >> 20) + i)*sizeof(u16), (ea >> 20) + i);
}
offset = io;
}
else
{
return CELL_GCM_ERROR_NO_IO_PAGE_TABLE;
}
Emu.GetGSManager().GetRender().m_main_mem_addr = Emu.GetGSManager().GetRender().m_ioAddress;
return CELL_OK;
}
int32_t cellGcmReserveIoMapSize(const u32 size)
{
if (size & 0xFFFFF)
return CELL_GCM_ERROR_INVALID_ALIGNMENT;
if (size > cellGcmGetMaxIoMapSize())
return CELL_GCM_ERROR_INVALID_VALUE;
Memory.RSXIOMem.Reserve(size);
return CELL_OK;
}
int32_t cellGcmUnmapEaIoAddress(u64 ea)
{
u32 size = Memory.RSXIOMem.UnmapRealAddress(ea);
if (size)
{
u64 io;
ea = ea >> 20;
io = Memory.Read16(offsetTable.io + (ea*sizeof(u16)));
for (u32 i = 0; i<size; i++)
{
Memory.Write16(offsetTable.io + ((ea + i)*sizeof(u16)), 0xFFFF);
Memory.Write16(offsetTable.ea + ((io + i)*sizeof(u16)), 0xFFFF);
}
}
else
{
return CELL_GCM_ERROR_FAILURE;
}
return CELL_OK;
}
int32_t cellGcmUnmapIoAddress(u64 io)
{
u32 size = Memory.RSXIOMem.UnmapAddress(io);
if (size)
{
u64 ea;
io = io >> 20;
ea = Memory.Read16(offsetTable.ea + (io*sizeof(u16)));
for (u32 i = 0; i<size; i++)
{
Memory.Write16(offsetTable.io + ((ea + i)*sizeof(u16)), 0xFFFF);
Memory.Write16(offsetTable.ea + ((io + i)*sizeof(u16)), 0xFFFF);
}
}
else
{
return CELL_GCM_ERROR_FAILURE;
}
return CELL_OK;
}
int32_t cellGcmUnreserveIoMapSize(u32 size)
{
if (size & 0xFFFFF)
return CELL_GCM_ERROR_INVALID_ALIGNMENT;
if (size > Memory.RSXIOMem.GetReservedAmount())
return CELL_GCM_ERROR_INVALID_VALUE;
Memory.RSXIOMem.Unreserve(size);
return CELL_OK;
}
//----------------------------------------------------------------------------
// Cursor
//----------------------------------------------------------------------------
int cellGcmInitCursor()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetCursorPosition(s32 x, s32 y)
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetCursorDisable()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmUpdateCursor()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetCursorEnable()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetCursorImageOffset(u32 offset)
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
//------------------------------------------------------------------------
// Functions for Maintaining Compatibility
//------------------------------------------------------------------------
void cellGcmSetDefaultCommandBuffer()
{
cellGcmSys.Warning("cellGcmSetDefaultCommandBuffer()");
Memory.Write32(Emu.GetGSManager().GetRender().m_ctxt_addr, gcm_info.context_addr);
}
//------------------------------------------------------------------------
// Other
//------------------------------------------------------------------------
int cellGcmSetFlipCommand(u32 ctx, u32 id)
{
return cellGcmSetPrepareFlip(ctx, id);
}
s64 cellGcmFunc15()
{
cellGcmSys.Error("cellGcmFunc15()");
return 0;
}
int cellGcmSetFlipCommandWithWaitLabel(u32 ctx, u32 id, u32 label_index, u32 label_value)
{
int res = cellGcmSetPrepareFlip(ctx, id);
Memory.Write32(Memory.RSXCMDMem.GetStartAddr() + 0x10 * label_index, label_value);
return res < 0 ? CELL_GCM_ERROR_FAILURE : CELL_OK;
}
int cellGcmSetTile(u8 index, u8 location, u32 offset, u32 size, u32 pitch, u8 comp, u16 base, u8 bank)
{
cellGcmSys.Warning("cellGcmSetTile(index=%d, location=%d, offset=%d, size=%d, pitch=%d, comp=%d, base=%d, bank=%d)",
index, location, offset, size, pitch, comp, base, bank);
// Copied form cellGcmSetTileInfo
if(index >= RSXThread::m_tiles_count || base >= 800 || bank >= 4)
{
return CELL_GCM_ERROR_INVALID_VALUE;
}
if(offset & 0xffff || size & 0xffff || pitch & 0xf)
{
return CELL_GCM_ERROR_INVALID_ALIGNMENT;
}
if(location >= 2 || (comp != 0 && (comp < 7 || comp > 12)))
{
return CELL_GCM_ERROR_INVALID_ENUM;
}
if(comp)
{
cellGcmSys.Error("cellGcmSetTile: bad comp! (%d)", comp);
}
auto& tile = Emu.GetGSManager().GetRender().m_tiles[index];
tile.m_location = location;
tile.m_offset = offset;
tile.m_size = size;
tile.m_pitch = pitch;
tile.m_comp = comp;
tile.m_base = base;
tile.m_bank = bank;
Memory.WriteData(Emu.GetGSManager().GetRender().m_tiles_addr + sizeof(CellGcmTileInfo) * index, tile.Pack());
return CELL_OK;
}
//----------------------------------------------------------------------------
void cellGcmSys_init()
{
// Data Retrieval
//cellGcmSys.AddFunc(0xc8f3bd09, cellGcmGetCurrentField);
cellGcmSys.AddFunc(0xf80196c1, cellGcmGetLabelAddress);
//cellGcmSys.AddFunc(0x21cee035, cellGcmGetNotifyDataAddress);
//cellGcmSys.AddFunc(0x99d397ac, cellGcmGetReport);
//cellGcmSys.AddFunc(0x9a0159af, cellGcmGetReportDataAddress);
cellGcmSys.AddFunc(0x8572bce2, cellGcmGetReportDataAddressLocation);
//cellGcmSys.AddFunc(0xa6b180ac, cellGcmGetReportDataLocation);
cellGcmSys.AddFunc(0x5a41c10f, cellGcmGetTimeStamp);
//cellGcmSys.AddFunc(0x2ad4951b, cellGcmGetTimeStampLocation);
// Command Buffer Control
//cellGcmSys.AddFunc(, cellGcmCallbackForSnc);
//cellGcmSys.AddFunc(, cellGcmFinish);
//cellGcmSys.AddFunc(, cellGcmFlush);
cellGcmSys.AddFunc(0xa547adde, cellGcmGetControlRegister);
cellGcmSys.AddFunc(0x5e2ee0f0, cellGcmGetDefaultCommandWordSize);
cellGcmSys.AddFunc(0x8cdf8c70, cellGcmGetDefaultSegmentWordSize);
cellGcmSys.AddFunc(0xcaabd992, cellGcmInitDefaultFifoMode);
//cellGcmSys.AddFunc(, cellGcmReserveMethodSize);
//cellGcmSys.AddFunc(, cellGcmResetDefaultCommandBuffer);
cellGcmSys.AddFunc(0x9ba451e4, cellGcmSetDefaultFifoSize);
//cellGcmSys.AddFunc(, cellGcmSetupContextData);
// Hardware Resource Management
cellGcmSys.AddFunc(0x4524cccd, cellGcmBindTile);
cellGcmSys.AddFunc(0x9dc04436, cellGcmBindZcull);
//cellGcmSys.AddFunc(0x1f61b3ff, cellGcmDumpGraphicsError);
cellGcmSys.AddFunc(0xe315a0b2, cellGcmGetConfiguration);
//cellGcmSys.AddFunc(0x371674cf, cellGcmGetDisplayBufferByFlipIndex);
cellGcmSys.AddFunc(0x72a577ce, cellGcmGetFlipStatus);
//cellGcmSys.AddFunc(0x63387071, cellGcmgetLastFlipTime);
//cellGcmSys.AddFunc(0x23ae55a3, cellGcmGetLastSecondVTime);
cellGcmSys.AddFunc(0x055bd74d, cellGcmGetTiledPitchSize);
//cellGcmSys.AddFunc(0x723bbc7e, cellGcmGetVBlankCount);
cellGcmSys.AddFunc(0x15bae46b, cellGcmInit);
//cellGcmSys.AddFunc(0xfce9e764, cellGcmInitSystemMode);
cellGcmSys.AddFunc(0xb2e761d4, cellGcmResetFlipStatus);
cellGcmSys.AddFunc(0x51c9d62b, cellGcmSetDebugOutputLevel);
cellGcmSys.AddFunc(0xa53d12ae, cellGcmSetDisplayBuffer);
cellGcmSys.AddFunc(0xdc09357e, cellGcmSetFlip);
cellGcmSys.AddFunc(0xa41ef7e8, cellGcmSetFlipHandler);
//cellGcmSys.AddFunc(0xacee8542, cellGcmSetFlipImmediate);
cellGcmSys.AddFunc(0x4ae8d215, cellGcmSetFlipMode);
cellGcmSys.AddFunc(0xa47c09ff, cellGcmSetFlipStatus);
//cellGcmSys.AddFunc(, cellGcmSetFlipWithWaitLabel);
//cellGcmSys.AddFunc(0xd01b570d, cellGcmSetGraphicsHandler);
cellGcmSys.AddFunc(0x0b4b62d5, cellGcmSetPrepareFlip);
//cellGcmSys.AddFunc(0x0a862772, cellGcmSetQueueHandler);
cellGcmSys.AddFunc(0x4d7ce993, cellGcmSetSecondVFrequency);
//cellGcmSys.AddFunc(0xdc494430, cellGcmSetSecondVHandler);
cellGcmSys.AddFunc(0xbd100dbc, cellGcmSetTileInfo);
cellGcmSys.AddFunc(0x06edea9e, cellGcmSetUserHandler);
//cellGcmSys.AddFunc(0xffe0160e, cellGcmSetVBlankFrequency);
cellGcmSys.AddFunc(0xa91b0402, cellGcmSetVBlankHandler);
cellGcmSys.AddFunc(0x983fb9aa, cellGcmSetWaitFlip);
cellGcmSys.AddFunc(0xd34a420d, cellGcmSetZcull);
//cellGcmSys.AddFunc(0x25b40ab4, cellGcmSortRemapEaIoAddress);
cellGcmSys.AddFunc(0xd9b7653e, cellGcmUnbindTile);
cellGcmSys.AddFunc(0xa75640e8, cellGcmUnbindZcull);
cellGcmSys.AddFunc(0x657571f7, cellGcmGetTileInfo);
cellGcmSys.AddFunc(0xd9a0a879, cellGcmGetZcullInfo);
cellGcmSys.AddFunc(0x0e6b0dae, cellGcmGetDisplayInfo);
cellGcmSys.AddFunc(0x93806525, cellGcmGetCurrentDisplayBufferId);
// Memory Mapping
cellGcmSys.AddFunc(0x21ac3697, cellGcmAddressToOffset);
cellGcmSys.AddFunc(0xfb81c03e, cellGcmGetMaxIoMapSize);
cellGcmSys.AddFunc(0x2922aed0, cellGcmGetOffsetTable);
cellGcmSys.AddFunc(0x2a6fba9c, cellGcmIoOffsetToAddress);
cellGcmSys.AddFunc(0x63441cb4, cellGcmMapEaIoAddress);
cellGcmSys.AddFunc(0x626e8518, cellGcmMapEaIoAddressWithFlags);
cellGcmSys.AddFunc(0xdb769b32, cellGcmMapLocalMemory);
cellGcmSys.AddFunc(0xa114ec67, cellGcmMapMainMemory);
cellGcmSys.AddFunc(0xa7ede268, cellGcmReserveIoMapSize);
cellGcmSys.AddFunc(0xefd00f54, cellGcmUnmapEaIoAddress);
cellGcmSys.AddFunc(0xdb23e867, cellGcmUnmapIoAddress);
cellGcmSys.AddFunc(0x3b9bd5bd, cellGcmUnreserveIoMapSize);
// Cursor
cellGcmSys.AddFunc(0x107bf3a1, cellGcmInitCursor);
cellGcmSys.AddFunc(0xc47d0812, cellGcmSetCursorEnable);
cellGcmSys.AddFunc(0x69c6cc82, cellGcmSetCursorDisable);
cellGcmSys.AddFunc(0xf9bfdc72, cellGcmSetCursorImageOffset);
cellGcmSys.AddFunc(0x1a0de550, cellGcmSetCursorPosition);
cellGcmSys.AddFunc(0xbd2fa0a7, cellGcmUpdateCursor);
// Functions for Maintaining Compatibility
//cellGcmSys.AddFunc(, cellGcmGetCurrentBuffer);
//cellGcmSys.AddFunc(, cellGcmSetCurrentBuffer);
cellGcmSys.AddFunc(0xbc982946, cellGcmSetDefaultCommandBuffer);
//cellGcmSys.AddFunc(, cellGcmSetDefaultCommandBufferAndSegmentWordSize);
//cellGcmSys.AddFunc(, cellGcmSetUserCallback);
// Other
cellGcmSys.AddFunc(0x21397818, cellGcmSetFlipCommand);
cellGcmSys.AddFunc(0x3a33c1fd, cellGcmFunc15);
cellGcmSys.AddFunc(0xd8f88e1a, cellGcmSetFlipCommandWithWaitLabel);
cellGcmSys.AddFunc(0xd0b1d189, cellGcmSetTile);
}
void cellGcmSys_load()
{
current_config.ioAddress = 0;
current_config.localAddress = 0;
local_size = 0;
local_addr = 0;
}
void cellGcmSys_unload()
{
}<|fim▁end|> | {
return CELL_GCM_ERROR_INVALID_VALUE;
}
|
<|file_name|>common_test.go<|end_file_name|><|fim▁begin|>package connectors
import (
"regexp"
"sync"
"testing"
"github.com/etcinit/phabulous/app/interfaces"
"github.com/etcinit/phabulous/app/testing/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
)
func Test_processMessage_WithSelf(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockBot := mocks.NewMockBot(mockCtrl)
mockMsg := mocks.NewMockMessage(mockCtrl)
mockMsg.EXPECT().IsSelf().Times(1).Return(true)
processMessage(mockBot, mockMsg)
}
func Test_processMessage_WithPublic(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockBot := mocks.NewMockBot(mockCtrl)
mockMsg := mocks.NewMockMessage(mockCtrl)
mockTuple := mocks.NewMockHandlerTuple(mockCtrl)
mockMsg.EXPECT().IsSelf().Times(1).Return(false)
mockMsg.EXPECT().HasUser().Times(1).Return(true)
mockMsg.EXPECT().GetContent().Times(1).Return("Hello World")
mockMsg.EXPECT().IsIM().Times(1).Return(false)
mockBot.EXPECT().GetHandlers().Times(1).Return([]interfaces.HandlerTuple{
mockTuple,
})
ran := make(chan bool)
pattern, _ := regexp.Compile("Hello World")
mockTuple.EXPECT().GetPattern().Times(1).Return(pattern)
mockTuple.EXPECT().GetHandler().Times(1).Return(
func(bot interfaces.Bot, msg interfaces.Message, result []string) {
assert.Equal(t, bot, mockBot)
assert.Equal(t, msg, mockMsg)
assert.Equal(t, result, []string{"Hello World"})
ran <- true
},
)
processMessage(mockBot, mockMsg)
<-ran
}
// Test_processMessage_SkipDuplicates asserts that multiple matches of the same element are only handled once.
func Test_processMessage_SkipDuplicates(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockBot := mocks.NewMockBot(mockCtrl)
mockMsg := mocks.NewMockMessage(mockCtrl)
mockTuple := mocks.NewMockHandlerTuple(mockCtrl)
mockMsg.EXPECT().IsSelf().Times(1).Return(false)
mockMsg.EXPECT().HasUser().Times(1).Return(true)
mockMsg.EXPECT().GetContent().Times(1).Return("We have T1 and T100 and T100 again.")
mockMsg.EXPECT().IsIM().Times(1).Return(false)
mockBot.EXPECT().GetHandlers().Times(1).Return([]interfaces.HandlerTuple{
mockTuple,
})
ran := make(chan bool)
pattern, _ := regexp.Compile("([T|D][0-9]{1,16})")
mockTuple.EXPECT().GetPattern().Times(1).Return(pattern)
// we expect only two calls to GetHandler, even though the regex matches three times, T100 exists twice.
mockTuple.EXPECT().GetHandler().Times(2).Return(
func(bot interfaces.Bot, msg interfaces.Message, result []string) {
assert.Equal(t, bot, mockBot)
assert.Equal(t, msg, mockMsg)
assert.Contains(t, [][]string{{"T1"}, {"T100"}}, result)
ran <- true
},
)
processMessage(mockBot, mockMsg)
<-ran
}
func Test_processMessage_WithHandledIM(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockBot := mocks.NewMockBot(mockCtrl)
mockMsg := mocks.NewMockMessage(mockCtrl)
mockTuple := mocks.NewMockHandlerTuple(mockCtrl)
mockMsg.EXPECT().IsSelf().Times(1).Return(false)
mockMsg.EXPECT().HasUser().Times(1).Return(true)
mockMsg.EXPECT().GetContent().Times(1).Return("Hello World")
mockMsg.EXPECT().IsIM().Times(1).Return(true)
mockBot.EXPECT().GetIMHandlers().Times(1).Return([]interfaces.HandlerTuple{
mockTuple,
})
<|fim▁hole|> pattern, _ := regexp.Compile("Hello World")
mockTuple.EXPECT().GetPattern().Times(1).Return(pattern)
mockTuple.EXPECT().GetHandler().Times(1).Return(
func(bot interfaces.Bot, msg interfaces.Message, result []string) {
assert.Equal(t, bot, mockBot)
assert.Equal(t, msg, mockMsg)
assert.Equal(t, result, []string{"Hello World"})
wg.Done()
},
)
wg.Add(1)
processMessage(mockBot, mockMsg)
wg.Wait()
}
func Test_processMessage_WithUnhandledIM(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
var wg sync.WaitGroup
mockBot := mocks.NewMockBot(mockCtrl)
mockMsg := mocks.NewMockMessage(mockCtrl)
mockMsg.EXPECT().IsSelf().Times(1).Return(false)
mockMsg.EXPECT().HasUser().Times(1).Return(true)
mockMsg.EXPECT().GetContent().Times(1).Return("Hello World")
mockMsg.EXPECT().IsIM().Times(1).Return(true)
mockBot.EXPECT().GetIMHandlers().Times(1).Return(
[]interfaces.HandlerTuple{},
)
wg.Add(1)
mockBot.EXPECT().GetUsageHandler().Times(1).Return(
func(b interfaces.Bot, m interfaces.Message, matches []string) {
wg.Done()
},
)
processMessage(mockBot, mockMsg)
wg.Wait()
}<|fim▁end|> | var wg sync.WaitGroup
|
<|file_name|>test_api_system.py<|end_file_name|><|fim▁begin|>#
# Copyright (c) 2014, Arista Networks, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# Neither the name of Arista Networks nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import os
import unittest
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../lib'))
from testlib import random_string
from systestlib import DutSystemTest
class TestApiSystem(DutSystemTest):
def test_get(self):
for dut in self.duts:
dut.config('default hostname')
resp = dut.api('system').get()
keys = ['hostname', 'iprouting', 'banner_motd', 'banner_login']
self.assertEqual(sorted(keys), sorted(resp.keys()))
def test_get_with_period(self):
for dut in self.duts:
dut.config('hostname host.domain.net')
response = dut.api('system').get()
self.assertEqual(response['hostname'], 'host.domain.net')
def test_get_check_hostname(self):
for dut in self.duts:
dut.config('hostname teststring')
response = dut.api('system').get()
self.assertEqual(response['hostname'], 'teststring')
def test_get_check_banners(self):
for dut in self.duts:
motd_banner_value = random_string() + "\n"
login_banner_value = random_string() + "\n"
dut.config([dict(cmd="banner motd", input=motd_banner_value)])
dut.config([dict(cmd="banner login", input=login_banner_value)])
resp = dut.api('system').get()
self.assertEqual(resp['banner_login'], login_banner_value.rstrip())
self.assertEqual(resp['banner_motd'], motd_banner_value.rstrip())
def test_get_banner_with_EOF(self):
for dut in self.duts:
motd_banner_value = '!!!newlinebaner\nSecondLIneEOF!!!newlinebanner\n'
dut.config([dict(cmd="banner motd", input=motd_banner_value)])
resp = dut.api('system').get()
self.assertEqual(resp['banner_motd'], motd_banner_value.rstrip())
def test_set_hostname_with_value(self):
for dut in self.duts:
dut.config('default hostname')
value = random_string()
response = dut.api('system').set_hostname(value)
self.assertTrue(response, 'dut=%s' % dut)
value = 'hostname %s' % value
self.assertIn(value, dut.running_config)
def test_set_hostname_with_no_value(self):
for dut in self.duts:
dut.config('hostname test')
response = dut.api('system').set_hostname(disable=True)
self.assertTrue(response, 'dut=%s' % dut)
value = 'no hostname'
self.assertIn(value, dut.running_config)
def test_set_hostname_with_default(self):
for dut in self.duts:
dut.config('hostname test')
response = dut.api('system').set_hostname(default=True)
self.assertTrue(response, 'dut=%s' % dut)
value = 'no hostname'
self.assertIn(value, dut.running_config)
def test_set_hostname_default_over_value(self):
for dut in self.duts:
dut.config('hostname test')
response = dut.api('system').set_hostname(value='foo', default=True)
self.assertTrue(response, 'dut=%s' % dut)
value = 'no hostname'
self.assertIn(value, dut.running_config)
def test_set_iprouting_to_true(self):
for dut in self.duts:
dut.config('no ip routing')
resp = dut.api('system').set_iprouting(True)
self.assertTrue(resp, 'dut=%s' % dut)
self.assertNotIn('no ip rotuing', dut.running_config)
def test_set_iprouting_to_false(self):
for dut in self.duts:
dut.config('ip routing')
resp = dut.api('system').set_iprouting(False)
self.assertTrue(resp, 'dut=%s' % dut)
self.assertIn('no ip routing', dut.running_config)
def test_set_iprouting_to_no(self):
for dut in self.duts:
dut.config('ip routing')
resp = dut.api('system').set_iprouting(disable=True)
self.assertTrue(resp, 'dut=%s' % dut)
self.assertIn('no ip routing', dut.running_config)
def test_set_iprouting_to_default(self):
for dut in self.duts:
dut.config('ip routing')
resp = dut.api('system').set_iprouting(default=True)
self.assertTrue(resp, 'dut=%s' % dut)
self.assertIn('no ip routing', dut.running_config)
def test_set_hostname_with_period(self):
for dut in self.duts:
dut.config('hostname localhost')
response = dut.api('system').set_hostname(value='host.domain.net')
self.assertTrue(response, 'dut=%s' % dut)
value = 'hostname host.domain.net'
self.assertIn(value, dut.running_config)
def test_set_banner_motd(self):
for dut in self.duts:
banner_value = random_string()
dut.config([dict(cmd="banner motd",
input=banner_value)])
self.assertIn(banner_value, dut.running_config)
banner_api_value = random_string()
resp = dut.api('system').set_banner("motd", banner_api_value)
self.assertTrue(resp, 'dut=%s' % dut)
self.assertIn(banner_api_value, dut.running_config)
def test_set_banner_motd_donkey(self):
for dut in self.duts:
donkey_chicken = r"""
/\ /\
( \\ // )
\ \\ // /
\_\\||||//_/
\/ _ _ \
\/|(o)(O)|
\/ | |
___________________\/ \ /
// // |____| Cluck cluck cluck!
// || / \
//| \| \ 0 0 /
// \ ) V / \____/
// \ / ( /
"" \ /_________| |_/
/ /\ / | ||
/ / / / \ ||
| | | | | ||
| | | | | ||
|_| |_| |_||
\_\ \_\ \_\\
"""
resp = dut.api('system').set_banner("motd", donkey_chicken)
self.assertTrue(resp, 'dut=%s' % dut)
self.assertIn(donkey_chicken, dut.running_config)
def test_set_banner_motd_default(self):
for dut in self.duts:
dut.config([dict(cmd="banner motd",
input="!!!!REMOVE BANNER TEST!!!!")])
dut.api('system').set_banner('motd', None, True)
self.assertIn('no banner motd', dut.running_config)
def test_set_banner_login(self):
for dut in self.duts:
banner_value = random_string()
dut.config([dict(cmd="banner login",
input=banner_value)])
self.assertIn(banner_value, dut.running_config)
banner_api_value = random_string()
resp = dut.api('system').set_banner("login", banner_api_value)
self.assertTrue(resp, 'dut=%s' % dut)
self.assertIn(banner_api_value, dut.running_config)
config_login_banner = dut.api('system').get()['banner_login']
self.assertTrue(config_login_banner, banner_api_value.strip())
<|fim▁hole|> def test_set_banner_login_default(self):
for dut in self.duts:
dut.config([dict(cmd="banner login",
input="!!!!REMOVE LOGIN BANNER TEST!!!!")])
dut.api('system').set_banner('login', None, True)
self.assertIn('no banner login', dut.running_config)
def test_set_banner_login_negate(self):
for dut in self.duts:
dut.config([dict(cmd="banner login",
input="!!!!REMOVE LOGIN BANNER TEST!!!!")])
dut.api('system').set_banner('login', None, False, True)
self.assertIn('no banner login', dut.running_config)
if __name__ == '__main__':
unittest.main()<|fim▁end|> | |
<|file_name|>gui5.py<|end_file_name|><|fim▁begin|>"""Tables, Widgets, and Groups!
An example of tables and most of the included widgets.
"""
import pygame
from pygame.locals import *
# the following line is not needed if pgu is installed
import sys; sys.path.insert(0, "..")
from pgu import gui
# Load an alternate theme to show how it is done. You can also
# specify a path (absolute or relative) to your own custom theme:
#
# app = gui.Desktop(theme=gui.Theme("path/to/theme"))
#
app = gui.Desktop()
app.connect(gui.QUIT,app.quit,None)
##The table code is entered much like HTML.
##::
c = gui.Table()
c.tr()
c.td(gui.Label("Gui Widgets"),colspan=4)
def cb():
print("Clicked!")
btn = gui.Button("Click Me!")
btn.connect(gui.CLICK, cb)
c.tr()
c.td(gui.Label("Button"))
c.td(btn,colspan=3)
##
c.tr()
c.td(gui.Label("Switch"))
c.td(gui.Switch(False),colspan=3)
c.tr()
c.td(gui.Label("Checkbox"))
##Note how Groups are used for Radio buttons, Checkboxes, and Tools.
##::
g = gui.Group(value=[1,3])
c.td(gui.Checkbox(g,value=1))
c.td(gui.Checkbox(g,value=2))
c.td(gui.Checkbox(g,value=3))
##
c.tr()
c.td(gui.Label("Radio"))
g = gui.Group()
c.td(gui.Radio(g,value=1))
c.td(gui.Radio(g,value=2))
c.td(gui.Radio(g,value=3))
c.tr()
c.td(gui.Label("Select"))
e = gui.Select()
e.add("Goat",'goat')
e.add("Horse",'horse')
e.add("Dog",'dog')
e.add("Pig",'pig')
c.td(e,colspan=3)
c.tr()
c.td(gui.Label("Tool"))
g = gui.Group(value='b')
c.td(gui.Tool(g,gui.Label('A'),value='a'))
c.td(gui.Tool(g,gui.Label('B'),value='b'))
c.td(gui.Tool(g,gui.Label('C'),value='c'))
c.tr()
c.td(gui.Label("Input"))
def cb():
print("Input received")
w = gui.Input(value='Cuzco',size=8)
w.connect("activate", cb)
c.td(w,colspan=3)
<|fim▁hole|>
c.tr()
c.td(gui.Label("Keysym"))
c.td(gui.Keysym(),colspan=3)
c.tr()
c.td(gui.Label("Text Area"), colspan=4, align=-1)
c.tr()
c.td(gui.TextArea(value="Cuzco the Goat", width=150, height=70), colspan=4)
app.run(c)<|fim▁end|> | c.tr()
c.td(gui.Label("Slider"))
c.td(gui.HSlider(value=23,min=0,max=100,size=20,width=120),colspan=3) |
<|file_name|>presale.rs<|end_file_name|><|fim▁begin|>// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.<|fim▁hole|>// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use ethcore::ethstore::{PresaleWallet, EthStore};
use ethcore::ethstore::dir::RootDiskDirectory;
use ethcore::account_provider::{AccountProvider, AccountProviderSettings};
use helpers::{password_prompt, password_from_file};
use params::SpecType;
#[derive(Debug, PartialEq)]
pub struct ImportWallet {
pub iterations: u32,
pub path: String,
pub spec: SpecType,
pub wallet_path: String,
pub password_file: Option<String>,
}
pub fn execute(cmd: ImportWallet) -> Result<String, String> {
let password: String = match cmd.password_file {
Some(file) => password_from_file(file)?,
None => password_prompt()?,
};
let dir = Box::new(RootDiskDirectory::create(cmd.path).unwrap());
let secret_store = Box::new(EthStore::open_with_iterations(dir, cmd.iterations).unwrap());
let acc_provider = AccountProvider::new(secret_store, AccountProviderSettings::default());
let wallet = PresaleWallet::open(cmd.wallet_path).map_err(|_| "Unable to open presale wallet.")?;
let kp = wallet.decrypt(&password).map_err(|_| "Invalid password.")?;
let address = acc_provider.insert_account(kp.secret().clone(), &password).unwrap();
Ok(format!("{:?}", address))
}<|fim▁end|> |
// You should have received a copy of the GNU General Public License |
<|file_name|>AsyncHTTPClient.cpp<|end_file_name|><|fim▁begin|>#include "AsyncHTTPClient.h"
#include "../httprequest.h"
#include "../GlobalFuncs.h"
#include <comutil.h>
#include <winhttp.h>
AsyncHTTPClient::AsyncHTTPClient() :
m_url(""),
m_currentStatus(AsyncHTTPClient::HTTP_READY),
m_response(""),
m_responseCode(0)
{}
AsyncHTTPClient::~AsyncHTTPClient()
{
}
void AsyncHTTPClient::addArgument(const std::string & argName, const std::string & content)
{
m_args.emplace_back(argName, content);
}
void AsyncHTTPClient::asyncSendWorker()
{
// To prevent the destructor from beeing executed.
std::shared_ptr<AsyncHTTPClient> lock = shared_from_this();
// FIXME: Only apply arg list in URL for GET, otherwise pass as data.
std::string fullArgList = "";
for (const std::pair<std::string, std::string>& argPack : m_args) {
fullArgList += argPack.first + "=" + url_encode(argPack.second) + "&";
}
if (fullArgList.length() > 0) {
fullArgList = fullArgList.substr(0, fullArgList.length() - 1); // To remove the extra "&"
}
std::string method = "";
switch (m_method) {
case HTTP_POST:
method = "POST";
break;
case HTTP_GET:
default:
method = "GET";
break;
}
HRESULT hr;
CLSID clsid;
IWinHttpRequest *pIWinHttpRequest = NULL;
_variant_t varFalse(false);
_variant_t varData(fullArgList.c_str());
_variant_t varContent("");
if (m_method == HTTP_POST)
varContent = fullArgList.c_str();
hr = CLSIDFromProgID(L"WinHttp.WinHttpRequest.5.1", &clsid);
if (SUCCEEDED(hr)) {
hr = CoCreateInstance(clsid, NULL,
CLSCTX_INPROC_SERVER,
IID_IWinHttpRequest,
(void **)&pIWinHttpRequest);
}
if (SUCCEEDED(hr)) {
hr = pIWinHttpRequest->SetTimeouts(1000, 1000, 2000, 1000);
}
if (SUCCEEDED(hr)) {
_bstr_t method(method.c_str());
_bstr_t url;
if (m_method == HTTP_GET) {
url = ((m_url + (fullArgList.empty() ? "" : "?") + fullArgList).c_str());
}
else
{
url = m_url.c_str();
}
hr = pIWinHttpRequest->Open(method, url, varFalse);
}
if (m_method == HTTP_POST) {
if (SUCCEEDED(hr)) {
hr = pIWinHttpRequest->SetRequestHeader(bstr_t("Content-Type"), bstr_t("application/x-www-form-urlencoded"));
}
}
if (SUCCEEDED(hr)) {
hr = pIWinHttpRequest->Send(varContent);
if ((hr & 0xFFFF) == ERROR_WINHTTP_TIMEOUT)
m_responseCode = 408; // If timeout then set the HTTP response code.
}
if (SUCCEEDED(hr)) {
LONG statusCode = 0;
hr = pIWinHttpRequest->get_Status(&statusCode);
m_responseCode = statusCode;
}
_variant_t responseRaw("");
if (SUCCEEDED(hr)) {
if (m_responseCode == 200) {
hr = pIWinHttpRequest->get_ResponseBody(&responseRaw);
}
else {
hr = E_FAIL;
}
}
if (SUCCEEDED(hr)) {
// body
long upperBounds;
long lowerBounds;
byte* buff;
if (responseRaw.vt == (VT_ARRAY | VT_UI1)) {<|fim▁hole|> SafeArrayGetLBound(responseRaw.parray, 1, &lowerBounds);
SafeArrayGetUBound(responseRaw.parray, 1, &upperBounds);
upperBounds++;
SafeArrayAccessData(responseRaw.parray, (void**)&buff);
m_response = std::string(reinterpret_cast<const char *>(buff), upperBounds-lowerBounds);
SafeArrayUnaccessData(responseRaw.parray);
}
}
}
m_currentStatus.store(HTTP_FINISHED, std::memory_order_relaxed);
m_asyncSendWorkerThread.detach(); // To be absolutely safe
pIWinHttpRequest->Release();
m_finishNotifier.notify_all();
}
void AsyncHTTPClient::asynSend()
{
if (getStatus() != HTTP_READY)
return;
m_currentStatus.store(HTTP_PROCESSING, std::memory_order_relaxed);
m_asyncSendWorkerThread = std::thread([this]() { asyncSendWorker(); });
}
std::string AsyncHTTPClient::getResponseData() const
{
if (getStatus() != HTTP_FINISHED)
return "";
return m_response;
}
AsyncHTTPClient::AsyncHTTPStatus AsyncHTTPClient::getStatus() const
{
return m_currentStatus.load(std::memory_order_relaxed);
}
void AsyncHTTPClient::setUrl(const std::string& url)
{
if (getStatus() != HTTP_READY)
return;
m_url = url;
}
std::string AsyncHTTPClient::getUrl() const
{
if (getStatus() != HTTP_READY)
return "";
return m_url;
}
int AsyncHTTPClient::getStatusCode() const
{
if (getStatus() != HTTP_FINISHED)
return 0;
return m_responseCode;
}
void AsyncHTTPClient::waitUntilResponse()
{
if (getStatus() != HTTP_PROCESSING)
return;
std::unique_lock<std::mutex> lock(m_asyncSendMutex);
m_finishNotifier.wait(lock);
}<|fim▁end|> | long dims = SafeArrayGetDim(responseRaw.parray);
if (dims == 1) { |
<|file_name|>test_agraph.py<|end_file_name|><|fim▁begin|>"""Unit tests for PyGraphviz interface."""
import os
import tempfile
import pytest
import pytest
pygraphviz = pytest.importorskip('pygraphviz')
from networkx.testing import assert_edges_equal, assert_nodes_equal, \
assert_graphs_equal
import networkx as nx
class TestAGraph(object):
def build_graph(self, G):
edges = [('A', 'B'), ('A', 'C'), ('A', 'C'), ('B', 'C'), ('A', 'D')]
G.add_edges_from(edges)
G.add_node('E')
G.graph['metal'] = 'bronze'
return G
def assert_equal(self, G1, G2):
assert_nodes_equal(G1.nodes(), G2.nodes())
assert_edges_equal(G1.edges(), G2.edges())
assert G1.graph['metal'] == G2.graph['metal']
def agraph_checks(self, G):
G = self.build_graph(G)<|fim▁hole|>
fname = tempfile.mktemp()
nx.drawing.nx_agraph.write_dot(H, fname)
Hin = nx.nx_agraph.read_dot(fname)
os.unlink(fname)
self.assert_equal(H, Hin)
(fd, fname) = tempfile.mkstemp()
with open(fname, 'w') as fh:
nx.drawing.nx_agraph.write_dot(H, fh)
with open(fname, 'r') as fh:
Hin = nx.nx_agraph.read_dot(fh)
os.unlink(fname)
self.assert_equal(H, Hin)
def test_from_agraph_name(self):
G = nx.Graph(name='test')
A = nx.nx_agraph.to_agraph(G)
H = nx.nx_agraph.from_agraph(A)
assert G.name == 'test'
def test_undirected(self):
self.agraph_checks(nx.Graph())
def test_directed(self):
self.agraph_checks(nx.DiGraph())
def test_multi_undirected(self):
self.agraph_checks(nx.MultiGraph())
def test_multi_directed(self):
self.agraph_checks(nx.MultiDiGraph())
def test_view_pygraphviz(self):
G = nx.Graph() # "An empty graph cannot be drawn."
pytest.raises(nx.NetworkXException, nx.nx_agraph.view_pygraphviz, G)
G = nx.barbell_graph(4, 6)
nx.nx_agraph.view_pygraphviz(G)
def test_view_pygraphviz_edgelable(self):
G = nx.Graph()
G.add_edge(1, 2, weight=7)
G.add_edge(2, 3, weight=8)
nx.nx_agraph.view_pygraphviz(G, edgelabel='weight')
def test_graph_with_reserved_keywords(self):
# test attribute/keyword clash case for #1582
# node: n
# edges: u,v
G = nx.Graph()
G = self.build_graph(G)
G.nodes['E']['n'] = 'keyword'
G.edges[('A', 'B')]['u'] = 'keyword'
G.edges[('A', 'B')]['v'] = 'keyword'
A = nx.nx_agraph.to_agraph(G)
def test_round_trip(self):
G = nx.Graph()
A = nx.nx_agraph.to_agraph(G)
H = nx.nx_agraph.from_agraph(A)
#assert_graphs_equal(G, H)
AA = nx.nx_agraph.to_agraph(H)
HH = nx.nx_agraph.from_agraph(AA)
assert_graphs_equal(H, HH)
G.graph['graph'] = {}
G.graph['node'] = {}
G.graph['edge'] = {}
assert_graphs_equal(G, HH)
def test_2d_layout(self):
G = nx.Graph()
G = self.build_graph(G)
G.graph["dimen"] = 2
pos = nx.nx_agraph.pygraphviz_layout(G, prog='neato')
pos = list(pos.values())
assert len(pos) == 5
assert len(pos[0]) == 2
def test_3d_layout(self):
G = nx.Graph()
G = self.build_graph(G)
G.graph["dimen"] = 3
pos = nx.nx_agraph.pygraphviz_layout(G, prog='neato')
pos = list(pos.values())
assert len(pos) == 5
assert len(pos[0]) == 3<|fim▁end|> | A = nx.nx_agraph.to_agraph(G)
H = nx.nx_agraph.from_agraph(A)
self.assert_equal(G, H) |
<|file_name|>about_test.go<|end_file_name|><|fim▁begin|><|fim▁hole|> "bytes"
"testing"
"github.com/Masterminds/glide/msg"
)
func TestAbout(t *testing.T) {
var buf bytes.Buffer
old := msg.Default.Stdout
msg.Default.Stdout = &buf
About()
if buf.Len() < len(aboutMessage) {
t.Errorf("expected this to match aboutMessage: %q", buf.String())
}
msg.Default.Stdout = old
}<|fim▁end|> | package action
import ( |
<|file_name|>ExtendedImplementation.java<|end_file_name|><|fim▁begin|>package org.apache.sftp.protocol.packetdata;
<|fim▁hole|>
import org.apache.sftp.protocol.Response;
public interface ExtendedImplementation<T extends Extended<T, S>, S extends Response<S>>
extends Implementation<T> {
public String getExtendedRequest();
public Implementation<S> getExtendedReplyImplementation();
}<|fim▁end|> | |
<|file_name|>message.py<|end_file_name|><|fim▁begin|># Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
SQS Message
A Message represents the data stored in an SQS queue. The rules for what is allowed within an SQS
Message are here:
http://docs.amazonwebservices.com/AWSSimpleQueueService/2008-01-01/SQSDeveloperGuide/Query_QuerySendMessage.html
So, at it's simplest level a Message just needs to allow a developer to store bytes in it and get the bytes
back out. However, to allow messages to have richer semantics, the Message class must support the
following interfaces:
The constructor for the Message class must accept a keyword parameter "queue" which is an instance of a
boto Queue object and represents the queue that the message will be stored in. The default value for
this parameter is None.
The constructor for the Message class must accept a keyword parameter "body" which represents the
content or body of the message. The format of this parameter will depend on the behavior of the
particular Message subclass. For example, if the Message subclass provides dictionary-like behavior to the
user the body passed to the constructor should be a dict-like object that can be used to populate
the initial state of the message.
The Message class must provide an encode method that accepts a value of the same type as the body
parameter of the constructor and returns a string of characters that are able to be stored in an
SQS message body (see rules above).
The Message class must provide a decode method that accepts a string of characters that can be
stored (and probably were stored!) in an SQS message and return an object of a type that is consistent
with the "body" parameter accepted on the class constructor.
The Message class must provide a __len__ method that will return the size of the encoded message
that would be stored in SQS based on the current state of the Message object.
The Message class must provide a get_body method that will return the body of the message in the
same format accepted in the constructor of the class.
The Message class must provide a set_body method that accepts a message body in the same format
accepted by the constructor of the class. This method should alter to the internal state of the
Message object to reflect the state represented in the message body parameter.
The Message class must provide a get_body_encoded method that returns the current body of the message
in the format in which it would be stored in SQS.
"""
import base64
import boto
from boto.compat import StringIO
from boto.compat import six
from boto.sqs.attributes import Attributes
from boto.sqs.messageattributes import MessageAttributes
from boto.exception import SQSDecodeError
class RawMessage(object):
"""
Base class for SQS messages. RawMessage does not encode the message
in any way. Whatever you store in the body of the message is what
will be written to SQS and whatever is returned from SQS is stored
directly into the body of the message.
"""
def __init__(self, queue=None, body=''):
self.queue = queue
self.set_body(body)
self.id = None
self.receipt_handle = None
self.md5 = None
self.attributes = Attributes(self)
self.message_attributes = MessageAttributes(self)
self.md5_message_attributes = None
def __len__(self):
return len(self.encode(self._body))
def startElement(self, name, attrs, connection):
if name == 'Attribute':
return self.attributes
if name == 'MessageAttribute':
return self.message_attributes
return None
def endElement(self, name, value, connection):
if name == 'Body':
self.set_body(value)
elif name == 'MessageId':
self.id = value
elif name == 'ReceiptHandle':
self.receipt_handle = value
elif name == 'MD5OfBody':
self.md5 = value
elif name == 'MD5OfMessageAttributes':
self.md5_message_attributes = value
else:
setattr(self, name, value)
def endNode(self, connection):
self.set_body(self.decode(self.get_body()))
def encode(self, value):
"""Transform body object into serialized byte array format."""
return value
def decode(self, value):
"""Transform seralized byte array into any object."""
return value
def set_body(self, body):
"""Override the current body for this object, using decoded format."""
self._body = body
def get_body(self):
return self._body
def get_body_encoded(self):
"""
This method is really a semi-private method used by the Queue.write
method when writing the contents of the message to SQS.
You probably shouldn't need to call this method in the normal course of events.
"""
return self.encode(self.get_body())
def delete(self):
if self.queue:
return self.queue.delete_message(self)
def change_visibility(self, visibility_timeout):
if self.queue:
self.queue.connection.change_message_visibility(self.queue,
self.receipt_handle,
visibility_timeout)
class Message(RawMessage):
"""
The default Message class used for SQS queues. This class automatically
encodes/decodes the message body using Base64 encoding to avoid any
illegal characters in the message body. See:
https://forums.aws.amazon.com/thread.jspa?threadID=13067
for details on why this is a good idea. The encode/decode is meant to
be transparent to the end-user.
"""
def encode(self, value):
if not isinstance(value, six.binary_type):
value = value.encode('utf-8')
return base64.b64encode(value).decode('utf-8')
def decode(self, value):
try:
value = base64.b64decode(value.encode('utf-8')).decode('utf-8')
except:
boto.log.warning('Unable to decode message')
return value
return value
class MHMessage(Message):
"""
The MHMessage class provides a message that provides RFC821-like
headers like this:
HeaderName: HeaderValue
The encoding/decoding of this is handled automatically and after
the message body has been read, the message instance can be treated
like a mapping object, i.e. m['HeaderName'] would return 'HeaderValue'.
"""
def __init__(self, queue=None, body=None, xml_attrs=None):
if body is None or body == '':
body = {}
super(MHMessage, self).__init__(queue, body)
def decode(self, value):
try:
msg = {}
fp = StringIO(value)
line = fp.readline()
while line:
delim = line.find(':')
key = line[0:delim]
value = line[delim+1:].strip()
msg[key.strip()] = value.strip()
line = fp.readline()
except:
raise SQSDecodeError('Unable to decode message', self)
return msg
def encode(self, value):
s = ''
for item in value.items():
s = s + '%s: %s\n' % (item[0], item[1])
return s
def __contains__(self, key):
return key in self._body
def __getitem__(self, key):
if key in self._body:
return self._body[key]
else:
raise KeyError(key)
def __setitem__(self, key, value):
self._body[key] = value
self.set_body(self._body)
def keys(self):
return self._body.keys()
def values(self):
return self._body.values()
def items(self):
return self._body.items()
def has_key(self, key):
return key in self._body
def update(self, d):
self._body.update(d)
self.set_body(self._body)
def get(self, key, default=None):
return self._body.get(key, default)
class EncodedMHMessage(MHMessage):
"""
The EncodedMHMessage class provides a message that provides RFC821-like
headers like this:<|fim▁hole|> The message instance can be treated like a mapping object,
i.e. m['HeaderName'] would return 'HeaderValue'.
"""
def decode(self, value):
try:
value = base64.b64decode(value.encode('utf-8')).decode('utf-8')
except:
raise SQSDecodeError('Unable to decode message', self)
return super(EncodedMHMessage, self).decode(value)
def encode(self, value):
value = super(EncodedMHMessage, self).encode(value)
return base64.b64encode(value.encode('utf-8')).decode('utf-8')<|fim▁end|> |
HeaderName: HeaderValue
This variation encodes/decodes the body of the message in base64 automatically. |
<|file_name|>NewList.py<|end_file_name|><|fim▁begin|># Simple class SimgleList
class SingleList:
"""Documentation for SingleList
"""
def __init__(self, initial_list=None):
self.__list = []
if initial_list:
for value in initial_list:
if value not in self.__list:
self.__list.append(value)
def __str__(self):
temp_string = ""
i = 0
for i in range(len(self)):
temp_string += "%12d" % self.__list[i]
if (i + 1) % 4 == 0:
temp_string += "\n"
if i % 4 != 0:
temp_string += "\n"
return temp_string
def __len__(self):
return len(self.__list)
def __getitem__(self, index):<|fim▁hole|> return self.__list[index]
def __setitem__(self, index, value):
if value in self.__list:
raise ValueError("List already contains value %s" % str(value))
self.__list[index] = value
def __eq__(self, other):
if len(self) != len(other):
return 0
for i in range(0, len(self)):
if self.__list[i] != other.__list[i]:
return 0
return 1
def __ne__(self, other):
return not (self == other)<|fim▁end|> | |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Copyright 2013-2015 Julian Metzler
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from setuptools import setup, find_packages
metadata = {}
with open('tweetpony/metadata.py') as f:
exec(f.read(), metadata)
setup(
name = metadata['name'],
version = metadata['version'],
description = metadata['description'],
license = metadata['license'],
author = metadata['author'],
author_email = metadata['author_email'],
install_requires = metadata['requires'],<|fim▁hole|> use_2to3 = True,
)<|fim▁end|> | url = metadata['url'],
keywords = metadata['keywords'],
packages = find_packages(), |
<|file_name|>forwarding_rule_rules_scanner_test.py<|end_file_name|><|fim▁begin|># Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Forwarding Rules Rule Scanner Test"""
from builtins import object
import unittest.mock as mock
from tests.unittest_utils import ForsetiTestCase
from google.cloud.forseti.scanner.scanners import forwarding_rule_scanner
from tests.unittest_utils import get_datafile_path
from google.cloud.forseti.common.gcp_type import forwarding_rule as fr
class ForwardingRule(object):
"""Represents ForwardRule resource."""
class ForwardingRuleScannerTest(ForsetiTestCase):
def test_forwarding_rules_scanner_all_match(self):
rules_local_path = get_datafile_path(__file__,
'forward_rule_test_1.yaml')
scanner = forwarding_rule_scanner.ForwardingRuleScanner(
{}, {}, mock.MagicMock(), '', '', rules_local_path)
project_id = "abc-123"
gcp_forwarding_rules_resource_data = [
{
"id": "46",
"creationTimestamp": "2017-06-01 04:19:37",
"name": "abc-123",
"description": "",
"region": "https://www.googleapis.com/compute/v1/projects/abc-123/regions/asia-east1",
"IPAddress": "198.51.100.99",
"IPProtocol": "UDP",
"portRange": "4500-4500",
"ports": [],
"target": "https://www.googleapis.com/compute/v1/projects/abc-123/regions/asia-east1/abc-123/abc-123",
"loadBalancingScheme": "EXTERNAL",
},
{
"id": "23",
"creationTimestamp": "2017-06-01 04:19:37",
"name": "abc-123",
"description": "",
"region": "https://www.googleapis.com/compute/v1/projects/abc-123/regions/asia-east1",
"IPAddress": "198.51.100.23",
"IPProtocol": "TCP",
"ports": [8080],
"target": "https://www.googleapis.com/compute/v1/projects/abc-123/regions/asia-east1/abc-123/abc-123",
"loadBalancingScheme": "INTERNAL",
},
{
"id": "46",
"creationTimestamp": "2017-06-01 04:19:37",
"name": "abc-123",
"description": "",
"region": "https://www.googleapis.com/compute/v1/projects/abc-123/regions/asia-east1",
"IPAddress": "198.51.100.46",
"IPProtocol": "ESP",
"ports": [],
"target": "https://www.googleapis.com/compute/v1/projects/abc-123/regions/asia-east1/abc-123/abc-123",
"loadBalancingScheme": "EXTERNAL",
},
{
"id": "46",
"creationTimestamp": "2017-06-01 04:19:37",
"name": "abc-123",
"description": "",
"region": "https://www.googleapis.com/compute/v1/projects/abc-123/regions/asia-east1",
"IPAddress": "198.51.100.35",
"IPProtocol": "TCP",
"portRange": "4500-4500",
"target": "https://www.googleapis.com/compute/v1/projects/abc-123/regions/asia-east1/abc-123/abc-123",
"loadBalancingScheme": "EXTERNAL",
}
]
gcp_forwarding_rules_resource_objs = []
for gcp_forwarding_rule_resource_data in gcp_forwarding_rules_resource_data:
gcp_forwarding_rules_resource_objs.append(
fr.ForwardingRule.from_dict(
project_id, '', gcp_forwarding_rule_resource_data))
violations = scanner._find_violations(gcp_forwarding_rules_resource_objs)
self.assertEqual(0, len(violations))
def test_forwarding_rules_scanner_no_match(self):
rules_local_path = get_datafile_path(__file__,
'forward_rule_test_1.yaml')
scanner = forwarding_rule_scanner.ForwardingRuleScanner(
{}, {}, mock.MagicMock(), '', '', rules_local_path)
project_id = "abc-123"
gcp_forwarding_rules_resource_data = [
{
"id": "46",
"creationTimestamp": "2017-06-01 04:19:37",
"name": "abc-123",
"description": "",
"region": "https://www.googleapis.com/compute/v1/projects/abc-123/regions/asia-east1",
"IPAddress": "198.51.100.99",
"IPProtocol": "TCP",
"portRange": "4500-4500",
"ports": [],
"target": "https://www.googleapis.com/compute/v1/projects/abc-123/regions/asia-east1/abc-123/abc-123",
"loadBalancingScheme": "EXTERNAL",
},
{
"id": "23",
"creationTimestamp": "2017-06-01 04:19:37",
"name": "abc-123",
"description": "",
"region": "https://www.googleapis.com/compute/v1/projects/abc-123/regions/asia-east1",
"IPAddress": "198.51.100.23",
"IPProtocol": "TCP",
"ports": [8081],
"target": "https://www.googleapis.com/compute/v1/projects/abc-123/regions/asia-east1/abc-123/abc-123",
"loadBalancingScheme": "INTERNAL",
},
{
"id": "46",
"creationTimestamp": "2017-06-01 04:19:37",
"name": "abc-123",
"description": "",
"region": "https://www.googleapis.com/compute/v1/projects/abc-123/regions/asia-east1",
"IPAddress": "198.51.101.46",
"IPProtocol": "ESP",
"ports": [],
"target": "https://www.googleapis.com/compute/v1/projects/abc-123/regions/asia-east1/abc-123/abc-123",
"loadBalancingScheme": "EXTERNAL",
},
{
"id": "46",
"creationTimestamp": "2017-06-01 04:19:37",
"name": "abc-123",
"description": "",
"region": "https://www.googleapis.com/compute/v1/projects/abc-123/regions/asia-east1",
"IPAddress": "198.51.100.35",
"IPProtocol": "TCP",
"portRange": "4400-4500",
"target": "https://www.googleapis.com/compute/v1/projects/abc-123/regions/asia-east1/abc-123/abc-123",
"loadBalancingScheme": "EXTERNAL",
}
]
gcp_forwarding_rules_resource_objs = []
for gcp_forwarding_rule_resource_data in gcp_forwarding_rules_resource_data:
gcp_forwarding_rules_resource_objs.append(
fr.ForwardingRule.from_dict(
project_id, '', gcp_forwarding_rule_resource_data)
)<|fim▁hole|>
if __name__ == '__main__':
unittest.main()<|fim▁end|> |
violations = scanner._find_violations(gcp_forwarding_rules_resource_objs)
self.assertEqual(4, len(violations))
|
<|file_name|>modeling.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2014 The ProteinDF development team.
# see also AUTHORS and README if provided.
#
# This file is a part of the ProteinDF software package.
#
# The ProteinDF is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# The ProteinDF is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ProteinDF. If not, see <http://www.gnu.org/licenses/>.
from .superposer import Superposer
from .matrix import Matrix
from .atomgroup import AtomGroup
from .atom import Atom
from .functions import load_msgpack
from .position import Position
from .error import BrInputError
# from .xyz import Xyz
import os
import math
import re
import logging
logger = logging.getLogger(__name__)
class Modeling:
_ACE_ALA_NME_path_base = os.path.join(
os.environ.get('PDF_HOME', '.'),
'data',
"ACE_ALA_NME_{}.brd")
_ACE_ALA_NME_comformers = ["trans1", "trans2", "cis1", "cis2"]
def __init__(self):
self._ACE_ALA_NME = {}
for comformer in self._ACE_ALA_NME_comformers:
brd_path = self._ACE_ALA_NME_path_base.format(comformer)
# print(comformer, brd_path)
atomgroup = AtomGroup(load_msgpack(brd_path))
assert(atomgroup.get_number_of_all_atoms() > 0)
self._ACE_ALA_NME[comformer] = atomgroup
def _get_ACE_ALA_NME(self, comformer):
assert(comformer in self._ACE_ALA_NME_comformers)
return self._ACE_ALA_NME[comformer]
# -----------------------------------------------------------------
def get_ACE_simple(self, next_aa):
"""
隣のC-alphaの位置をメチル基にする。
"""
answer = AtomGroup()
CAs = next_aa.pickup_atoms('CA')
if len(CAs) > 0:
answer.set_atom('CA', CAs[0])
else:
raise BrInputError(next_aa,
'cannot found "CA" atom on building ACE.')
Cs = next_aa.pickup_atoms('C')
if len(Cs) > 0:
answer.set_atom('C', Cs[0])
else:
raise BrInputError(next_aa,
'cannot found "C" atom on building ACE.')
Os = next_aa.pickup_atoms('O')
if len(Os) > 0:
answer.set_atom('O', Os[0])
else:
raise BrInputError(next_aa,
'cannot found "O" atom on building ACE.')
answer |= self.add_methyl(answer['CA'], answer['C'])
answer.path = '/ACE'
return answer
def get_NME_simple(self, next_aa):
"""
隣のC-alphaの位置をメチル基にする。
"""
answer = AtomGroup()
CAs = next_aa.pickup_atoms('CA')
if len(CAs) > 0:
answer.set_atom('CA', CAs[0])
else:
raise BrInputError(next_aa,
'cannot found "CA" atom on building NME.')
Ns = next_aa.pickup_atoms('N')
if len(Ns) > 0:
answer.set_atom('N', Ns[0])
else:
raise BrInputError(next_aa,
'cannot found "N" atom on building NME.')
Hs = next_aa.pickup_atoms('H')
if len(Hs) > 0:
answer.set_atom('H', Hs[0])
else:
# for proline
CDs = next_aa.pickup_atoms('CD')
if len(CDs) > 0:
dummy_H = Atom(CDs[0])
dummy_H.symbol = 'H'
answer.set_atom('H', dummy_H)
else:
raise BrInputError(next_aa,
'cannot found "H" or "CD" atom(for proline) on building NME.')
answer |= self.add_methyl(answer['CA'], answer['N'])
answer.path = '/NME'
return answer
# -----------------------------------------------------------------
def get_ACE(self, res, next_aa=None):
"""
template (ACE-ALA-NME) format:
HH3[1-3]-CH3-C - N-CA(HA)-C- N-CH3-HH3[1-3]
|| | | || |
O H CB O H
"""
AAN = None
rmsd_min = 1000.0
for comformer in self._ACE_ALA_NME_comformers:
ref_AAN = self._get_ACE_ALA_NME(comformer)
(matched, rmsd) = self._match_ACE(ref_AAN, res, next_aa)
# print(comformer, rmsd)
if rmsd < rmsd_min:
rmsd_min = rmsd
AAN = matched
if rmsd_min > 1.0:
logger.warn("RMSD value is too large: {}".format(rmsd))
answer = AtomGroup(AAN['1'])
answer.path = '/ACE'
return answer
def _match_ACE(self, AAN, res, next_aa):
'''AAN (ACE-ALA-NME)
'''
assert(isinstance(AAN, AtomGroup))
assert(isinstance(res, AtomGroup))
(AAN_part, res_part) = self._match_residues(AAN['2'], res)
# for ACE
if next_aa is not None:
if next_aa.has_atom('N'):
AAN_part.set_atom('N2', AAN['3']['N'])
res_part.set_atom('N2', next_aa['N'])
if next_aa.has_atom('H'):
AAN_part.set_atom('NH2', AAN['3']['H'])
res_part.set_atom('NH2', next_aa['H'])
if next_aa.has_atom('CA'):
AAN_part.set_atom('CH3', AAN['3']['CH3'])
res_part.set_atom('CH3', next_aa['CA'])
sp = Superposer(AAN_part, res_part)
rmsd = sp.rmsd
matched_AAN = sp.superimpose(AAN)
return (matched_AAN, rmsd)
def get_NME(self, res, next_aa=None):
"""
template (ACE-ALA-NME) format:
HH3[1-3]-CH3-C - N-CA(HA)-C- N-CH3-HH3[1-3]
|| | | || |
O H CB O H
"""
AAN = None
rmsd_min = 1000.0
for comformer in self._ACE_ALA_NME_comformers:
ref_AAN = self._get_ACE_ALA_NME(comformer)
(matched, rmsd) = self._match_NME(ref_AAN, res, next_aa)
# print(comformer, rmsd)
if rmsd < rmsd_min:
rmsd_min = rmsd
AAN = matched
if rmsd_min > 1.0:
logger.warn("RMSD value is too large: {}".format(rmsd))
answer = AtomGroup(AAN['3'])
answer.path = '/NME'
return answer
def _match_NME(self, AAN, res, next_aa):
'''AAN (ACE-ALA-NME)
'''
assert(isinstance(AAN, AtomGroup))
assert(isinstance(res, AtomGroup))
(AAN_part, res_part) = self._match_residues(AAN['2'], res)
# for NME
if next_aa is not None:
if next_aa.has_atom('C'):
AAN_part.set_atom('C2', AAN['1']['C'])
res_part.set_atom('C2', next_aa['C'])
if next_aa.has_atom('O'):
AAN_part.set_atom('O2', AAN['1']['O'])
res_part.set_atom('O2', next_aa['O'])
if next_aa.has_atom('CA'):
AAN_part.set_atom('CH3', AAN['1']['CH3'])
res_part.set_atom('CH3', next_aa['CA'])
sp = Superposer(AAN_part, res_part)
rmsd = sp.rmsd
matched_AAN = sp.superimpose(AAN)
return (matched_AAN, rmsd)
def _match_residues(self, res1, res2, max_number_of_atoms=-1):
"""
2つのアミノ酸残基のN, H, CA, HA, C, Oの原子を突き合わせる。
アミノ酸残基がプロリンだった場合は、CDの炭素をHに命名する。
GLYはHA1, HA2とあるので突き合せない。
"""
atom_names = ['CA', 'O', 'C', 'N', 'CB', 'HA']
if max_number_of_atoms == -1:
max_number_of_atoms = len(atom_names)
ans_res1 = AtomGroup()
ans_res2 = AtomGroup()
for atom_name in atom_names:
pickup_atoms1 = res1.pickup_atoms(atom_name)
if len(pickup_atoms1) > 0:
pickup_atoms2 = res2.pickup_atoms(atom_name)
if len(pickup_atoms2) > 0:
ans_res1.set_atom(atom_name, pickup_atoms1[0])
ans_res2.set_atom(atom_name, pickup_atoms2[0])
if ans_res1.get_number_of_atoms() >= max_number_of_atoms:
break
# match amino-'H'
if ans_res1.get_number_of_atoms() < max_number_of_atoms:
res1_H = None
res2_H = None
if res1.has_atom('H'):
res1_H = res1['H']
elif res1.has_atom('CD'):
# for proline
res1_H = res1['CD']
if res2.has_atom('H'):
res2_H = res2['H']
elif res2.has_atom('CD'):
res2_H = res2['CD']
if ((res1_H is not None) and (res2_H is not None)):
ans_res1.set_atom('H', res1_H)
ans_res2.set_atom('H', res2_H)
return (ans_res1, ans_res2)
# -----------------------------------------------------------------
def add_methyl(self, C1, C2):
"""
-CH3の水素を付加
C1に水素を付加
"""
assert(isinstance(C1, Atom))
assert(isinstance(C2, Atom))
ethane = AtomGroup()
ethane.set_atom('C1', Atom(symbol='C', name='C1',
position=Position(0.00000, 0.00000, 0.00000)))
ethane.set_atom('H11', Atom(symbol='H', name='H11',
position=Position(-0.85617, -0.58901, -0.35051)))
ethane.set_atom('H12', Atom(symbol='H', name='H12',
position=Position(-0.08202, 1.03597, -0.35051)))
ethane.set_atom('H13', Atom(symbol='H', name='H13',
position=Position(0.93818, -0.44696, -0.35051)))
ethane.set_atom('C2', Atom(symbol='C', name='C2',
position=Position(0.00000, 0.00000, 1.47685)))
ethane.set_atom('H21', Atom(symbol='H', name='H21',
position=Position(-0.93818, 0.44696, 1.82736)))
ethane.set_atom('H22', Atom(symbol='H', name='H22',
position=Position(0.85617, 0.58901, 1.82736)))
ethane.set_atom('H23', Atom(symbol='H', name='H23',
position=Position(0.08202, -1.03597, 1.82736)))
inC21 = C2.xyz - C1.xyz
refC21 = ethane['C2'].xyz - ethane['C1'].xyz
shift = C1.xyz - ethane['C1'].xyz
rot = self.arbitary_rotate_matrix(inC21, refC21)
ethane.rotate(rot)
ethane.shift_by(shift)
assert(C1.xyz == ethane['C1'].xyz)
answer = AtomGroup()
answer.set_atom('H11', ethane['H11'])
answer.set_atom('H12', ethane['H12'])
answer.set_atom('H13', ethane['H13'])
return answer
# -----------------------------------------------------------------
def get_NH3(self, angle=0.5 * math.pi, length=1.0):
pi23 = math.pi * 2.0 / 3.0 # (pi * 2/3)
sin23 = math.sin(pi23)
cos23 = math.cos(pi23)
# pi43 = math.pi * 4.0 / 3.0 # (pi * 4/3)
# sin43 = math.sin(pi43)
# cos43 = math.cos(pi43)
sin_input = math.sin(angle)
cos_input = math.cos(angle)
# z軸まわりに120度回転
# z1_rot = Matrix(3, 3)
# z1_rot.set(0, 0, cos23)
# z1_rot.set(0, 1, -sin23)
# z1_rot.set(1, 0, sin23)
# z1_rot.set(1, 1, cos23)
# z1_rot.set(2, 2, 1.0)
# z軸まわりに240度回転
# z2_rot = Matrix(3, 3)
# z2_rot.set(0, 0, cos43)
# z2_rot.set(0, 1, -sin43)
# z2_rot.set(1, 0, sin43)
# z2_rot.set(1, 1, cos43)
# z2_rot.set(2, 2, 1.0)
# y軸まわりに回転
# y_rot = Matrix(3, 3)
# y_rot.set(0, 0, cos_input)
# y_rot.set(0, 2, -sin_input)
# y_rot.set(2, 0, sin_input)
# y_rot.set(2, 2, cos_input)
# y_rot.set(1, 1, 1.0)
# pos_H1 = Position(1.0, 0.0, 0.0)
# pos_H1.rotate(y_rot)
# pos_H1 *= length
# pos_H2 = Position(1.0, 0.0, 0.0)
# pos_H2.rotate(y_rot)
# pos_H2.rotate(z1_rot)
# pos_H2 *= length
# pos_H3 = Position(1.0, 0.0, 0.0)
# pos_H3.rotate(y_rot)
# pos_H3.rotate(z2_rot)
# pos_H3 *= length
# X-Z平面上、Y軸に対してangle度開く
xz_rot = Matrix(3, 3)
xz_rot.set(0, 0, cos_input)
xz_rot.set(0, 2, -sin_input)
xz_rot.set(2, 0, sin_input)
xz_rot.set(2, 2, cos_input)
xz_rot.set(1, 1, 1.0)
# X-Y平面上、Z軸に対して120度開く
xy_rot = Matrix(3, 3)
xy_rot.set(0, 0, cos23)
xy_rot.set(0, 1, -sin23)
xy_rot.set(1, 0, sin23)
xy_rot.set(1, 1, cos23)
xy_rot.set(2, 2, 1.0)
pos_H1 = Position(0.0, 0.0, 1.0)
pos_H1.rotate(xz_rot)
pos_H2 = Position(0.0, 0.0, 1.0)
pos_H2.rotate(xz_rot)
pos_H2.rotate(xy_rot)
pos_H3 = Position(0.0, 0.0, 1.0)
pos_H3.rotate(xz_rot)
pos_H3.rotate(xy_rot)
pos_H3.rotate(xy_rot)
pos_H1 *= length
pos_H2 *= length
pos_H3 *= length
NH3 = AtomGroup()
N = Atom(symbol='N',
position=Position(0.0, 0.0, 0.0))
H1 = Atom(symbol='H',
position=pos_H1)
H2 = Atom(symbol='H',
position=pos_H2)
H3 = Atom(symbol='H',
position=pos_H3)
# X1 = Atom(symbol = 'X',
# position = Position(1.0, 0.0, 0.0))
# X2 = Atom(symbol = 'X',
# position = Position(0.0, 1.0, 0.0))
# X3 = Atom(symbol = 'X',
# position = Position(0.0, 0.0, 1.0))
NH3.set_atom('N', N)
NH3.set_atom('H1', H1)
NH3.set_atom('H2', H2)
NH3.set_atom('H3', H3)
# NH3.set_atom('X1', X1)
# NH3.set_atom('X2', X2)
# NH3.set_atom('X3', X3)
return NH3
# -----------------------------------------------------------------
def select_residues(self, chain, from_resid, to_resid):
'''
連続したアミノ酸残基を返す
'''
answer = AtomGroup()
for resid, res in chain.groups():
resid = int(resid)
if from_resid <= resid <= to_resid:
answer |= res
return answer
# -----------------------------------------------------------------
def arbitary_rotate_matrix(self, in_a, in_b):
"""
ベクトルaをbへ合わせる回転行列(3x3)を返す
"""
assert(isinstance(in_a, Position))
assert(isinstance(in_b, Position))
a = Position(in_a)
b = Position(in_b)
a.norm()
b.norm()
cos_theta = a.dot(b)
sin_theta = math.sqrt(1 - cos_theta * cos_theta)
n = a.cross(b)
n.norm()
nx = n.x
ny = n.y
nz = n.z
rot = Matrix(3, 3)
rot.set(0, 0, nx * nx * (1.0 - cos_theta) + cos_theta)
rot.set(0, 1, nx * ny * (1.0 - cos_theta) + nz * sin_theta)
rot.set(0, 2, nx * nz * (1.0 - cos_theta) - ny * sin_theta)
rot.set(1, 0, nx * ny * (1.0 - cos_theta) - nz * sin_theta)
rot.set(1, 1, ny * ny * (1.0 - cos_theta) + cos_theta)
rot.set(1, 2, nx * nz * (1.0 - cos_theta) + nx * sin_theta)
rot.set(2, 0, nx * nz * (1.0 - cos_theta) + ny * sin_theta)
rot.set(2, 1, ny * nz * (1.0 - cos_theta) - nx * sin_theta)
rot.set(2, 2, nz * nz * (1.0 - cos_theta) + cos_theta)
return rot
# -----------------------------------------------------------------
def get_last_index(self, res):
answer = 0
re_obj = re.compile('([0-9]+)')
for key, atom in res.atoms():
m = re_obj.search(key)
if m is not None:
num = m.group(0)
num = int(num)
answer = max(num, answer)
return answer
# -----------------------------------------------------------------
def neutralize_Nterm(self, res):
answer = None
if res.name == "PRO":
answer = self._neutralize_Nterm_PRO(res)
else:
answer = self._neutralize_Nterm(res)
return answer
def _neutralize_Nterm(self, res):
"""
N末端側を中性化するためにCl-(AtomGroup)を返す
H1, N2, HXT(or H3)が指定されている必要があります。
"""
ag = AtomGroup()
ag.set_atom('N', res['N'])
ag.set_atom('H1', res['H1'])
ag.set_atom('H2', res['H2'])
if res.has_atom('HXT'):
ag.set_atom('H3', res['HXT'])
elif res.has_atom('H3'):
ag.set_atom('H3', res['H3'])<|fim▁hole|> pos = self._get_neutralize_pos_NH3_type(ag)
answer = AtomGroup()
Cl = Atom(symbol='Cl',
name='Cl',
position=pos)
answer.set_atom('Cl', Cl)
return answer
def _neutralize_Nterm_PRO(self, res):
"""in case of 'PRO', neutralize N-term
"""
ag = AtomGroup()
ag.set_atom('N', res['N'])
ag.set_atom('H2', res['H2'])
if res.has_atom('HXT'):
ag.set_atom('H1', res['HXT'])
elif res.has_atom('H3'):
ag.set_atom('H1', res['H3'])
pos = self._get_neutralize_pos_NH2_type(ag)
answer = AtomGroup()
Cl = Atom(symbol='Cl',
name='Cl',
position=pos)
answer.set_atom('Cl', Cl)
return answer
def neutralize_Cterm(self, res):
"""
C末端側を中性化するためにNa+(AtomGroup)を返す
"""
ag = AtomGroup()
ag.set_atom('C', res['C'])
ag.set_atom('O1', res['O'])
ag.set_atom('O2', res['OXT'])
pos = self._get_neutralize_pos_COO_type(ag)
answer = AtomGroup()
Na = Atom(symbol='Na',
name='Na',
position=pos)
answer.set_atom('Na', Na)
return answer
# -----------------------------------------------------------------
def neutralize_GLU(self, res):
ag = AtomGroup()
ag.set_atom('C', res['CD'])
ag.set_atom('O1', res['OE1'])
ag.set_atom('O2', res['OE2'])
pos = self._get_neutralize_pos_COO_type(ag)
answer = AtomGroup()
Na = Atom(symbol='Na',
name='Na',
position=pos)
key = self.get_last_index(res)
answer.set_atom('{}_Na'.format(key + 1), Na)
return answer
def neutralize_ASP(self, res):
ag = AtomGroup()
ag.set_atom('C', res['CG'])
ag.set_atom('O1', res['OD1'])
ag.set_atom('O2', res['OD2'])
pos = self._get_neutralize_pos_COO_type(ag)
answer = AtomGroup()
Na = Atom(symbol='Na',
name='Na',
position=pos)
key = self.get_last_index(res)
answer.set_atom('{}_Na'.format(key + 1), Na)
return answer
def neutralize_LYS(self, res):
ag = AtomGroup()
ag.set_atom('N', res['NZ'])
ag.set_atom('H1', res['HZ1'])
ag.set_atom('H2', res['HZ2'])
ag.set_atom('H3', res['HZ3'])
pos = self._get_neutralize_pos_NH3_type(ag)
answer = AtomGroup()
Cl = Atom(symbol='Cl',
name='Cl',
position=pos)
key = self.get_last_index(res)
answer.set_atom('{}_Cl'.format(key + 1), Cl)
return answer
def neutralize_ARG(self, res, case=0):
"""
case: 0; 中央
case: 1; NH1側
case: 2; NH2側
"""
case = int(case)
pos = Position()
if case == 0:
length = 3.0
NH1 = res['NH1']
NH2 = res['NH2']
CZ = res['CZ']
M = Position(0.5 * (NH1.xyz.x + NH2.xyz.x),
0.5 * (NH1.xyz.y + NH2.xyz.y),
0.5 * (NH1.xyz.z + NH2.xyz.z))
vCM = M - CZ.xyz
vCM.norm()
pos = CZ.xyz + length * vCM
elif case == 1:
length = 2.0
HH11 = res['HH11']
HH12 = res['HH12']
N = res['NH1']
M = Position(0.5 * (HH11.xyz.x + HH12.xyz.x),
0.5 * (HH11.xyz.y + HH12.xyz.y),
0.5 * (HH11.xyz.z + HH12.xyz.z))
vNM = M - N.xyz
vNM.norm()
pos = N.xyz + length * vNM
elif case == 2:
length = 2.0
HH21 = res['HH21']
HH22 = res['HH22']
N = res['NH2']
M = Position(0.5 * (HH21.xyz.x + HH22.xyz.x),
0.5 * (HH21.xyz.y + HH22.xyz.y),
0.5 * (HH21.xyz.z + HH22.xyz.z))
vNM = M - N.xyz
vNM.norm()
pos = N.xyz + length * vNM
else:
pass
answer = AtomGroup()
Cl = Atom(symbol='Cl',
name='Cl',
position=pos)
key = self.get_last_index(res)
answer.set_atom('{}_Cl'.format(key + 1), Cl)
return answer
# ------------------------------------------------------------------
def neutralize_FAD(self, ag):
print("neutralize_FAD")
print(ag)
answer = AtomGroup()
POO1 = AtomGroup()
POO1.set_atom('P', ag['P'])
# amber format: OP1, pdb: O1P
if ag.has_atom('O1P'):
POO1.set_atom('O1', ag['O1P'])
elif ag.has_atom('OP1'):
POO1.set_atom('O1', ag['OP1'])
else:
raise
# amber format: OP2, pdb: O2P
if ag.has_atom('O2P'):
POO1.set_atom('O2', ag['O2P'])
elif ag.has_atom('OP2'):
POO1.set_atom('O2', ag['OP2'])
else:
raise
Na1 = Atom(symbol='Na',
name='Na',
position=self._get_neutralize_pos_POO_type(POO1))
POO2 = AtomGroup()
POO2.set_atom('P', ag['PA'])
POO2.set_atom('O1', ag['O1A']) # amber format: OA1, pdb: O1A
POO2.set_atom('O2', ag['O2A']) # amber format: OA2, pdb: O2A
Na2 = Atom(symbol='Na',
name='Na',
position=self._get_neutralize_pos_POO_type(POO2))
key = self.get_last_index(ag)
answer.set_atom('{}_Na1'.format(key + 1), Na1)
answer.set_atom('{}_Na2'.format(key + 1), Na2)
return answer
# ------------------------------------------------------------------
def _get_neutralize_pos_NH3_type(self, ag):
length = 3.187
H1 = ag['H1']
H2 = ag['H2']
H3 = ag['H3']
N = ag['N']
# 重心を計算
M = Position((H1.xyz.x + H2.xyz.x + H3.xyz.x) / 3.0,
(H1.xyz.y + H2.xyz.y + H3.xyz.y) / 3.0,
(H1.xyz.z + H2.xyz.z + H3.xyz.z) / 3.0)
vNM = M - N.xyz
vNM.norm()
return N.xyz + length * vNM
def _get_neutralize_pos_NH2_type(self, ag):
length = 3.187
H1 = ag['H1']
H2 = ag['H2']
N = ag['N']
vNH1 = H1.xyz - N.xyz
vNH2 = H2.xyz - N.xyz
vM = 0.5 * (vNH1 + vNH2)
vM.norm()
answer = N.xyz + length * vM
return answer
def _get_neutralize_pos_COO_type(self, ag):
length = 2.521
O1 = ag['O1']
O2 = ag['O2']
C = ag['C']
# 中点を計算
M = Position(0.5 * (O1.xyz.x + O2.xyz.x),
0.5 * (O1.xyz.y + O2.xyz.y),
0.5 * (O1.xyz.z + O2.xyz.z))
vCM = M - C.xyz
vCM.norm()
return C.xyz + length * vCM
# -----------------------------------------------------------------
def _get_neutralize_pos_POO_type(self, ag):
length = 2.748
O1 = ag['O1']
O2 = ag['O2']
P = ag['P']
M = Position(0.5 * (O1.xyz.x + O2.xyz.x),
0.5 * (O1.xyz.y + O2.xyz.y),
0.5 * (O1.xyz.z + O2.xyz.z))
vPM = M - P.xyz
vPM.norm()
return P.xyz + length * vPM
if __name__ == "__main__":
import doctest
doctest.testmod()<|fim▁end|> | |
<|file_name|>族語辭典1轉檔.py<|end_file_name|><|fim▁begin|>from os import makedirs
from os.path import join
from posix import listdir
from django.conf import settings
from django.core.management.base import BaseCommand
from libavwrapper.avconv import Input, Output, AVConv
from libavwrapper.codec import AudioCodec, NO_VIDEO
from 匯入.族語辭典 import 代碼對應
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'語言',
type=str,
help='選擇的族語'
)
def handle(self, *args, **參數):
# 檢查avconv有裝無
代碼 = 代碼對應[參數['語言']]
語料目錄 = join(settings.BASE_DIR, '語料', '族語辭典', 代碼)
目標目錄 = join(settings.BASE_DIR, '語料', '族語辭典wav', 代碼)
makedirs(目標目錄, exist_ok=True)<|fim▁hole|> 來源 = join(語料目錄, 檔名)
目標 = join(目標目錄, 檔名[:-4] + '.wav')
目標聲音格式 = AudioCodec('pcm_s16le')
目標聲音格式.channels(1)
目標聲音格式.frequence(16000)
原始檔案 = Input(來源)
網頁檔案 = Output(目標).overwrite()
指令 = AVConv('avconv', 原始檔案, 目標聲音格式, NO_VIDEO, 網頁檔案)
程序 = 指令.run()
程序.wait()<|fim▁end|> | for 檔名 in sorted(listdir(語料目錄)):
if 檔名.endswith('.mp3'): |
<|file_name|>waves.js<|end_file_name|><|fim▁begin|>/*!
* Waves v0.5.3
* http://fian.my.id/Waves
*
* Copyright 2014 Alfiana E. Sibuea and other contributors
* Released under the MIT license
* https://github.com/fians/Waves/blob/master/LICENSE
*/
;(function(window) {
'use strict';
var Waves = Waves || {};
var $$ = document.querySelectorAll.bind(document);
// Find exact position of element
function isWindow(obj) {
return obj !== null && obj === obj.window;
}
function getWindow(elem) {
return isWindow(elem) ? elem : elem.nodeType === 9 && elem.defaultView;
}
function offset(elem) {
var docElem, win,
box = {top: 0, left: 0},
doc = elem && elem.ownerDocument;
docElem = doc.documentElement;
if (typeof elem.getBoundingClientRect !== typeof undefined) {
box = elem.getBoundingClientRect();
}
win = getWindow(doc);
return {
top: box.top + win.pageYOffset - docElem.clientTop,
left: box.left + win.pageXOffset - docElem.clientLeft
};
}
function convertStyle(obj) {
var style = '';
for (var a in obj) {
if (obj.hasOwnProperty(a)) {
style += (a + ':' + obj[a] + ';');
}
}
return style;
}
var Effect = {
// Effect delay
duration: 500,
show: function(e) {
// Disable right click
if (e.button === 2) {
return false;
}
var el = this;
// Create ripple
var ripple = document.createElement('div');
ripple.className = 'waves-ripple';
el.appendChild(ripple);
// Get click coordinate and element witdh
var pos = offset(el);
var relativeY = (e.pageY - pos.top) - 10;
var relativeX = (e.pageX - pos.left) - 10;
// var scale = 'scale('+((el.clientWidth / 100) * 2.5)+')';
var scale = 'scale(15)';
// Support for touch devices
if ('touches' in e) {
relativeY = (e.touches[0].pageY - pos.top) - 45;
relativeX = (e.touches[0].pageX - pos.left) - 45;
}
// Attach data to element
ripple.setAttribute('data-hold', Date.now());
ripple.setAttribute('data-scale', scale);
ripple.setAttribute('data-x', relativeX);
ripple.setAttribute('data-y', relativeY);
// Set ripple position
var rippleStyle = {
'top': relativeY+'px',
'left': relativeX+'px'
};
ripple.className = ripple.className + ' waves-notransition';
ripple.setAttribute('style', convertStyle(rippleStyle));
ripple.className = ripple.className.replace('waves-notransition', '');
// Scale the ripple
rippleStyle['-webkit-transform'] = scale;
rippleStyle['-moz-transform'] = scale;
rippleStyle['-ms-transform'] = scale;
rippleStyle['-o-transform'] = scale;
rippleStyle.transform = scale;
rippleStyle.opacity = '1';
rippleStyle['-webkit-transition-duration'] = Effect.duration + 'ms';
rippleStyle['-moz-transition-duration'] = Effect.duration + 'ms';
rippleStyle['-o-transition-duration'] = Effect.duration + 'ms';
rippleStyle['transition-duration'] = Effect.duration + 'ms';
ripple.setAttribute('style', convertStyle(rippleStyle));
},
hide: function() {
var el = this;
var width = el.clientWidth * 1.4;
// Get first ripple
var ripple = null;
var childrenLength = el.children.length;
for (var a = 0; a < childrenLength; a++) {
if (el.children[a].className.indexOf('waves-ripple') !== -1) {
ripple = el.children[a];
continue;
}
}
if (!ripple) {
return false;
}
var relativeX = ripple.getAttribute('data-x');
var relativeY = ripple.getAttribute('data-y');
var scale = ripple.getAttribute('data-scale');
// Get delay beetween mousedown and mouse leave
var diff = Date.now() - Number(ripple.getAttribute('data-hold'));
var delay = 500 - diff;
if (delay < 0) {
delay = 0;
}
// Fade out ripple after delay
setTimeout(function() {
var style = {
'top': relativeY+'px',
'left': relativeX+'px',
'opacity': '0',
// Duration
'-webkit-transition-duration': Effect.duration + 'ms',
'-moz-transition-duration': Effect.duration + 'ms',
'-o-transition-duration': Effect.duration + 'ms',
'transition-duration': Effect.duration + 'ms',
'-webkit-transform': scale,
'-moz-transform': scale,
'-ms-transform': scale,
'-o-transform': scale,
'transform': scale,
};
ripple.setAttribute('style', convertStyle(style));
setTimeout(function() {
try {
el.removeChild(ripple);
} catch(e) {
return false;
}
}, Effect.duration);
}, delay);
},
// Little hack to make <input> can perform waves effect
wrapInput: function(elements) {
for (var a = 0; a < elements.length; a++) {
var el = elements[a];
if (el.tagName.toLowerCase() === 'input') {
var parent = el.parentNode;
// If input already have parent just pass through
if (parent.tagName.toLowerCase() === 'i' && parent.className.indexOf('waves-effect') !== -1) {
return false;
}
// Put element class and style to the specified parent
var wrapper = document.createElement('i');
wrapper.className = el.className + ' waves-input-wrapper';
var elementStyle = el.getAttribute('style');
var dimensionStyle = 'width:'+el.offsetWidth+'px;height:'+el.clientHeight+'px;';
if (!elementStyle) {
elementStyle = '';
}
wrapper.setAttribute('style', dimensionStyle+elementStyle);
el.className = 'waves-button-input';
el.removeAttribute('style');
// Put element as child
parent.replaceChild(wrapper, el);<|fim▁hole|>
}
}
}
};
Waves.displayEffect = function(options) {
options = options || {};
if ('duration' in options) {
Effect.duration = options.duration;
}
//Wrap input inside <i> tag
Effect.wrapInput($$('.waves-effect'));
Array.prototype.forEach.call($$('.waves-effect'), function(i) {
if ('ontouchstart' in window) {
i.addEventListener('mouseup', Effect.hide, false); i.addEventListener('touchstart', Effect.show, false);
i.addEventListener('mouseleave', Effect.hide, false); i.addEventListener('touchend', Effect.hide, false);
i.addEventListener('touchcancel', Effect.hide, false);
} else {
i.addEventListener('mousedown', Effect.show, false);
i.addEventListener('mouseup', Effect.hide, false);
i.addEventListener('mouseleave', Effect.hide, false);
}
});
};
window.Waves = Waves;
Waves.displayEffect();
})(window);<|fim▁end|> | wrapper.appendChild(el); |
<|file_name|>CreateInstanceRequestOrBuilder.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/redis/v1/cloud_redis.proto
package com.google.cloud.redis.v1;
public interface CreateInstanceRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.redis.v1.CreateInstanceRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required. The resource name of the instance location using the form:
* `projects/{project_id}/locations/{location_id}`
* where `location_id` refers to a GCP region.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
java.lang.String getParent();
/**
*
*
* <pre>
* Required. The resource name of the instance location using the form:
* `projects/{project_id}/locations/{location_id}`
* where `location_id` refers to a GCP region.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
com.google.protobuf.ByteString getParentBytes();
/**
*
*
* <pre>
* Required. The logical name of the Redis instance in the customer project
* with the following restrictions:
* * Must contain only lowercase letters, numbers, and hyphens.
* * Must start with a letter.
* * Must be between 1-40 characters.
* * Must end with a number or a letter.
* * Must be unique within the customer project / location
* </pre>
*
* <code>string instance_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The instanceId.
*/
java.lang.String getInstanceId();
/**
*
*
* <pre>
* Required. The logical name of the Redis instance in the customer project
* with the following restrictions:
* * Must contain only lowercase letters, numbers, and hyphens.
* * Must start with a letter.
* * Must be between 1-40 characters.
* * Must end with a number or a letter.
* * Must be unique within the customer project / location
* </pre>
*<|fim▁hole|> * @return The bytes for instanceId.
*/
com.google.protobuf.ByteString getInstanceIdBytes();
/**
*
*
* <pre>
* Required. A Redis [Instance] resource
* </pre>
*
* <code>.google.cloud.redis.v1.Instance instance = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the instance field is set.
*/
boolean hasInstance();
/**
*
*
* <pre>
* Required. A Redis [Instance] resource
* </pre>
*
* <code>.google.cloud.redis.v1.Instance instance = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
com.google.cloud.redis.v1.Instance getInstance();
/**
*
*
* <pre>
* Required. A Redis [Instance] resource
* </pre>
*
* <code>.google.cloud.redis.v1.Instance instance = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
com.google.cloud.redis.v1.InstanceOrBuilder getInstanceOrBuilder();
}<|fim▁end|> | * <code>string instance_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>#[macro_use]
extern crate gfx;
extern crate gfx_support;
extern crate image;
use std::io::Cursor;
use std::time::Instant;
use gfx::format::Rgba8;
use gfx_support::{BackbufferView, ColorFormat};
use gfx::{Bundle, GraphicsPoolExt};
gfx_defines!{<|fim▁hole|> }
constant Locals {
offsets: [f32; 2] = "u_Offsets",
}
pipeline pipe {
vbuf: gfx::VertexBuffer<Vertex> = (),
color: gfx::TextureSampler<[f32; 4]> = "t_Color",
flow: gfx::TextureSampler<[f32; 4]> = "t_Flow",
noise: gfx::TextureSampler<[f32; 4]> = "t_Noise",
offset0: gfx::Global<f32> = "f_Offset0",
offset1: gfx::Global<f32> = "f_Offset1",
locals: gfx::ConstantBuffer<Locals> = "Locals",
out: gfx::RenderTarget<ColorFormat> = "Target0",
}
}
impl Vertex {
fn new(p: [f32; 2], u: [f32; 2]) -> Vertex {
Vertex {
pos: p,
uv: u,
}
}
}
fn load_texture<R, D>(device: &mut D, data: &[u8])
-> Result<gfx::handle::ShaderResourceView<R, [f32; 4]>, String>
where R: gfx::Resources, D: gfx::Device<R> {
use gfx::texture as t;
let img = image::load(Cursor::new(data), image::PNG).unwrap().to_rgba();
let (width, height) = img.dimensions();
let kind = t::Kind::D2(width as t::Size, height as t::Size, t::AaMode::Single);
let (_, view) = device.create_texture_immutable_u8::<Rgba8>(kind, &[&img]).unwrap();
Ok(view)
}
struct App<B: gfx::Backend> {
views: Vec<BackbufferView<B::Resources>>,
bundle: Bundle<B, pipe::Data<B::Resources>>,
cycles: [f32; 2],
time_start: Instant,
}
impl<B: gfx::Backend> gfx_support::Application<B> for App<B> {
fn new(device: &mut B::Device,
_: &mut gfx::queue::GraphicsQueue<B>,
backend: gfx_support::shade::Backend,
window_targets: gfx_support::WindowTargets<B::Resources>) -> Self
{
use gfx::traits::DeviceExt;
let vs = gfx_support::shade::Source {
glsl_120: include_bytes!("shader/flowmap_120.glslv"),
glsl_150: include_bytes!("shader/flowmap_150.glslv"),
hlsl_40: include_bytes!("data/vertex.fx"),
msl_11: include_bytes!("shader/flowmap_vertex.metal"),
.. gfx_support::shade::Source::empty()
};
let ps = gfx_support::shade::Source {
glsl_120: include_bytes!("shader/flowmap_120.glslf"),
glsl_150: include_bytes!("shader/flowmap_150.glslf"),
hlsl_40: include_bytes!("data/pixel.fx"),
msl_11: include_bytes!("shader/flowmap_frag.metal"),
.. gfx_support::shade::Source::empty()
};
let vertex_data = [
Vertex::new([-1.0, -1.0], [0.0, 0.0]),
Vertex::new([ 1.0, -1.0], [1.0, 0.0]),
Vertex::new([ 1.0, 1.0], [1.0, 1.0]),
Vertex::new([-1.0, -1.0], [0.0, 0.0]),
Vertex::new([ 1.0, 1.0], [1.0, 1.0]),
Vertex::new([-1.0, 1.0], [0.0, 1.0]),
];
let (vbuf, slice) = device.create_vertex_buffer_with_slice(&vertex_data, ());
let water_texture = load_texture(device, &include_bytes!("image/water.png")[..]).unwrap();
let flow_texture = load_texture(device, &include_bytes!("image/flow.png")[..]).unwrap();
let noise_texture = load_texture(device, &include_bytes!("image/noise.png")[..]).unwrap();
let sampler = device.create_sampler_linear();
let pso = device.create_pipeline_simple(
vs.select(backend).unwrap(),
ps.select(backend).unwrap(),
pipe::new()
).unwrap();
let data = pipe::Data {
vbuf: vbuf,
color: (water_texture, sampler.clone()),
flow: (flow_texture, sampler.clone()),
noise: (noise_texture, sampler.clone()),
offset0: 0.0,
offset1: 0.0,
locals: device.create_constant_buffer(1),
out: window_targets.views[0].0.clone(),
};
App {
views: window_targets.views,
bundle: Bundle::new(slice, pso, data),
cycles: [0.0, 0.5],
time_start: Instant::now(),
}
}
fn render(&mut self, (frame, sync): (gfx::Frame, &gfx_support::SyncPrimitives<B::Resources>),
pool: &mut gfx::GraphicsCommandPool<B>, queue: &mut gfx::queue::GraphicsQueue<B>)
{
let delta = self.time_start.elapsed();
self.time_start = Instant::now();
let delta = delta.as_secs() as f32 + delta.subsec_nanos() as f32 / 1000_000_000.0;
// since we sample our diffuse texture twice we need to lerp between
// them to get a smooth transition (shouldn't even be noticeable).
// They start half a cycle apart (0.5) and is later used to calculate
// the interpolation amount via `2.0 * abs(cycle0 - .5f)`
self.cycles[0] += 0.25 * delta;
if self.cycles[0] > 1.0 {
self.cycles[0] -= 1.0;
}
self.cycles[1] += 0.25 * delta;
if self.cycles[1] > 1.0 {
self.cycles[1] -= 1.0;
}
let (cur_color, _) = self.views[frame.id()].clone();
self.bundle.data.out = cur_color;
let mut encoder = pool.acquire_graphics_encoder();
self.bundle.data.offset0 = self.cycles[0];
self.bundle.data.offset1 = self.cycles[1];
let locals = Locals { offsets: self.cycles };
encoder.update_constant_buffer(&self.bundle.data.locals, &locals);
encoder.clear(&self.bundle.data.out, [0.3, 0.3, 0.3, 1.0]);
self.bundle.encode(&mut encoder);
encoder.synced_flush(queue, &[&sync.rendering], &[], Some(&sync.frame_fence))
.expect("Could not flush encoder");
}
fn on_resize(&mut self, window_targets: gfx_support::WindowTargets<B::Resources>) {
self.views = window_targets.views;
}
}
pub fn main() {
use gfx_support::Application;
App::launch_simple("Flowmap example");
}<|fim▁end|> | vertex Vertex {
pos: [f32; 2] = "a_Pos",
uv: [f32; 2] = "a_Uv", |
<|file_name|>types.go<|end_file_name|><|fim▁begin|>// Copyright 2015 Netflix, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//<|fim▁hole|>// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package handlers
import "github.com/netflix/rend/common"
type HandlerConst func() (Handler, error)
// NilHandler is used as a placeholder for when there is no handler needed.
// Since the Server API is a composition of a few things, including Handlers,
// there needs to be a placeholder for when it's not needed.
func NilHandler() (Handler, error) { return nil, nil }
type Handler interface {
Set(cmd common.SetRequest) error
Add(cmd common.SetRequest) error
Replace(cmd common.SetRequest) error
Append(cmd common.SetRequest) error
Prepend(cmd common.SetRequest) error
Get(cmd common.GetRequest) (<-chan common.GetResponse, <-chan error)
GetE(cmd common.GetRequest) (<-chan common.GetEResponse, <-chan error)
GAT(cmd common.GATRequest) (common.GetResponse, error)
Delete(cmd common.DeleteRequest) error
Touch(cmd common.TouchRequest) error
Close() error
}<|fim▁end|> | // Unless required by applicable law or agreed to in writing, software |
<|file_name|>PathOpsOpCubicThreadedTest.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "PathOpsExtendedTest.h"
#include "PathOpsThreadedCommon.h"
static void testOpCubicsMain(PathOpsThreadState* data) {
#if DEBUG_SHOW_TEST_NAME
strncpy(DEBUG_FILENAME_STRING, "", DEBUG_FILENAME_STRING_LENGTH);
#endif
SkASSERT(data);
PathOpsThreadState& state = *data;
char pathStr[1024]; // gdb: set print elements 400
bool progress = state.fReporter->verbose(); // FIXME: break out into its own parameter?
if (progress) {
sk_bzero(pathStr, sizeof(pathStr));
}
for (int a = 0 ; a < 6; ++a) {
for (int b = a + 1 ; b < 7; ++b) {
for (int c = 0 ; c < 6; ++c) {
for (int d = c + 1 ; d < 7; ++d) {
for (int e = SkPath::kWinding_FillType ; e <= SkPath::kEvenOdd_FillType; ++e) {
for (int f = SkPath::kWinding_FillType ; f <= SkPath::kEvenOdd_FillType; ++f) {
SkPath pathA, pathB;
if (progress) {
char* str = pathStr;
str += sprintf(str, " path.setFillType(SkPath::k%s_FillType);\n",
e == SkPath::kWinding_FillType ? "Winding" : e == SkPath::kEvenOdd_FillType
? "EvenOdd" : "?UNDEFINED");
str += sprintf(str, " path.moveTo(%d,%d);\n", state.fA, state.fB);
str += sprintf(str, " path.cubicTo(%d,%d, %d,%d, %d,%d);\n", state.fC, state.fD,
b, a, d, c);
str += sprintf(str, " path.close();\n");
str += sprintf(str, " pathB.setFillType(SkPath::k%s_FillType);\n",
f == SkPath::kWinding_FillType ? "Winding" : f == SkPath::kEvenOdd_FillType
? "EvenOdd" : "?UNDEFINED");
str += sprintf(str, " pathB.moveTo(%d,%d);\n", a, b);
str += sprintf(str, " pathB.cubicTo(%d,%d, %d,%d, %d,%d);\n", c, d,<|fim▁hole|> state.fB, state.fA, state.fD, state.fC);
str += sprintf(str, " pathB.close();\n");
}
pathA.setFillType((SkPath::FillType) e);
pathA.moveTo(SkIntToScalar(state.fA), SkIntToScalar(state.fB));
pathA.cubicTo(SkIntToScalar(state.fC), SkIntToScalar(state.fD), SkIntToScalar(b),
SkIntToScalar(a), SkIntToScalar(d), SkIntToScalar(c));
pathA.close();
pathB.setFillType((SkPath::FillType) f);
pathB.moveTo(SkIntToScalar(a), SkIntToScalar(b));
pathB.cubicTo(SkIntToScalar(c), SkIntToScalar(d), SkIntToScalar(state.fB),
SkIntToScalar(state.fA), SkIntToScalar(state.fD), SkIntToScalar(state.fC));
pathB.close();
for (int op = 0 ; op <= kXOR_PathOp; ++op) {
if (progress) {
outputProgress(state.fPathStr, pathStr, (SkPathOp) op);
}
testThreadedPathOp(state.fReporter, pathA, pathB, (SkPathOp) op, "cubics");
}
}
}
}
}
}
}
}
DEF_TEST(PathOpsOpCubicsThreaded, reporter) {
int threadCount = initializeTests(reporter, "cubicOp");
PathOpsThreadedTestRunner testRunner(reporter, threadCount);
for (int a = 0; a < 6; ++a) { // outermost
for (int b = a + 1; b < 7; ++b) {
for (int c = 0 ; c < 6; ++c) {
for (int d = c + 1; d < 7; ++d) {
*testRunner.fRunnables.append() = SkNEW_ARGS(PathOpsThreadedRunnable,
(&testOpCubicsMain, a, b, c, d, &testRunner));
}
}
if (!reporter->allowExtendedTest()) goto finish;
}
}
finish:
testRunner.render();
ShowTestArray();
}<|fim▁end|> | |
<|file_name|>validate-header.hook.ts<|end_file_name|><|fim▁begin|>// FoalTS
import { ValidateFunction } from 'ajv';
import {
ApiParameter,
ApiResponse,
Context,
Hook,
HookDecorator,
HttpResponseBadRequest,
IApiHeaderParameter,
OpenApi,
ServiceManager
} from '../../core';
import { getAjvInstance } from '../utils';
import { isFunction } from './is-function.util';
/**
* Hook - Validate a specific header against an AJV schema.
*
* @export
* @param {string} name - Header name.
* @param {(object | ((controller: any) => object))} [schema={ type: 'string' }] - Schema used to
* validate the header.
* @param {{ openapi?: boolean, required?: boolean }} [options={}] - Options.
* @param {boolean} [options.openapi] - Add OpenApi metadata.
* @param {boolean} [options.required] - Specify is the header is optional.
* @returns {HookDecorator} The hook.
*/
export function ValidateHeader(
name: string,
schema: object | ((controller: any) => object) = { type: 'string' },
options: { openapi?: boolean, required?: boolean } = {}
): HookDecorator {
// tslint:disable-next-line
const required = options.required ?? true;
name = name.toLowerCase();
let validateSchema: ValidateFunction|undefined;
function validate(this: any, ctx: Context, services: ServiceManager) {
if (!validateSchema) {
const ajvSchema = isFunction(schema) ? schema(this) : schema;
const components = services.get(OpenApi).getComponents(this);
validateSchema = getAjvInstance().compile({
components,
properties: {
[name]: ajvSchema
},<|fim▁hole|> });
}
if (!validateSchema(ctx.request.headers)) {
return new HttpResponseBadRequest({ headers: validateSchema.errors });
}
}
const param: IApiHeaderParameter = { in: 'header', name };
if (required) {
param.required = required;
}
const openapi = [
ApiParameter((c: any) => ({
...param,
schema: isFunction(schema) ? schema(c) : schema
})),
ApiResponse(400, { description: 'Bad request.' })
];
return Hook(validate, openapi, options);
}<|fim▁end|> | required: required ? [ name ] : [],
type: 'object', |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import lxml.html
from .bills import NHBillScraper
from .legislators import NHLegislatorScraper
from .committees import NHCommitteeScraper
metadata = {
'abbreviation': 'nh',
'name': 'New Hampshire',
'capitol_timezone': 'America/New_York',
'legislature_name': 'New Hampshire General Court',
'legislature_url': 'http://www.gencourt.state.nh.us/',
'chambers': {
'upper': {'name': 'Senate', 'title': 'Senator'},
'lower': {'name': 'House', 'title': 'Representative'},
},
'terms': [
{'name': '2011-2012', 'sessions': ['2011', '2012'],
'start_year': 2011, 'end_year': 2012},
{'name': '2013-2014', 'sessions': ['2013', '2014'],
'start_year': 2013, 'end_year': 2014},
{'name': '2015-2016', 'sessions': ['2015', '2016'],
'start_year': 2015, 'end_year': 2016},
{'name': '2017-2018', 'sessions': ['2017'],
'start_year': 2017, 'end_year': 2018}
],<|fim▁hole|> 'session_details': {
'2011': {'display_name': '2011 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2011%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2011 Session',
},
'2012': {'display_name': '2012 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2012%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2012 Session',
},
'2013': {'display_name': '2013 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2013%20Session%20Bill%20Status%20Tables.zip',
# Their dump filename changed, probably just a hiccup.
'_scraped_name': '2013',
# '_scraped_name': '2013 Session',
},
'2014': {'display_name': '2014 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2014%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2014 Session',
},
'2015': {'display_name': '2015 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2015%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2015 Session',
},
'2016': {'display_name': '2016 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2016%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2016 Session',
},
'2017': {'display_name': '2017 Regular Session',
'_scraped_name': '2017 Session',
},
},
'feature_flags': ['subjects', 'influenceexplorer'],
'_ignored_scraped_sessions': ['2013 Session','2017 Session Bill Status Tables Link.txt'],
}
def session_list():
from billy.scrape.utils import url_xpath
zips = url_xpath('http://gencourt.state.nh.us/downloads/',
'//a[contains(@href, "Bill%20Status%20Tables")]/text()')
return [zip.replace(' Bill Status Tables.zip', '') for zip in zips]
def extract_text(doc, data):
doc = lxml.html.fromstring(data)
return doc.xpath('//html')[0].text_content()<|fim▁end|> | |
<|file_name|>0004_auto__add_item__add_time.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Item'
db.create_table('books_item', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=50)),
('cost', self.gf('django.db.models.fields.DecimalField')(max_digits=8, decimal_places=2)),
('quantity', self.gf('django.db.models.fields.PositiveIntegerField')(blank=True)),
))
db.send_create_signal('books', ['Item'])
# Adding model 'Time'
db.create_table('books_time', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('task', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['books.Task'], null=True, blank=True)),
('notes', self.gf('django.db.models.fields.CharField')(max_length=1000)),
('rate_per_hour', self.gf('django.db.models.fields.PositiveIntegerField')(blank=True)),
('time', self.gf('django.db.models.fields.PositiveIntegerField')(blank=True)),
))
db.send_create_signal('books', ['Time'])
def backwards(self, orm):
# Deleting model 'Item'
db.delete_table('books_item')
# Deleting model 'Time'
db.delete_table('books_time')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'books.client': {
'Meta': {'object_name': 'Client'},
'city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'country': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '100'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'organization_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'phone': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'postal_code': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'state': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'street_adress': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'})
},
'books.expense': {
'Meta': {'object_name': 'Expense'},
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'books.invoice': {
'Meta': {'object_name': 'Invoice'},
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'client': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['books.Client']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_of_issue': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'invoice_number': ('django.db.models.fields.PositiveIntegerField', [], {'blank': 'True'}),
'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'notes': ('django.db.models.fields.CharField', [], {'max_length': '1000'}),
'terms': ('django.db.models.fields.CharField', [], {'max_length': '1000'})
},
'books.item': {
'Meta': {'object_name': 'Item'},
'cost': ('django.db.models.fields.DecimalField', [], {'max_digits': '8', 'decimal_places': '2'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'quantity': ('django.db.models.fields.PositiveIntegerField', [], {'blank': 'True'})
},
'books.project': {
'Meta': {'object_name': 'Project'},
'client': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['books.Client']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'rate_per_hour': ('django.db.models.fields.PositiveIntegerField', [], {'blank': 'True'})
},
'books.task': {
'Meta': {'object_name': 'Task'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['books.Project']"}),
'rate_per_hour': ('django.db.models.fields.PositiveIntegerField', [], {'blank': 'True'})
},
'books.tax': {
'Meta': {'object_name': 'Tax'},
'compound_tax': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'number': ('django.db.models.fields.PositiveIntegerField', [], {'blank': 'True'}),
'rate': ('django.db.models.fields.PositiveIntegerField', [], {})
},
'books.time': {
'Meta': {'object_name': 'Time'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'notes': ('django.db.models.fields.CharField', [], {'max_length': '1000'}),
'rate_per_hour': ('django.db.models.fields.PositiveIntegerField', [], {'blank': 'True'}),
'task': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['books.Task']", 'null': 'True', 'blank': 'True'}),<|fim▁hole|> 'time': ('django.db.models.fields.PositiveIntegerField', [], {'blank': 'True'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['books']<|fim▁end|> | |
<|file_name|>field_mixins.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.forms import fields
from django.forms import widgets
from djng.forms import field_mixins
from . import widgets as bs3widgets
class BooleanFieldMixin(field_mixins.BooleanFieldMixin):
def get_converted_widget(self):
assert(isinstance(self, fields.BooleanField))
if isinstance(self.widget, widgets.CheckboxInput):
self.widget_css_classes = None
if not isinstance(self.widget, bs3widgets.CheckboxInput):
new_widget = bs3widgets.CheckboxInput(self.label)
new_widget.__dict__, new_widget.choice_label = self.widget.__dict__, new_widget.choice_label
self.label = '' # label is rendered by the widget and not by BoundField.label_tag()
return new_widget
class ChoiceFieldMixin(field_mixins.ChoiceFieldMixin):
def get_converted_widget(self):
assert(isinstance(self, fields.ChoiceField))<|fim▁hole|> new_widget = bs3widgets.RadioSelect()
new_widget.__dict__ = self.widget.__dict__
return new_widget
class MultipleChoiceFieldMixin(field_mixins.MultipleChoiceFieldMixin):
def get_converted_widget(self):
assert(isinstance(self, fields.MultipleChoiceField))
if isinstance(self.widget, widgets.CheckboxSelectMultiple):
self.widget_css_classes = None
if not isinstance(self.widget, bs3widgets.CheckboxSelectMultiple):
new_widget = bs3widgets.CheckboxSelectMultiple()
new_widget.__dict__ = self.widget.__dict__
return new_widget<|fim▁end|> | if isinstance(self.widget, widgets.RadioSelect):
self.widget_css_classes = None
if not isinstance(self.widget, bs3widgets.RadioSelect): |
<|file_name|>test_qipackage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" Test QiPackage """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import os
import pytest
import qitoolchain.qipackage
import qisys.archive
from qisys.test.conftest import skip_on_win
def test_equality():
""" Test Equality """
foo1 = qitoolchain.qipackage.QiPackage("foo", "1.2")
foo2 = qitoolchain.qipackage.QiPackage("foo", "1.2")
foo3 = qitoolchain.qipackage.QiPackage("foo", "1.3")
bar1 = qitoolchain.qipackage.QiPackage("bar", "1.2")
assert foo1 == foo2
assert foo2 < foo3
assert foo1 != bar1
def test_from_archive(tmpdir):
""" Test From Archive """
foo1 = tmpdir.mkdir("foo")
foo_xml = foo1.join("package.xml")
foo_xml.write("""<package name="foo" version="0.1"/>""")
archive = qisys.archive.compress(foo1.strpath, flat=True)
package = qitoolchain.qipackage.from_archive(archive)
assert package.name == "foo"
assert package.version == "0.1"
def test_skip_package_xml(tmpdir):
""" Test Skip Package Xml """
foo1 = tmpdir.mkdir("foo")
foo_xml = foo1.join("package.xml")
foo_xml.write("""<package name="foo" version="0.1"/>""")
foo1.ensure("include", "foo.h", file=True)
foo1.ensure("lib", "libfoo.so", file=True)
package = qitoolchain.qipackage.QiPackage("foo", path=foo1.strpath)<|fim▁hole|> package.install(dest.strpath)
assert dest.join("include", "foo.h").check(file=True)
assert dest.join("lib", "libfoo.so").check(file=True)
assert not dest.join("package.xml").check(file=True)
def test_reads_runtime_manifest(tmpdir):
""" Test Read Runtime Manifest """""
boost_path = tmpdir.mkdir("boost")
boost_path.ensure("include", "boost.h", file=True)
boost_path.ensure("lib", "libboost.so", file=True)
runtime_manifest = boost_path.ensure("install_manifest_runtime.txt", file=True)
runtime_manifest.write(b"""lib/libboost.so\n""")
package = qitoolchain.qipackage.QiPackage("boost", path=boost_path.strpath)
dest = tmpdir.join("dest")
installed = package.install(dest.strpath, components=["runtime"])
assert not dest.join("include", "boost.h").check(file=True)
libbost_so = dest.join("lib", "libboost.so")
assert libbost_so.check(file=True)
assert installed == ["lib/libboost.so"]
def test_backward_compat_runtime_install(tmpdir):
""" Test Backward Compat Runtime """
boost_path = tmpdir.mkdir("boost")
boost_path.ensure("include", "boost.h", file=True)
boost_path.ensure("lib", "libboost.so", file=True)
boost_path.ensure("package.xml", file=True)
package = qitoolchain.qipackage.QiPackage("boost", path=boost_path.strpath)
dest = tmpdir.join("dest")
installed = package.install(dest.strpath, components=["runtime"])
assert not dest.join("include", "boost.h").check(file=True)
libbost_so = dest.join("lib", "libboost.so")
assert libbost_so.check(file=True)
assert installed == ["lib/libboost.so"]
def test_reads_release_mask(tmpdir):
""" Test Reads Release Mask """
qt_path = tmpdir.mkdir("qt")
qt_path.ensure("include", "qt.h", file=True)
qt_path.ensure("lib", "QtCore4.lib", file=True)
qt_path.ensure("lib", "QtCored4.lib", file=True)
qt_path.ensure("bin", "QtCore4.dll", file=True)
qt_path.ensure("bin", "QtCored4.dll", file=True)
runtime_mask = qt_path.ensure("runtime.mask", file=True)
runtime_mask.write(b"""\n# headers\nexclude include/.*\n\n# .lib\nexclude lib/.*\\.lib\n""")
release_mask = qt_path.ensure("release.mask", file=True)
release_mask.write(b"""\nexclude bin/QtCored4.dll\n""")
package = qitoolchain.qipackage.QiPackage("qt", path=qt_path.strpath)
dest = tmpdir.join("dest")
package.install(dest.strpath, release=True, components=["runtime"])
assert dest.join("bin", "QtCore4.dll").check(file=True)
assert not dest.join("lib", "QtCored4.lib").check(file=True)
def test_include_in_mask(tmpdir):
""" Test Include in Mask """
qt_path = tmpdir.mkdir("qt")
qt_path.ensure("bin", "assitant.exe")
qt_path.ensure("bin", "moc.exe")
qt_path.ensure("bin", "lrelease.exe")
qt_path.ensure("bin", "lupdate.exe")
runtime_mask = qt_path.ensure("runtime.mask", file=True)
runtime_mask.write(b"""\nexclude bin/.*\\.exe\ninclude bin/lrelease.exe\ninclude bin/lupdate.exe\n""")
dest = tmpdir.join("dest")
package = qitoolchain.qipackage.QiPackage("qt", path=qt_path.strpath)
package.install(dest.strpath, release=True, components=["runtime"])
assert dest.join("bin", "lrelease.exe").check(file=True)
assert not dest.join("bin", "moc.exe").check(file=True)
def test_load_deps(tmpdir):
""" Test Load Dependencies """
libqi_path = tmpdir.mkdir("libqi")
libqi_path.ensure("package.xml").write(b"""
<package name="libqi">
<depends testtime="true" names="gtest" />
<depends runtime="true" names="boost python" />
</package>
""")
package = qitoolchain.qipackage.QiPackage("libqi", path=libqi_path.strpath)
package.load_deps()
assert package.build_depends == set()
assert package.run_depends == set(["boost", "python"])
assert package.test_depends == set(["gtest"])
def test_extract_legacy_bad_top_dir(tmpdir):
""" Test Extract Legacy Bad Top Dir """
src = tmpdir.mkdir("src")
boost = src.mkdir("boost")
boost.ensure("lib", "libboost.so", file=True)
res = qisys.archive.compress(boost.strpath)
dest = tmpdir.mkdir("dest").join("boost-1.55")
qitoolchain.qipackage.extract(res, dest.strpath)
assert dest.join("lib", "libboost.so").check(file=True)
def test_extract_legacy_ok_top_dir(tmpdir):
""" Test Extract Legacy Ok Top Dir """
src = tmpdir.mkdir("src")
boost = src.mkdir("boost-1.55")
boost.ensure("lib", "libboost.so", file=True)
res = qisys.archive.compress(boost.strpath)
dest = tmpdir.mkdir("dest").join("boost-1.55")
qitoolchain.qipackage.extract(res, dest.strpath)
assert dest.join("lib", "libboost.so").check(file=True)
def test_extract_modern(tmpdir):
""" Test Extract Modern """
src = tmpdir.mkdir("src")
src.ensure("package.xml", file=True)
src.ensure("lib", "libboost.so", file=True)
output = tmpdir.join("boost.zip")
res = qisys.archive.compress(src.strpath, output=output.strpath, flat=True)
dest = tmpdir.mkdir("dest").join("boost-1.55")
qitoolchain.qipackage.extract(res, dest.strpath)
assert dest.join("lib", "libboost.so").check(file=True)
def test_installing_test_component(tmpdir):
""" Test Installing Test Component """
boost_path = tmpdir.mkdir("boost")
boost_path.ensure("include", "boost.h", file=True)
boost_path.ensure("lib", "libboost.so", file=True)
boost_path.ensure("package.xml", file=True)
package = qitoolchain.qipackage.QiPackage("boost", path=boost_path.strpath)
dest = tmpdir.join("dest")
_installed = package.install(dest.strpath, components=["test", "runtime"])
assert not dest.join("include", "boost.h").check(file=True)
def test_get_set_license(tmpdir):
""" Test Get Set Licence """
boost_path = tmpdir.mkdir("boost")
boost_path.join("package.xml").write("""\n<package name="boost" version="1.58" />\n""")
package = qitoolchain.qipackage.QiPackage("boost", path=boost_path.strpath)
assert package.license is None
package.license = "BSD"
package2 = qitoolchain.qipackage.QiPackage("boost", path=boost_path.strpath)
assert package2.license == "BSD"
def test_post_add_noop(tmpdir):
""" Test Post Add Noop """
boost_path = tmpdir.mkdir("boost")
boost_path.join("package.xml").write("""\n<package name="boost" version="1.58" />\n""")
package = qitoolchain.qipackage.QiPackage("boost", path=boost_path.strpath)
package.post_add() # no-op
def test_post_add_does_not_exist(tmpdir):
""" Test Post Add Does Not Exist """
boost_path = tmpdir.mkdir("boost")
boost_path.join("package.xml").write(
b"""\n<package name="boost" version="1.58" post-add="asdf" />\n"""
)
package = qitoolchain.qipackage.QiPackage("boost", path=boost_path.strpath)
package.load_package_xml()
with pytest.raises(qisys.command.NotInPath):
package.post_add()
def test_version_str_to_int(tmpdir):
""" Test version converter """
assert qitoolchain.qipackage.version_str_to_int("1") == 1
assert qitoolchain.qipackage.version_str_to_int("1.0") == 10
assert qitoolchain.qipackage.version_str_to_int("1.0.2") == 102
assert qitoolchain.qipackage.version_str_to_int("1.5.4") == 154
assert qitoolchain.qipackage.version_str_to_int("1.5.0-r152") == 150
@skip_on_win
def test_post_add(tmpdir):
""" Test Post Add """
boost_path = tmpdir.mkdir("boost")
boost_path.join("package.xml").write(
b"""\n<package name="boost" version="1.58" post-add="post-add.sh hello world" />\n"""
)
script = boost_path.join("post-add.sh")
script.write(
'#!/bin/sh\n'
'echo $@ > foobar\n'
)
os.chmod(script.strpath, 0o755)
package = qitoolchain.qipackage.QiPackage("boost", path=boost_path.strpath)
package.load_package_xml()
package.post_add()
with open(os.path.join(boost_path.strpath, 'foobar')) as f:
txt = f.read()
assert "hello world" in txt<|fim▁end|> | dest = tmpdir.join("dest") |
<|file_name|>0008_auto_20151224_1528.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-24 15:28
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('emailer', '0007_auto_20150509_1922'),
]
<|fim▁hole|> model_name='email',
name='recipient',
field=models.EmailField(db_index=True, max_length=254),
),
]<|fim▁end|> | operations = [
migrations.AlterField( |
<|file_name|>icon.js<|end_file_name|><|fim▁begin|>import { Class } from '../mixin/index';
export default function (UIkit) {
UIkit.component('icon', UIkit.components.svg.extend({
mixins: [Class],
name: 'icon',
args: 'icon',
<|fim▁hole|> defaults: {exclude: ['id', 'style', 'class', 'src']},
init() {
this.$el.addClass('uk-icon');
}
}));
[
'close',
'navbar-toggle-icon',
'overlay-icon',
'pagination-previous',
'pagination-next',
'slidenav',
'search-icon',
'totop'
].forEach(name => UIkit.component(name, UIkit.components.icon.extend({name})));
}<|fim▁end|> |
props: ['icon'],
|
<|file_name|>auth.ts<|end_file_name|><|fim▁begin|>import fetch from './util/fetch-wrapper';
import config, {
baseUrl, clientAuthorization, isTokenExpired, token,
} from './util/config';
import qsEncode from './util/qs-encode';
export interface IAOuthToken {
access_token: string;
refresh_token: string;
expires_in: number;
}
export interface IConfigUser {
access_token?: string;
refresh_token?: string;
expires_at?: number;
}
function oauthToken(body: { [key: string]: string }) {
return fetch<IAOuthToken>(`${baseUrl()}/oauth/token`, {
method: 'POST',
body: qsEncode({
client_id: config.get('registry.oauth.client_id'),
client_secret: config.get('registry.oauth.client_secret'),
...body,
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Authorization': `Basic ${clientAuthorization()}`,
},
}).then((data: IAOuthToken) => {
let user: IConfigUser = config.get('user');
if (!user) {
user = {};
config.set('user', user);
}
const expiredAt = new Date();
expiredAt.setSeconds(expiredAt.getSeconds() + data.expires_in);
user.access_token = data.access_token;
user.refresh_token = data.refresh_token;
user.expires_at = expiredAt.getTime();
// update config file if any
return config.save('user');
});
}
export default {
login(username: string, password: string) {
return oauthToken({ username, password, grant_type: 'password', scope: 'read%20write' });
},
logout() {
config.set('user.access_token', null);
config.set('user.expires_at', 0);
return Promise.resolve();
},
refresh() {
const refreshToken = config.get('user.refresh_token');
if (refreshToken) {
return oauthToken({
grant_type: 'refresh_token',
refresh_token: refreshToken,
scope: 'read%20write',
});
} else {
return Promise.reject(new Error(`Invalid refresh_token: ${refreshToken}`));
}
},
ensureLogin() {
const accessToken = this.getToken();
if (accessToken) {
if (this.isTokenExpired()) {
return this.refresh();
} else {
return Promise.resolve();
}
} else {
return Promise.reject(new Error('Unable to find valid token'));
}
},
getToken() {
return token();
},<|fim▁hole|>};<|fim▁end|> | isTokenExpired() {
return isTokenExpired();
}, |
<|file_name|>log.cpp<|end_file_name|><|fim▁begin|>#include "log.h"
#include <iostream>
using WhatsAcppi::Util::Log;
using std::cout;
using std::endl;<|fim▁hole|>}
Log::~Log(){
cout << this->ss.str() << endl;
}
void Log::setLogLevel(Log::LogMsgType level){
Log::logLevel = level;
}<|fim▁end|> |
Log::LogMsgType Log::logLevel = CriticalMsg;
Log::Log(Log::LogMsgType type) : level(type) { |
<|file_name|>base.py<|end_file_name|><|fim▁begin|>import pytest
from pontoon.test import factories
@pytest.fixture
def admin():
"""Admin - a superuser"""
return factories.UserFactory.create(username="admin", is_superuser=True,)
@pytest.fixture
def client_superuser(client, admin):
"""Provides a client with a logged in superuser. """
client.force_login(admin)
return client
@pytest.fixture
def user_a():
return factories.UserFactory(username="user_a")
@pytest.fixture
def user_b():
return factories.UserFactory(username="user_b")
@pytest.fixture
def user_c():
return factories.UserFactory(username="user_c")
@pytest.fixture
def member(client, user_a):
"""Provides a `LoggedInMember` with the attributes `user` and `client`
the `client` is authenticated
"""
class LoggedInMember(object):
def __init__(self, user, client):
client.force_login(user)
self.client = client
self.user = user
return LoggedInMember(user_a, client)
@pytest.fixture
def locale_a():
return factories.LocaleFactory(code="kg", name="Klingon",)
@pytest.fixture
def google_translate_locale(locale_a):
"""Set the Google Cloud Translation API locale code for locale_a"""
locale_a.google_translate_code = "bg"
locale_a.save()
return locale_a
@pytest.fixture
def ms_locale(locale_a):
"""Set the Microsoft API locale code for locale_a"""
locale_a.ms_translator_code = "gb"
locale_a.save()
return locale_a
@pytest.fixture
def locale_b():
return factories.LocaleFactory(code="gs", name="Geonosian",)
@pytest.fixture
def project_a():
return factories.ProjectFactory(
slug="project_a", name="Project A", repositories=[],
)
@pytest.fixture
def project_b():
return factories.ProjectFactory(slug="project_b", name="Project B")
@pytest.fixture
def system_project_a():
return factories.ProjectFactory(
slug="system_project_a",
name="System Project A",
repositories=[],
system_project=True,
)
@pytest.fixture
def resource_a(project_a):
return factories.ResourceFactory(
project=project_a, path="resource_a.po", format="po"
)
@pytest.fixture<|fim▁hole|> project=project_b, path="resource_b.po", format="po"
)
@pytest.fixture
def entity_a(resource_a):
return factories.EntityFactory(resource=resource_a, string="entity a")
@pytest.fixture
def entity_b(resource_b):
return factories.EntityFactory(resource=resource_b, string="entity b")
@pytest.fixture
def project_locale_a(project_a, locale_a):
return factories.ProjectLocaleFactory(project=project_a, locale=locale_a,)
@pytest.fixture
def translation_a(locale_a, project_locale_a, entity_a, user_a):
"""Return a translation.
Note that we require the `project_locale_a` fixture because a
valid ProjectLocale is needed in order to query Translations.
"""
translation_a = factories.TranslationFactory(
entity=entity_a,
locale=locale_a,
user=user_a,
string="Translation for entity_a",
)
translation_a.locale.refresh_from_db()
translation_a.entity.resource.project.refresh_from_db()
return translation_a
@pytest.fixture
def tag_a(resource_a, project_a, locale_a):
# Tags require a TranslatedResource to work.
factories.TranslatedResourceFactory.create(resource=resource_a, locale=locale_a)
tag = factories.TagFactory.create(slug="tag", name="Tag", project=project_a,)
tag.resources.add(resource_a)
return tag<|fim▁end|> | def resource_b(project_b):
return factories.ResourceFactory( |
<|file_name|>string-lit.rs<|end_file_name|><|fim▁begin|>// rustfmt-force_format_strings: true
// rustfmt-error_on_line_overflow: false
// Long string literals
fn main() -> &'static str {
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAaAA \
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAa";
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAa";
let str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
let too_many_lines = "Hello";
// Make sure we don't break after an escape character.
let odd_length_name =
"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
let even_length_name =
"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
let really_long_variable_name = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
let raw_string = r#"Do
not
remove
formatting"#;
filename.replace(" ", "\\");
let xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx =
funktion("yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy");
let unicode = "a̐éö̲\r\n";
let unicode2 = "Löwe 老虎 Léopard";
let unicode3 = "中华Việt Nam";
let unicode4 = "☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃☃";
"stuffin'"
}
fn issue682() {
let a = "hello \\ o/";
let b = a.replace("\\ ", "\\");
}
fn issue716() {
println!(
"forall x. mult(e(), x) = x /\\
forall x. mult(x, x) = e()"
);
}
fn issue_1282() {
{
match foo {
Permission::AndroidPermissionAccessLocationExtraCommands => {
"android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"
}
}<|fim▁hole|>
// #1987
#[link_args = "-s NO_FILESYSTEM=1 -s NO_EXIT_RUNTIME=1 -s EXPORTED_RUNTIME_METHODS=[\"_malloc\"] \
-s NO_DYNAMIC_EXECUTION=1 -s ELIMINATE_DUPLICATE_FUNCTIONS=1 -s EVAL_CTORS=1"]
extern "C" {}<|fim▁end|> | }
} |
<|file_name|>api_mock.py<|end_file_name|><|fim▁begin|>import datetime
class FakeHeatTemplateManager(object):
def __init__(self):
self.templates = {
1: 'Dummy description #1.',
3: 'Dummy description #3.',
4: 'Dummy description #4.',
6: 'Dummy description #6.'}
def get_description(self, template_id):
return self.templates[template_id]
def list_templates(self):
return self.templates.keys()
class FakeNovaAPI(object):
def __init__(self):
self.flavors = {
1: {
'name': 'flavor1', },
2: {
'name': 'flavor2', }}
def get_flavor(self, flavor_id):
return self.flavors[flavor_id]
def list_flavors(self):
return self.flavors.keys()
class FakeHeatAPI(object):
def __init__(self):
self.stacks = {
'stack1': {
'email': 'dummy1@localhost', },
'stack2': {
'email': 'dummy2@localhost', }}
self.expired_stacks = {
'stack3': {
'email': 'dummy3@localhost', }}
def create_stack(self, name, template_id, **params):
# TODO(sheeprine): Implement checks
if name in self.stacks or name in self.expired_stacks:
return False
self.stacks[name] = params
return True
def delete_stack(self, name):
if name is self.stacks:
self.stacks.pop(name)
return True
else:
return False
def expired_stacks(self):
return ['stack1', 'stack2']
def disable_expired_stacks(self):
return len(self.expired_stacks)
def purge_expired_stacks(self):
purged = len(self.expired_stacks)<|fim▁hole|> if name in self.expired_stacks:
return datetime.datetime.utcnow()
def list_new_stacks(self):
return ['stack4']
def get_stack_details(self, name):
return self.stacks[name]<|fim▁end|> | self.expired_stacks = {}
return purged
def extend_stack_validity(self, name, days): |
<|file_name|>ScoreBox.tsx<|end_file_name|><|fim▁begin|>import * as React from 'react'
import { onlyInParentGroup, ScoreHistory, ScoreHistoryEntry } from '../../../../definitions/ScoreSystem'
import { text } from '../../../utils/text'
import { BatchScores, ScoreDetails } from '../../../../calculators/calcScore'
import { MultiLangStringSet } from '../../../../definitions/auxiliary/MultiLang'
interface PropTypes {
scoreDetails: ScoreDetails
history: ScoreHistory
name: string
}
const scoreStyle = {
fontWeight: 'bolder',
} as React.CSSProperties
const LabelTexts: {[key: string]: MultiLangStringSet} = {
education: {
en: 'Level of education',
zh_hans: '学历',
},
language: {
en: 'Official languages proficiency',
zh_hans: '官方语言能力',
},
age: {
en: 'Age',
zh_hans: '年龄',
},
canadaWork: {
en: 'Canada work experience',
zh_hans: '加拿大工作经验',
},
transferable: {
en: 'Skill Transferability factors'
},
additions: {
en: 'Additional',
zh_hans: '额外加分',
},
'language-primary:listening': {
en: 'Primary language: Listening',
zh_hans: '第一语言:听力',
},
'language-primary:writing': {
en: 'Primary language: Writing',
zh_hans: '第一语言:写作',
},
'language-primary:speaking': {
en: 'Primary language: Speaking',
zh_hans: '第一语言:口语',
},
'language-primary:reading': {
en: 'Primary language: Reading',
zh_hans: '第一语言:阅读',
},
'language-secondary:listening': {
en: 'Secondary language: Listening',
zh_hans: '第二语言:听力',
},
'language-secondary:writing': {
en: 'Secondary language: Writing',
zh_hans: '第二语言:写作',
},
'language-secondary:speaking': {
en: 'Secondary language: Speaking',
zh_hans: '第二语言:口语',
},
'language-secondary:reading': {
en: 'Secondary language: Reading',
zh_hans: '第二语言:阅读',
},
union: {
en: 'Union status',
zh_hans: '婚姻状况',
},
'spouse-bonus': {
en: 'Spouse bonus',
zh_hans: '配偶加分',
},
'transferability:language+education': {
en: 'Language + Education',
},
'transferability:canada_work+education': {
en: 'Canada work experience + Education'
},
'transferability:work+education': {
en: 'Work experience + Education'
},
'transferability:foreign_work+canada_work': {
en: 'Foreign work experience + Canada work experience'
},
'transferability:language+certification': {
en: 'Language + Trade certification'
},
'additional:sibling': {
en: 'Sibling'
},
'additional:french': {
en: 'French'
},
'additional:canada-education': {
en: 'Canadian education'
},
'additional:job-offer': {
en: 'Job offer'
},
'additional:provincial-nomination': {
en: 'Provincial or territorial nomination'
}
}
const Row = (props: { text: string, score: number, level: number }) => (
<tr>
<td style={{
paddingLeft: `${props.level * 1}em`,
fontWeight: props.level === 0 ? 'bold' : 'normal',
}}>
{props.text}
</td>
<td style={{
textAlign: 'right',
}}>
{props.score}
</td>
</tr>
)
<|fim▁hole|> <div>
<span style={scoreStyle}>
{props.entry.lowestScore}
</span>
{'@'}
{[
props.entry.date.year,
props.entry.date.month,
props.entry.date.day,
].join('-')}
</div>
)
class ScoreBox extends React.PureComponent<PropTypes, {}> {
render() {
const scoreDetails = this.props.scoreDetails
return (
<div>
<div style={{fontSize: '1.2em'}}>
{this.props.name}
</div>
<table>
<thead>
<tr>
<th>
{
text({
en: 'Your score',
zh_hans: '分数',
})
}
</th>
<th style={scoreStyle}>
{scoreDetails.score}
</th>
</tr>
</thead>
<tbody>
{
Object.keys(scoreDetails.groups).map(group => {
const conditionGroup = scoreDetails.groups[group]
let batchesForDisplay: BatchScores
if (Object.keys(conditionGroup.batches).length === 1
&& Object.keys(conditionGroup.batches)[0] === onlyInParentGroup
) {
batchesForDisplay = {}
}
else {
batchesForDisplay = conditionGroup.batches
}
return [
<Row
key={group}
text={text(LabelTexts[group])}
score={conditionGroup.score}
level={0}
/>,
Object.keys(batchesForDisplay).sort().map(batch =>
<Row
key={batch}
text={text(LabelTexts[batch])}
score={conditionGroup.batches[batch]}
level={1}
/>
)
]
}
)
}
</tbody>
</table>
<div>
{
text({
en: 'Previous lowest scores for entry: ',
zh_hans: '过往分数线: ',
})
}
{
this.props.history.map(entry =>
<HistoryEntry
key={[entry.date.year, entry.date.month, entry.date.day].join('-')}
entry={entry}
/>
)
}
</div>
</div>
)
}
}
export default ScoreBox<|fim▁end|> | const HistoryEntry = (props: { entry: ScoreHistoryEntry }) => ( |
<|file_name|>say.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, Michael DeHaan <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: say
version_added: "1.2"
short_description: Makes a computer to speak.
description:
- makes a computer speak! Amuse your friends, annoy your coworkers!
notes:
- In 2.5, this module has been renamed from C(osx_say) to M(say).
- If you like this module, you may also be interested in the osx_say callback plugin.
options:
msg:
description:
What to say
required: true
voice:
description:
What voice to use
required: false
requirements: [ say or espeak or espeak-ng ]
author:
- "Ansible Core Team"
- "Michael DeHaan (@mpdehaan)"
'''
EXAMPLES = '''
- say:
msg: '{{ inventory_hostname }} is all done'
voice: Zarvox
delegate_to: localhost
'''
import os
from ansible.module_utils.basic import AnsibleModule, get_platform<|fim▁hole|>
def say(module, executable, msg, voice):
cmd = [executable, msg]
if voice:
cmd.extend(('-v', voice))
module.run_command(cmd, check_rc=True)
def main():
module = AnsibleModule(
argument_spec=dict(
msg=dict(required=True),
voice=dict(required=False),
),
supports_check_mode=True
)
msg = module.params['msg']
voice = module.params['voice']
possibles = ('say', 'espeak', 'espeak-ng')
if get_platform() != 'Darwin':
# 'say' binary available, it might be GNUstep tool which doesn't support 'voice' parameter
voice = None
for possible in possibles:
executable = module.get_bin_path(possible)
if executable:
break
else:
module.fail_json(msg='Unable to find either %s' % ', '.join(possibles))
if module.check_mode:
module.exit_json(msg=msg, changed=False)
say(module, executable, msg, voice)
module.exit_json(msg=msg, changed=True)
if __name__ == '__main__':
main()<|fim▁end|> | |
<|file_name|>xhrio.js<|end_file_name|><|fim▁begin|>// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Wrapper class for handling XmlHttpRequests.
*
* One off requests can be sent through goog.net.XhrIo.send() or an
* instance can be created to send multiple requests. Each request uses its
* own XmlHttpRequest object and handles clearing of the event callback to
* ensure no leaks.
*
* XhrIo is event based, it dispatches events on success, failure, finishing,
* ready-state change, or progress (download and upload).
*
* The ready-state or timeout event fires first, followed by
* a generic completed event. Then the abort, error, or success event
* is fired as appropriate. Progress events are fired as they are
* received. Lastly, the ready event will fire to indicate that the
* object may be used to make another request.
*
* The error event may also be called before completed and
* ready-state-change if the XmlHttpRequest.open() or .send() methods throw.
*
* This class does not support multiple requests, queuing, or prioritization.
*
* When progress events are supported by the browser, and progress is
* enabled via .setProgressEventsEnabled(true), the
* goog.net.EventType.PROGRESS event will be the re-dispatched browser
* progress event. Additionally, a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event
* will be fired for download and upload progress respectively.
*/
goog.provide('goog.net.XhrIo');
goog.provide('goog.net.XhrIo.ResponseType');
goog.forwardDeclare('goog.Uri');
goog.require('goog.Timer');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.debug.entryPointRegistry');
goog.require('goog.events.EventTarget');
goog.require('goog.json.hybrid');
goog.require('goog.log');
goog.require('goog.net.ErrorCode');
goog.require('goog.net.EventType');
goog.require('goog.net.HttpStatus');
goog.require('goog.net.XmlHttp');
goog.require('goog.object');
goog.require('goog.string');
goog.require('goog.structs');
goog.require('goog.structs.Map');
goog.require('goog.uri.utils');
goog.require('goog.userAgent');
goog.scope(function() {
/**
* Basic class for handling XMLHttpRequests.
* @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when
* creating XMLHttpRequest objects.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.net.XhrIo = function(opt_xmlHttpFactory) {
XhrIo.base(this, 'constructor');
/**
* Map of default headers to add to every request, use:
* XhrIo.headers.set(name, value)
* @type {!goog.structs.Map}
*/
this.headers = new goog.structs.Map();
/**
* Optional XmlHttpFactory
* @private {goog.net.XmlHttpFactory}
*/
this.xmlHttpFactory_ = opt_xmlHttpFactory || null;
/**
* Whether XMLHttpRequest is active. A request is active from the time send()
* is called until onReadyStateChange() is complete, or error() or abort()
* is called.
* @private {boolean}
*/
this.active_ = false;
/**
* The XMLHttpRequest object that is being used for the transfer.
* @private {?goog.net.XhrLike.OrNative}
*/
this.xhr_ = null;
/**
* The options to use with the current XMLHttpRequest object.
* @private {?Object}
*/
this.xhrOptions_ = null;
/**
* Last URL that was requested.
* @private {string|goog.Uri}
*/
this.lastUri_ = '';
/**
* Method for the last request.
* @private {string}
*/
this.lastMethod_ = '';
/**
* Last error code.
* @private {!goog.net.ErrorCode}
*/
this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;
/**
* Last error message.
* @private {Error|string}
*/
this.lastError_ = '';
/**
* Used to ensure that we don't dispatch an multiple ERROR events. This can
* happen in IE when it does a synchronous load and one error is handled in
* the ready statte change and one is handled due to send() throwing an
* exception.
* @private {boolean}
*/
this.errorDispatched_ = false;
/**
* Used to make sure we don't fire the complete event from inside a send call.
* @private {boolean}
*/
this.inSend_ = false;
/**
* Used in determining if a call to {@link #onReadyStateChange_} is from
* within a call to this.xhr_.open.
* @private {boolean}
*/
this.inOpen_ = false;
/**
* Used in determining if a call to {@link #onReadyStateChange_} is from
* within a call to this.xhr_.abort.
* @private {boolean}
*/
this.inAbort_ = false;
/**
* Number of milliseconds after which an incomplete request will be aborted
* and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout
* is set.
* @private {number}
*/
this.timeoutInterval_ = 0;
/**
* Timer to track request timeout.
* @private {?number}
*/
this.timeoutId_ = null;
/**
* The requested type for the response. The empty string means use the default
* XHR behavior.
* @private {goog.net.XhrIo.ResponseType}
*/
this.responseType_ = ResponseType.DEFAULT;
/**
* Whether a "credentialed" request is to be sent (one that is aware of
* cookies and authentication). This is applicable only for cross-domain
* requests and more recent browsers that support this part of the HTTP Access
* Control standard.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute
*
* @private {boolean}
*/
this.withCredentials_ = false;
/**
* Whether progress events are enabled for this request. This is
* disabled by default because setting a progress event handler
* causes pre-flight OPTIONS requests to be sent for CORS requests,
* even in cases where a pre-flight request would not otherwise be
* sent.
*
* @see http://xhr.spec.whatwg.org/#security-considerations
*
* Note that this can cause problems for Firefox 22 and below, as an
* older "LSProgressEvent" will be dispatched by the browser. That
* progress event is no longer supported, and can lead to failures,
* including throwing exceptions.
*
* @see http://bugzilla.mozilla.org/show_bug.cgi?id=845631
* @see b/23469793
*
* @private {boolean}
*/
this.progressEventsEnabled_ = false;
/**
* True if we can use XMLHttpRequest's timeout directly.
* @private {boolean}
*/
this.useXhr2Timeout_ = false;
};
goog.inherits(goog.net.XhrIo, goog.events.EventTarget);
var XhrIo = goog.net.XhrIo;
/**
* Response types that may be requested for XMLHttpRequests.
* @enum {string}
* @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute
*/
goog.net.XhrIo.ResponseType = {
DEFAULT: '',
TEXT: 'text',
DOCUMENT: 'document',
// Not supported as of Chrome 10.0.612.1 dev
BLOB: 'blob',
ARRAY_BUFFER: 'arraybuffer',
};
var ResponseType = goog.net.XhrIo.ResponseType;
/**
* A reference to the XhrIo logger
* @private {?goog.log.Logger}
* @const
*/
goog.net.XhrIo.prototype.logger_ = goog.log.getLogger('goog.net.XhrIo');
/**
* The Content-Type HTTP header name
* @type {string}
*/
goog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type';
/**
* The Content-Transfer-Encoding HTTP header name
* @type {string}
*/
goog.net.XhrIo.CONTENT_TRANSFER_ENCODING = 'Content-Transfer-Encoding';
/**
* The pattern matching the 'http' and 'https' URI schemes
* @type {!RegExp}
*/
goog.net.XhrIo.HTTP_SCHEME_PATTERN = /^https?$/i;
/**
* The methods that typically come along with form data. We set different
* headers depending on whether the HTTP action is one of these.
* @type {!Array<string>}
*/
goog.net.XhrIo.METHODS_WITH_FORM_DATA = ['POST', 'PUT'];
/**
* The Content-Type HTTP header value for a url-encoded form
* @type {string}
*/
goog.net.XhrIo.FORM_CONTENT_TYPE =
'application/x-www-form-urlencoded;charset=utf-8';
/**
* The XMLHttpRequest Level two timeout delay ms property name.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
*
* @private {string}
* @const
*/
goog.net.XhrIo.XHR2_TIMEOUT_ = 'timeout';
/**
* The XMLHttpRequest Level two ontimeout handler property name.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
*
* @private {string}
* @const
*/
goog.net.XhrIo.XHR2_ON_TIMEOUT_ = 'ontimeout';
/**
* All non-disposed instances of goog.net.XhrIo created
* by {@link goog.net.XhrIo.send} are in this Array.
* @see goog.net.XhrIo.cleanup
* @private {!Array<!goog.net.XhrIo>}
*/
goog.net.XhrIo.sendInstances_ = [];
/**
* Static send that creates a short lived instance of XhrIo to send the
* request.
* @see goog.net.XhrIo.cleanup
* @param {string|goog.Uri} url Uri to make request to.
* @param {?function(this:goog.net.XhrIo, ?)=} opt_callback Callback function
* for when request is complete.
* @param {string=} opt_method Send method, default: GET.
* @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}
* opt_content Body data.
* @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the
* request.
* @param {number=} opt_timeoutInterval Number of milliseconds after which an
* incomplete request will be aborted; 0 means no timeout is set.
* @param {boolean=} opt_withCredentials Whether to send credentials with the
* request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}.
* @return {!goog.net.XhrIo} The sent XhrIo.
*/
goog.net.XhrIo.send = function(
url, opt_callback, opt_method, opt_content, opt_headers,
opt_timeoutInterval, opt_withCredentials) {
var x = new goog.net.XhrIo();
goog.net.XhrIo.sendInstances_.push(x);
if (opt_callback) {
x.listen(goog.net.EventType.COMPLETE, opt_callback);
}
x.listenOnce(goog.net.EventType.READY, x.cleanupSend_);
if (opt_timeoutInterval) {
x.setTimeoutInterval(opt_timeoutInterval);
}
if (opt_withCredentials) {
x.setWithCredentials(opt_withCredentials);
}
x.send(url, opt_method, opt_content, opt_headers);
return x;
};
/**
* Disposes all non-disposed instances of goog.net.XhrIo created by
* {@link goog.net.XhrIo.send}.
* {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance
* it creates when the request completes or fails. However, if
* the request never completes, then the goog.net.XhrIo is not disposed.
* This can occur if the window is unloaded before the request completes.
* We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo
* it creates and make the client of {@link goog.net.XhrIo.send} be
* responsible for disposing it in this case. However, this makes things
* significantly more complicated for the client, and the whole point
* of {@link goog.net.XhrIo.send} is that it's simple and easy to use.
* Clients of {@link goog.net.XhrIo.send} should call
* {@link goog.net.XhrIo.cleanup} when doing final
* cleanup on window unload.
*/
goog.net.XhrIo.cleanup = function() {
var instances = goog.net.XhrIo.sendInstances_;
while (instances.length) {
instances.pop().dispose();
}
};
/**
* Installs exception protection for all entry point introduced by
* goog.net.XhrIo instances which are not protected by
* {@link goog.debug.ErrorHandler#protectWindowSetTimeout},
* {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or
* {@link goog.events.protectBrowserEventEntryPoint}.
*
* @param {goog.debug.ErrorHandler} errorHandler Error handler with which to
* protect the entry point(s).
*/
goog.net.XhrIo.protectEntryPoints = function(errorHandler) {
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =
errorHandler.protectEntryPoint(
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);
};
/**
* Disposes of the specified goog.net.XhrIo created by
* {@link goog.net.XhrIo.send} and removes it from
* {@link goog.net.XhrIo.pendingStaticSendInstances_}.
* @private
*/
goog.net.XhrIo.prototype.cleanupSend_ = function() {
this.dispose();
goog.array.remove(goog.net.XhrIo.sendInstances_, this);
};
/**
* Returns the number of milliseconds after which an incomplete request will be
* aborted, or 0 if no timeout is set.
* @return {number} Timeout interval in milliseconds.
*/
goog.net.XhrIo.prototype.getTimeoutInterval = function() {
return this.timeoutInterval_;
};
/**
* Sets the number of milliseconds after which an incomplete request will be
* aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no
* timeout is set.
* @param {number} ms Timeout interval in milliseconds; 0 means none.
*/
goog.net.XhrIo.prototype.setTimeoutInterval = function(ms) {
this.timeoutInterval_ = Math.max(0, ms);
};
/**
* Sets the desired type for the response. At time of writing, this is only
* supported in very recent versions of WebKit (10.0.612.1 dev and later).
*
* If this is used, the response may only be accessed via {@link #getResponse}.
*
* @param {goog.net.XhrIo.ResponseType} type The desired type for the response.
*/
goog.net.XhrIo.prototype.setResponseType = function(type) {
this.responseType_ = type;
};
/**
* Gets the desired type for the response.
* @return {goog.net.XhrIo.ResponseType} The desired type for the response.
*/
goog.net.XhrIo.prototype.getResponseType = function() {
return this.responseType_;
};
/**
* Sets whether a "credentialed" request that is aware of cookie and
* authentication information should be made. This option is only supported by
* browsers that support HTTP Access Control. As of this writing, this option
* is not supported in IE.
*
* @param {boolean} withCredentials Whether this should be a "credentialed"
* request.
*/
goog.net.XhrIo.prototype.setWithCredentials = function(withCredentials) {
this.withCredentials_ = withCredentials;
};
/**
* Gets whether a "credentialed" request is to be sent.
* @return {boolean} The desired type for the response.
*/
goog.net.XhrIo.prototype.getWithCredentials = function() {
return this.withCredentials_;
};
/**
* Sets whether progress events are enabled for this request. Note
* that progress events require pre-flight OPTIONS request handling
* for CORS requests, and may cause trouble with older browsers. See
* progressEventsEnabled_ for details.
* @param {boolean} enabled Whether progress events should be enabled.
*/
goog.net.XhrIo.prototype.setProgressEventsEnabled = function(enabled) {
this.progressEventsEnabled_ = enabled;
};
/**
* Gets whether progress events are enabled.
* @return {boolean} Whether progress events are enabled for this request.
*/
goog.net.XhrIo.prototype.getProgressEventsEnabled = function() {
return this.progressEventsEnabled_;
};
/**
* Instance send that actually uses XMLHttpRequest to make a server call.
* @param {string|goog.Uri} url Uri to make request to.
* @param {string=} opt_method Send method, default: GET.
* @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}
* opt_content Body data.
* @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the
* request.
* @suppress {deprecated} Use deprecated goog.structs.forEach to allow different
* types of parameters for opt_headers.
*/
goog.net.XhrIo.prototype.send = function(
url, opt_method, opt_content, opt_headers) {
if (this.xhr_) {
throw new Error(
'[goog.net.XhrIo] Object is active with another request=' +
this.lastUri_ + '; newUri=' + url);
}
var method = opt_method ? opt_method.toUpperCase() : 'GET';
this.lastUri_ = url;
this.lastError_ = '';
this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;
this.lastMethod_ = method;
this.errorDispatched_ = false;
this.active_ = true;
// Use the factory to create the XHR object and options
this.xhr_ = this.createXhr();
this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() :
goog.net.XmlHttp.getOptions();
// Set up the onreadystatechange callback
this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this);
// Set up upload/download progress events, if progress events are supported.
if (this.getProgressEventsEnabled() && 'onprogress' in this.xhr_) {
this.xhr_.onprogress =
goog.bind(function(e) { this.onProgressHandler_(e, true); }, this);
if (this.xhr_.upload) {
this.xhr_.upload.onprogress = goog.bind(this.onProgressHandler_, this);
}
}
/**
* Try to open the XMLHttpRequest (always async), if an error occurs here it
* is generally permission denied
*/
try {
goog.log.fine(this.logger_, this.formatMsg_('Opening Xhr'));
this.inOpen_ = true;
this.xhr_.open(method, String(url), true); // Always async!
this.inOpen_ = false;
} catch (err) {
goog.log.fine(
this.logger_, this.formatMsg_('Error opening Xhr: ' + err.message));
this.error_(goog.net.ErrorCode.EXCEPTION, err);
return;
}
// We can't use null since this won't allow requests with form data to have a
// content length specified which will cause some proxies to return a 411
// error.
var content = opt_content || '';
var headers = this.headers.clone();
// Add headers specific to this request
if (opt_headers) {
goog.structs.forEach(
opt_headers, function(value, key) { headers.set(key, value); });
}
// Find whether a content type header is set, ignoring case.
// HTTP header names are case-insensitive. See:
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
var contentTypeKey =
goog.array.find(headers.getKeys(), goog.net.XhrIo.isContentTypeHeader_);
var contentIsFormData =
(goog.global['FormData'] && (content instanceof goog.global['FormData']));
if (goog.array.contains(goog.net.XhrIo.METHODS_WITH_FORM_DATA, method) &&
!contentTypeKey && !contentIsFormData) {
// For requests typically with form data, default to the url-encoded form
// content type unless this is a FormData request. For FormData,
// the browser will automatically add a multipart/form-data content type
// with an appropriate multipart boundary.
headers.set(
goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE);
}
// Add the headers to the Xhr object
headers.forEach(function(value, key) {
this.xhr_.setRequestHeader(key, value);
}, this);
if (this.responseType_) {
this.xhr_.responseType = this.responseType_;
}
// Set xhr_.withCredentials only when the value is different, or else in
// synchronous XMLHtppRequest.open Firefox will throw an exception.
// https://bugzilla.mozilla.org/show_bug.cgi?id=736340
if ('withCredentials' in this.xhr_ &&
this.xhr_.withCredentials !== this.withCredentials_) {
this.xhr_.withCredentials = this.withCredentials_;
}
/**
* Try to send the request, or other wise report an error (404 not found).
*/
try {
this.cleanUpTimeoutTimer_(); // Paranoid, should never be running.
if (this.timeoutInterval_ > 0) {
this.useXhr2Timeout_ = goog.net.XhrIo.shouldUseXhr2Timeout_(this.xhr_);
goog.log.fine(
this.logger_, this.formatMsg_(
'Will abort after ' + this.timeoutInterval_ +
'ms if incomplete, xhr2 ' + this.useXhr2Timeout_));
if (this.useXhr2Timeout_) {
this.xhr_[goog.net.XhrIo.XHR2_TIMEOUT_] = this.timeoutInterval_;
this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] =
goog.bind(this.timeout_, this);
} else {
this.timeoutId_ =
goog.Timer.callOnce(this.timeout_, this.timeoutInterval_, this);
}
}
goog.log.fine(this.logger_, this.formatMsg_('Sending request'));
this.inSend_ = true;
this.xhr_.send(content);
this.inSend_ = false;
} catch (err) {
goog.log.fine(this.logger_, this.formatMsg_('Send error: ' + err.message));
this.error_(goog.net.ErrorCode.EXCEPTION, err);
}
};
/**
* Determines if the argument is an XMLHttpRequest that supports the level 2
* timeout value and event.
*
* Currently, FF 21.0 OS X has the fields but won't actually call the timeout
* handler. Perhaps the confusion in the bug referenced below hasn't
* entirely been resolved.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
* @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816
*
* @param {!goog.net.XhrLike.OrNative} xhr The request.
* @return {boolean} True if the request supports level 2 timeout.
* @private
*/
goog.net.XhrIo.shouldUseXhr2Timeout_ = function(xhr) {
return goog.userAgent.IE && goog.userAgent.isVersionOrHigher(9) &&
typeof xhr[goog.net.XhrIo.XHR2_TIMEOUT_] === 'number' &&
xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_] !== undefined;
};
/**
* @param {string} header An HTTP header key.
* @return {boolean} Whether the key is a content type header (ignoring
* case.
* @private
*/
goog.net.XhrIo.isContentTypeHeader_ = function(header) {
return goog.string.caseInsensitiveEquals(
goog.net.XhrIo.CONTENT_TYPE_HEADER, header);
};
/**
* Creates a new XHR object.
* @return {!goog.net.XhrLike.OrNative} The newly created XHR object.
* @protected
*/
goog.net.XhrIo.prototype.createXhr = function() {
return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() :
goog.net.XmlHttp();
};
/**
* The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_}
* milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts
* the request.
* @private
*/
goog.net.XhrIo.prototype.timeout_ = function() {
if (typeof goog == 'undefined') {
// If goog is undefined then the callback has occurred as the application
// is unloading and will error. Thus we let it silently fail.
} else if (this.xhr_) {
this.lastError_ =
'Timed out after ' + this.timeoutInterval_ + 'ms, aborting';
this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT;
goog.log.fine(this.logger_, this.formatMsg_(this.lastError_));
this.dispatchEvent(goog.net.EventType.TIMEOUT);
this.abort(goog.net.ErrorCode.TIMEOUT);
}
};
/**
* Something errorred, so inactivate, fire error callback and clean up
* @param {goog.net.ErrorCode} errorCode The error code.
* @param {Error} err The error object.
* @private
*/
goog.net.XhrIo.prototype.error_ = function(errorCode, err) {
this.active_ = false;
if (this.xhr_) {
this.inAbort_ = true;
this.xhr_.abort(); // Ensures XHR isn't hung (FF)
this.inAbort_ = false;
}
this.lastError_ = err;
this.lastErrorCode_ = errorCode;
this.dispatchErrors_();
this.cleanUpXhr_();
};
/**
* Dispatches COMPLETE and ERROR in case of an error. This ensures that we do
* not dispatch multiple error events.
* @private
*/
goog.net.XhrIo.prototype.dispatchErrors_ = function() {
if (!this.errorDispatched_) {
this.errorDispatched_ = true;
this.dispatchEvent(goog.net.EventType.COMPLETE);
this.dispatchEvent(goog.net.EventType.ERROR);
}
};
/**
* Abort the current XMLHttpRequest
* @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use -
* defaults to ABORT.
*/
goog.net.XhrIo.prototype.abort = function(opt_failureCode) {
if (this.xhr_ && this.active_) {
goog.log.fine(this.logger_, this.formatMsg_('Aborting'));
this.active_ = false;
this.inAbort_ = true;
this.xhr_.abort();
this.inAbort_ = false;
this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT;
this.dispatchEvent(goog.net.EventType.COMPLETE);
this.dispatchEvent(goog.net.EventType.ABORT);
this.cleanUpXhr_();
}
};
/**
* Nullifies all callbacks to reduce risks of leaks.
* @override
* @protected
*/
goog.net.XhrIo.prototype.disposeInternal = function() {
if (this.xhr_) {
// We explicitly do not call xhr_.abort() unless active_ is still true.
// This is to avoid unnecessarily aborting a successful request when
// dispose() is called in a callback triggered by a complete response, but
// in which browser cleanup has not yet finished.
// (See http://b/issue?id=1684217.)
if (this.active_) {
this.active_ = false;
this.inAbort_ = true;
this.xhr_.abort();
this.inAbort_ = false;
}
this.cleanUpXhr_(true);
}
XhrIo.base(this, 'disposeInternal');
};
/**
* Internal handler for the XHR object's readystatechange event. This method
* checks the status and the readystate and fires the correct callbacks.
* If the request has ended, the handlers are cleaned up and the XHR object is
* nullified.
* @private
*/
goog.net.XhrIo.prototype.onReadyStateChange_ = function() {
if (this.isDisposed()) {
// This method is the target of an untracked goog.Timer.callOnce().
return;
}
if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) {
// Were not being called from within a call to this.xhr_.send
// this.xhr_.abort, or this.xhr_.open, so this is an entry point
this.onReadyStateChangeEntryPoint_();
} else {
this.onReadyStateChangeHelper_();
}
};
/**
* Used to protect the onreadystatechange handler entry point. Necessary
* as {#onReadyStateChange_} maybe called from within send or abort, this
* method is only called when {#onReadyStateChange_} is called as an
* entry point.
* {@see #protectEntryPoints}
* @private
*/
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() {
this.onReadyStateChangeHelper_();
};
/**
* Helper for {@link #onReadyStateChange_}. This is used so that
* entry point calls to {@link #onReadyStateChange_} can be routed through
* {@link #onReadyStateChangeEntryPoint_}.
* @private
*/
goog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() {
if (!this.active_) {
// can get called inside abort call
return;
}
if (typeof goog == 'undefined') {
// NOTE(user): If goog is undefined then the callback has occurred as the
// application is unloading and will error. Thus we let it silently fail.
} else if (
this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] &&
this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE &&
this.getStatus() == 2) {
// NOTE(user): In IE if send() errors on a *local* request the readystate
// is still changed to COMPLETE. We need to ignore it and allow the
// try/catch around send() to pick up the error.
goog.log.fine(
this.logger_,
this.formatMsg_('Local request error detected and ignored'));
} else {
// In IE when the response has been cached we sometimes get the callback
// from inside the send call and this usually breaks code that assumes that
// XhrIo is asynchronous. If that is the case we delay the callback
// using a timer.
if (this.inSend_ &&
this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) {
goog.Timer.callOnce(this.onReadyStateChange_, 0, this);
return;
}
this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE);
// readyState indicates the transfer has finished
if (this.isComplete()) {
goog.log.fine(this.logger_, this.formatMsg_('Request complete'));
this.active_ = false;
try {
// Call the specific callbacks for success or failure. Only call the
// success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED)
if (this.isSuccess()) {
this.dispatchEvent(goog.net.EventType.COMPLETE);
this.dispatchEvent(goog.net.EventType.SUCCESS);
} else {
this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR;
this.lastError_ =
this.getStatusText() + ' [' + this.getStatus() + ']';
this.dispatchErrors_();
}
} finally {
this.cleanUpXhr_();
}
}
}
};
/**
* Internal handler for the XHR object's onprogress event. Fires both a generic
* PROGRESS event and either a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event to
* allow specific binding for each XHR progress event.
* @param {!ProgressEvent} e XHR progress event.
* @param {boolean=} opt_isDownload Whether the current progress event is from a
* download. Used to determine whether DOWNLOAD_PROGRESS or UPLOAD_PROGRESS
* event should be dispatched.
* @private
*/
goog.net.XhrIo.prototype.onProgressHandler_ = function(e, opt_isDownload) {
goog.asserts.assert(
e.type === goog.net.EventType.PROGRESS,
'goog.net.EventType.PROGRESS is of the same type as raw XHR progress.');
this.dispatchEvent(
goog.net.XhrIo.buildProgressEvent_(e, goog.net.EventType.PROGRESS));
this.dispatchEvent(
goog.net.XhrIo.buildProgressEvent_(
e, opt_isDownload ? goog.net.EventType.DOWNLOAD_PROGRESS :
goog.net.EventType.UPLOAD_PROGRESS));
};
/**
* Creates a representation of the native ProgressEvent. IE doesn't support
* constructing ProgressEvent via "new", and the alternatives (e.g.,
* ProgressEvent.initProgressEvent) are non-standard or deprecated.
* @param {!ProgressEvent} e XHR progress event.
* @param {!goog.net.EventType} eventType The type of the event.
* @return {!ProgressEvent} The progress event.
* @private
*/
goog.net.XhrIo.buildProgressEvent_ = function(e, eventType) {
return /** @type {!ProgressEvent} */ ({
type: eventType,
lengthComputable: e.lengthComputable,
loaded: e.loaded,
total: e.total,
});
};
/**
* Remove the listener to protect against leaks, and nullify the XMLHttpRequest
* object.
* @param {boolean=} opt_fromDispose If this is from the dispose (don't want to
* fire any events).
* @private
*/
goog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) {
if (this.xhr_) {
// Cancel any pending timeout event handler.
this.cleanUpTimeoutTimer_();
// Save reference so we can mark it as closed after the READY event. The
// READY event may trigger another request, thus we must nullify this.xhr_
var xhr = this.xhr_;
var clearedOnReadyStateChange =
this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ?
goog.nullFunction :
null;
this.xhr_ = null;
this.xhrOptions_ = null;
if (!opt_fromDispose) {
this.dispatchEvent(goog.net.EventType.READY);
}
try {
// NOTE(user): Not nullifying in FireFox can still leak if the callbacks
// are defined in the same scope as the instance of XhrIo. But, IE doesn't
// allow you to set the onreadystatechange to NULL so nullFunction is
// used.
xhr.onreadystatechange = clearedOnReadyStateChange;
} catch (e) {
// This seems to occur with a Gears HTTP request. Delayed the setting of
// this onreadystatechange until after READY is sent out and catching the
// error to see if we can track down the problem.
goog.log.error(
this.logger_,
'Problem encountered resetting onreadystatechange: ' + e.message);
}
}
};
/**
* Make sure the timeout timer isn't running.
* @private
*/
goog.net.XhrIo.prototype.cleanUpTimeoutTimer_ = function() {
if (this.xhr_ && this.useXhr2Timeout_) {
this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = null;
}
if (this.timeoutId_) {
goog.Timer.clear(this.timeoutId_);
this.timeoutId_ = null;
}
};
/**
* @return {boolean} Whether there is an active request.
*/
goog.net.XhrIo.prototype.isActive = function() {
return !!this.xhr_;
};
/**
* @return {boolean} Whether the request has completed.
*/
goog.net.XhrIo.prototype.isComplete = function() {
return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;
};
/**
* @return {boolean} Whether the request completed with a success.
*/
goog.net.XhrIo.prototype.isSuccess = function() {
var status = this.getStatus();
// A zero status code is considered successful for local files.
return goog.net.HttpStatus.isSuccess(status) ||
status === 0 && !this.isLastUriEffectiveSchemeHttp_();
};
/**
* @return {boolean} whether the effective scheme of the last URI that was
* fetched was 'http' or 'https'.
* @private
*/
goog.net.XhrIo.prototype.isLastUriEffectiveSchemeHttp_ = function() {
var scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_));
return goog.net.XhrIo.HTTP_SCHEME_PATTERN.test(scheme);
};
/**
* Get the readystate from the Xhr object
* Will only return correct result when called from the context of a callback
* @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*.
*/
goog.net.XhrIo.prototype.getReadyState = function() {
return this.xhr_ ?
/** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) :
goog.net.XmlHttp.ReadyState
.UNINITIALIZED;
};
/**
* Get the status from the Xhr object
* Will only return correct result when called from the context of a callback
* @return {number} Http status.
*/
goog.net.XhrIo.prototype.getStatus = function() {
/**
* IE doesn't like you checking status until the readystate is greater than 2
* (i.e. it is receiving or complete). The try/catch is used for when the
* page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.
*/
try {
return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?
this.xhr_.status :
-1;
} catch (e) {
return -1;
}
};
/**
* Get the status text from the Xhr object
* Will only return correct result when called from the context of a callback
* @return {string} Status text.
*/
goog.net.XhrIo.prototype.getStatusText = function() {
/**
* IE doesn't like you checking status until the readystate is greater than 2
* (i.e. it is receiving or complete). The try/catch is used for when the
* page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.
*/
try {
return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?
this.xhr_.statusText :
'';
} catch (e) {
goog.log.fine(this.logger_, 'Can not get status: ' + e.message);
return '';
}
};
/**
* Get the last Uri that was requested
* @return {string} Last Uri.
*/
goog.net.XhrIo.prototype.getLastUri = function() {
return String(this.lastUri_);
};
/**
* Get the response text from the Xhr object
* Will only return correct result when called from the context of a callback.
* @return {string} Result from the server, or '' if no result available.
*/
goog.net.XhrIo.prototype.getResponseText = function() {
try {
return this.xhr_ ? this.xhr_.responseText : '';
} catch (e) {
// http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute
// states that responseText should return '' (and responseXML null)
// when the state is not LOADING or DONE. Instead, IE can
// throw unexpected exceptions, for example when a request is aborted
// or no data is available yet.
goog.log.fine(this.logger_, 'Can not get responseText: ' + e.message);
return '';
}
};
/**
* Get the response body from the Xhr object. This property is only available
* in IE since version 7 according to MSDN:
* http://msdn.microsoft.com/en-us/library/ie/ms534368(v=vs.85).aspx
* Will only return correct result when called from the context of a callback.
*
* One option is to construct a VBArray from the returned object and convert
* it to a JavaScript array using the toArray method:
* `(new window['VBArray'](xhrIo.getResponseBody())).toArray()`
* This will result in an array of numbers in the range of [0..255]
*
* Another option is to use the VBScript CStr method to convert it into a
* string as outlined in http://stackoverflow.com/questions/1919972
*
* @return {Object} Binary result from the server or null if not available.
*/
goog.net.XhrIo.prototype.getResponseBody = function() {
try {
if (this.xhr_ && 'responseBody' in this.xhr_) {
return this.xhr_['responseBody'];
}
} catch (e) {
// IE can throw unexpected exceptions, for example when a request is aborted
// or no data is yet available.
goog.log.fine(this.logger_, 'Can not get responseBody: ' + e.message);
}
return null;
};
/**
* Get the response XML from the Xhr object
* Will only return correct result when called from the context of a callback.
* @return {Document} The DOM Document representing the XML file, or null
* if no result available.
*/
goog.net.XhrIo.prototype.getResponseXml = function() {
try {
return this.xhr_ ? this.xhr_.responseXML : null;
} catch (e) {
goog.log.fine(this.logger_, 'Can not get responseXML: ' + e.message);
return null;
}
};
/**
* Get the response and evaluates it as JSON from the Xhr object
* Will only return correct result when called from the context of a callback
* @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for
* stripping of the response before parsing. This needs to be set only if
* your backend server prepends the same prefix string to the JSON response.
* @throws Error if the response text is invalid JSON.
* @return {Object|undefined} JavaScript object.
*/
goog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) {
if (!this.xhr_) {
return undefined;
}
var responseText = this.xhr_.responseText;
if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) {
responseText = responseText.substring(opt_xssiPrefix.length);
}
return goog.json.hybrid.parse(responseText);
};
/**
* Get the response as the type specificed by {@link #setResponseType}. At time
* of writing, this is only directly supported in very recent versions of WebKit
* (10.0.612.1 dev and later). If the field is not supported directly, we will
* try to emulate it.
*
* Emulating the response means following the rules laid out at
* http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute
*
* On browsers with no support for this (Chrome < 10, Firefox < 4, etc), only
* response types of DEFAULT or TEXT may be used, and the response returned will
* be the text response.
*
* On browsers with Mozilla's draft support for array buffers (Firefox 4, 5),
* only response types of DEFAULT, TEXT, and ARRAY_BUFFER may be used, and the
* response returned will be either the text response or the Mozilla
* implementation of the array buffer response.
*
* On browsers will full support, any valid response type supported by the
* browser may be used, and the response provided by the browser will be
* returned.
*
* @return {*} The response.
*/
goog.net.XhrIo.prototype.getResponse = function() {
try {
if (!this.xhr_) {
return null;
}
if ('response' in this.xhr_) {
return this.xhr_.response;
}
switch (this.responseType_) {
case ResponseType.DEFAULT:
case ResponseType.TEXT:
return this.xhr_.responseText;
// DOCUMENT and BLOB don't need to be handled here because they are
// introduced in the same spec that adds the .response field, and would
// have been caught above.
// ARRAY_BUFFER needs an implementation for Firefox 4, where it was
// implemented using a draft spec rather than the final spec.
case ResponseType.ARRAY_BUFFER:
if ('mozResponseArrayBuffer' in this.xhr_) {
return this.xhr_.mozResponseArrayBuffer;
}
}
// Fell through to a response type that is not supported on this browser.
goog.log.error(
this.logger_, 'Response type ' + this.responseType_ + ' is not ' +
'supported on this browser');
return null;
} catch (e) {
goog.log.fine(this.logger_, 'Can not get response: ' + e.message);
return null;
}
};
/**
* Get the value of the response-header with the given name from the Xhr object
* Will only return correct result when called from the context of a callback
* and the request has completed
* @param {string} key The name of the response-header to retrieve.
* @return {string|undefined} The value of the response-header named key.
*/
goog.net.XhrIo.prototype.getResponseHeader = function(key) {
if (!this.xhr_ || !this.isComplete()) {
return undefined;
}
var value = this.xhr_.getResponseHeader(key);
return value === null ? undefined : value;
};
/**
* Gets the text of all the headers in the response.
* Will only return correct result when called from the context of a callback
* and the request has completed.
* @return {string} The value of the response headers or empty string.<|fim▁hole|> */
goog.net.XhrIo.prototype.getAllResponseHeaders = function() {
// getAllResponseHeaders can return null if no response has been received,
// ensure we always return an empty string.
return this.xhr_ && this.isComplete() ?
(this.xhr_.getAllResponseHeaders() || '') :
'';
};
/**
* Returns all response headers as a key-value map.
* Multiple values for the same header key can be combined into one,
* separated by a comma and a space.
* Note that the native getResponseHeader method for retrieving a single header
* does a case insensitive match on the header name. This method does not
* include any case normalization logic, it will just return a key-value
* representation of the headers.
* See: http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method
* @return {!Object<string, string>} An object with the header keys as keys
* and header values as values.
*/
goog.net.XhrIo.prototype.getResponseHeaders = function() {
// TODO(user): Make this function parse headers as per the spec
// (https://tools.ietf.org/html/rfc2616#section-4.2).
var headersObject = {};
var headersArray = this.getAllResponseHeaders().split('\r\n');
for (var i = 0; i < headersArray.length; i++) {
if (goog.string.isEmptyOrWhitespace(headersArray[i])) {
continue;
}
var keyValue =
goog.string.splitLimit(headersArray[i], ':', /* maxSplitCount= */ 1);
var key = keyValue[0];
var value = keyValue[1];
if (typeof value !== 'string') {
// There must be a value but it can be the empty string.
continue;
}
// Whitespace at the start and end of the value is meaningless.
value = value.trim();
// The key should not contain whitespace but we currently ignore that.
var values = headersObject[key] || [];
headersObject[key] = values;
values.push(value);
}
return goog.object.map(headersObject, function(values) {
return values.join(', ');
});
};
/**
* Get the value of the response-header with the given name from the Xhr object.
* As opposed to {@link #getResponseHeader}, this method does not require that
* the request has completed.
* @param {string} key The name of the response-header to retrieve.
* @return {?string} The value of the response-header, or null if it is
* unavailable.
*/
goog.net.XhrIo.prototype.getStreamingResponseHeader = function(key) {
return this.xhr_ ? this.xhr_.getResponseHeader(key) : null;
};
/**
* Gets the text of all the headers in the response. As opposed to
* {@link #getAllResponseHeaders}, this method does not require that the request
* has completed.
* @return {string} The value of the response headers or empty string.
*/
goog.net.XhrIo.prototype.getAllStreamingResponseHeaders = function() {
return this.xhr_ ? this.xhr_.getAllResponseHeaders() : '';
};
/**
* Get the last error message
* @return {!goog.net.ErrorCode} Last error code.
*/
goog.net.XhrIo.prototype.getLastErrorCode = function() {
return this.lastErrorCode_;
};
/**
* Get the last error message
* @return {string} Last error message.
*/
goog.net.XhrIo.prototype.getLastError = function() {
return typeof this.lastError_ === 'string' ? this.lastError_ :
String(this.lastError_);
};
/**
* Adds the last method, status and URI to the message. This is used to add
* this information to the logging calls.
* @param {string} msg The message text that we want to add the extra text to.
* @return {string} The message with the extra text appended.
* @private
*/
goog.net.XhrIo.prototype.formatMsg_ = function(msg) {
return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' +
this.getStatus() + ']';
};
// Register the xhr handler as an entry point, so that
// it can be monitored for exception handling, etc.
goog.debug.entryPointRegistry.register(
/**
* @param {function(!Function): !Function} transformer The transforming
* function.
*/
function(transformer) {
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =
transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);
});
}); // goog.scope<|fim▁end|> | |
<|file_name|>17.py<|end_file_name|><|fim▁begin|>import struct<|fim▁hole|>
''' Refer to docs for all the exact formats. There are many so check them out before converting things yourself '''
''' If there's a specific offset you want to do things from, use pack_into and unack_into from the docs '''
#Integer to string
i1= 1234
print "Int to string as 8 byte little endian", repr(struct.pack("<Q",i1))
print "Int to string as 8 byte big endian", repr(struct.pack(">Q",i1))
#String to integer. Make sure size of destination matches the length of the string
s1= '1234'
print "String to 4 byte integer little endian", struct.unpack("<i", s1)
print "String to 4 byte integer big endian", struct.unpack(">i", s1)
''' Whenever you want to convert to and from binary, think of binascii '''
import binascii
h1= binascii.b2a_hex(s1)
print "String to hex", h1
uh1= binascii.a2b_hex(h1)
print "Hex to string, even a binary string", uh1<|fim▁end|> | |
<|file_name|>atom.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
werkzeug.contrib.atom
~~~~~~~~~~~~~~~~~~~~~
This module provides a class called :class:`AtomFeed` which can be
used to generate feeds in the Atom syndication format (see :rfc:`4287`).
Example::
def atom_feed(request):
feed = AtomFeed("My Blog", feed_url=request.url,
url=request.host_url,
subtitle="My example blog for a feed test.")
for post in Post.query.limit(10).all():
feed.add(post.title, post.body, content_type='html',
author=post.author, url=post.url, id=post.uid,
updated=post.last_update, published=post.pub_date)
return feed.get_response()
:copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from datetime import datetime
from werkzeug.utils import escape
from werkzeug.wrappers import BaseResponse
XHTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'
def _make_text_block(name, content, content_type=None):
"""Helper function for the builder that creates an XML text block."""
if content_type == 'xhtml':
return u'<%s type="xhtml"><div xmlns="%s">%s</div></%s>\n' % \
(name, XHTML_NAMESPACE, content, name)
if not content_type:
return u'<%s>%s</%s>\n' % (name, escape(content), name)
return u'<%s type="%s">%s</%s>\n' % (name, content_type,
escape(content), name)
def format_iso8601(obj):
"""Format a datetime object for iso8601"""
return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
class AtomFeed(object):
"""A helper class that creates Atom feeds.
:param title: the title of the feed. Required.
:param title_type: the type attribute for the title element. One of
``'html'``, ``'text'`` or ``'xhtml'``.
:param url: the url for the feed (not the url *of* the feed)
:param id: a globally unique id for the feed. Must be an URI. If
not present the `feed_url` is used, but one of both is
required.
:param updated: the time the feed was modified the last time. Must
be a :class:`datetime.datetime` object. If not
present the latest entry's `updated` is used.
:param feed_url: the URL to the feed. Should be the URL that was
requested.
:param author: the author of the feed. Must be either a string (the
name) or a dict with name (required) and uri or
email (both optional). Can be a list of (may be
mixed, too) strings and dicts, too, if there are
multiple authors. Required if not every entry has an
author element.
:param icon: an icon for the feed.
:param logo: a logo for the feed.
:param rights: copyright information for the feed.
:param rights_type: the type attribute for the rights element. One of
``'html'``, ``'text'`` or ``'xhtml'``. Default is
``'text'``.
:param subtitle: a short description of the feed.
:param subtitle_type: the type attribute for the subtitle element.
One of ``'text'``, ``'html'``, ``'text'``
or ``'xhtml'``. Default is ``'text'``.
:param links: additional links. Must be a list of dictionaries with
href (required) and rel, type, hreflang, title, length
(all optional)
:param generator: the software that generated this feed. This must be
a tuple in the form ``(name, url, version)``. If
you don't want to specify one of them, set the item
to `None`.
:param entries: a list with the entries for the feed. Entries can also
be added later with :meth:`add`.
For more information on the elements see
http://www.atomenabled.org/developers/syndication/
Everywhere where a list is demanded, any iterable can be used.
"""
default_generator = ('Werkzeug', None, None)
def __init__(self, title=None, entries=None, **kwargs):
self.title = title
self.title_type = kwargs.get('title_type', 'text')
self.url = kwargs.get('url')
self.feed_url = kwargs.get('feed_url', self.url)
self.id = kwargs.get('id', self.feed_url)
self.updated = kwargs.get('updated')
self.author = kwargs.get('author', ())
self.icon = kwargs.get('icon')
self.logo = kwargs.get('logo')
self.rights = kwargs.get('rights')
self.rights_type = kwargs.get('rights_type')
self.subtitle = kwargs.get('subtitle')
self.subtitle_type = kwargs.get('subtitle_type', 'text')
self.generator = kwargs.get('generator')
if self.generator is None:
self.generator = self.default_generator
self.links = kwargs.get('links', [])
self.entries = entries and list(entries) or []
if not hasattr(self.author, '__iter__') \
or isinstance(self.author, (basestring, dict)):
self.author = [self.author]
for i, author in enumerate(self.author):
if not isinstance(author, dict):
self.author[i] = {'name': author}
if not self.title:
raise ValueError('title is required')
if not self.id:
raise ValueError('id is required')
for author in self.author:
if 'name' not in author:
raise TypeError('author must contain at least a name')
def add(self, *args, **kwargs):
"""Add a new entry to the feed. This function can either be called
with a :class:`FeedEntry` or some keyword and positional arguments
that are forwarded to the :class:`FeedEntry` constructor.
"""
if len(args) == 1 and not kwargs and isinstance(args[0], FeedEntry):
self.entries.append(args[0])
else:
kwargs['feed_url'] = self.feed_url
self.entries.append(FeedEntry(*args, **kwargs))
def __repr__(self):
return '<%s %r (%d entries)>' % (
self.__class__.__name__,
self.title,
len(self.entries)
)
def generate(self):
"""Return a generator that yields pieces of XML."""
# atom demands either an author element in every entry or a global one
if not self.author:
if False in map(lambda e: bool(e.author), self.entries):
self.author = ({'name': u'unbekannter Autor'},)
if not self.updated:
dates = sorted([entry.updated for entry in self.entries])
self.updated = dates and dates[-1] or datetime.utcnow()
yield u'<?xml version="1.0" encoding="utf-8"?>\n'
yield u'<feed xmlns="http://www.w3.org/2005/Atom">\n'
yield ' ' + _make_text_block('title', self.title, self.title_type)
yield u' <id>%s</id>\n' % escape(self.id)
yield u' <updated>%s</updated>\n' % format_iso8601(self.updated)
if self.url:
yield u' <link href="%s" />\n' % escape(self.url, True)
if self.feed_url:
yield u' <link href="%s" rel="self" />\n' % \
escape(self.feed_url, True)
for link in self.links:
yield u' <link %s/>\n' % ''.join('%s="%s" ' % \
(k, escape(link[k], True)) for k in link)
for author in self.author:
yield u' <author>\n'
yield u' <name>%s</name>\n' % escape(author['name'])
if 'uri' in author:
yield u' <uri>%s</uri>\n' % escape(author['uri'])
if 'email' in author:
yield ' <email>%s</email>\n' % escape(author['email'])<|fim▁hole|> self.subtitle_type)
if self.icon:
yield u' <icon>%s</icon>\n' % escape(self.icon)
if self.logo:
yield u' <logo>%s</logo>\n' % escape(self.logo)
if self.rights:
yield ' ' + _make_text_block('rights', self.rights,
self.rights_type)
generator_name, generator_url, generator_version = self.generator
if generator_name or generator_url or generator_version:
tmp = [u' <generator']
if generator_url:
tmp.append(u' uri="%s"' % escape(generator_url, True))
if generator_version:
tmp.append(u' version="%s"' % escape(generator_version, True))
tmp.append(u'>%s</generator>\n' % escape(generator_name))
yield u''.join(tmp)
for entry in self.entries:
for line in entry.generate():
yield u' ' + line
yield u'</feed>\n'
def to_string(self):
"""Convert the feed into a string."""
return u''.join(self.generate())
def get_response(self):
"""Return a response object for the feed."""
return BaseResponse(self.to_string(), mimetype='application/atom+xml')
def __call__(self, environ, start_response):
"""Use the class as WSGI response object."""
return self.get_response()(environ, start_response)
def __unicode__(self):
return self.to_string()
def __str__(self):
return self.to_string().encode('utf-8')
class FeedEntry(object):
"""Represents a single entry in a feed.
:param title: the title of the entry. Required.
:param title_type: the type attribute for the title element. One of
``'html'``, ``'text'`` or ``'xhtml'``.
:param content: the content of the entry.
:param content_type: the type attribute for the content element. One
of ``'html'``, ``'text'`` or ``'xhtml'``.
:param summary: a summary of the entry's content.
:param summary_type: the type attribute for the summary element. One
of ``'html'``, ``'text'`` or ``'xhtml'``.
:param url: the url for the entry.
:param id: a globally unique id for the entry. Must be an URI. If
not present the URL is used, but one of both is required.
:param updated: the time the entry was modified the last time. Must
be a :class:`datetime.datetime` object. Required.
:param author: the author of the feed. Must be either a string (the
name) or a dict with name (required) and uri or
email (both optional). Can be a list of (may be
mixed, too) strings and dicts, too, if there are
multiple authors. Required if not every entry has an
author element.
:param published: the time the entry was initially published. Must
be a :class:`datetime.datetime` object.
:param rights: copyright information for the entry.
:param rights_type: the type attribute for the rights element. One of
``'html'``, ``'text'`` or ``'xhtml'``. Default is
``'text'``.
:param links: additional links. Must be a list of dictionaries with
href (required) and rel, type, hreflang, title, length
(all optional)
:param xml_base: The xml base (url) for this feed item. If not provided
it will default to the item url.
For more information on the elements see
http://www.atomenabled.org/developers/syndication/
Everywhere where a list is demanded, any iterable can be used.
"""
def __init__(self, title=None, content=None, feed_url=None, **kwargs):
self.title = title
self.title_type = kwargs.get('title_type', 'text')
self.content = content
self.content_type = kwargs.get('content_type', 'html')
self.url = kwargs.get('url')
self.id = kwargs.get('id', self.url)
self.updated = kwargs.get('updated')
self.summary = kwargs.get('summary')
self.summary_type = kwargs.get('summary_type', 'html')
self.author = kwargs.get('author')
self.published = kwargs.get('published')
self.rights = kwargs.get('rights')
self.links = kwargs.get('links', [])
self.xml_base = kwargs.get('xml_base', feed_url)
if not hasattr(self.author, '__iter__') \
or isinstance(self.author, (basestring, dict)):
self.author = [self.author]
for i, author in enumerate(self.author):
if not isinstance(author, dict):
self.author[i] = {'name': author}
if not self.title:
raise ValueError('title is required')
if not self.id:
raise ValueError('id is required')
if not self.updated:
raise ValueError('updated is required')
def __repr__(self):
return '<%s %r>' % (
self.__class__.__name__,
self.title
)
def generate(self):
"""Yields pieces of ATOM XML."""
base = ''
if self.xml_base:
base = ' xml:base="%s"' % escape(self.xml_base, True)
yield u'<entry%s>\n' % base
yield u' ' + _make_text_block('title', self.title, self.title_type)
yield u' <id>%s</id>\n' % escape(self.id)
yield u' <updated>%s</updated>\n' % format_iso8601(self.updated)
if self.published:
yield u' <published>%s</published>\n' % \
format_iso8601(self.published)
if self.url:
yield u' <link href="%s" />\n' % escape(self.url)
for author in self.author:
yield u' <author>\n'
yield u' <name>%s</name>\n' % escape(author['name'])
if 'uri' in author:
yield u' <uri>%s</uri>\n' % escape(author['uri'])
if 'email' in author:
yield u' <email>%s</email>\n' % escape(author['email'])
yield u' </author>\n'
for link in self.links:
yield u' <link %s/>\n' % ''.join('%s="%s" ' % \
(k, escape(link[k], True)) for k in link)
if self.summary:
yield u' ' + _make_text_block('summary', self.summary,
self.summary_type)
if self.content:
yield u' ' + _make_text_block('content', self.content,
self.content_type)
yield u'</entry>\n'
def to_string(self):
"""Convert the feed item into a unicode object."""
return u''.join(self.generate())
def __unicode__(self):
return self.to_string()
def __str__(self):
return self.to_string().encode('utf-8')<|fim▁end|> | yield ' </author>\n'
if self.subtitle:
yield ' ' + _make_text_block('subtitle', self.subtitle, |
<|file_name|>regionmanip.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// #![warn(deprecated_mode)]
use middle::ty;
use middle::ty_fold;
use middle::ty_fold::TypeFolder;
use collections::HashMap;
use util::ppaux::Repr;
use util::ppaux;
// Helper functions related to manipulating region types.
pub fn replace_late_bound_regions_in_fn_sig(
tcx: &ty::ctxt,
fn_sig: &ty::FnSig,
mapf: |ty::BoundRegion| -> ty::Region)
-> (HashMap<ty::BoundRegion,ty::Region>, ty::FnSig) {
debug!("replace_late_bound_regions_in_fn_sig({})", fn_sig.repr(tcx));
let mut map = HashMap::new();
let fn_sig = {
let mut f = ty_fold::RegionFolder::regions(tcx, |r| {
debug!("region r={}", r.to_str());
match r {
ty::ReLateBound(s, br) if s == fn_sig.binder_id => {
*map.find_or_insert_with(br, |_| mapf(br))
}
_ => r
}
});
ty_fold::super_fold_sig(&mut f, fn_sig)
};
debug!("resulting map: {}", map);
(map, fn_sig)
}
pub fn relate_nested_regions(tcx: &ty::ctxt,
opt_region: Option<ty::Region>,
ty: ty::t,
relate_op: |ty::Region, ty::Region|) {
/*!
* This rather specialized function walks each region `r` that appear
* in `ty` and invokes `relate_op(r_encl, r)` for each one. `r_encl`
* here is the region of any enclosing `&'r T` pointer. If there is
* no enclosing pointer, and `opt_region` is Some, then `opt_region.get()`
* is used instead. Otherwise, no callback occurs at all).
*
* Here are some examples to give you an intution:
*
* - `relate_nested_regions(Some('r1), &'r2 uint)` invokes
* - `relate_op('r1, 'r2)`
* - `relate_nested_regions(Some('r1), &'r2 &'r3 uint)` invokes
* - `relate_op('r1, 'r2)`
* - `relate_op('r2, 'r3)`
* - `relate_nested_regions(None, &'r2 &'r3 uint)` invokes
* - `relate_op('r2, 'r3)`
* - `relate_nested_regions(None, &'r2 &'r3 &'r4 uint)` invokes
* - `relate_op('r2, 'r3)`
* - `relate_op('r2, 'r4)`
* - `relate_op('r3, 'r4)`
*
* This function is used in various pieces of code because we enforce the
* constraint that a region pointer cannot outlive the things it points at.
* Hence, in the second example above, `'r2` must be a subregion of `'r3`.
*/
let mut rr = RegionRelator { tcx: tcx,
stack: Vec::new(),
relate_op: relate_op };
match opt_region {
Some(o_r) => { rr.stack.push(o_r); }
None => {}
}
rr.fold_ty(ty);
struct RegionRelator<'a> {
tcx: &'a ty::ctxt,
stack: Vec<ty::Region>,
relate_op: |ty::Region, ty::Region|: 'a,
}
// FIXME(#10151) -- Define more precisely when a region is
// considered "nested". Consider taking variance into account as
// well.
impl<'a> TypeFolder for RegionRelator<'a> {
fn tcx<'a>(&'a self) -> &'a ty::ctxt {
self.tcx
}
fn fold_ty(&mut self, ty: ty::t) -> ty::t {
match ty::get(ty).sty {
ty::ty_rptr(r, ty::mt {ty, ..}) => {
self.relate(r);
self.stack.push(r);
ty_fold::super_fold_ty(self, ty);
self.stack.pop().unwrap();
}
_ => {
ty_fold::super_fold_ty(self, ty);
}
}
ty
}
fn fold_region(&mut self, r: ty::Region) -> ty::Region {
self.relate(r);
r
}
}
impl<'a> RegionRelator<'a> {
fn relate(&mut self, r_sub: ty::Region) {
for &r in self.stack.iter() {
if !r.is_bound() && !r_sub.is_bound() {
(self.relate_op)(r, r_sub);<|fim▁hole|> }
}
}
pub fn relate_free_regions(tcx: &ty::ctxt, fn_sig: &ty::FnSig) {
/*!
* This function populates the region map's `free_region_map`.
* It walks over the transformed self type and argument types
* for each function just before we check the body of that
* function, looking for types where you have a borrowed
* pointer to other borrowed data (e.g., `&'a &'b [uint]`.
* We do not allow references to outlive the things they
* point at, so we can assume that `'a <= 'b`.
*
* Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
*/
debug!("relate_free_regions >>");
let mut all_tys = Vec::new();
for arg in fn_sig.inputs.iter() {
all_tys.push(*arg);
}
for &t in all_tys.iter() {
debug!("relate_free_regions(t={})", ppaux::ty_to_str(tcx, t));
relate_nested_regions(tcx, None, t, |a, b| {
match (&a, &b) {
(&ty::ReFree(free_a), &ty::ReFree(free_b)) => {
tcx.region_maps.relate_free_regions(free_a, free_b);
}
_ => {}
}
})
}
debug!("<< relate_free_regions");
}<|fim▁end|> | }
} |
<|file_name|>lxd.go<|end_file_name|><|fim▁begin|>// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
// +build go1.3
package lxd
import (
"github.com/juju/loggo"
"github.com/juju/juju/environs/tags"
"github.com/juju/juju/provider/lxd/lxdclient"
)
// The metadata keys used when creating new instances.
const (
metadataKeyIsState = tags.JujuEnv
metadataKeyCloudInit = lxdclient.UserdataKey
)
// Common metadata values used when creating new instances.
const (
metadataValueTrue = "true"
metadataValueFalse = "false"
)
var (
logger = loggo.GetLogger("juju.provider.lxd")<|fim▁hole|><|fim▁end|> | ) |
<|file_name|>images.d.ts<|end_file_name|><|fim▁begin|>declare module "*.png"<|fim▁hole|><|fim▁end|> | declare module "*.webp" |
<|file_name|>cargo_common_metadata.rs<|end_file_name|><|fim▁begin|>//! lint on missing cargo common metadata
use clippy_utils::{diagnostics::span_lint, is_lint_allowed};
use rustc_hir::hir_id::CRATE_HIR_ID;
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_tool_lint, impl_lint_pass};
use rustc_span::source_map::DUMMY_SP;
declare_clippy_lint! {
/// ### What it does
/// Checks to see if all common metadata is defined in
/// `Cargo.toml`. See: https://rust-lang-nursery.github.io/api-guidelines/documentation.html#cargotoml-includes-all-common-metadata-c-metadata
///
/// ### Why is this bad?
/// It will be more difficult for users to discover the
/// purpose of the crate, and key information related to it.
///
/// ### Example
/// ```toml
/// # This `Cargo.toml` is missing a description field:
/// [package]
/// name = "clippy"
/// version = "0.0.212"
/// repository = "https://github.com/rust-lang/rust-clippy"
/// readme = "README.md"
/// license = "MIT OR Apache-2.0"
/// keywords = ["clippy", "lint", "plugin"]
/// categories = ["development-tools", "development-tools::cargo-plugins"]
/// ```
///
/// Should include a description field like:
///
/// ```toml
/// # This `Cargo.toml` includes all common metadata
/// [package]
/// name = "clippy"
/// version = "0.0.212"
/// description = "A bunch of helpful lints to avoid common pitfalls in Rust"
/// repository = "https://github.com/rust-lang/rust-clippy"
/// readme = "README.md"
/// license = "MIT OR Apache-2.0"
/// keywords = ["clippy", "lint", "plugin"]
/// categories = ["development-tools", "development-tools::cargo-plugins"]
/// ```
pub CARGO_COMMON_METADATA,
cargo,
"common metadata is defined in `Cargo.toml`"
}
#[derive(Copy, Clone, Debug)]
pub struct CargoCommonMetadata {
ignore_publish: bool,
}
impl CargoCommonMetadata {
pub fn new(ignore_publish: bool) -> Self {
Self { ignore_publish }
}
}
impl_lint_pass!(CargoCommonMetadata => [
CARGO_COMMON_METADATA
]);
fn missing_warning(cx: &LateContext<'_>, package: &cargo_metadata::Package, field: &str) {
let message = format!("package `{}` is missing `{}` metadata", package.name, field);
span_lint(cx, CARGO_COMMON_METADATA, DUMMY_SP, &message);
}
fn is_empty_str<T: AsRef<std::ffi::OsStr>>(value: &Option<T>) -> bool {
value.as_ref().map_or(true, |s| s.as_ref().is_empty())
}
fn is_empty_vec(value: &[String]) -> bool {
// This works because empty iterators return true
value.iter().all(String::is_empty)
}
impl LateLintPass<'_> for CargoCommonMetadata {
fn check_crate(&mut self, cx: &LateContext<'_>) {
if is_lint_allowed(cx, CARGO_COMMON_METADATA, CRATE_HIR_ID) {
return;
}
let metadata = unwrap_cargo_metadata!(cx, CARGO_COMMON_METADATA, false);
for package in metadata.packages {
// only run the lint if publish is `None` (`publish = true` or skipped entirely)
// or if the vector isn't empty (`publish = ["something"]`)
if package.publish.as_ref().filter(|publish| publish.is_empty()).is_none() || self.ignore_publish {
if is_empty_str(&package.description) {<|fim▁hole|> }
if is_empty_str(&package.license) && is_empty_str(&package.license_file) {
missing_warning(cx, &package, "either package.license or package.license_file");
}
if is_empty_str(&package.repository) {
missing_warning(cx, &package, "package.repository");
}
if is_empty_str(&package.readme) {
missing_warning(cx, &package, "package.readme");
}
if is_empty_vec(&package.keywords) {
missing_warning(cx, &package, "package.keywords");
}
if is_empty_vec(&package.categories) {
missing_warning(cx, &package, "package.categories");
}
}
}
}
}<|fim▁end|> | missing_warning(cx, &package, "package.description"); |
<|file_name|>mnist_model.py<|end_file_name|><|fim▁begin|># Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Simple generator and discriminator models.
Based on the convolutional and "deconvolutional" models presented in
"Unsupervised Representation Learning with Deep Convolutional Generative
Adversarial Networks" by A. Radford et. al.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
def _leaky_relu(x):
return tf.nn.leaky_relu(x, alpha=0.2)
def _batch_norm(x, is_training, name):
return tf.layers.batch_normalization(
x, momentum=0.9, epsilon=1e-5, training=is_training, name=name)
def _dense(x, channels, name):
return tf.layers.dense(
x, channels,
kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),
name=name)
def _conv2d(x, filters, kernel_size, stride, name):
return tf.layers.conv2d(
x, filters, [kernel_size, kernel_size],
strides=[stride, stride], padding='same',
kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),
name=name)
def _deconv2d(x, filters, kernel_size, stride, name):
return tf.layers.conv2d_transpose(
x, filters, [kernel_size, kernel_size],
strides=[stride, stride], padding='same',
kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),
name=name)
def discriminator(x, is_training=True, scope='Discriminator'):
# conv64-lrelu + conv128-bn-lrelu + fc1024-bn-lrelu + fc1
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
x = _conv2d(x, 64, 4, 2, name='d_conv1')
x = _leaky_relu(x)
x = _conv2d(x, 128, 4, 2, name='d_conv2')
x = _leaky_relu(_batch_norm(x, is_training, name='d_bn2'))
x = tf.reshape(x, [-1, 7 * 7 * 128])
x = _dense(x, 1024, name='d_fc3')
x = _leaky_relu(_batch_norm(x, is_training, name='d_bn3'))
x = _dense(x, 1, name='d_fc4')
return x
def generator(x, is_training=True, scope='Generator'):
# fc1024-bn-relu + fc6272-bn-relu + deconv64-bn-relu + deconv1-tanh
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
x = _dense(x, 1024, name='g_fc1')
x = tf.nn.relu(_batch_norm(x, is_training, name='g_bn1'))
x = _dense(x, 7 * 7 * 128, name='g_fc2')
x = tf.nn.relu(_batch_norm(x, is_training, name='g_bn2'))
x = tf.reshape(x, [-1, 7, 7, 128])
x = _deconv2d(x, 64, 4, 2, name='g_dconv3')
x = tf.nn.relu(_batch_norm(x, is_training, name='g_bn3'))
x = _deconv2d(x, 1, 4, 2, name='g_dconv4')
x = tf.tanh(x)<|fim▁hole|><|fim▁end|> |
return x
# TODO(chrisying): objective score (e.g. MNIST score) |
<|file_name|>qt4.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from .. import mlog
from .. import build
from ..mesonlib import MesonException, Popen_safe
from ..dependencies import Qt4Dependency
from . import ExtensionModule
import xml.etree.ElementTree as ET
from . import ModuleReturnValue
class Qt4Module(ExtensionModule):
tools_detected = False
def _detect_tools(self, env, method):
if self.tools_detected:
return
mlog.log('Detecting Qt4 tools')
# FIXME: We currently require Qt4 to exist while importing the module.
# We should make it gracefully degrade and not create any targets if
# the import is marked as 'optional' (not implemented yet)
kwargs = {'required': 'true', 'modules': 'Core', 'silent': 'true', 'method': method}
qt4 = Qt4Dependency(env, kwargs)
# Get all tools and then make sure that they are the right version
self.moc, self.uic, self.rcc = qt4.compilers_detect()
# Moc, uic and rcc write their version strings to stderr.
# Moc and rcc return a non-zero result when doing so.
# What kind of an idiot thought that was a good idea?
if self.moc.found():
stdout, stderr = Popen_safe(self.moc.get_command() + ['-v'])[1:3]
stdout = stdout.strip()
stderr = stderr.strip()
if 'Qt Meta' in stderr:
moc_ver = stderr
else:
raise MesonException('Moc preprocessor is not for Qt 4. Output:\n%s\n%s' %
(stdout, stderr))
mlog.log(' moc:', mlog.green('YES'), '(%s, %s)' %
(self.moc.get_path(), moc_ver.split()[-1]))
else:
mlog.log(' moc:', mlog.red('NO'))
if self.uic.found():
stdout, stderr = Popen_safe(self.uic.get_command() + ['-v'])[1:3]
stdout = stdout.strip()
stderr = stderr.strip()
if 'version 4.' in stderr:
uic_ver = stderr
else:
raise MesonException('Uic compiler is not for Qt4. Output:\n%s\n%s' %
(stdout, stderr))
mlog.log(' uic:', mlog.green('YES'), '(%s, %s)' %
(self.uic.get_path(), uic_ver.split()[-1]))
else:
mlog.log(' uic:', mlog.red('NO'))
if self.rcc.found():
stdout, stderr = Popen_safe(self.rcc.get_command() + ['-v'])[1:3]
stdout = stdout.strip()
stderr = stderr.strip()
if 'version 4.' in stderr:
rcc_ver = stderr
else:<|fim▁hole|> mlog.log(' rcc:', mlog.green('YES'), '(%s, %s)'
% (self.rcc.get_path(), rcc_ver.split()[-1]))
else:
mlog.log(' rcc:', mlog.red('NO'))
self.tools_detected = True
def parse_qrc(self, state, fname):
abspath = os.path.join(state.environment.source_dir, state.subdir, fname)
relative_part = os.path.split(fname)[0]
try:
tree = ET.parse(abspath)
root = tree.getroot()
result = []
for child in root[0]:
if child.tag != 'file':
mlog.warning("malformed rcc file: ", os.path.join(state.subdir, fname))
break
else:
result.append(os.path.join(state.subdir, relative_part, child.text))
return result
except Exception:
return []
def preprocess(self, state, args, kwargs):
rcc_files = kwargs.pop('qresources', [])
if not isinstance(rcc_files, list):
rcc_files = [rcc_files]
ui_files = kwargs.pop('ui_files', [])
if not isinstance(ui_files, list):
ui_files = [ui_files]
moc_headers = kwargs.pop('moc_headers', [])
if not isinstance(moc_headers, list):
moc_headers = [moc_headers]
moc_sources = kwargs.pop('moc_sources', [])
if not isinstance(moc_sources, list):
moc_sources = [moc_sources]
sources = kwargs.pop('sources', [])
if not isinstance(sources, list):
sources = [sources]
sources += args[1:]
method = kwargs.get('method', 'auto')
self._detect_tools(state.environment, method)
err_msg = "{0} sources specified and couldn't find {1}, " \
"please check your qt4 installation"
if len(moc_headers) + len(moc_sources) > 0 and not self.moc.found():
raise MesonException(err_msg.format('MOC', 'moc-qt4'))
if len(rcc_files) > 0:
if not self.rcc.found():
raise MesonException(err_msg.format('RCC', 'rcc-qt4'))
qrc_deps = []
for i in rcc_files:
qrc_deps += self.parse_qrc(state, i)
if len(args) > 0:
name = args[0]
else:
basename = os.path.split(rcc_files[0])[1]
name = 'qt4-' + basename.replace('.', '_')
rcc_kwargs = {'input': rcc_files,
'output': name + '.cpp',
'command': [self.rcc, '-o', '@OUTPUT@', '@INPUT@'],
'depend_files': qrc_deps}
res_target = build.CustomTarget(name, state.subdir, rcc_kwargs)
sources.append(res_target)
if len(ui_files) > 0:
if not self.uic.found():
raise MesonException(err_msg.format('UIC', 'uic-qt4'))
ui_kwargs = {'output': 'ui_@[email protected]',
'arguments': ['-o', '@OUTPUT@', '@INPUT@']}
ui_gen = build.Generator([self.uic], ui_kwargs)
ui_output = ui_gen.process_files('Qt4 ui', ui_files, state)
sources.append(ui_output)
if len(moc_headers) > 0:
moc_kwargs = {'output': 'moc_@[email protected]',
'arguments': ['@INPUT@', '-o', '@OUTPUT@']}
moc_gen = build.Generator([self.moc], moc_kwargs)
moc_output = moc_gen.process_files('Qt4 moc header', moc_headers, state)
sources.append(moc_output)
if len(moc_sources) > 0:
moc_kwargs = {'output': '@[email protected]',
'arguments': ['@INPUT@', '-o', '@OUTPUT@']}
moc_gen = build.Generator([self.moc], moc_kwargs)
moc_output = moc_gen.process_files('Qt4 moc source', moc_sources, state)
sources.append(moc_output)
return ModuleReturnValue(sources, sources)
def initialize():
mlog.warning('rcc dependencies will not work properly until this upstream issue is fixed:',
mlog.bold('https://bugreports.qt.io/browse/QTBUG-45460'))
return Qt4Module()<|fim▁end|> | raise MesonException('Rcc compiler is not for Qt 4. Output:\n%s\n%s' %
(stdout, stderr)) |
<|file_name|>create_restore.py<|end_file_name|><|fim▁begin|>''' Dialogs and widgets Responsible for creation, restoration of accounts are
defined here.
Namely: CreateAccountDialog, CreateRestoreDialog, RestoreSeedDialog
'''
from functools import partial
from kivy.app import App
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.properties import ObjectProperty, StringProperty, OptionProperty
from kivy.core.window import Window
from electrum_gui.kivy.uix.dialogs import EventsDialog
from electrum.i18n import _
Builder.load_string('''<|fim▁hole|>
<WizardTextInput@TextInput>
border: 4, 4, 4, 4
font_size: '15sp'
padding: '15dp', '15dp'
background_color: (1, 1, 1, 1) if self.focus else (0.454, 0.698, 0.909, 1)
foreground_color: (0.31, 0.31, 0.31, 1) if self.focus else (0.835, 0.909, 0.972, 1)
hint_text_color: self.foreground_color
background_active: 'atlas://gui/kivy/theming/light/create_act_text_active'
background_normal: 'atlas://gui/kivy/theming/light/create_act_text_active'
size_hint_y: None
height: '48sp'
<WizardButton@Button>:
root: None
size_hint: 1, None
height: '48sp'
on_press: if self.root: self.root.dispatch('on_press', self)
on_release: if self.root: self.root.dispatch('on_release', self)
<-WizardDialog>
text_color: .854, .925, .984, 1
#auto_dismiss: False
size_hint: None, None
canvas.before:
Color:
rgba: 0, 0, 0, .9
Rectangle:
size: Window.size
Color:
rgba: .239, .588, .882, 1
Rectangle:
size: Window.size
crcontent: crcontent
# add electrum icon
BoxLayout:
orientation: 'vertical' if self.width < self.height else 'horizontal'
padding:
min(dp(42), self.width/8), min(dp(60), self.height/9.7),\
min(dp(42), self.width/8), min(dp(72), self.height/8)
spacing: '27dp'
GridLayout:
id: grid_logo
cols: 1
pos_hint: {'center_y': .5}
size_hint: 1, .42
#height: self.minimum_height
Image:
id: logo_img
mipmap: True
allow_stretch: True
size_hint: 1, None
height: '110dp'
source: 'atlas://gui/kivy/theming/light/electrum_icon640'
Widget:
size_hint: 1, None
height: 0 if stepper.opacity else dp(15)
Label:
color: root.text_color
opacity: 0 if stepper.opacity else 1
text: 'ELECTRUM'
size_hint: 1, None
height: self.texture_size[1] if self.opacity else 0
font_size: '33sp'
font_name: 'data/fonts/tron/Tr2n.ttf'
Image:
id: stepper
allow_stretch: True
opacity: 0
source: 'atlas://gui/kivy/theming/light/stepper_left'
size_hint: 1, None
height: grid_logo.height/2.5 if self.opacity else 0
Widget:
size_hint: None, None
size: '5dp', '5dp'
GridLayout:
cols: 1
id: crcontent
spacing: '13dp'
<CreateRestoreDialog>
Label:
color: root.text_color
size_hint: 1, None
text_size: self.width, None
height: self.texture_size[1]
text:
_("Wallet file not found!!")+"\\n\\n" +\
_("Do you want to create a new wallet ")+\
_("or restore an existing one?")
Widget
size_hint: 1, None
height: dp(15)
GridLayout:
id: grid
orientation: 'vertical'
cols: 1
spacing: '14dp'
size_hint: 1, None
height: self.minimum_height
WizardButton:
id: create
text: _('Create a new seed')
root: root
WizardButton:
id: restore
text: _('I already have a seed')
root: root
<RestoreSeedDialog>
Label:
color: root.text_color
size_hint: 1, None
text_size: self.width, None
height: self.texture_size[1]
text: "[b]ENTER YOUR SEED PHRASE[/b]"
GridLayout
cols: 1
padding: 0, '12dp'
orientation: 'vertical'
spacing: '12dp'
size_hint: 1, None
height: self.minimum_height
WizardTextInput:
id: text_input_seed
size_hint: 1, None
height: '110dp'
hint_text:
_('Enter your seedphrase')
on_text: root._trigger_check_seed()
Label:
font_size: '12sp'
text_size: self.width, None
size_hint: 1, None
height: self.texture_size[1]
halign: 'justify'
valign: 'middle'
text: root.message
on_ref_press:
import webbrowser
webbrowser.open('https://electrum.org/faq.html#seed')
GridLayout:
rows: 1
spacing: '12dp'
size_hint: 1, None
height: self.minimum_height
WizardButton:
id: back
text: _('Back')
root: root
Button:
id: scan
text: _('QR')
on_release: root.scan_seed()
WizardButton:
id: next
text: _('Next')
root: root
<ShowSeedDialog>
spacing: '12dp'
Label:
color: root.text_color
size_hint: 1, None
text_size: self.width, None
height: self.texture_size[1]
text: "[b]PLEASE WRITE DOWN YOUR SEED PHRASE[/b]"
GridLayout:
id: grid
cols: 1
pos_hint: {'center_y': .5}
size_hint_y: None
height: dp(180)
orientation: 'vertical'
Button:
border: 4, 4, 4, 4
halign: 'justify'
valign: 'middle'
font_size: self.width/15
text_size: self.width - dp(24), self.height - dp(12)
#size_hint: 1, None
#height: self.texture_size[1] + dp(24)
color: .1, .1, .1, 1
background_normal: 'atlas://gui/kivy/theming/light/white_bg_round_top'
background_down: self.background_normal
text: root.seed_text
Label:
rows: 1
size_hint: 1, .7
id: but_seed
border: 4, 4, 4, 4
halign: 'justify'
valign: 'middle'
font_size: self.width/21
text: root.message
text_size: self.width - dp(24), self.height - dp(12)
GridLayout:
rows: 1
spacing: '12dp'
size_hint: 1, None
height: self.minimum_height
WizardButton:
id: back
text: _('Back')
root: root
WizardButton:
id: confirm
text: _('Confirm')
root: root
''')
class WizardDialog(EventsDialog):
''' Abstract dialog to be used as the base for all Create Account Dialogs
'''
crcontent = ObjectProperty(None)
def __init__(self, **kwargs):
super(WizardDialog, self).__init__(**kwargs)
self.action = kwargs.get('action')
_trigger_size_dialog = Clock.create_trigger(self._size_dialog)
Window.bind(size=_trigger_size_dialog,
rotation=_trigger_size_dialog)
_trigger_size_dialog()
Window.softinput_mode = 'pan'
def _size_dialog(self, dt):
app = App.get_running_app()
if app.ui_mode[0] == 'p':
self.size = Window.size
else:
#tablet
if app.orientation[0] == 'p':
#portrait
self.size = Window.size[0]/1.67, Window.size[1]/1.4
else:
self.size = Window.size[0]/2.5, Window.size[1]
def add_widget(self, widget, index=0):
if not self.crcontent:
super(WizardDialog, self).add_widget(widget)
else:
self.crcontent.add_widget(widget, index=index)
def on_dismiss(self):
app = App.get_running_app()
if app.wallet is None and self._on_release is not None:
print "on dismiss: stopping app"
app.stop()
else:
Window.softinput_mode = 'below_target'
class CreateRestoreDialog(WizardDialog):
''' Initial Dialog for creating or restoring seed'''
def on_parent(self, instance, value):
if value:
app = App.get_running_app()
self._back = _back = partial(app.dispatch, 'on_back')
class ShowSeedDialog(WizardDialog):
seed_text = StringProperty('')
message = StringProperty('')
def on_parent(self, instance, value):
if value:
app = App.get_running_app()
stepper = self.ids.stepper
stepper.opacity = 1
stepper.source = 'atlas://gui/kivy/theming/light/stepper_full'
self._back = _back = partial(self.ids.back.dispatch, 'on_release')
class RestoreSeedDialog(WizardDialog):
message = StringProperty('')
def __init__(self, **kwargs):
super(RestoreSeedDialog, self).__init__(**kwargs)
self._test = kwargs['test']
self._trigger_check_seed = Clock.create_trigger(self.check_seed)
def check_seed(self, dt):
self.ids.next.disabled = not bool(self._test(self.get_seed_text()))
def get_seed_text(self):
ti = self.ids.text_input_seed
text = unicode(ti.text).strip()
text = ' '.join(text.split())
return text
def scan_seed(self):
def on_complete(text):
self.ids.text_input_seed.text = text
app = App.get_running_app()
app.scan_qr(on_complete)
def on_parent(self, instance, value):
if value:
tis = self.ids.text_input_seed
tis.focus = True
tis._keyboard.bind(on_key_down=self.on_key_down)
stepper = self.ids.stepper
stepper.opacity = 1
stepper.source = ('atlas://gui/kivy/theming'
'/light/stepper_restore_seed')
self._back = _back = partial(self.ids.back.dispatch,
'on_release')
app = App.get_running_app()
#app.navigation_higherarchy.append(_back)
def on_key_down(self, keyboard, keycode, key, modifiers):
if keycode[0] in (13, 271):
self.on_enter()
return True
def on_enter(self):
#self._remove_keyboard()
# press next
next = self.ids.next
if not next.disabled:
next.dispatch('on_release')
def _remove_keyboard(self):
tis = self.ids.text_input_seed
if tis._keyboard:
tis._keyboard.unbind(on_key_down=self.on_key_down)
tis.focus = False
def close(self):
self._remove_keyboard()
app = App.get_running_app()
#if self._back in app.navigation_higherarchy:
# app.navigation_higherarchy.pop()
# self._back = None
super(RestoreSeedDialog, self).close()<|fim▁end|> | #:import Window kivy.core.window.Window
#:import _ electrum.i18n._
|
<|file_name|>RiskScatterPanel.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import os<|fim▁hole|>from Borg import Borg
import matplotlib
matplotlib.use('WXAgg')
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import \
FigureCanvasWxAgg as FigCanvas, \
NavigationToolbar2WxAgg as NavigationToolbar
def riskColourCode(riskScore):
if (riskScore <= 1):
return '#fef2ec'
elif (riskScore == 2):
return '#fcd9c8'
elif (riskScore == 3):
return '#f7ac91'
elif (riskScore == 4):
return '#f67e61'
elif (riskScore == 5):
return '#f2543d'
elif (riskScore == 6):
return '#e42626'
elif (riskScore == 7):
return '#b9051a'
elif (riskScore == 8):
return '#900014'
else:
return '#52000D'
class RiskScatterPanel(wx.Panel):
def __init__(self,parent):
wx.Panel.__init__(self,parent,armid.RISKSCATTER_ID)
b = Borg()
self.dbProxy = b.dbProxy
self.dpi = 100
self.fig = Figure((5.0, 4.0), dpi=self.dpi)
self.canvas = FigCanvas(self, -1, self.fig)
self.axes = self.fig.add_subplot(111,xlabel='Severity',ylabel='Likelihood',autoscale_on=False)
self.axes.set_xticklabels(['Marginal','Critical','Catastrophic'])
self.axes.set_yticks([0,1,2,3,4,5])
self.toolbar = NavigationToolbar(self.canvas)
envs = self.dbProxy.getDimensionNames('environment')
self.envCombo = wx.ComboBox(self,armid.RISKSCATTER_COMBOENVIRONMENT_ID,envs[0],choices=envs,size=(300,-1),style=wx.CB_DROPDOWN)
self.envCombo.Bind(wx.EVT_COMBOBOX,self.onEnvironmentChange)
self.vbox = wx.BoxSizer(wx.VERTICAL)
self.vbox.Add(self.toolbar, 0, wx.EXPAND)
self.vbox.Add(self.envCombo,0, wx.EXPAND)
self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
self.SetSizer(self.vbox)
self.vbox.Fit(self)
self.drawScatter(envs[0])
def drawScatter(self,envName):
self.axes.clear()
self.axes.grid(True)
self.axes.set_xlabel('Severity')
self.axes.set_ylabel('Likelihood')
self.axes.set_xbound(0,4)
self.axes.set_ybound(0,5)
xs,ys,cs = self.dbProxy.riskScatter(envName)
ccs = []
for c in cs:
ccs.append(riskColourCode(c))
if ((len(xs) > 0) and (len(ys) > 0)):
self.axes.scatter(xs,ys,c=ccs,marker='d')
self.canvas.draw()
def onEnvironmentChange(self,evt):
envName = self.envCombo.GetStringSelection()
self.drawScatter(envName)
def on_save_plot(self, event):
fileChoices = "PNG (*.png)|*.png"
dlg = wx.FileDialog(self,message="Save risk scatter",defaultDir=os.getcwd(),defaultFile="scatter.png",wildcard=fileChoices,style=wx.SAVE)
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
self.canvas.print_figure(path, dpi=self.dpi)<|fim▁end|> | import pprint
import random
import wx
import armid |
<|file_name|>suite.spec.js<|end_file_name|><|fim▁begin|>'use strict';
var assert = require('assert');
var run = require('./helpers').runMocha;
var args = [];
describe('suite w/no callback', function() {
it('should throw a helpful error message when a callback for suite is not supplied', function(done) {
run(
'suite/suite-no-callback.fixture.js',
args,
function(err, res) {
if (err) {
return done(err);
}
var result = res.output.match(/no callback was supplied/) || [];
assert.equal(result.length, 1);
done();
},
{stdio: 'pipe'}
);
});
});
describe('skipped suite w/no callback', function() {
it('should not throw an error when a callback for skipped suite is not supplied', function(done) {
run('suite/suite-skipped-no-callback.fixture.js', args, function(err, res) {
if (err) {
return done(err);
}
var pattern = new RegExp('Error', 'g');
var result = res.output.match(pattern) || [];
assert.equal(result.length, 0);
done();
});
});
});
describe('skipped suite w/ callback', function() {
it('should not throw an error when a callback for skipped suite is supplied', function(done) {
run('suite/suite-skipped-callback.fixture.js', args, function(err, res) {
if (err) {
return done(err);
}
var pattern = new RegExp('Error', 'g');
var result = res.output.match(pattern) || [];
assert.equal(result.length, 0);
done();
});
});
});
describe('suite returning a value', function() {
it('should give a deprecation warning for suite callback returning a value', function(done) {
run(
'suite/suite-returning-value.fixture.js',<|fim▁hole|> }
var pattern = new RegExp('Deprecation Warning', 'g');
var result = res.output.match(pattern) || [];
assert.equal(result.length, 1);
done();
},
{stdio: 'pipe'}
);
});
});<|fim▁end|> | args,
function(err, res) {
if (err) {
return done(err); |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
from __future__ import division
<|fim▁hole|><|fim▁end|> | __author__ = 'youval.dar' |
<|file_name|>CodeImpl.java<|end_file_name|><|fim▁begin|>/*******************************************************************************
* Copyright (c) 2006, 2009 David A Carlson
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David A Carlson (XMLmodeling.com) - initial API and implementation
*******************************************************************************/
package org.openhealthtools.mdht.emf.w3c.xhtml.internal.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.openhealthtools.mdht.emf.w3c.xhtml.Code;
import org.openhealthtools.mdht.emf.w3c.xhtml.MifClassType;
import org.openhealthtools.mdht.emf.w3c.xhtml.StyleSheet;
import org.openhealthtools.mdht.emf.w3c.xhtml.XhtmlPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Code</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.openhealthtools.mdht.emf.w3c.xhtml.internal.impl.CodeImpl#getClass_ <em>Class</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.w3c.xhtml.internal.impl.CodeImpl#getLang <em>Lang</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.w3c.xhtml.internal.impl.CodeImpl#getStyle <em>Style</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class CodeImpl extends InlineImpl implements Code {
/**
* The default value of the '{@link #getClass_() <em>Class</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getClass_()
* @generated
* @ordered
*/
protected static final MifClassType CLASS_EDEFAULT = MifClassType.INSERTED;
/**
* The cached value of the '{@link #getClass_() <em>Class</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getClass_()
* @generated
* @ordered
*/
protected MifClassType class_ = CLASS_EDEFAULT;
/**
* This is true if the Class attribute has been set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
protected boolean classESet;
/**
* The default value of the '{@link #getLang() <em>Lang</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLang()
* @generated
* @ordered
*/
protected static final String LANG_EDEFAULT = null;
/**
* The cached value of the '{@link #getLang() <em>Lang</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLang()
* @generated
* @ordered
*/
protected String lang = LANG_EDEFAULT;
/**
* The default value of the '{@link #getStyle() <em>Style</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getStyle()
* @generated
* @ordered
*/
protected static final StyleSheet STYLE_EDEFAULT = StyleSheet.REQUIREMENT;
/**
* The cached value of the '{@link #getStyle() <em>Style</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getStyle()
* @generated
* @ordered
*/
protected StyleSheet style = STYLE_EDEFAULT;
/**
* This is true if the Style attribute has been set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
protected boolean styleESet;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected CodeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
<|fim▁hole|> return XhtmlPackage.Literals.CODE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MifClassType getClass_() {
return class_;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setClass(MifClassType newClass) {
MifClassType oldClass = class_;
class_ = newClass == null
? CLASS_EDEFAULT
: newClass;
boolean oldClassESet = classESet;
classESet = true;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(
this, Notification.SET, XhtmlPackage.CODE__CLASS, oldClass, class_, !oldClassESet));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void unsetClass() {
MifClassType oldClass = class_;
boolean oldClassESet = classESet;
class_ = CLASS_EDEFAULT;
classESet = false;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(
this, Notification.UNSET, XhtmlPackage.CODE__CLASS, oldClass, CLASS_EDEFAULT, oldClassESet));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isSetClass() {
return classESet;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLang() {
return lang;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setLang(String newLang) {
String oldLang = lang;
lang = newLang;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, XhtmlPackage.CODE__LANG, oldLang, lang));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public StyleSheet getStyle() {
return style;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setStyle(StyleSheet newStyle) {
StyleSheet oldStyle = style;
style = newStyle == null
? STYLE_EDEFAULT
: newStyle;
boolean oldStyleESet = styleESet;
styleESet = true;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(
this, Notification.SET, XhtmlPackage.CODE__STYLE, oldStyle, style, !oldStyleESet));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void unsetStyle() {
StyleSheet oldStyle = style;
boolean oldStyleESet = styleESet;
style = STYLE_EDEFAULT;
styleESet = false;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(
this, Notification.UNSET, XhtmlPackage.CODE__STYLE, oldStyle, STYLE_EDEFAULT, oldStyleESet));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isSetStyle() {
return styleESet;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case XhtmlPackage.CODE__CLASS:
return getClass_();
case XhtmlPackage.CODE__LANG:
return getLang();
case XhtmlPackage.CODE__STYLE:
return getStyle();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case XhtmlPackage.CODE__CLASS:
setClass((MifClassType) newValue);
return;
case XhtmlPackage.CODE__LANG:
setLang((String) newValue);
return;
case XhtmlPackage.CODE__STYLE:
setStyle((StyleSheet) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case XhtmlPackage.CODE__CLASS:
unsetClass();
return;
case XhtmlPackage.CODE__LANG:
setLang(LANG_EDEFAULT);
return;
case XhtmlPackage.CODE__STYLE:
unsetStyle();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case XhtmlPackage.CODE__CLASS:
return isSetClass();
case XhtmlPackage.CODE__LANG:
return LANG_EDEFAULT == null
? lang != null
: !LANG_EDEFAULT.equals(lang);
case XhtmlPackage.CODE__STYLE:
return isSetStyle();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) {
return super.toString();
}
StringBuffer result = new StringBuffer(super.toString());
result.append(" (class: ");
if (classESet) {
result.append(class_);
} else {
result.append("<unset>");
}
result.append(", lang: ");
result.append(lang);
result.append(", style: ");
if (styleESet) {
result.append(style);
} else {
result.append("<unset>");
}
result.append(')');
return result.toString();
}
} // CodeImpl<|fim▁end|> | * @generated
*/
@Override
protected EClass eStaticClass() {
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
Implements counterwallet asset-related support as a counterblock plugin
DEPENDENCIES: This module requires the assets module to be loaded before it.
Python 2.x, as counterblock is still python 2.x
"""
import os
import sys
import time
import datetime
import logging
import decimal
import urllib.request
import urllib.parse
import urllib.error
import json
import operator
import base64
import configparser
import calendar
import pymongo
from bson.son import SON
import dateutil.parser
from counterblock.lib import config, util, blockfeed, blockchain
from counterblock.lib.modules import DEX_PRIORITY_PARSE_TRADEBOOK
from counterblock.lib.processor import MessageProcessor, MempoolMessageProcessor, BlockProcessor, StartUpProcessor, CaughtUpProcessor, RollbackProcessor, API, start_task
from . import assets_trading, dex
D = decimal.Decimal
EIGHT_PLACES = decimal.Decimal(10) ** -8
COMPILE_MARKET_PAIR_INFO_PERIOD = 10 * 60 # in seconds (this is every 10 minutes currently)
COMPILE_ASSET_MARKET_INFO_PERIOD = 30 * 60 # in seconds (this is every 30 minutes currently)
logger = logging.getLogger(__name__)
@API.add_method
def get_market_price_summary(asset1, asset2, with_last_trades=0):
# DEPRECATED 1.5
result = assets_trading.get_market_price_summary(asset1, asset2, with_last_trades)
return result if result is not None else False
#^ due to current bug in our jsonrpc stack, just return False if None is returned
@API.add_method
def get_market_cap_history(start_ts=None, end_ts=None):
now_ts = calendar.timegm(time.gmtime())
if not end_ts: # default to current datetime
end_ts = now_ts
if not start_ts: # default to 30 days before the end date
start_ts = end_ts - (30 * 24 * 60 * 60)
data = {}
results = {}
#^ format is result[market_cap_as][asset] = [[block_time, market_cap], [block_time2, market_cap2], ...]
for market_cap_as in (config.XCP, config.BTC):
caps = config.mongo_db.asset_marketcap_history.aggregate([
{"$match": {
"market_cap_as": market_cap_as,
"block_time": {
"$gte": datetime.datetime.utcfromtimestamp(start_ts)
} if end_ts == now_ts else {
"$gte": datetime.datetime.utcfromtimestamp(start_ts),
"$lte": datetime.datetime.utcfromtimestamp(end_ts)
}
}},
{"$project": {
"year": {"$year": "$block_time"},
"month": {"$month": "$block_time"},
"day": {"$dayOfMonth": "$block_time"},
"hour": {"$hour": "$block_time"},
"asset": 1,
"market_cap": 1,
}},
{"$sort": {"block_time": pymongo.ASCENDING}},
{"$group": {
"_id": {"asset": "$asset", "year": "$year", "month": "$month", "day": "$day", "hour": "$hour"},
"market_cap": {"$avg": "$market_cap"}, # use the average marketcap during the interval
}},
])
data[market_cap_as] = {}
for e in caps:
interval_time = int(calendar.timegm(datetime.datetime(e['_id']['year'], e['_id']['month'], e['_id']['day'], e['_id']['hour']).timetuple()) * 1000)
data[market_cap_as].setdefault(e['_id']['asset'], [])
data[market_cap_as][e['_id']['asset']].append([interval_time, e['market_cap']])
results[market_cap_as] = []
for asset in data[market_cap_as]:
#for z in data[market_cap_as][asset]: assert z[0] and z[0] > 0 and z[1] and z[1] >= 0
results[market_cap_as].append(
{'name': asset, 'data': sorted(data[market_cap_as][asset], key=operator.itemgetter(0))})
return results
@API.add_method
def get_market_info(assets):
assets_market_info = list(config.mongo_db.asset_market_info.find({'asset': {'$in': assets}}, {'_id': 0}))
extended_asset_info = config.mongo_db.asset_extended_info.find({'asset': {'$in': assets}})
extended_asset_info_dict = {}
for e in extended_asset_info:
if not e.get('disabled', False): # skip assets marked disabled
extended_asset_info_dict[e['asset']] = e
for a in assets_market_info:
if a['asset'] in extended_asset_info_dict and extended_asset_info_dict[a['asset']].get('processed', False):
extended_info = extended_asset_info_dict[a['asset']]
a['extended_image'] = bool(extended_info.get('image', ''))
a['extended_description'] = extended_info.get('description', '')
a['extended_website'] = extended_info.get('website', '')
a['extended_pgpsig'] = extended_info.get('pgpsig', '')
else:
a['extended_image'] = a['extended_description'] = a['extended_website'] = a['extended_pgpsig'] = ''
return assets_market_info
@API.add_method
def get_market_info_leaderboard(limit=100):
"""returns market leaderboard data for both the XCP and BTC markets"""
# do two queries because we limit by our sorted results, and we might miss an asset with a high BTC trading value
# but with little or no XCP trading activity, for instance if we just did one query
assets_market_info_xcp = list(config.mongo_db.asset_market_info.find({}, {'_id': 0}).sort('market_cap_in_{}'.format(config.XCP.lower()), pymongo.DESCENDING).limit(limit))
assets_market_info_btc = list(config.mongo_db.asset_market_info.find({}, {'_id': 0}).sort('market_cap_in_{}'.format(config.BTC.lower()), pymongo.DESCENDING).limit(limit))
assets_market_info = {
config.XCP.lower(): [a for a in assets_market_info_xcp if a['price_in_{}'.format(config.XCP.lower())]],
config.BTC.lower(): [a for a in assets_market_info_btc if a['price_in_{}'.format(config.BTC.lower())]]
}
# throw on extended info, if it exists for a given asset
assets = list(set([a['asset'] for a in assets_market_info[config.XCP.lower()]] + [a['asset'] for a in assets_market_info[config.BTC.lower()]]))
extended_asset_info = config.mongo_db.asset_extended_info.find({'asset': {'$in': assets}})
extended_asset_info_dict = {}
for e in extended_asset_info:
if not e.get('disabled', False): # skip assets marked disabled
extended_asset_info_dict[e['asset']] = e
for r in (assets_market_info[config.XCP.lower()], assets_market_info[config.BTC.lower()]):
for a in r:
if a['asset'] in extended_asset_info_dict:
extended_info = extended_asset_info_dict[a['asset']]
if 'extended_image' not in a or 'extended_description' not in a or 'extended_website' not in a:
continue # asset has been recognized as having a JSON file description, but has not been successfully processed yet
a['extended_image'] = bool(extended_info.get('image', ''))
a['extended_description'] = extended_info.get('description', '')
a['extended_website'] = extended_info.get('website', '')
else:
a['extended_image'] = a['extended_description'] = a['extended_website'] = ''
return assets_market_info
@API.add_method
def get_market_price_history(asset1, asset2, start_ts=None, end_ts=None, as_dict=False):
"""Return block-by-block aggregated market history data for the specified asset pair, within the specified date range.
@returns List of lists (or list of dicts, if as_dict is specified).
* If as_dict is False, each embedded list has 8 elements [block time (epoch in MS), open, high, low, close, volume, # trades in block, block index]
* If as_dict is True, each dict in the list has the keys: block_time (epoch in MS), block_index, open, high, low, close, vol, count
Aggregate on an an hourly basis
"""
now_ts = calendar.timegm(time.gmtime())
if not end_ts: # default to current datetime
end_ts = now_ts
if not start_ts: # default to 180 days before the end date
start_ts = end_ts - (180 * 24 * 60 * 60)
base_asset, quote_asset = util.assets_to_asset_pair(asset1, asset2)
# get ticks -- open, high, low, close, volume
result = config.mongo_db.trades.aggregate([
{"$match": {
"base_asset": base_asset,
"quote_asset": quote_asset,
"block_time": {
"$gte": datetime.datetime.utcfromtimestamp(start_ts)
} if end_ts == now_ts else {
"$gte": datetime.datetime.utcfromtimestamp(start_ts),
"$lte": datetime.datetime.utcfromtimestamp(end_ts)
}
}},
{"$project": {
"year": {"$year": "$block_time"},
"month": {"$month": "$block_time"},
"day": {"$dayOfMonth": "$block_time"},
"hour": {"$hour": "$block_time"},
"block_index": 1,
"unit_price": 1,
"base_quantity_normalized": 1 # to derive volume
}},
{"$group": {
"_id": {"year": "$year", "month": "$month", "day": "$day", "hour": "$hour"},
"open": {"$first": "$unit_price"},
"high": {"$max": "$unit_price"},
"low": {"$min": "$unit_price"},
"close": {"$last": "$unit_price"},
"vol": {"$sum": "$base_quantity_normalized"},
"count": {"$sum": 1},
}},
{"$sort": SON([("_id.year", pymongo.ASCENDING), ("_id.month", pymongo.ASCENDING), ("_id.day", pymongo.ASCENDING), ("_id.hour", pymongo.ASCENDING)])},
])
result = list(result)
if not len(result):
return False
midline = [((r['high'] + r['low']) / 2.0) for r in result]
if as_dict:
for i in range(len(result)):
result[i]['interval_time'] = int(calendar.timegm(datetime.datetime(
result[i]['_id']['year'], result[i]['_id']['month'], result[i]['_id']['day'], result[i]['_id']['hour']).timetuple()) * 1000)
result[i]['midline'] = midline[i]
del result[i]['_id']
return result
else:
list_result = []
for i in range(len(result)):
list_result.append([
int(calendar.timegm(datetime.datetime(
result[i]['_id']['year'], result[i]['_id']['month'], result[i]['_id']['day'], result[i]['_id']['hour']).timetuple()) * 1000),
result[i]['open'], result[i]['high'], result[i]['low'], result[i]['close'], result[i]['vol'],<|fim▁hole|> return list_result
@API.add_method
def get_trade_history(asset1=None, asset2=None, start_ts=None, end_ts=None, limit=50):
"""
Gets last N of trades within a specific date range (normally, for a specified asset pair, but this can
be left blank to get any/all trades).
"""
assert (asset1 and asset2) or (not asset1 and not asset2) # cannot have one asset, but not the other
if limit > 500:
raise Exception("Requesting history of too many trades")
now_ts = calendar.timegm(time.gmtime())
if not end_ts: # default to current datetime
end_ts = now_ts
if not start_ts: # default to 30 days before the end date
start_ts = end_ts - (30 * 24 * 60 * 60)
filters = {
"block_time": {
"$gte": datetime.datetime.utcfromtimestamp(start_ts)
} if end_ts == now_ts else {
"$gte": datetime.datetime.utcfromtimestamp(start_ts),
"$lte": datetime.datetime.utcfromtimestamp(end_ts)
}
}
if asset1 and asset2:
base_asset, quote_asset = util.assets_to_asset_pair(asset1, asset2)
filters["base_asset"] = base_asset
filters["quote_asset"] = quote_asset
last_trades = config.mongo_db.trades.find(filters, {'_id': 0}).sort("block_time", pymongo.DESCENDING).limit(limit)
if not last_trades.count():
return False # no suitable trade data to form a market price
last_trades = list(last_trades)
return last_trades
def _get_order_book(base_asset, quote_asset,
bid_book_min_pct_fee_provided=None, bid_book_min_pct_fee_required=None, bid_book_max_pct_fee_required=None,
ask_book_min_pct_fee_provided=None, ask_book_min_pct_fee_required=None, ask_book_max_pct_fee_required=None):
"""Gets the current order book for a specified asset pair
@param: normalized_fee_required: Only specify if buying BTC. If specified, the order book will be pruned down to only
show orders at and above this fee_required
@param: normalized_fee_provided: Only specify if selling BTC. If specified, the order book will be pruned down to only
show orders at and above this fee_provided
"""
base_asset_info = config.mongo_db.tracked_assets.find_one({'asset': base_asset})
quote_asset_info = config.mongo_db.tracked_assets.find_one({'asset': quote_asset})
if not base_asset_info or not quote_asset_info:
raise Exception("Invalid asset(s)")
# TODO: limit # results to 8 or so for each book (we have to sort as well to limit)
base_bid_filters = [
{"field": "get_asset", "op": "==", "value": base_asset},
{"field": "give_asset", "op": "==", "value": quote_asset},
]
base_ask_filters = [
{"field": "get_asset", "op": "==", "value": quote_asset},
{"field": "give_asset", "op": "==", "value": base_asset},
]
if base_asset == config.BTC or quote_asset == config.BTC:
extra_filters = [
{'field': 'give_remaining', 'op': '>', 'value': 0}, # don't show empty BTC orders
{'field': 'get_remaining', 'op': '>', 'value': 0}, # don't show empty BTC orders
{'field': 'fee_required_remaining', 'op': '>=', 'value': 0},
{'field': 'fee_provided_remaining', 'op': '>=', 'value': 0},
]
base_bid_filters += extra_filters
base_ask_filters += extra_filters
base_bid_orders = util.call_jsonrpc_api(
"get_orders", {
'filters': base_bid_filters,
'show_expired': False,
'status': 'open',
'order_by': 'block_index',
'order_dir': 'asc',
}, abort_on_error=True)['result']
base_ask_orders = util.call_jsonrpc_api(
"get_orders", {
'filters': base_ask_filters,
'show_expired': False,
'status': 'open',
'order_by': 'block_index',
'order_dir': 'asc',
}, abort_on_error=True)['result']
def get_o_pct(o):
if o['give_asset'] == config.BTC: # NB: fee_provided could be zero here
pct_fee_provided = float((D(o['fee_provided_remaining']) / D(o['give_quantity'])))
else:
pct_fee_provided = None
if o['get_asset'] == config.BTC: # NB: fee_required could be zero here
pct_fee_required = float((D(o['fee_required_remaining']) / D(o['get_quantity'])))
else:
pct_fee_required = None
return pct_fee_provided, pct_fee_required
# filter results by pct_fee_provided and pct_fee_required for BTC pairs as appropriate
filtered_base_bid_orders = []
filtered_base_ask_orders = []
if base_asset == config.BTC or quote_asset == config.BTC:
for o in base_bid_orders:
pct_fee_provided, pct_fee_required = get_o_pct(o)
addToBook = True
if bid_book_min_pct_fee_provided is not None and pct_fee_provided is not None and pct_fee_provided < bid_book_min_pct_fee_provided:
addToBook = False
if bid_book_min_pct_fee_required is not None and pct_fee_required is not None and pct_fee_required < bid_book_min_pct_fee_required:
addToBook = False
if bid_book_max_pct_fee_required is not None and pct_fee_required is not None and pct_fee_required > bid_book_max_pct_fee_required:
addToBook = False
if addToBook:
filtered_base_bid_orders.append(o)
for o in base_ask_orders:
pct_fee_provided, pct_fee_required = get_o_pct(o)
addToBook = True
if ask_book_min_pct_fee_provided is not None and pct_fee_provided is not None and pct_fee_provided < ask_book_min_pct_fee_provided:
addToBook = False
if ask_book_min_pct_fee_required is not None and pct_fee_required is not None and pct_fee_required < ask_book_min_pct_fee_required:
addToBook = False
if ask_book_max_pct_fee_required is not None and pct_fee_required is not None and pct_fee_required > ask_book_max_pct_fee_required:
addToBook = False
if addToBook:
filtered_base_ask_orders.append(o)
else:
filtered_base_bid_orders += base_bid_orders
filtered_base_ask_orders += base_ask_orders
def make_book(orders, isBidBook):
book = {}
for o in orders:
if o['give_asset'] == base_asset:
if base_asset == config.BTC and o['give_quantity'] <= config.ORDER_BTC_DUST_LIMIT_CUTOFF:
continue # filter dust orders, if necessary
give_quantity = blockchain.normalize_quantity(o['give_quantity'], base_asset_info['divisible'])
get_quantity = blockchain.normalize_quantity(o['get_quantity'], quote_asset_info['divisible'])
unit_price = float((D(get_quantity) / D(give_quantity)))
remaining = blockchain.normalize_quantity(o['give_remaining'], base_asset_info['divisible'])
else:
if quote_asset == config.BTC and o['give_quantity'] <= config.ORDER_BTC_DUST_LIMIT_CUTOFF:
continue # filter dust orders, if necessary
give_quantity = blockchain.normalize_quantity(o['give_quantity'], quote_asset_info['divisible'])
get_quantity = blockchain.normalize_quantity(o['get_quantity'], base_asset_info['divisible'])
unit_price = float((D(give_quantity) / D(get_quantity)))
remaining = blockchain.normalize_quantity(o['get_remaining'], base_asset_info['divisible'])
id = "%s_%s_%s" % (base_asset, quote_asset, unit_price)
#^ key = {base}_{bid}_{unit_price}, values ref entries in book
book.setdefault(id, {'unit_price': unit_price, 'quantity': 0, 'count': 0})
book[id]['quantity'] += remaining # base quantity outstanding
book[id]['count'] += 1 # num orders at this price level
book = sorted(iter(book.values()), key=operator.itemgetter('unit_price'), reverse=isBidBook)
#^ convert to list and sort -- bid book = descending, ask book = ascending
return book
# compile into a single book, at volume tiers
base_bid_book = make_book(filtered_base_bid_orders, True)
base_ask_book = make_book(filtered_base_ask_orders, False)
# get stats like the spread and median
if base_bid_book and base_ask_book:
# don't do abs(), as this is "the amount by which the ask price exceeds the bid", so I guess it could be negative
# if there is overlap in the book (right?)
bid_ask_spread = float((D(base_ask_book[0]['unit_price']) - D(base_bid_book[0]['unit_price'])))
bid_ask_median = float((D(max(base_ask_book[0]['unit_price'], base_bid_book[0]['unit_price'])) - (D(abs(bid_ask_spread)) / 2)))
else:
bid_ask_spread = 0
bid_ask_median = 0
# compose depth and round out quantities
bid_depth = D(0)
for o in base_bid_book:
o['quantity'] = float(D(o['quantity']))
bid_depth += D(o['quantity'])
o['depth'] = float(D(bid_depth))
bid_depth = float(D(bid_depth))
ask_depth = D(0)
for o in base_ask_book:
o['quantity'] = float(D(o['quantity']))
ask_depth += D(o['quantity'])
o['depth'] = float(D(ask_depth))
ask_depth = float(D(ask_depth))
# compose raw orders
orders = filtered_base_bid_orders + filtered_base_ask_orders
for o in orders:
# add in the blocktime to help makes interfaces more user-friendly (i.e. avoid displaying block
# indexes and display datetimes instead)
o['block_time'] = calendar.timegm(util.get_block_time(o['block_index']).timetuple()) * 1000
result = {
'base_bid_book': base_bid_book,
'base_ask_book': base_ask_book,
'bid_depth': bid_depth,
'ask_depth': ask_depth,
'bid_ask_spread': bid_ask_spread,
'bid_ask_median': bid_ask_median,
'raw_orders': orders,
'base_asset': base_asset,
'quote_asset': quote_asset
}
return result
@API.add_method
def get_order_book_simple(asset1, asset2, min_pct_fee_provided=None, max_pct_fee_required=None):
# DEPRECATED 1.5
base_asset, quote_asset = util.assets_to_asset_pair(asset1, asset2)
result = _get_order_book(
base_asset, quote_asset,
bid_book_min_pct_fee_provided=min_pct_fee_provided,
bid_book_max_pct_fee_required=max_pct_fee_required,
ask_book_min_pct_fee_provided=min_pct_fee_provided,
ask_book_max_pct_fee_required=max_pct_fee_required)
return result
@API.add_method
def get_order_book_buysell(buy_asset, sell_asset, pct_fee_provided=None, pct_fee_required=None):
# DEPRECATED 1.5
base_asset, quote_asset = util.assets_to_asset_pair(buy_asset, sell_asset)
bid_book_min_pct_fee_provided = None
bid_book_min_pct_fee_required = None
bid_book_max_pct_fee_required = None
ask_book_min_pct_fee_provided = None
ask_book_min_pct_fee_required = None
ask_book_max_pct_fee_required = None
if base_asset == config.BTC:
if buy_asset == config.BTC:
# if BTC is base asset and we're buying it, we're buying the BASE. we require a BTC fee (we're on the bid (bottom) book and we want a lower price)
# - show BASE buyers (bid book) that require a BTC fee >= what we require (our side of the book)
# - show BASE sellers (ask book) that provide a BTC fee >= what we require
bid_book_min_pct_fee_required = pct_fee_required # my competition at the given fee required
ask_book_min_pct_fee_provided = pct_fee_required
elif sell_asset == config.BTC:
# if BTC is base asset and we're selling it, we're selling the BASE. we provide a BTC fee (we're on the ask (top) book and we want a higher price)
# - show BASE buyers (bid book) that provide a BTC fee >= what we provide
# - show BASE sellers (ask book) that require a BTC fee <= what we provide (our side of the book)
bid_book_max_pct_fee_required = pct_fee_provided
ask_book_min_pct_fee_provided = pct_fee_provided # my competition at the given fee provided
elif quote_asset == config.BTC:
assert base_asset == config.XCP # only time when this is the case
if buy_asset == config.BTC:
# if BTC is quote asset and we're buying it, we're selling the BASE. we require a BTC fee (we're on the ask (top) book and we want a higher price)
# - show BASE buyers (bid book) that provide a BTC fee >= what we require
# - show BASE sellers (ask book) that require a BTC fee >= what we require (our side of the book)
bid_book_min_pct_fee_provided = pct_fee_required
ask_book_min_pct_fee_required = pct_fee_required # my competition at the given fee required
elif sell_asset == config.BTC:
# if BTC is quote asset and we're selling it, we're buying the BASE. we provide a BTC fee (we're on the bid (bottom) book and we want a lower price)
# - show BASE buyers (bid book) that provide a BTC fee >= what we provide (our side of the book)
# - show BASE sellers (ask book) that require a BTC fee <= what we provide
bid_book_min_pct_fee_provided = pct_fee_provided # my compeitition at the given fee provided
ask_book_max_pct_fee_required = pct_fee_provided
result = _get_order_book(
base_asset, quote_asset,
bid_book_min_pct_fee_provided=bid_book_min_pct_fee_provided,
bid_book_min_pct_fee_required=bid_book_min_pct_fee_required,
bid_book_max_pct_fee_required=bid_book_max_pct_fee_required,
ask_book_min_pct_fee_provided=ask_book_min_pct_fee_provided,
ask_book_min_pct_fee_required=ask_book_min_pct_fee_required,
ask_book_max_pct_fee_required=ask_book_max_pct_fee_required)
# filter down raw_orders to be only open sell orders for what the caller is buying
open_sell_orders = []
for o in result['raw_orders']:
if o['give_asset'] == buy_asset:
open_sell_orders.append(o)
result['raw_orders'] = open_sell_orders
return result
@API.add_method
def get_users_pairs(addresses=[], max_pairs=12):
return dex.get_users_pairs(addresses, max_pairs, quote_assets=[config.XCP, config.XBTC])
@API.add_method
def get_market_orders(asset1, asset2, addresses=[], min_fee_provided=0.95, max_fee_required=0.95):
return dex.get_market_orders(asset1, asset2, addresses, None, min_fee_provided, max_fee_required)
@API.add_method
def get_market_trades(asset1, asset2, addresses=[], limit=50):
return dex.get_market_trades(asset1, asset2, addresses, limit)
@API.add_method
def get_markets_list(quote_asset=None, order_by=None):
return dex.get_markets_list(quote_asset=quote_asset, order_by=order_by)
@API.add_method
def get_market_details(asset1, asset2, min_fee_provided=0.95, max_fee_required=0.95):
return dex.get_market_details(asset1, asset2, min_fee_provided, max_fee_required)
def task_compile_asset_pair_market_info():
assets_trading.compile_asset_pair_market_info()
# all done for this run...call again in a bit
start_task(task_compile_asset_pair_market_info, delay=COMPILE_MARKET_PAIR_INFO_PERIOD)
def task_compile_asset_market_info():
assets_trading.compile_asset_market_info()
# all done for this run...call again in a bit
start_task(task_compile_asset_market_info, delay=COMPILE_ASSET_MARKET_INFO_PERIOD)
@MessageProcessor.subscribe(priority=DEX_PRIORITY_PARSE_TRADEBOOK)
def parse_trade_book(msg, msg_data):
# book trades
if(msg['category'] == 'order_matches' and
((msg['command'] == 'update' and msg_data['status'] == 'completed') or # for a trade with BTC involved, but that is settled (completed)
('forward_asset' in msg_data and msg_data['forward_asset'] != config.BTC and msg_data['backward_asset'] != config.BTC)
)
): # or for a trade without BTC on either end
if msg['command'] == 'update' and msg_data['status'] == 'completed':
# an order is being updated to a completed status (i.e. a BTCpay has completed)
tx0_hash, tx1_hash = msg_data['order_match_id'][:64], msg_data['order_match_id'][65:]
# get the order_match this btcpay settles
order_match = util.jsonrpc_api(
"get_order_matches",
{'filters': [
{'field': 'tx0_hash', 'op': '==', 'value': tx0_hash},
{'field': 'tx1_hash', 'op': '==', 'value': tx1_hash}]
}, abort_on_error=False)['result'][0]
else:
assert msg_data['status'] == 'completed' # should not enter a pending state for non BTC matches
order_match = msg_data
forward_asset_info = config.mongo_db.tracked_assets.find_one({'asset': order_match['forward_asset']})
backward_asset_info = config.mongo_db.tracked_assets.find_one({'asset': order_match['backward_asset']})
assert forward_asset_info and backward_asset_info
base_asset, quote_asset = util.assets_to_asset_pair(order_match['forward_asset'], order_match['backward_asset'])
# don't create trade records from order matches with BTC that are under the dust limit
if((order_match['forward_asset'] == config.BTC and
order_match['forward_quantity'] <= config.ORDER_BTC_DUST_LIMIT_CUTOFF)
or (order_match['backward_asset'] == config.BTC and
order_match['backward_quantity'] <= config.ORDER_BTC_DUST_LIMIT_CUTOFF)):
logger.debug("Order match %s ignored due to %s under dust limit." % (order_match['tx0_hash'] + order_match['tx1_hash'], config.BTC))
return 'ABORT_THIS_MESSAGE_PROCESSING'
# take divisible trade quantities to floating point
forward_quantity = blockchain.normalize_quantity(order_match['forward_quantity'], forward_asset_info['divisible'])
backward_quantity = blockchain.normalize_quantity(order_match['backward_quantity'], backward_asset_info['divisible'])
# compose trade
trade = {
'block_index': config.state['cur_block']['block_index'],
'block_time': config.state['cur_block']['block_time_obj'],
'message_index': msg['message_index'], # secondary temporaral ordering off of when
'order_match_id': order_match['tx0_hash'] + '_' + order_match['tx1_hash'],
'order_match_tx0_index': order_match['tx0_index'],
'order_match_tx1_index': order_match['tx1_index'],
'order_match_tx0_address': order_match['tx0_address'],
'order_match_tx1_address': order_match['tx1_address'],
'base_asset': base_asset,
'quote_asset': quote_asset,
'base_quantity': order_match['forward_quantity'] if order_match['forward_asset'] == base_asset else order_match['backward_quantity'],
'quote_quantity': order_match['backward_quantity'] if order_match['forward_asset'] == base_asset else order_match['forward_quantity'],
'base_quantity_normalized': forward_quantity if order_match['forward_asset'] == base_asset else backward_quantity,
'quote_quantity_normalized': backward_quantity if order_match['forward_asset'] == base_asset else forward_quantity,
}
d = D(trade['quote_quantity_normalized']) / D(trade['base_quantity_normalized'])
d = d.quantize(EIGHT_PLACES, rounding=decimal.ROUND_HALF_EVEN, context=decimal.Context(prec=30))
trade['unit_price'] = float(d)
d = D(trade['base_quantity_normalized']) / D(trade['quote_quantity_normalized'])
d = d.quantize(EIGHT_PLACES, rounding=decimal.ROUND_HALF_EVEN, context=decimal.Context(prec=30))
trade['unit_price_inverse'] = float(d)
config.mongo_db.trades.insert(trade)
logger.info("Procesed Trade from tx %s :: %s" % (msg['message_index'], trade))
@StartUpProcessor.subscribe()
def init():
# init db and indexes
# trades
config.mongo_db.trades.ensure_index(
[("base_asset", pymongo.ASCENDING),
("quote_asset", pymongo.ASCENDING),
("block_time", pymongo.DESCENDING)
])
config.mongo_db.trades.ensure_index( # tasks.py and elsewhere (for singlular block_index index access)
[("block_index", pymongo.ASCENDING),
("base_asset", pymongo.ASCENDING),
("quote_asset", pymongo.ASCENDING)
])
# asset_market_info
config.mongo_db.asset_market_info.ensure_index('asset', unique=True)
# asset_marketcap_history
config.mongo_db.asset_marketcap_history.ensure_index('block_index')
config.mongo_db.asset_marketcap_history.ensure_index( # tasks.py
[
("market_cap_as", pymongo.ASCENDING),
("asset", pymongo.ASCENDING),
("block_index", pymongo.DESCENDING)
])
config.mongo_db.asset_marketcap_history.ensure_index( # api.py
[
("market_cap_as", pymongo.ASCENDING),
("block_time", pymongo.DESCENDING)
])
# asset_pair_market_info
config.mongo_db.asset_pair_market_info.ensure_index( # event.py, api.py
[("base_asset", pymongo.ASCENDING),
("quote_asset", pymongo.ASCENDING)
], unique=True)
config.mongo_db.asset_pair_market_info.ensure_index('last_updated')
@CaughtUpProcessor.subscribe()
def start_tasks():
start_task(task_compile_asset_pair_market_info)
start_task(task_compile_asset_market_info)
@RollbackProcessor.subscribe()
def process_rollback(max_block_index):
if not max_block_index: # full reparse
config.mongo_db.trades.drop()
config.mongo_db.asset_market_info.drop()
config.mongo_db.asset_marketcap_history.drop()
config.mongo_db.pair_market_info.drop()
else: # rollback
config.mongo_db.trades.remove({"block_index": {"$gt": max_block_index}})
config.mongo_db.asset_marketcap_history.remove({"block_index": {"$gt": max_block_index}})<|fim▁end|> | result[i]['count'], midline[i]
]) |
<|file_name|>mutations.js<|end_file_name|><|fim▁begin|>export default {
cache: function (state, payload) {
state.apiCache[payload.api_url] = payload.api_response;
},
addConfiguredType: function (state, type) {
state.configuredTypes.push(type);
},
removeConfiguredType: function (state, index) {
state.configuredTypes.splice(index, 1);
},
updateConfiguredType: function (state, type) {
for (var i = 0, len = state.configuredTypes.length; i < len; i++) {
if (state.configuredTypes[i].name === type.name) {<|fim▁hole|> return;
}
}
},
setBaseExtraFormTypes: function (state, types) {
state.baseTypes = types;
},
setConfiguredExtraFormTypes: function (state, types) {
state.configuredTypes = types;
}
};<|fim▁end|> | state.configuredTypes.splice(i, 1);
state.configuredTypes.push(type);
// Avoid too keep looping over a spliced array |
<|file_name|>not_understood.rs<|end_file_name|><|fim▁begin|>use crate::messages::Message;
use serde_derive::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct NotUnderstood {
pub path: Vec<String>,
}
impl Message for NotUnderstood {
fn name(&self) -> String {
String::from("NOT_UNDERSTOOD")
}
}
impl PartialEq for NotUnderstood {
fn eq(&self, other: &Self) -> bool {
self.path == other.path
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_name() {
// Arrange
let message = NotUnderstood { path: vec![] };
// Act
let name = message.name();
// Assert
assert_eq!(name, "NOT_UNDERSTOOD");
}
#[test]
fn test_asoutgoing() {
// Arrange
let message = NotUnderstood { path: vec![] };
let message_ref = message.clone();
// Act
let outgoing = message.as_outgoing();
<|fim▁hole|> assert_eq!(outgoing.content, message_ref);
}
}<|fim▁end|> | // Assert
assert_eq!(outgoing.result_type, "NOT_UNDERSTOOD"); |
<|file_name|>ScrollText.cpp<|end_file_name|><|fim▁begin|>// ScrollText.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "ScrollText.h"
#include "ScrollTextDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CScrollTextApp
BEGIN_MESSAGE_MAP(CScrollTextApp, CWinApp)
<|fim▁hole|> // NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CScrollTextApp construction
CScrollTextApp::CScrollTextApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CScrollTextApp object
CScrollTextApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CScrollTextApp initialization
BOOL CScrollTextApp::InitInstance()
{
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
CScrollTextDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}<|fim▁end|> | //{{AFX_MSG_MAP(CScrollTextApp)
|
<|file_name|>macros.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#[macro_export]
macro_rules! make_getter(
( $attr:ident, $htmlname:tt ) => (
fn $attr(&self) -> DOMString {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
let element = self.upcast::<Element>();
element.get_string_attribute(&local_name!($htmlname))
}
);
);
#[macro_export]
macro_rules! make_bool_getter(
( $attr:ident, $htmlname:tt ) => (
fn $attr(&self) -> bool {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
let element = self.upcast::<Element>();
element.has_attribute(&local_name!($htmlname))
}
);
);
#[macro_export]
macro_rules! make_limited_int_setter(
($attr:ident, $htmlname:tt, $default:expr) => (
fn $attr(&self, value: i32) -> $crate::dom::bindings::error::ErrorResult {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
let value = if value < 0 {
return Err($crate::dom::bindings::error::Error::IndexSize);
} else {
value
};
let element = self.upcast::<Element>();
element.set_int_attribute(&local_name!($htmlname), value);
Ok(())
}
);
);
#[macro_export]
macro_rules! make_int_setter(
($attr:ident, $htmlname:tt, $default:expr) => (
fn $attr(&self, value: i32) {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
let element = self.upcast::<Element>();
element.set_int_attribute(&local_name!($htmlname), value)
}
);
($attr:ident, $htmlname:tt) => {
make_int_setter!($attr, $htmlname, 0);
};
);
#[macro_export]
macro_rules! make_int_getter(
($attr:ident, $htmlname:tt, $default:expr) => (
fn $attr(&self) -> i32 {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
let element = self.upcast::<Element>();
element.get_int_attribute(&local_name!($htmlname), $default)
}
);
($attr:ident, $htmlname:tt) => {
make_int_getter!($attr, $htmlname, 0);
};
);
#[macro_export]
macro_rules! make_uint_getter(
($attr:ident, $htmlname:tt, $default:expr) => (
fn $attr(&self) -> u32 {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
let element = self.upcast::<Element>();
element.get_uint_attribute(&local_name!($htmlname), $default)
}
);
($attr:ident, $htmlname:tt) => {
make_uint_getter!($attr, $htmlname, 0);
};
);
#[macro_export]
macro_rules! make_url_getter(
( $attr:ident, $htmlname:tt ) => (
fn $attr(&self) -> DOMString {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
let element = self.upcast::<Element>();
element.get_url_attribute(&local_name!($htmlname))
}
);
);
#[macro_export]
macro_rules! make_form_action_getter(
( $attr:ident, $htmlname:tt ) => (
fn $attr(&self) -> DOMString {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
let element = self.upcast::<Element>();
let doc = ::dom::node::document_from_node(self);
let attr = element.get_attribute(&ns!(), &local_name!($htmlname));
let value = attr.as_ref().map(|attr| attr.value());
let value = match value {
Some(ref value) if !value.is_empty() => &***value,
_ => return doc.url().into_string().into(),
};
match doc.base_url().join(value) {
Ok(parsed) => parsed.into_string().into(),
Err(_) => value.to_owned().into(),
}
}
);
);
#[macro_export]
macro_rules! make_enumerated_getter(
( $attr:ident, $htmlname:tt, $default:expr, $($choices: pat)|+) => (
fn $attr(&self) -> DOMString {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
use std::ascii::AsciiExt;
let element = self.upcast::<Element>();
let mut val = element.get_string_attribute(&local_name!($htmlname));
val.make_ascii_lowercase();
// https://html.spec.whatwg.org/multipage/#attr-fs-method
match &*val {
$($choices)|+ => val,
_ => DOMString::from($default)
}
}
);
);
// concat_idents! doesn't work for function name positions, so
// we have to specify both the content name and the HTML name here
#[macro_export]
macro_rules! make_setter(
( $attr:ident, $htmlname:tt ) => (
fn $attr(&self, value: DOMString) {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
let element = self.upcast::<Element>();
element.set_string_attribute(&local_name!($htmlname), value)
}
);
);
#[macro_export]
macro_rules! make_bool_setter(
( $attr:ident, $htmlname:tt ) => (
fn $attr(&self, value: bool) {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
let element = self.upcast::<Element>();
element.set_bool_attribute(&local_name!($htmlname), value)
}
);
);
#[macro_export]
macro_rules! make_url_setter(
( $attr:ident, $htmlname:tt ) => (
fn $attr(&self, value: DOMString) {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
let element = self.upcast::<Element>();
element.set_url_attribute(&local_name!($htmlname), value);
}
);
);
#[macro_export]
macro_rules! make_uint_setter(
($attr:ident, $htmlname:tt, $default:expr) => (
fn $attr(&self, value: u32) {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
use dom::values::UNSIGNED_LONG_MAX;
let value = if value > UNSIGNED_LONG_MAX {
$default
} else {
value
};
let element = self.upcast::<Element>();
element.set_uint_attribute(&local_name!($htmlname), value)
}
);
($attr:ident, $htmlname:tt) => {
make_uint_setter!($attr, $htmlname, 0);
};
);
#[macro_export]
macro_rules! make_limited_uint_setter(
($attr:ident, $htmlname:tt, $default:expr) => (
fn $attr(&self, value: u32) -> $crate::dom::bindings::error::ErrorResult {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
use dom::values::UNSIGNED_LONG_MAX;
let value = if value == 0 {
return Err($crate::dom::bindings::error::Error::IndexSize);
} else if value > UNSIGNED_LONG_MAX {
$default
} else {
value
};
let element = self.upcast::<Element>();
element.set_uint_attribute(&local_name!($htmlname), value);
Ok(())
}
);
($attr:ident, $htmlname:tt) => {
make_limited_uint_setter!($attr, $htmlname, 1);
};
);
#[macro_export]
macro_rules! make_atomic_setter(
( $attr:ident, $htmlname:tt ) => (
fn $attr(&self, value: DOMString) {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
let element = self.upcast::<Element>();
element.set_atomic_attribute(&local_name!($htmlname), value)
}
);
);
#[macro_export]
macro_rules! make_legacy_color_setter(
( $attr:ident, $htmlname:tt ) => (
fn $attr(&self, value: DOMString) {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
use style::attr::AttrValue;
let element = self.upcast::<Element>();
let value = AttrValue::from_legacy_color(value.into());
element.set_attribute(&local_name!($htmlname), value)
}
);
);
#[macro_export]
macro_rules! make_dimension_setter(
( $attr:ident, $htmlname:tt ) => (
fn $attr(&self, value: DOMString) {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
let element = self.upcast::<Element>();
let value = AttrValue::from_dimension(value.into());
element.set_attribute(&local_name!($htmlname), value)
}
);
);
#[macro_export]
macro_rules! make_nonzero_dimension_setter(
( $attr:ident, $htmlname:tt ) => (
fn $attr(&self, value: DOMString) {
use dom::bindings::inheritance::Castable;
use dom::element::Element;
let element = self.upcast::<Element>();
let value = AttrValue::from_nonzero_dimension(value.into());
element.set_attribute(&local_name!($htmlname), value)
}
);
);
/// For use on non-jsmanaged types
/// Use #[derive(JSTraceable)] on JS managed types
macro_rules! unsafe_no_jsmanaged_fields(
($($ty:ty),+) => (
$(
#[allow(unsafe_code)]
unsafe impl $crate::dom::bindings::trace::JSTraceable for $ty {
#[inline]
unsafe fn trace(&self, _: *mut ::js::jsapi::JSTracer) {
// Do nothing
}
}
)+
);
);
macro_rules! jsmanaged_array(
($count:expr) => (
#[allow(unsafe_code)]
unsafe impl<T> $crate::dom::bindings::trace::JSTraceable for [T; $count]
where T: $crate::dom::bindings::trace::JSTraceable
{
#[inline]
unsafe fn trace(&self, tracer: *mut ::js::jsapi::JSTracer) {
for v in self.iter() {
v.trace(tracer);
}
}
}
);
);
/// These are used to generate a event handler which has no special case.
macro_rules! define_event_handler(
($handler: ty, $event_type: ident, $getter: ident, $setter: ident, $setter_fn: ident) => (
fn $getter(&self) -> Option<::std::rc::Rc<$handler>> {
use dom::bindings::inheritance::Castable;
use dom::eventtarget::EventTarget;
let eventtarget = self.upcast::<EventTarget>();
eventtarget.get_event_handler_common(stringify!($event_type))
}
fn $setter(&self, listener: Option<::std::rc::Rc<$handler>>) {
use dom::bindings::inheritance::Castable;
use dom::eventtarget::EventTarget;
let eventtarget = self.upcast::<EventTarget>();
eventtarget.$setter_fn(stringify!($event_type), listener)
}
)
);
macro_rules! define_window_owned_event_handler(
($handler: ty, $event_type: ident, $getter: ident, $setter: ident) => (
fn $getter(&self) -> Option<::std::rc::Rc<$handler>> {
let document = document_from_node(self);
if document.has_browsing_context() {
document.window().$getter()
} else {
None
}
}
fn $setter(&self, listener: Option<::std::rc::Rc<$handler>>) {
let document = document_from_node(self);
if document.has_browsing_context() {
document.window().$setter(listener)
}
}
)
);
macro_rules! event_handler(
($event_type: ident, $getter: ident, $setter: ident) => (
define_event_handler!(
::dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull,
$event_type,
$getter,
$setter,
set_event_handler_common
);
)
);
macro_rules! error_event_handler(
($event_type: ident, $getter: ident, $setter: ident) => (
define_event_handler!(
::dom::bindings::codegen::Bindings::EventHandlerBinding::OnErrorEventHandlerNonNull,
$event_type,
$getter,
$setter,
set_error_event_handler
);
)
);
macro_rules! beforeunload_event_handler(
($event_type: ident, $getter: ident, $setter: ident) => (
define_event_handler!(
::dom::bindings::codegen::Bindings::EventHandlerBinding::OnBeforeUnloadEventHandlerNonNull,
$event_type,
$getter,
$setter,
set_beforeunload_event_handler
);
)
);
macro_rules! window_owned_event_handler(
($event_type: ident, $getter: ident, $setter: ident) => (
define_window_owned_event_handler!(
::dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull,
$event_type,
$getter,
$setter
);
)
);
macro_rules! window_owned_beforeunload_event_handler(
($event_type: ident, $getter: ident, $setter: ident) => (
define_window_owned_event_handler!(
::dom::bindings::codegen::Bindings::EventHandlerBinding::OnBeforeUnloadEventHandlerNonNull,
$event_type,
$getter,
$setter
);
)
);
// https://html.spec.whatwg.org/multipage/#globaleventhandlers
// see webidls/EventHandler.webidl
// As more methods get added, just update them here.
macro_rules! global_event_handlers(
() => (
event_handler!(blur, GetOnblur, SetOnblur);
event_handler!(focus, GetOnfocus, SetOnfocus);
event_handler!(load, GetOnload, SetOnload);
event_handler!(resize, GetOnresize, SetOnresize);
event_handler!(scroll, GetOnscroll, SetOnscroll);
global_event_handlers!(NoOnload);
);
(NoOnload) => (
event_handler!(abort, GetOnabort, SetOnabort);
event_handler!(cancel, GetOncancel, SetOncancel);
event_handler!(canplay, GetOncanplay, SetOncanplay);
event_handler!(canplaythrough, GetOncanplaythrough, SetOncanplaythrough);
event_handler!(change, GetOnchange, SetOnchange);
event_handler!(click, GetOnclick, SetOnclick);
event_handler!(close, GetOnclose, SetOnclose);
event_handler!(contextmenu, GetOncontextmenu, SetOncontextmenu);
event_handler!(cuechange, GetOncuechange, SetOncuechange);
event_handler!(dblclick, GetOndblclick, SetOndblclick);
event_handler!(drag, GetOndrag, SetOndrag);
event_handler!(dragend, GetOndragend, SetOndragend);
event_handler!(dragenter, GetOndragenter, SetOndragenter);
event_handler!(dragexit, GetOndragexit, SetOndragexit);
event_handler!(dragleave, GetOndragleave, SetOndragleave);
event_handler!(dragover, GetOndragover, SetOndragover);
event_handler!(dragstart, GetOndragstart, SetOndragstart);
event_handler!(drop, GetOndrop, SetOndrop);
event_handler!(durationchange, GetOndurationchange, SetOndurationchange);
event_handler!(emptied, GetOnemptied, SetOnemptied);
event_handler!(ended, GetOnended, SetOnended);
error_event_handler!(error, GetOnerror, SetOnerror);
event_handler!(input, GetOninput, SetOninput);
event_handler!(invalid, GetOninvalid, SetOninvalid);
event_handler!(keydown, GetOnkeydown, SetOnkeydown);
event_handler!(keypress, GetOnkeypress, SetOnkeypress);
event_handler!(keyup, GetOnkeyup, SetOnkeyup);
event_handler!(loadeddata, GetOnloadeddata, SetOnloadeddata);
event_handler!(loadedmetata, GetOnloadedmetadata, SetOnloadedmetadata);
event_handler!(loadstart, GetOnloadstart, SetOnloadstart);
event_handler!(mousedown, GetOnmousedown, SetOnmousedown);
event_handler!(mouseenter, GetOnmouseenter, SetOnmouseenter);
event_handler!(mouseleave, GetOnmouseleave, SetOnmouseleave);
event_handler!(mousemove, GetOnmousemove, SetOnmousemove);
event_handler!(mouseout, GetOnmouseout, SetOnmouseout);
event_handler!(mouseover, GetOnmouseover, SetOnmouseover);
event_handler!(mouseup, GetOnmouseup, SetOnmouseup);
event_handler!(wheel, GetOnwheel, SetOnwheel);
event_handler!(pause, GetOnpause, SetOnpause);
event_handler!(play, GetOnplay, SetOnplay);
event_handler!(playing, GetOnplaying, SetOnplaying);
event_handler!(progress, GetOnprogress, SetOnprogress);
event_handler!(ratechange, GetOnratechange, SetOnratechange);
event_handler!(reset, GetOnreset, SetOnreset);
event_handler!(seeked, GetOnseeked, SetOnseeked);
event_handler!(seeking, GetOnseeking, SetOnseeking);
event_handler!(select, GetOnselect, SetOnselect);
event_handler!(show, GetOnshow, SetOnshow);
event_handler!(stalled, GetOnstalled, SetOnstalled);
event_handler!(submit, GetOnsubmit, SetOnsubmit);
event_handler!(suspend, GetOnsuspend, SetOnsuspend);
event_handler!(timeupdate, GetOntimeupdate, SetOntimeupdate);
event_handler!(toggle, GetOntoggle, SetOntoggle);
event_handler!(transitionend, GetOntransitionend, SetOntransitionend);
event_handler!(volumechange, GetOnvolumechange, SetOnvolumechange);
event_handler!(waiting, GetOnwaiting, SetOnwaiting);
)
);
// https://html.spec.whatwg.org/multipage/#windoweventhandlers
// see webidls/EventHandler.webidl
// As more methods get added, just update them here.
macro_rules! window_event_handlers(
() => (
event_handler!(afterprint, GetOnafterprint, SetOnafterprint);
event_handler!(beforeprint, GetOnbeforeprint, SetOnbeforeprint);
beforeunload_event_handler!(beforeunload, GetOnbeforeunload,
SetOnbeforeunload);
event_handler!(hashchange, GetOnhashchange, SetOnhashchange);
event_handler!(languagechange, GetOnlanguagechange,
SetOnlanguagechange);
event_handler!(message, GetOnmessage, SetOnmessage);
event_handler!(offline, GetOnoffline, SetOnoffline);
event_handler!(online, GetOnonline, SetOnonline);
event_handler!(pagehide, GetOnpagehide, SetOnpagehide);
event_handler!(pageshow, GetOnpageshow, SetOnpageshow);
event_handler!(popstate, GetOnpopstate, SetOnpopstate);
event_handler!(rejectionhandled, GetOnrejectionhandled,
SetOnrejectionhandled);
event_handler!(storage, GetOnstorage, SetOnstorage);
event_handler!(unhandledrejection, GetOnunhandledrejection,
SetOnunhandledrejection);
event_handler!(unload, GetOnunload, SetOnunload);
event_handler!(vrdisplayconnect, GetOnvrdisplayconnect, SetOnvrdisplayconnect);
event_handler!(vrdisplaydisconnect, GetOnvrdisplaydisconnect, SetOnvrdisplaydisconnect);
event_handler!(vrdisplayactivate, GetOnvrdisplayactivate, SetOnvrdisplayactivate);
event_handler!(vrdisplaydeactivate, GetOnvrdisplaydeactivate, SetOnvrdisplaydeactivate);
event_handler!(vrdisplayblur, GetOnvrdisplayblur, SetOnvrdisplayblur);
event_handler!(vrdisplayfocus, GetOnvrdisplayfocus, SetOnvrdisplayfocus);
event_handler!(vrdisplaypresentchange, GetOnvrdisplaypresentchange, SetOnvrdisplaypresentchange);
);
(ForwardToWindow) => (
window_owned_event_handler!(afterprint, GetOnafterprint,
SetOnafterprint);
window_owned_event_handler!(beforeprint, GetOnbeforeprint,
SetOnbeforeprint);
window_owned_beforeunload_event_handler!(beforeunload,
GetOnbeforeunload,
SetOnbeforeunload);
window_owned_event_handler!(hashchange, GetOnhashchange,
SetOnhashchange);
window_owned_event_handler!(languagechange, GetOnlanguagechange,
SetOnlanguagechange);
window_owned_event_handler!(message, GetOnmessage, SetOnmessage);
window_owned_event_handler!(offline, GetOnoffline, SetOnoffline);
window_owned_event_handler!(online, GetOnonline, SetOnonline);
window_owned_event_handler!(pagehide, GetOnpagehide, SetOnpagehide);
window_owned_event_handler!(pageshow, GetOnpageshow, SetOnpageshow);
window_owned_event_handler!(popstate, GetOnpopstate, SetOnpopstate);
window_owned_event_handler!(rejectionhandled, GetOnrejectionhandled,
SetOnrejectionhandled);
window_owned_event_handler!(storage, GetOnstorage, SetOnstorage);
window_owned_event_handler!(unhandledrejection, GetOnunhandledrejection,
SetOnunhandledrejection);
window_owned_event_handler!(unload, GetOnunload, SetOnunload);
window_owned_event_handler!(vrdisplayconnect, GetOnvrdisplayconnect, SetOnvrdisplayconnect);
window_owned_event_handler!(vrdisplaydisconnect, GetOnvrdisplaydisconnect, SetOnvrdisplaydisconnect);
window_owned_event_handler!(vrdisplayactivate, GetOnvrdisplayactivate, SetOnvrdisplayactivate);
window_owned_event_handler!(vrdisplaydeactivate, GetOnvrdisplaydeactivate, SetOnvrdisplaydeactivate);
window_owned_event_handler!(vrdisplayblur, GetOnvrdisplayblur, SetOnvrdisplayblur);
window_owned_event_handler!(vrdisplayfocus, GetOnvrdisplayfocus, SetOnvrdisplayfocus);
window_owned_event_handler!(vrdisplaypresentchange, GetOnvrdisplaypresentchange, SetOnvrdisplaypresentchange);
);
);
// https://html.spec.whatwg.org/multipage/#documentandelementeventhandlers
// see webidls/EventHandler.webidl
// As more methods get added, just update them here.
macro_rules! document_and_element_event_handlers(
() => (
event_handler!(cut, GetOncut, SetOncut);
event_handler!(copy, GetOncopy, SetOncopy);
event_handler!(paste, GetOnpaste, SetOnpaste);
)
);
#[macro_export]
macro_rules! rooted_vec {
(let mut $name:ident) => {
let mut root = $crate::dom::bindings::trace::RootableVec::new_unrooted();<|fim▁hole|> let mut root = $crate::dom::bindings::trace::RootableVec::new_unrooted();
let $name = $crate::dom::bindings::trace::RootedVec::from_iter(&mut root, $iter);
};
(let mut $name:ident <- $iter:expr) => {
let mut root = $crate::dom::bindings::trace::RootableVec::new_unrooted();
let mut $name = $crate::dom::bindings::trace::RootedVec::from_iter(&mut root, $iter);
}
}
/// DOM struct implementation for simple interfaces inheriting from PerformanceEntry.
macro_rules! impl_performance_entry_struct(
($binding:ident, $struct:ident, $type:expr) => (
use dom::bindings::codegen::Bindings::$binding;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString;
use dom::globalscope::GlobalScope;
use dom::performanceentry::PerformanceEntry;
use dom_struct::dom_struct;
#[dom_struct]
pub struct $struct {
entry: PerformanceEntry,
}
impl $struct {
fn new_inherited(name: DOMString, start_time: f64, duration: f64)
-> $struct {
$struct {
entry: PerformanceEntry::new_inherited(name,
DOMString::from($type),
start_time,
duration)
}
}
#[allow(unrooted_must_root)]
pub fn new(global: &GlobalScope,
name: DOMString,
start_time: f64,
duration: f64) -> DomRoot<$struct> {
let entry = $struct::new_inherited(name, start_time, duration);
reflect_dom_object(Box::new(entry), global, $binding::Wrap)
}
}
);
);<|fim▁end|> | let mut $name = $crate::dom::bindings::trace::RootedVec::new(&mut root);
};
(let $name:ident <- $iter:expr) => { |
<|file_name|>scalar.rs<|end_file_name|><|fim▁begin|>use std::cmp;
use std::fmt;
use std::ops;
use num;
use math::common::LinearInterpolate;
pub type IntScalar = i32;
#[cfg(not(feature = "float64"))]
pub type FloatScalar = f32;
#[cfg(feature = "float64")]<|fim▁hole|> Self: Copy + Clone + fmt::Debug + cmp::PartialOrd,
Self: num::Num + num::NumCast + num::ToPrimitive,
Self: ops::AddAssign + ops::SubAssign + ops::MulAssign + ops::DivAssign {}
pub trait BaseFloat: BaseNum + num::Float + num::Signed {}
pub trait BaseInt: BaseNum {}
impl BaseNum for i8 {}
impl BaseNum for i16 {}
impl BaseNum for i32 {}
impl BaseNum for i64 {}
impl BaseNum for isize {}
impl BaseNum for u8 {}
impl BaseNum for u16 {}
impl BaseNum for u32 {}
impl BaseNum for u64 {}
impl BaseNum for usize {}
impl BaseNum for f32 {}
impl BaseNum for f64 {}
impl BaseInt for i8 {}
impl BaseInt for i16 {}
impl BaseInt for i32 {}
impl BaseInt for i64 {}
impl BaseInt for isize {}
impl BaseInt for u8 {}
impl BaseInt for u16 {}
impl BaseInt for u32 {}
impl BaseInt for u64 {}
impl BaseInt for usize {}
impl BaseFloat for f32 {}
impl BaseFloat for f64 {}
pub fn partial_min<T: cmp::PartialOrd>(a: T, b: T) -> T {
if a < b {
a
} else {
b
}
}
pub fn partial_max<T: cmp::PartialOrd>(a: T, b: T) -> T {
if a > b {
a
} else {
b
}
}
impl LinearInterpolate for f32 {
type Scalar = f32;
}
impl LinearInterpolate for f64 {
type Scalar = f64;
}<|fim▁end|> | pub type FloatScalar = f64;
pub trait BaseNum where |
<|file_name|>Init.cpp<|end_file_name|><|fim▁begin|>/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2016 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#include "Init.hpp"
#include <curl/curl.h>
void
Net::Initialise()
{
curl_global_init(CURL_GLOBAL_WIN32);
}
void
Net::Deinitialise()<|fim▁hole|> curl_global_cleanup();
}<|fim▁end|> | { |
<|file_name|>i386_apple_ios.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your<|fim▁hole|>use super::apple_ios_base::{opts, Arch};
pub fn target() -> Target {
Target {
data_layout: "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16\
-i32:32:32-i64:32:64\
-f32:32:32-f64:32:64-v64:64:64\
-v128:128:128-a:0:64-f80:128:128\
-n8:16:32".to_string(),
llvm_target: "i386-apple-ios".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
arch: "x86".to_string(),
target_os: "ios".to_string(),
target_env: "".to_string(),
options: opts(Arch::I386)
}
}<|fim▁end|> | // option. This file may not be copied, modified, or distributed
// except according to those terms.
use target::Target; |
<|file_name|>CorporateActionRate21.go<|end_file_name|><|fim▁begin|>package iso20022
// Specifies rate details.
type CorporateActionRate21 struct {
// Quantity of additional intermediate securities/new equities awarded for a given quantity of securities derived from subscription.
AdditionalQuantityForSubscribedResultantSecurities *RatioFormat3Choice `xml:"AddtlQtyForSbcbdRsltntScties,omitempty"`
// Quantity of additional securities for a given quantity of underlying securities where underlying securities are not exchanged or debited, for example, 1 for 1: 1 new equity credited for every 1 underlying equity = 2 resulting equities.
AdditionalQuantityForExistingSecurities *RatioFormat3Choice `xml:"AddtlQtyForExstgScties,omitempty"`
// Quantity of new securities for a given quantity of underlying securities, where the underlying securities will be exchanged or debited, for example, 2 for 1: 2 new equities credited for every 1 underlying equity debited = 2 resulting equities.
NewToOld *RatioFormat4Choice `xml:"NewToOd,omitempty"`
}
func (c *CorporateActionRate21) AddAdditionalQuantityForSubscribedResultantSecurities() *RatioFormat3Choice {
c.AdditionalQuantityForSubscribedResultantSecurities = new(RatioFormat3Choice)
return c.AdditionalQuantityForSubscribedResultantSecurities
}
func (c *CorporateActionRate21) AddAdditionalQuantityForExistingSecurities() *RatioFormat3Choice {
c.AdditionalQuantityForExistingSecurities = new(RatioFormat3Choice)
return c.AdditionalQuantityForExistingSecurities<|fim▁hole|>func (c *CorporateActionRate21) AddNewToOld() *RatioFormat4Choice {
c.NewToOld = new(RatioFormat4Choice)
return c.NewToOld
}<|fim▁end|> | }
|
<|file_name|>frames.py<|end_file_name|><|fim▁begin|>from collections import OrderedDict as odict
from values import decode_kv_pairs, encode_kv_pairs
from loops import decode_loops, encode_loops<|fim▁hole|>def split_frames(lines):
'''
splits a list of lines into lines that are not part of a frame,
and a list of lines, where each list is part of the same frame.
frames start with a `save_` and end with a `stop_`. They also
end with the next data block, but this function is only called
with lines from a single data block.
'''
def parse_frame_name(line):
return line.split()[0][len('save_'):]
def frame_starts(line):
return line.startswith('save_')
def frame_stops(line):
return line.startswith('stop_')
outer = []
frame = None
frames = odict()
for line in lines:
if frame_stops(line):
frame = None
elif frame_starts(line):
name = parse_frame_name(line, 'save_')
if name not in frames:
frames[name] = []
frame = frames[name]
elif frame is None:
outer.append(line)
else:
frame.append(line)
return outer, frames
def decode_frames(lines):
outer, frames = split_frames(lines)
for key in frames:
frames[key] = decode_frame(frames[key])
return outer, frames
def decode_frame(lines):
outer, loops = decode_loops(lines)
frame = decode_kv_pairs(outer)
for key in loops:
frame[key] = loops[key]
return frame
def encode_frames(block):
def block_frames(block):
return [(k, block[k]) for k in block if isinstance(block[k], dict)]
lines = []
for name, frame in block_frames(block):
lines.append('save_%s' % name)
lines.append(encode_frame(frame))
lines.append('stop_')
return '\n'.join(lines)
def encode_frame(frame):
lines = []
lines.append(encode_kv_pairs(frame))
lines.append(encode_loops(frame))
return '\n'.join(lines)<|fim▁end|> | |
<|file_name|>test_03_filter6.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#encoding:utf8
#
# file: filter6_tests.py
# author: sl0
# date: 2013-03-06
#
import unittest
from adm6.filter6 import IP6_Filter, Ip6_Filter_Rule
from sys import stdout
from os.path import expanduser as homedir
from ipaddr import IPv6Network
from os import getenv as get_env
home_dir_replacement = get_env("HOME")
rule = {}
class Ip6_Filter_Rule_tests(unittest.TestCase):
"""
some tests for class Ip6_Filter_Rule
"""
def test_01_create_Filter_Rule(self):
"""
fr-01 create Filter_Rule object
"""
my_err = False
try:
f = Ip6_Filter_Rule(rule)
except:
my_err = True
self.assertFalse(my_err)
self.assertFalse(f['i_am_d'])
self.assertFalse(f['i_am_s'])
self.assertFalse(f['travers'])
self.assertFalse(f['insec'])
self.assertFalse(f['noif'])
self.assertFalse(f['nonew'])
self.assertFalse(f['nostate'])
self.assertEqual(f['sport'], u'1024:')
self.assertEqual(['Rule-Nr', 'Pair-Nr', 'RuleText'], f.CommentList)
self.assertEqual(['Output', 'debuglevel'], f.NeverDisplay)
displaylist = ['Rule-Nr', 'Pair-Nr', 'System-Name', 'System-Forward',
'OS', 'Asymmetric', 'RuleText', 'Source', 'Destin', 'Protocol',
'sport', 'dport', 'Action', 'nonew', 'noif', 'nostate', 'insec',
'i_am_s', 'i_am_d', 'travers', 'source-if', 'source-rn',
'src-linklocal', 'src-multicast', 'destin-if', 'destin-rn',
'dst-linklocal', 'dst-multicast', ]
self.assertEqual(displaylist, f.DisplayList)
#f['debuglevel'] = True
#print f
def test_02_produce_for_invalid_os_name(self):
"""
fr-02 produce for invalid os name
"""
my_err = False
try:
fr = Ip6_Filter_Rule(rule)
except:
my_err = True
fr['OS'] = 'Invalid os name'
self.assertRaises(ValueError, fr.produce ,stdout)
def test_03_produce_for_linux_as_traversed(self):
"""
fr-03 produce for linux as traversed host
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "22"
fr['System-Forward'] = True
fr['i_am_s'] = False
fr['i_am_d'] = False
fr['travers'] = True
fr['source-if'] = "eth0"
fr['destin-if'] = "eth1"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'Debian'
except:
my_err = True
fr.produce(ofile)
expect = """/sbin/ip6tables -A forward_new -i eth0 -s 2001:db8:1::1 -d 2001:db8:2::1 -p tcp --sport 1024: --dport 22 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT -m comment --comment "1,1"
/sbin/ip6tables -A forward_new -i eth1 -d 2001:db8:1::1 -s 2001:db8:2::1 -p tcp --dport 1024: --sport 22 -m state --state ESTABLISHED,RELATED -j ACCEPT -m comment --comment "1,1"
echo -n ".";"""
print "M:", fr.msg
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_04_produce_for_openbsd(self):
"""
fr-04 produce for OpenBSD
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "22"
fr['System-Forward'] = True
fr['i_am_s'] = False
fr['i_am_d'] = False
fr['travers'] = True
fr['source-if'] = "eth0"
fr['destin-if'] = "eth0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'OpenBSD'
except:
my_err = True
fr.produce(ofile)
expect = "# OpenBSD implementation _not_ ready!"
#expect = """# n o t y e t i m p l e m e n t e d !"""
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_05_produce_for_bsd(self):
"""
fr-05 produce for BSD
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "22"
fr['System-Forward'] = True
fr['i_am_s'] = False
fr['i_am_d'] = False
fr['travers'] = True
fr['source-if'] = "eth0"
fr['destin-if'] = "eth0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'BSD'
except:
my_err = True
fr.produce(ofile)
expect = "# IPF is n o t y e t i m p l e m e n t e d !"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_06_produce_for_opensolaris(self):
"""
fr-06 produce for OpenSolaris
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "22"
fr['System-Forward'] = True
fr['i_am_s'] = False
fr['i_am_d'] = False
fr['travers'] = True
fr['source-if'] = "eth0"
fr['destin-if'] = "eth0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'OpenSolaris'
except:
my_err = True
fr.produce(ofile)
expect = "# IPF is n o t y e t i m p l e m e n t e d !"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_07_produce_for_wxp(self):
"""
fr-07 produce for WXP
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "22"
fr['System-Forward'] = True
fr['i_am_s'] = False
fr['i_am_d'] = False
fr['travers'] = True
fr['source-if'] = "eth0"
fr['destin-if'] = "eth0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'Win-XP-SP3'
except:
my_err = True
fr.produce(ofile)
expect = "# System should not forward until redesigned"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_08_repr_with_debuglevel(self):
"""
fr-08 repr with debuglevel
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "22"
fr['System-Forward'] = True
fr['i_am_s'] = False
fr['i_am_d'] = False
fr['travers'] = True
fr['source-if'] = "eth0"
fr['destin-if'] = "eth0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'Debian'
except:
my_err = True
fr.produce(ofile)
fr['debuglevel'] = True
value = str(fr)
print "V:", value
expect = """# Rule-Nr : 1 #
# Pair-Nr : 1 #
# System-Forward : True #
# OS : Debian #
# Source : 2001:db8:1::1 #
# Destin : 2001:db8:2::1 #
# Protocol : tcp #
# sport : 1024: #
# dport : 22 #
# Action : accept #
# nonew : False #
# noif : False #
# nostate : False #
# insec : False #
# i_am_s : False #
# i_am_d : False #
# travers : True #
# source-if : eth0 #
# src-linklocal : False #
# destin-if : eth0 #
# dst-linklocal : False #
"""
self.assertEquals(expect, value)
def test_09_repr_without_debuglevel(self):
"""
fr-09 repr without debuglevel
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "22"
fr['System-Forward'] = True
fr['i_am_s'] = False
fr['i_am_d'] = False
fr['travers'] = True
fr['source-if'] = "eth0"
fr['destin-if'] = "eth0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'Debian'
except:
my_err = True
fr.produce(ofile)
fr['debuglevel'] = False
fr['Abrakadabra'] = True
value = str(fr)
print "V:", value
expect = """# Rule-Nr : 1 #
# Pair-Nr : 1 #
# Abrakadabra : True #
"""
self.assertEquals(expect, value)
def test_10_produce_for_linux_as_source(self):
"""
fr-10 produce for linux as source host
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "22"
fr['System-Forward'] = True
fr['i_am_s'] = True
fr['travers'] = False
fr['source-if'] = "eth0"
fr['destin-if'] = "eth1"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'Debian'
except:
my_err = True
fr.produce(ofile)
expect = """/sbin/ip6tables -A output__new -o eth1 -s 2001:db8:1::1 -d 2001:db8:2::1 -p tcp --sport 1024: --dport 22 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT -m comment --comment "1,1"
/sbin/ip6tables -A input___new -i eth1 -d 2001:db8:1::1 -s 2001:db8:2::1 -p tcp --dport 1024: --sport 22 -m state --state ESTABLISHED,RELATED -j ACCEPT -m comment --comment "1,1"
echo -n ".";"""
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_11_produce_for_linux_as_source_icmpv6(self):
"""
fr-11 produce for linux as source host icmpv6
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "icmpv6"
fr['dport'] = "echo-request"
fr['System-Forward'] = True
fr['i_am_s'] = True
fr['travers'] = False
fr['noif'] = True
fr['source-if'] = "eth0"
fr['destin-if'] = "eth1"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'Debian'
except:
my_err = True
fr.produce(ofile)
expect = """/sbin/ip6tables -A output__new -s 2001:db8:1::1 -d 2001:db8:2::1 -p icmpv6 --icmpv6-type echo-request -j ACCEPT -m comment --comment "1,1"\necho -n ".";"""
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_12_produce_for_linux_as_source_nonew(self):
"""
fr-12 produce for linux as source host nonew
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "21"
fr['nonew'] = True
fr['System-Forward'] = True
fr['i_am_s'] = True
fr['travers'] = False
fr['source-if'] = "eth0"
fr['destin-if'] = "eth1"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'Debian'
except:
my_err = True
fr.produce(ofile)
expect = """/sbin/ip6tables -A output__new -o eth1 -s 2001:db8:1::1 -d 2001:db8:2::1 -p tcp --sport 1024: --dport 21 -m state --state ESTABLISHED,RELATED -j ACCEPT -m comment --comment "1,1"
/sbin/ip6tables -A input___new -i eth1 -d 2001:db8:1::1 -s 2001:db8:2::1 -p tcp --dport 1024: --sport 21 -m state --state ESTABLISHED,RELATED -j ACCEPT -m comment --comment "1,1"
echo -n ".";"""
print fr.msg
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_13_produce_for_linux_as_dest(self):
"""
fr-13 produce for linux as dest host
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "22"
fr['System-Forward'] = True
fr['i_am_s'] = False
fr['i_am_d'] = True
fr['travers'] = False
fr['source-if'] = "eth0"
fr['destin-if'] = "eth0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'Debian'
except:
my_err = True
fr.produce(ofile)
expect = """/sbin/ip6tables -A input___new -i eth0 -s 2001:db8:1::1 -d 2001:db8:2::1 -p tcp --sport 1024: --dport 22 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT -m comment --comment "1,1"
/sbin/ip6tables -A output__new -o eth0 -d 2001:db8:1::1 -s 2001:db8:2::1 -p tcp --dport 1024: --sport 22 -m state --state ESTABLISHED,RELATED -j ACCEPT -m comment --comment "1,1"
echo -n ".";"""
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_14_produce_for_linux_as_traversed(self):
"""
fr-14 produce for linux as traversed host
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "22"
fr['System-Forward'] = True
fr['i_am_s'] = False
fr['i_am_d'] = False
fr['travers'] = True
fr['source-if'] = "eth0"
fr['destin-if'] = "eth1"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'Debian'
except:
my_err = True
fr.produce(ofile)
expect = """/sbin/ip6tables -A forward_new -i eth0 -s 2001:db8:1::1 -d 2001:db8:2::1 -p tcp --sport 1024: --dport 22 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT -m comment --comment "1,1"
/sbin/ip6tables -A forward_new -i eth1 -d 2001:db8:1::1 -s 2001:db8:2::1 -p tcp --dport 1024: --sport 22 -m state --state ESTABLISHED,RELATED -j ACCEPT -m comment --comment "1,1"
echo -n ".";"""
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_15_produce_for_linux_as_traversed_reject(self):
"""
fr-15 produce for linux reject rule
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "reject"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "22"
fr['System-Forward'] = True
fr['i_am_s'] = False
fr['i_am_d'] = False
fr['travers'] = True
fr['source-if'] = "eth0"
fr['destin-if'] = "eth1"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'Debian'
except:
my_err = True
fr.produce(ofile)
expect = """/sbin/ip6tables -A forward_new -i eth0 -s 2001:db8:1::1 -d 2001:db8:2::1 -p tcp --sport 1024: --dport 22 -m state --state NEW,ESTABLISHED,RELATED -j REJECT -m comment --comment "1,1"
/sbin/ip6tables -A forward_new -i eth1 -d 2001:db8:1::1 -s 2001:db8:2::1 -p tcp --dport 1024: --sport 22 -m state --state ESTABLISHED,RELATED -j REJECT -m comment --comment "1,1"
echo -n ".";"""
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_16_produce_for_linux_as_traversed_drop(self):
"""
fr-16 produce for linux drop rule
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "drop"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "22"
fr['System-Forward'] = True
fr['i_am_s'] = False
fr['i_am_d'] = False
fr['travers'] = True
fr['source-if'] = "eth0"
fr['destin-if'] = "eth1"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'Debian'
except:
my_err = True
fr.produce(ofile)
expect = """/sbin/ip6tables -A forward_new -i eth0 -s 2001:db8:1::1 -d 2001:db8:2::1 -p tcp --sport 1024: --dport 22 -m state --state NEW,ESTABLISHED,RELATED -j DROP -m comment --comment "1,1"
/sbin/ip6tables -A forward_new -i eth1 -d 2001:db8:1::1 -s 2001:db8:2::1 -p tcp --dport 1024: --sport 22 -m state --state ESTABLISHED,RELATED -j DROP -m comment --comment "1,1"
echo -n ".";"""
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_17_produce_for_linux_as_traversed_insec(self):
"""
fr-17 produce for linux accept rule insec
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "22"
fr['insec'] = True
fr['System-Forward'] = True
fr['i_am_s'] = False
fr['i_am_d'] = False
fr['travers'] = True
fr['source-if'] = "eth0"
fr['destin-if'] = "eth1"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'Debian'
except:
my_err = True
fr.produce(ofile)
expect = """/sbin/ip6tables -A forward_new -i eth0 -s 2001:db8:1::1 -d 2001:db8:2::1 -p tcp --sport 0: --dport 22 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT -m comment --comment "1,1"
/sbin/ip6tables -A forward_new -i eth1 -d 2001:db8:1::1 -s 2001:db8:2::1 -p tcp --dport 0: --sport 22 -m state --state ESTABLISHED,RELATED -j ACCEPT -m comment --comment "1,1"
echo -n ".";"""
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_18_produce_for_linux_ip6(self):
"""
fr-18 produce for linux ip6 accept rule
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "ip6"
fr['dport'] = "all"
fr['System-Forward'] = True
fr['i_am_s'] = False
fr['i_am_d'] = False
fr['travers'] = True
fr['source-if'] = "eth0"
fr['destin-if'] = "eth0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'Debian'
except:
my_err = True
fr.produce(ofile)
expect = """/sbin/ip6tables -A forward_new -i eth0 -s 2001:db8:1::1 -d 2001:db8:2::1 -j ACCEPT -m comment --comment "1,1"
echo -n ".";"""
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_19_produce_for_linux_ip6_forced(self):
"""
fr-19 produce for linux ip6 forced accept rule
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"<|fim▁hole|> fr['forced'] = True
fr['i_am_s'] = True
fr['i_am_d'] = True
fr['travers'] = True
fr['noif'] = True
fr['nostate'] = True
fr['source-if'] = "eth0"
fr['destin-if'] = "eth0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'Debian'
except:
my_err = True
fr.produce(ofile)
expect = """/sbin/ip6tables -A output__new -s 2001:db8:1::1 -d 2001:db8:2::1 -j ACCEPT -m comment --comment "1,1"
echo -n ".";/sbin/ip6tables -A input___new -s 2001:db8:1::1 -d 2001:db8:2::1 -j ACCEPT -m comment --comment "1,1"
echo -n ".";/sbin/ip6tables -A forward_new -s 2001:db8:1::1 -d 2001:db8:2::1 -j ACCEPT -m comment --comment "1,1"
echo -n ".";"""
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_20_produce_for_linux_forward_forbidden(self):
"""
fr-20 produce for linux ip6 forward forbidden
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "ip6"
fr['dport'] = "all"
fr['System-Forward'] = False
fr['forced'] = False
fr['i_am_s'] = False
fr['i_am_d'] = False
fr['travers'] = True
fr['noif'] = True
fr['nostate'] = True
fr['source-if'] = "eth0"
fr['destin-if'] = "eth0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'Debian'
except:
my_err = True
fr.produce(ofile)
expect = """# System-Forward: False ==> no rule generated"""
self.maxDiff = None
#print "M:", fr.msg
self.assertEquals(expect, fr.msg)
def test_21_produce_for_linux_forward_linklocal(self):
"""
fr-21 produce for linux forward linklocal
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 1
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "fe80::e:db8:1:1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "ip6"
fr['dport'] = "all"
fr['System-Forward'] = True
fr['forced'] = False
fr['i_am_s'] = False
fr['i_am_d'] = False
fr['travers'] = True
fr['source-if'] = "eth0"
fr['destin-if'] = "eth0"
fr['src-linklocal'] = True
fr['dst-linklocal'] = False
fr['OS'] = 'Debian'
except:
my_err = True
fr.produce(ofile)
expect = "# link-local ==> no forward"
self.maxDiff = None
#print "M:", fr.msg
self.assertEquals(expect, fr.msg)
def test_22_produce_for_openbsd_icmpv6(self):
"""
fr-22 produce for OpenBSD icmpv6
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 11
fr['Pair-Nr'] = 1
fr['Protocol'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "icmpv6"
fr['dport'] = "echo-request"
fr['System-Forward'] = True
fr['i_am_s'] = True
fr['i_am_d'] = False
fr['travers'] = False
fr['source-if'] = "sis0"
fr['destin-if'] = "sis0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'OpenBSD'
except:
my_err = True
fr.produce(ofile)
expect = "# OpenBSD implementation _not_ ready!"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_23_produce_for_openbsd_tcp_nonew(self):
"""
fr-23 produce for OpenBSD tcp nonew
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 11
fr['Pair-Nr'] = 1
fr['Action'] = "reject"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "4711"
fr['nonew'] = True
fr['System-Forward'] = True
fr['i_am_s'] = True
fr['i_am_d'] = False
fr['travers'] = False
fr['source-if'] = "sis0"
fr['destin-if'] = "sis0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'OpenBSD'
except:
my_err = True
fr.produce(ofile)
expect = "# OpenBSD implementation _not_ ready!"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_24_produce_for_openbsd_tcp_drop(self):
"""
fr-24 produce for OpenBSD tcp drop
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 11
fr['Pair-Nr'] = 1
fr['Action'] = "deny"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "4711"
fr['insec'] = True
fr['System-Forward'] = True
fr['i_am_s'] = True
fr['i_am_d'] = False
fr['travers'] = False
fr['source-if'] = "sis0"
fr['destin-if'] = "sis0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'OpenBSD'
except:
my_err = True
fr.produce(ofile)
expect = "# OpenBSD implementation _not_ ready!"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_25_produce_for_openbsd_ip6(self):
"""
fr-25 produce for OpenBSD ip6
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 11
fr['Pair-Nr'] = 1
fr['Action'] = "deny"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "ip6"
fr['dport'] = "all"
fr['System-Forward'] = True
fr['i_am_s'] = True
fr['i_am_d'] = False
fr['travers'] = False
fr['source-if'] = "sis0"
fr['destin-if'] = "sis0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'OpenBSD'
except:
my_err = True
fr.produce(ofile)
expect = "# OpenBSD implementation _not_ ready!"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_26_produce_for_openbsd_commented(self):
"""
fr-26 produce for OpenBSD commented
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 11
fr['Pair-Nr'] = 1
fr['Action'] = "deny"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "ip6"
fr['dport'] = "all"
fr['System-Forward'] = True
fr['i_am_s'] = True
fr['i_am_d'] = False
fr['travers'] = False
fr['source-if'] = "sis0"
fr['destin-if'] = "sis0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'OpenBSD'
except:
my_err = True
fr.produce_OpenBSD(ofile, True)
expect = "# OpenBSD implementation _not_ ready!"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_27_produce_for_openbsd_commented(self):
"""
fr-27 produce for OpenBSD forward forbidden
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 11
fr['Pair-Nr'] = 1
fr['Action'] = "deny"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "0:"
fr['System-Forward'] = False
fr['i_am_s'] = False
fr['i_am_d'] = False
fr['travers'] = True
fr['source-if'] = "sis0"
fr['destin-if'] = "sis0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'OpenBSD'
except:
my_err = True
fr.produce_OpenBSD(ofile, False)
expect = "# System does not forward by configuration"
#expect = "# OpenBSD implementation _not_ ready!"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_28_produce_for_openbsd_noif(self):
"""
fr-28 produce for OpenBSD forward noif
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 11
fr['Pair-Nr'] = 1
fr['Action'] = "deny"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "0:"
fr['noif'] = True
fr['System-Forward'] = True
fr['i_am_s'] = True
fr['i_am_d'] = False
fr['travers'] = False
fr['source-if'] = "sis0"
fr['destin-if'] = "sis0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'OpenBSD'
except:
my_err = True
fr.produce_OpenBSD(ofile, False)
expect = "# OpenBSD implementation _not_ ready!"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_29_produce_for_openbsd_dst_linklocal(self):
"""
fr-29 produce for OpenBSD forward dst-link-local
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 11
fr['Pair-Nr'] = 1
fr['Action'] = "deny"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "0:"
fr['noif'] = True
fr['System-Forward'] = True
fr['i_am_s'] = True
fr['i_am_d'] = False
fr['travers'] = False
fr['source-if'] = "sis0"
fr['destin-if'] = "sis0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = True
fr['OS'] = 'OpenBSD'
except:
my_err = True
fr.produce_OpenBSD(ofile, False)
expect = "# dst-link-local ==> no filter rule generated"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_30_produce_for_wxp_tcp(self):
"""
fr-30 produce for wxp tcp
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 11
fr['Pair-Nr'] = 1
fr['Action'] = "deny"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "0:"
fr['noif'] = True
fr['System-Forward'] = True
fr['i_am_s'] = True
fr['i_am_d'] = False
fr['travers'] = False
fr['source-if'] = "sis0"
fr['destin-if'] = "sis0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'winxp3'
except:
my_err = True
fr.produce_wxpsp3(ofile, False)
expect = "# WXP-SP3 n o t y e t r e a d y !"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_31_produce_for_wxp_icmpv6(self):
"""
fr-31 produce for wxp icmpv6
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 11
fr['Pair-Nr'] = 1
fr['Action'] = "deny"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "icmpv6"
fr['dport'] = "echo-request"
fr['noif'] = False
fr['System-Forward'] = True
fr['i_am_s'] = True
fr['i_am_d'] = False
fr['travers'] = False
fr['source-if'] = "sis0"
fr['destin-if'] = "sis0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'winxp3'
except:
my_err = True
fr.produce_wxpsp3(ofile, False)
expect = "# WXP-SP3 n o t y e t r e a d y !"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_32_produce_for_wxp_nonew(self):
"""
fr-32 produce for wxp nonew
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 11
fr['Pair-Nr'] = 1
fr['Action'] = "deny"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "25"
fr['nonew'] = True
fr['System-Forward'] = True
fr['i_am_s'] = True
fr['i_am_d'] = False
fr['travers'] = False
fr['source-if'] = "sis0"
fr['destin-if'] = "sis0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'winxp3'
except:
my_err = True
fr.produce_wxpsp3(ofile, False)
expect = "# WXP-SP3 n o t y e t r e a d y !"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_33_produce_for_wxp_reject_insec(self):
"""
fr-33 produce for wxp reject insec
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 11
fr['Pair-Nr'] = 1
fr['Action'] = "reject"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "tcp"
fr['dport'] = "25"
fr['insec'] = True
fr['System-Forward'] = True
fr['i_am_s'] = True
fr['i_am_d'] = False
fr['travers'] = False
fr['source-if'] = "sis0"
fr['destin-if'] = "sis0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'winxp3'
except:
my_err = True
fr.produce_wxpsp3(ofile, False)
expect = "# WXP-SP3 n o t y e t r e a d y !"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_34_produce_for_wxp_ip6_commented(self):
"""
fr-34 produce for wxp ip6 commented
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 11
fr['Pair-Nr'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "ip6"
fr['dport'] = "all"
fr['insec'] = False
fr['System-Forward'] = True
fr['i_am_s'] = True
fr['i_am_d'] = False
fr['travers'] = False
fr['source-if'] = "sis0"
fr['destin-if'] = "sis0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'winxp3'
except:
my_err = True
fr.produce_wxpsp3(ofile, True)
expect = "# WXP-SP3 n o t y e t r e a d y !"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_34_produce_for_wxp_ip6_commented(self):
"""
fr-34 produce for wxp ip6 commented
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 11
fr['Pair-Nr'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "ip6"
fr['dport'] = "all"
fr['insec'] = False
fr['System-Forward'] = False
fr['i_am_s'] = False
fr['i_am_d'] = False
fr['travers'] = True
fr['source-if'] = "sis0"
fr['destin-if'] = "sis0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = False
fr['OS'] = 'winxp3'
except:
my_err = True
fr.produce_wxpsp3(ofile, True)
expect = "# System should not forward by configuration"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
def test_35_produce_for_wxp_dst_linklocal(self):
"""
fr-35 produce for wxp dst-linklocal
"""
my_err = False
try:
ofile = open("/dev/null", 'w')
fr = Ip6_Filter_Rule(rule)
fr['debuglevel'] = False
fr['Rule-Nr'] = 11
fr['Pair-Nr'] = 1
fr['Action'] = "accept"
fr['Source'] = "2001:db8:1::1"
fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "ip6"
fr['dport'] = "all"
fr['insec'] = False
fr['System-Forward'] = False
fr['i_am_s'] = True
fr['i_am_d'] = False
fr['travers'] = False
fr['source-if'] = "sis0"
fr['destin-if'] = "sis0"
fr['src-linklocal'] = False
fr['dst-linklocal'] = True
fr['OS'] = 'winxp3'
except:
my_err = True
fr.produce_wxpsp3(ofile, True)
expect = "# dst-linklocal ==> no rule generated"
self.maxDiff = None
self.assertEquals(expect, fr.msg)
class Ip6_Filter_tests(unittest.TestCase):
'''some tests for class Ip6_Filter_Rule'''
def test_01_IP6_Filter_create_Debian(self):
"""
ft-01 IP6 Filter create an object for Debian
"""
#init__(self, debuglevel, path, name, os, fwd, asym, interfaces=None):
debug = False
name = "ns"
path = "desc/ns/"
os = "Debian GNU/Linux wheezy"
fwd = False
asym = False
fi = IP6_Filter(debug, path, name, os, fwd, asym, None)
self.assertIsInstance(fi, IP6_Filter)
self.assertEquals(fi.os, 'Debian')
def test_02_IP6_Filter_create_OpenBSD(self):
"""
ft-02 IP6 Filter create an object for OpenBSD
"""
#init__(self, debuglevel, path, name, os, fwd, asym, interfaces=None):
debug = False
name = "ns"
path = "desc/ns/"
os = "OpenBSD 4.5"
fwd = False
asym = False
fi = IP6_Filter(debug, path, name, os, fwd, asym, None)
self.assertIsInstance(fi, IP6_Filter)
self.assertEquals(fi.os, 'OpenBSD')
def test_03_IP6_Filter_create_OpenSolaris(self):
"""
ft-03 IP6 Filter create an object for OpenSolaris
"""
#init__(self, debuglevel, path, name, os, fwd, asym, interfaces=None):
debug = False
name = "ns"
path = "desc/ns/"
os = "OpenSolaris unknown version"
fwd = False
asym = False
fi = IP6_Filter(debug, path, name, os, fwd, asym, None)
self.assertIsInstance(fi, IP6_Filter)
self.assertEquals(fi.os, 'OpenSolaris')
def test_04_IP6_Filter_create_win_xp_sp3(self):
"""
ft-04 IP6 Filter create an object for WXP SP3
"""
#init__(self, debuglevel, path, name, os, fwd, asym, interfaces=None):
debug = False
name = "ns"
path = "desc/ns/"
os = "Win-XP-SP3"
fwd = False
asym = False
fi = IP6_Filter(debug, path, name, os, fwd, asym, None)
self.assertIsInstance(fi, IP6_Filter)
self.assertEquals(fi.os, 'Win-XP-SP3')
def test_05_IP6_Filter_create_unknown_os(self):
"""
ft-05 IP6 Filter create an object for unknown os
"""
#init__(self, debuglevel, path, name, os, fwd, asym, interfaces=None):
debug = False
name = "ns"
path = "desc/ns/"
os = "Unknown OS"
fwd = False
asym = False
fi = IP6_Filter(debug, path, name, os, fwd, asym, None)
self.assertIsInstance(fi, IP6_Filter)
self.assertEquals(fi.os, 'Unknown operating system for host: ns')
def test_06_IP6_Filter_append_first_rule(self):
"""
ft-06 IP6 Filter append first rule
"""
debug = False
name = "ns"
path = "desc/ns/"
os = "Debian GNU/Linux"
fwd = False
asym = False
rule_one = ['s', 'd', 'ip6', 'all', 'accept', "#", 'test-comment']
fi = IP6_Filter(debug, path, name, os, fwd, asym, None)
self.assertIsInstance(fi, IP6_Filter)
fi.append(rule_one)
expect = [rule_one, ]
self.assertEqual(expect, fi.rules)
def test_07_IP6_Filter_mangle_start_exist(self):
"""
ft-07 IP6 Filter mangle-start exisiting file
"""
debug = False
name = "www"
#path = "HOME_DIR/adm6/desc/www"
mach_dir = "~/adm6/desc/www"
path = homedir(mach_dir)
os = "Debian GNU/Linux"
fwd = False
asym = False
rule_one = ['s', 'd', 'ip6', 'all', 'accept', "#", 'test-comment']
ofile = open("/dev/null", 'w')
fi = IP6_Filter(debug, path, name, os, fwd, asym, None)
fi.msg = ""
self.assertIsInstance(fi, IP6_Filter)
file_to_read = "mangle-startup"
fi.mangle_file(ofile, file_to_read)
expect = "# start reading mangle-file: %s/" % (path)
expect += file_to_read
expect += "# mangle-startup file for testing \n"
value = fi.msg
self.assertEqual(expect, value)
def test_08_IP6_Filter_mangle_end_exist(self):
"""
ft-08 IP6 Filter mangle-end exisiting file
"""
debug = False
name = "ns"
path = "HOME_DIR/adm6/desc/ns"
mach_dir = "~/adm6/desc/adm6"
path = homedir(mach_dir)
os = "Debian GNU/Linux"
fwd = False
asym = False
rule_one = ['s', 'd', 'ip6', 'all', 'accept', "#", 'test-comment']
ofile = open("/dev/null", 'w')
fi = IP6_Filter(debug, path, name, os, fwd, asym, None)
self.assertIsInstance(fi, IP6_Filter)
file_to_read = "mangle-endup"
fi.msg = ""
fi.mangle_file(ofile, file_to_read)
expect = "# failed reading mangle-file: %s/" % (path)
#expect = "# start reading mangle-file: %s/" % (path)
expect += file_to_read
expect += ", but OK"
value = fi.msg
self.assertEqual(expect, value)
def test_09_IP6_Filter_mangle_end_non_exist(self):
"""
ft-09 IP6 Filter mangle-end non exisiting file
"""
debug = False
name = "adm6"
#path = "HOME_DIR/adm6/desc/adm6"
mach_dir = "~/adm6/desc/adm6"
path = homedir(mach_dir)
os = "Debian GNU/Linux"
fwd = False
asym = False
rule_one = ['s', 'd', 'ip6', 'all', 'accept', "#", 'test-comment']
ofile = open("/dev/null", 'w')
fi = IP6_Filter(debug, path, name, os, fwd, asym, None)
self.assertIsInstance(fi, IP6_Filter)
file_to_read = "mangle-endup"
fi.msg = ""
fi.mangle_file(ofile, file_to_read)
temp = "# failed reading mangle-file: %s/" % (path)
temp += file_to_read
temp = "# failed reading mangle-file: HOME_DIR/adm6/desc/adm6/mangle-endup, but OK"
expect = temp.replace("HOME_DIR", home_dir_replacement)
value = fi.msg
self.assertEqual(expect, value)
def test_10_IP6_Filter_final_this_rule(self):
"""
ft-10 IP6 Filter final this rule
"""
debug = True
name = "ns"
path = "HOME_DIR/adm6/desc/ns"
mach_dir = "~/adm6/desc/ns"
path = homedir(mach_dir)
os = "Debian GNU/Linux"
fwd = False
asym = False
rule_one = ['s', 'd', 'ip6', 'all', 'accept', "#", 'test-comment']
ofn = "/dev/null"
ofile = open(ofn, 'w')
fi = IP6_Filter(debug, path, name, os, fwd, asym, None)
self.assertIsInstance(fi, IP6_Filter)
rule = []
rule.append("RuleText") # RuleText
rule.append(True) # System-Fwd
rule.append(2) # Rule-Nr.
rule.append(3) # Pair-Nr.
rule.append(True)
rule.append(False)
rule.append(IPv6Network('fe80::1')) # source
rule.append(IPv6Network('ff80::4711')) # destin
rule.append('eth0') # source-if
rule.append(3) # source-rn
rule.append('eth0') # destin-if
rule.append(3) # destin-rn
rule.append('udp') # protocol
rule.append('4711:4713') # dport
rule.append('accept') # action
rule.append('NOIF NOSTATE') # append options at last
fi.rules.append(rule)
fi.final_this_rule(rule, ofile)
value = fi.msg
expect = """# ---------------------------------------------------------------------------- #
# Rule-Nr : 2 #
# Pair-Nr : 3 #
# System-Name : ns #
# System-Forward : True #
# OS : Debian #
# Asymmetric : False #
# RuleText : RuleText #
# Source : fe80::1/128 #
# Destin : ff80::4711/128 #
# Protocol : udp #
# sport : 1024: #
# dport : 4711:4713 #
# Action : accept #
# nonew : False #
# noif : True #
# nostate : True #
# insec : False #
# i_am_s : True #
# i_am_d : False #
# travers : False #
# source-if : eth0 #
# source-rn : 3 #
# src-linklocal : True #
# src-multicast : False #
# destin-if : eth0 #
# destin-rn : 3 #
# dst-linklocal : False #
# dst-multicast : True #
/sbin/ip6tables -A output__new -s fe80::1/128 -d ff80::4711/128 -p udp --sport 1024: --dport 4711:4713 -j ACCEPT -m comment --comment "2,3"
/sbin/ip6tables -A input___new -d fe80::1/128 -s ff80::4711/128 -p udp --dport 1024: --sport 4711:4713 -j ACCEPT -m comment --comment "2,3"
echo -n ".";"""
value = fi.msg
self.assertEqual(expect, value)
def test_11_IP6_Filter_final_this_rule_forced_linklocal(self):
"""
ft-11 IP6 Filter final this rule forced linklocal
"""
debug = True
name = "ns"
path = "HOME_DIR/adm6/desc/ns"
mach_dir = "~/adm6/desc/ns"
path = homedir(mach_dir)
os = "Debian GNU/Linux"
fwd = False
asym = False
rule_one = ['s', 'd', 'ip6', 'all', 'accept', "#", 'test-comment']
ofn = "/dev/null"
ofile = open(ofn, 'w')
fi = IP6_Filter(debug, path, name, os, fwd, asym, None)
self.assertIsInstance(fi, IP6_Filter)
rule = []
rule.append("RuleText") # RuleText
rule.append(True) # System-Fwd
rule.append(2) # Rule-Nr.
rule.append(3) # Pair-Nr.
rule.append(True) # i_am_s
rule.append(False) # i_am_d
rule.append(IPv6Network('fe80::1')) # source
rule.append(IPv6Network('ff80::4711')) # destin
rule.append('eth0') # source-if
rule.append(3) # source-rn
rule.append('eth0') # destin-if
rule.append(3) # destin-rn
rule.append('udp') # protocol
rule.append('4711:4713') # dport
rule.append('accept') # action
rule.append('NOIF NOSTATE FORCED') # options at last
fi.rules.append(rule)
fi.final_this_rule(rule, ofile)
value = fi.msg
expect = """# ---------------------------------------------------------------------------- #
# Rule-Nr : 2 #
# Pair-Nr : 3 #
# System-Name : ns #
# System-Forward : True #
# OS : Debian #
# Asymmetric : False #
# RuleText : RuleText #
# Source : fe80::1/128 #
# Destin : ff80::4711/128 #
# Protocol : udp #
# sport : 1024: #
# dport : 4711:4713 #
# Action : accept #
# nonew : False #
# noif : True #
# nostate : True #
# insec : False #
# i_am_s : True #
# i_am_d : True #
# travers : True #
# source-if : eth0 #
# source-rn : 3 #
# src-linklocal : True #
# src-multicast : False #
# destin-if : eth0 #
# destin-rn : 3 #
# dst-linklocal : False #
# dst-multicast : True #
# link-local ==> no forward"""
value = fi.msg
self.assertEqual(expect, value)
def test_12_IP6_Filter_mach_output_as_src(self):
"""
ft-12 IP6 Filter mach_output as src
"""
debug = True
name = "adm6"
mach_dir = "~/adm6/desc/%s" % (name)
path = homedir(mach_dir)
os = "Debian GNU/Linux"
fwd = False
asym = False
ofilename = "/dev/null"
fi = IP6_Filter(debug, path, name, os, fwd, asym, None)
self.assertIsInstance(fi, IP6_Filter)
rule = []
rule.append("should be RuleText") # RuleText
rule.append(True) # System-Fwd
rule.append(1) # Rule-Nr.
rule.append(1) # Pair-Nr.
rule.append(True) # i_am_s
rule.append(False) # i_am_d
rule.append(IPv6Network('2001:db8:1::1')) # source
rule.append(IPv6Network('2001:db8:2::11')) # destin
rule.append('eth0') # source-if
rule.append(1) # source-rn
rule.append('eth0') # destin-if
rule.append(1) # destin-rn
rule.append('udp') # protocol
rule.append('4711') # dport
rule.append('accept') # action
rule.append('NOIF NOSTATE FORCED') # options at last
fi.rules.append(rule)
fi.mach_output(ofilename)
value = fi.msg
temp = """#!/bin/bash
#
echo "**********************************************************************"
echo "**********************************************************************"
echo "## ##"
echo "## a d m 6 - A Device Manager for IPv6 packetfiltering ##"
echo "## ##"
echo "## version: 0.2 ##"
echo "## ##"
echo "## device-name: adm6 ##"
echo "## device-type: Debian GNU/Linux ##"
echo "## ##"
echo "## date: 2013-03-13 23:23 ##"
echo "## author: Johannes Hubertz, hubertz-it-consulting GmbH ##"
echo "## ##"
echo "## license: GNU general public license version 3 ##"
echo "## or any later version ##"
echo "## ##"
echo "**********************************************************************"
echo "**********************************************************************"
echo "## ##"
echo "## some magic abbreviations follow ##"
echo "## ##"
#
#POLICY_A='ACCEPT'
POLICY_D='DROP'
#
I6='/sbin/ip6tables '
IP6I='/sbin/ip6tables -A input___new '
IP6O='/sbin/ip6tables -A output__new '
IP6F='/sbin/ip6tables -A forward_new '
#
CHAINS="$CHAINS input__"
CHAINS="$CHAINS output_"
CHAINS="$CHAINS forward"
for chain in $CHAINS
do
/sbin/ip6tables -N ${chain}_act >/dev/null 2>/dev/null
/sbin/ip6tables -N ${chain}_new
done
# but ignore all the boring fault-messages
$I6 -P INPUT $POLICY_D
$I6 -P OUTPUT $POLICY_D
$I6 -P FORWARD $POLICY_D
#
# some things need to pass,
# even if you don't like them
# do local and multicast on every interface
LOCAL="fe80::/10"
MCAST="ff02::/10"
#
$IP6I -p ipv6-icmp -s ${LOCAL} -d ${LOCAL} -j ACCEPT
$IP6O -p ipv6-icmp -s ${LOCAL} -d ${LOCAL} -j ACCEPT
#
$IP6I -p ipv6-icmp -s ${MCAST} -j ACCEPT
$IP6I -p ipv6-icmp -d ${MCAST} -j ACCEPT
$IP6O -p ipv6-icmp -s ${MCAST} -j ACCEPT
#
# all prepared now, individual mangling and rules following
#
# failed reading mangle-file: HOME_DIR/adm6/desc/adm6/mangle-startup, but OK
# ---------------------------------------------------------------------------- #
# Rule-Nr : 1 #
# Pair-Nr : 1 #
# System-Name : adm6 #
# System-Forward : True #
# OS : Debian #
# Asymmetric : False #
# RuleText : should be RuleText #
# Source : 2001:db8:1::1/128 #
# Destin : 2001:db8:2::11/128 #
# Protocol : udp #
# sport : 1024: #
# dport : 4711 #
# Action : accept #
# nonew : False #
# noif : True #
# nostate : True #
# insec : False #
# i_am_s : True #
# i_am_d : True #
# travers : True #
# source-if : eth0 #
# source-rn : 1 #
# src-linklocal : False #
# src-multicast : False #
# destin-if : eth0 #
# destin-rn : 1 #
# dst-linklocal : False #
# dst-multicast : False #
/sbin/ip6tables -A output__new -s 2001:db8:1::1/128 -d 2001:db8:2::11/128 -p udp --sport 1024: --dport 4711 -j ACCEPT -m comment --comment "1,1"
/sbin/ip6tables -A input___new -d 2001:db8:1::1/128 -s 2001:db8:2::11/128 -p udp --dport 1024: --sport 4711 -j ACCEPT -m comment --comment "1,1"
echo -n ".";/sbin/ip6tables -A input___new -s 2001:db8:1::1/128 -d 2001:db8:2::11/128 -p udp --sport 1024: --dport 4711 -j ACCEPT -m comment --comment "1,1"
/sbin/ip6tables -A output__new -d 2001:db8:1::1/128 -s 2001:db8:2::11/128 -p udp --dport 1024: --sport 4711 -j ACCEPT -m comment --comment "1,1"
echo -n ".";/sbin/ip6tables -A forward_new -s 2001:db8:1::1/128 -d 2001:db8:2::11/128 -p udp --sport 1024: --dport 4711 -j ACCEPT -m comment --comment "1,1"
/sbin/ip6tables -A forward_new -d 2001:db8:1::1/128 -s 2001:db8:2::11/128 -p udp --dport 1024: --sport 4711 -j ACCEPT -m comment --comment "1,1"
echo -n ".";# failed reading mangle-file: HOME_DIR/adm6/desc/adm6/mangle-endup, but OK#
#$IP6I -p tcp --dport 22 -j ACCEPT
#$IP6O -p tcp --sport 22 -j ACCEPT
#
# allow ping and pong always (al gusto)
#$IP6O -p ipv6-icmp --icmpv6-type echo-request -j ACCEPT
#$IP6I -p ipv6-icmp --icmpv6-type echo-reply -j ACCEPT
##
#$IP6I -p ipv6-icmp --icmpv6-type echo-request -j ACCEPT
#$IP6O -p ipv6-icmp --icmpv6-type echo-reply -j ACCEPT
#
#ICMPv6types="${ICMPv6types} destination-unreachable"
ICMPv6types="${ICMPv6types} echo-request"
ICMPv6types="${ICMPv6types} echo-reply"
ICMPv6types="${ICMPv6types} neighbour-solicitation"
ICMPv6types="${ICMPv6types} neighbour-advertisement"
ICMPv6types="${ICMPv6types} router-solicitation"
ICMPv6types="${ICMPv6types} router-advertisement"
for icmptype in $ICMPv6types
do
$IP6I -p ipv6-icmp --icmpv6-type $icmptype -j ACCEPT
$IP6O -p ipv6-icmp --icmpv6-type $icmptype -j ACCEPT
done
$IP6I -p ipv6-icmp --icmpv6-type destination-unreachable -j LOG --log-prefix "unreach: " -m limit --limit 30/second --limit-burst 60
$IP6I -p ipv6-icmp --icmpv6-type destination-unreachable -j ACCEPT
#
CHAINS=""
CHAINS="$CHAINS input__"
CHAINS="$CHAINS output_"
CHAINS="$CHAINS forward"
#set -x
for chain in $CHAINS
do
/sbin/ip6tables -E "${chain}_act" "${chain}_old"
/sbin/ip6tables -E "${chain}_new" "${chain}_act"
done
#
$I6 -F INPUT
$I6 -A INPUT -m rt --rt-type 0 -j LOG --log-prefix "rt-0: " -m limit --limit 3/second --limit-burst 6
$I6 -A INPUT -m rt --rt-type 0 -j DROP
$I6 -A INPUT -m rt --rt-type 2 -j LOG --log-prefix "rt-2: " -m limit --limit 3/second --limit-burst 6
$I6 -A INPUT -m rt --rt-type 2 -j DROP
$I6 -A INPUT -i lo -j ACCEPT
$I6 -A INPUT --jump input___act
#
$I6 -F OUTPUT
$I6 -A OUTPUT -o lo -j ACCEPT
$I6 -A OUTPUT --jump output__act
#
$I6 -F FORWARD
$I6 -A FORWARD -m rt --rt-type 0 -j LOG --log-prefix "rt-0: " -m limit --limit 3/second --limit-burst 6
$I6 -A FORWARD -m rt --rt-type 0 -j DROP
$I6 -A FORWARD --jump forward_act
#
for chain in $CHAINS
do
/sbin/ip6tables -F "${chain}_old"
/sbin/ip6tables -X "${chain}_old"
done
$I6 -F logdrop >/dev/null 2>/dev/null
$I6 -X logdrop >/dev/null 2>/dev/null
$I6 -N logdrop
$I6 -A INPUT --jump logdrop
$I6 -A OUTPUT --jump logdrop
$I6 -A FORWARD --jump logdrop
$I6 -A logdrop -j LOG --log-prefix "drp: " -m limit --limit 3/second --limit-burst 6
$I6 -A logdrop -j DROP
#
/sbin/ip6tables-save -c >/root/last-filter
echo "**********************************************************************"
echo "**********************************************************************"
echo "## ##"
echo "## End of generated filter-rules ##"
echo "## ##"
echo "**********************************************************************"
echo "**********************************************************************"
# EOF
"""
expect = temp.replace("HOME_DIR", home_dir_replacement)
self.assertEquals(expect, value)
def test_13_IP6_Filter_mach_output_as_travers(self):
"""
ft-13 IP6 Filter mach_output as travers
"""
debug = True
name = "adm6"
mach_dir = "~/adm6/desc/%s" % (name)
path = homedir(mach_dir)
os = "Debian GNU/Linux"
fwd = False
asym = False
ofilename = "/dev/null"
fi = IP6_Filter(debug, path, name, os, fwd, asym, None)
self.assertIsInstance(fi, IP6_Filter)
rule = []
rule.append("should be RuleText") # RuleText
rule.append(True) # System-Fwd
rule.append(1) # Rule-Nr.
rule.append(1) # Pair-Nr.
rule.append(False) # i_am_s
rule.append(False) # i_am_d
rule.append(IPv6Network('2001:db8:1::1')) # source
rule.append(IPv6Network('2001:db8:2::11')) # destin
rule.append('eth0') # source-if
rule.append(1) # source-rn
rule.append('eth1') # destin-if
rule.append(3) # destin-rn
rule.append('udp') # protocol
rule.append('4711') # dport
rule.append('accept') # action
rule.append('NOSTATE') # options at last
fi.rules.append(rule)
fi.mach_output(ofilename)
value = fi.msg
temp = """#!/bin/bash
#
echo "**********************************************************************"
echo "**********************************************************************"
echo "## ##"
echo "## a d m 6 - A Device Manager for IPv6 packetfiltering ##"
echo "## ##"
echo "## version: 0.2 ##"
echo "## ##"
echo "## device-name: adm6 ##"
echo "## device-type: Debian GNU/Linux ##"
echo "## ##"
echo "## date: 2013-03-13 23:23 ##"
echo "## author: Johannes Hubertz, hubertz-it-consulting GmbH ##"
echo "## ##"
echo "## license: GNU general public license version 3 ##"
echo "## or any later version ##"
echo "## ##"
echo "**********************************************************************"
echo "**********************************************************************"
echo "## ##"
echo "## some magic abbreviations follow ##"
echo "## ##"
#
#POLICY_A='ACCEPT'
POLICY_D='DROP'
#
I6='/sbin/ip6tables '
IP6I='/sbin/ip6tables -A input___new '
IP6O='/sbin/ip6tables -A output__new '
IP6F='/sbin/ip6tables -A forward_new '
#
CHAINS="$CHAINS input__"
CHAINS="$CHAINS output_"
CHAINS="$CHAINS forward"
for chain in $CHAINS
do
/sbin/ip6tables -N ${chain}_act >/dev/null 2>/dev/null
/sbin/ip6tables -N ${chain}_new
done
# but ignore all the boring fault-messages
$I6 -P INPUT $POLICY_D
$I6 -P OUTPUT $POLICY_D
$I6 -P FORWARD $POLICY_D
#
# some things need to pass,
# even if you don't like them
# do local and multicast on every interface
LOCAL="fe80::/10"
MCAST="ff02::/10"
#
$IP6I -p ipv6-icmp -s ${LOCAL} -d ${LOCAL} -j ACCEPT
$IP6O -p ipv6-icmp -s ${LOCAL} -d ${LOCAL} -j ACCEPT
#
$IP6I -p ipv6-icmp -s ${MCAST} -j ACCEPT
$IP6I -p ipv6-icmp -d ${MCAST} -j ACCEPT
$IP6O -p ipv6-icmp -s ${MCAST} -j ACCEPT
#
# all prepared now, individual mangling and rules following
#
# failed reading mangle-file: HOME_DIR/adm6/desc/adm6/mangle-startup, but OK
# ---------------------------------------------------------------------------- #
# Rule-Nr : 1 #
# Pair-Nr : 1 #
# System-Name : adm6 #
# System-Forward : True #
# OS : Debian #
# Asymmetric : False #
# RuleText : should be RuleText #
# Source : 2001:db8:1::1/128 #
# Destin : 2001:db8:2::11/128 #
# Protocol : udp #
# sport : 1024: #
# dport : 4711 #
# Action : accept #
# nonew : False #
# noif : False #
# nostate : True #
# insec : False #
# i_am_s : False #
# i_am_d : False #
# travers : True #
# source-if : eth0 #
# source-rn : 1 #
# src-linklocal : False #
# src-multicast : False #
# destin-if : eth1 #
# destin-rn : 3 #
# dst-linklocal : False #
# dst-multicast : False #
/sbin/ip6tables -A forward_new -i eth0 -s 2001:db8:1::1/128 -d 2001:db8:2::11/128 -p udp --sport 1024: --dport 4711 -j ACCEPT -m comment --comment "1,1"
/sbin/ip6tables -A forward_new -i eth1 -d 2001:db8:1::1/128 -s 2001:db8:2::11/128 -p udp --dport 1024: --sport 4711 -j ACCEPT -m comment --comment "1,1"
echo -n ".";# failed reading mangle-file: HOME_DIR/adm6/desc/adm6/mangle-endup, but OK#
#$IP6I -p tcp --dport 22 -j ACCEPT
#$IP6O -p tcp --sport 22 -j ACCEPT
#
# allow ping and pong always (al gusto)
#$IP6O -p ipv6-icmp --icmpv6-type echo-request -j ACCEPT
#$IP6I -p ipv6-icmp --icmpv6-type echo-reply -j ACCEPT
##
#$IP6I -p ipv6-icmp --icmpv6-type echo-request -j ACCEPT
#$IP6O -p ipv6-icmp --icmpv6-type echo-reply -j ACCEPT
#
#ICMPv6types="${ICMPv6types} destination-unreachable"
ICMPv6types="${ICMPv6types} echo-request"
ICMPv6types="${ICMPv6types} echo-reply"
ICMPv6types="${ICMPv6types} neighbour-solicitation"
ICMPv6types="${ICMPv6types} neighbour-advertisement"
ICMPv6types="${ICMPv6types} router-solicitation"
ICMPv6types="${ICMPv6types} router-advertisement"
for icmptype in $ICMPv6types
do
$IP6I -p ipv6-icmp --icmpv6-type $icmptype -j ACCEPT
$IP6O -p ipv6-icmp --icmpv6-type $icmptype -j ACCEPT
done
$IP6I -p ipv6-icmp --icmpv6-type destination-unreachable -j LOG --log-prefix "unreach: " -m limit --limit 30/second --limit-burst 60
$IP6I -p ipv6-icmp --icmpv6-type destination-unreachable -j ACCEPT
#
CHAINS=""
CHAINS="$CHAINS input__"
CHAINS="$CHAINS output_"
CHAINS="$CHAINS forward"
#set -x
for chain in $CHAINS
do
/sbin/ip6tables -E "${chain}_act" "${chain}_old"
/sbin/ip6tables -E "${chain}_new" "${chain}_act"
done
#
$I6 -F INPUT
$I6 -A INPUT -m rt --rt-type 0 -j LOG --log-prefix "rt-0: " -m limit --limit 3/second --limit-burst 6
$I6 -A INPUT -m rt --rt-type 0 -j DROP
$I6 -A INPUT -m rt --rt-type 2 -j LOG --log-prefix "rt-2: " -m limit --limit 3/second --limit-burst 6
$I6 -A INPUT -m rt --rt-type 2 -j DROP
$I6 -A INPUT -i lo -j ACCEPT
$I6 -A INPUT --jump input___act
#
$I6 -F OUTPUT
$I6 -A OUTPUT -o lo -j ACCEPT
$I6 -A OUTPUT --jump output__act
#
$I6 -F FORWARD
$I6 -A FORWARD -m rt --rt-type 0 -j LOG --log-prefix "rt-0: " -m limit --limit 3/second --limit-burst 6
$I6 -A FORWARD -m rt --rt-type 0 -j DROP
$I6 -A FORWARD --jump forward_act
#
for chain in $CHAINS
do
/sbin/ip6tables -F "${chain}_old"
/sbin/ip6tables -X "${chain}_old"
done
$I6 -F logdrop >/dev/null 2>/dev/null
$I6 -X logdrop >/dev/null 2>/dev/null
$I6 -N logdrop
$I6 -A INPUT --jump logdrop
$I6 -A OUTPUT --jump logdrop
$I6 -A FORWARD --jump logdrop
$I6 -A logdrop -j LOG --log-prefix "drp: " -m limit --limit 3/second --limit-burst 6
$I6 -A logdrop -j DROP
#
/sbin/ip6tables-save -c >/root/last-filter
echo "**********************************************************************"
echo "**********************************************************************"
echo "## ##"
echo "## End of generated filter-rules ##"
echo "## ##"
echo "**********************************************************************"
echo "**********************************************************************"
# EOF
"""
#print "M:", value
expect = temp.replace("HOME_DIR", home_dir_replacement)
self.assertEquals(expect, value)
def test_14_IP6_Filter_mach_output_as_stateful_travers(self):
"""
ft-14 IP6 Filter mach_output as stateful travers
"""
debug = True
name = "adm6"
mach_dir = "~/adm6/desc/%s" % (name)
path = homedir(mach_dir)
os = "Debian GNU/Linux"
fwd = False
asym = False
ofilename = "/dev/null"
fi = IP6_Filter(debug, path, name, os, fwd, asym, None)
self.assertIsInstance(fi, IP6_Filter)
rule = []
rule.append("should be RuleText") # RuleText
rule.append(True) # System-Fwd
rule.append(1) # Rule-Nr.
rule.append(1) # Pair-Nr.
rule.append(False) # i_am_s
rule.append(False) # i_am_d
rule.append(IPv6Network('2001:db8:1::1')) # source
rule.append(IPv6Network('2001:db8:2::11')) # destin
rule.append('eth0') # source-if
rule.append(1) # source-rn
rule.append('eth1') # destin-if
rule.append(3) # destin-rn
rule.append('udp') # protocol
rule.append('4711') # dport
rule.append('accept') # action
rule.append('') # options at last
fi.rules.append(rule)
fi.mach_output(ofilename)
value = fi.msg
temp = """#!/bin/bash
#
echo "**********************************************************************"
echo "**********************************************************************"
echo "## ##"
echo "## a d m 6 - A Device Manager for IPv6 packetfiltering ##"
echo "## ##"
echo "## version: 0.2 ##"
echo "## ##"
echo "## device-name: adm6 ##"
echo "## device-type: Debian GNU/Linux ##"
echo "## ##"
echo "## date: 2013-03-13 23:23 ##"
echo "## author: Johannes Hubertz, hubertz-it-consulting GmbH ##"
echo "## ##"
echo "## license: GNU general public license version 3 ##"
echo "## or any later version ##"
echo "## ##"
echo "**********************************************************************"
echo "**********************************************************************"
echo "## ##"
echo "## some magic abbreviations follow ##"
echo "## ##"
#
#POLICY_A='ACCEPT'
POLICY_D='DROP'
#
I6='/sbin/ip6tables '
IP6I='/sbin/ip6tables -A input___new '
IP6O='/sbin/ip6tables -A output__new '
IP6F='/sbin/ip6tables -A forward_new '
#
CHAINS="$CHAINS input__"
CHAINS="$CHAINS output_"
CHAINS="$CHAINS forward"
for chain in $CHAINS
do
/sbin/ip6tables -N ${chain}_act >/dev/null 2>/dev/null
/sbin/ip6tables -N ${chain}_new
done
# but ignore all the boring fault-messages
$I6 -P INPUT $POLICY_D
$I6 -P OUTPUT $POLICY_D
$I6 -P FORWARD $POLICY_D
#
# some things need to pass,
# even if you don't like them
# do local and multicast on every interface
LOCAL="fe80::/10"
MCAST="ff02::/10"
#
$IP6I -p ipv6-icmp -s ${LOCAL} -d ${LOCAL} -j ACCEPT
$IP6O -p ipv6-icmp -s ${LOCAL} -d ${LOCAL} -j ACCEPT
#
$IP6I -p ipv6-icmp -s ${MCAST} -j ACCEPT
$IP6I -p ipv6-icmp -d ${MCAST} -j ACCEPT
$IP6O -p ipv6-icmp -s ${MCAST} -j ACCEPT
#
# all prepared now, individual mangling and rules following
#
# failed reading mangle-file: HOME_DIR/adm6/desc/adm6/mangle-startup, but OK
# ---------------------------------------------------------------------------- #
# Rule-Nr : 1 #
# Pair-Nr : 1 #
# System-Name : adm6 #
# System-Forward : True #
# OS : Debian #
# Asymmetric : False #
# RuleText : should be RuleText #
# Source : 2001:db8:1::1/128 #
# Destin : 2001:db8:2::11/128 #
# Protocol : udp #
# sport : 1024: #
# dport : 4711 #
# Action : accept #
# nonew : False #
# noif : False #
# nostate : False #
# insec : False #
# i_am_s : False #
# i_am_d : False #
# travers : True #
# source-if : eth0 #
# source-rn : 1 #
# src-linklocal : False #
# src-multicast : False #
# destin-if : eth1 #
# destin-rn : 3 #
# dst-linklocal : False #
# dst-multicast : False #
/sbin/ip6tables -A forward_new -i eth0 -s 2001:db8:1::1/128 -d 2001:db8:2::11/128 -p udp --sport 1024: --dport 4711 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT -m comment --comment "1,1"
/sbin/ip6tables -A forward_new -i eth1 -d 2001:db8:1::1/128 -s 2001:db8:2::11/128 -p udp --dport 1024: --sport 4711 -m state --state ESTABLISHED,RELATED -j ACCEPT -m comment --comment "1,1"
echo -n ".";# failed reading mangle-file: HOME_DIR/adm6/desc/adm6/mangle-endup, but OK#
#$IP6I -p tcp --dport 22 -j ACCEPT
#$IP6O -p tcp --sport 22 -j ACCEPT
#
# allow ping and pong always (al gusto)
#$IP6O -p ipv6-icmp --icmpv6-type echo-request -j ACCEPT
#$IP6I -p ipv6-icmp --icmpv6-type echo-reply -j ACCEPT
##
#$IP6I -p ipv6-icmp --icmpv6-type echo-request -j ACCEPT
#$IP6O -p ipv6-icmp --icmpv6-type echo-reply -j ACCEPT
#
#ICMPv6types="${ICMPv6types} destination-unreachable"
ICMPv6types="${ICMPv6types} echo-request"
ICMPv6types="${ICMPv6types} echo-reply"
ICMPv6types="${ICMPv6types} neighbour-solicitation"
ICMPv6types="${ICMPv6types} neighbour-advertisement"
ICMPv6types="${ICMPv6types} router-solicitation"
ICMPv6types="${ICMPv6types} router-advertisement"
for icmptype in $ICMPv6types
do
$IP6I -p ipv6-icmp --icmpv6-type $icmptype -j ACCEPT
$IP6O -p ipv6-icmp --icmpv6-type $icmptype -j ACCEPT
done
$IP6I -p ipv6-icmp --icmpv6-type destination-unreachable -j LOG --log-prefix "unreach: " -m limit --limit 30/second --limit-burst 60
$IP6I -p ipv6-icmp --icmpv6-type destination-unreachable -j ACCEPT
#
CHAINS=""
CHAINS="$CHAINS input__"
CHAINS="$CHAINS output_"
CHAINS="$CHAINS forward"
#set -x
for chain in $CHAINS
do
/sbin/ip6tables -E "${chain}_act" "${chain}_old"
/sbin/ip6tables -E "${chain}_new" "${chain}_act"
done
#
$I6 -F INPUT
$I6 -A INPUT -m rt --rt-type 0 -j LOG --log-prefix "rt-0: " -m limit --limit 3/second --limit-burst 6
$I6 -A INPUT -m rt --rt-type 0 -j DROP
$I6 -A INPUT -m rt --rt-type 2 -j LOG --log-prefix "rt-2: " -m limit --limit 3/second --limit-burst 6
$I6 -A INPUT -m rt --rt-type 2 -j DROP
$I6 -A INPUT -i lo -j ACCEPT
$I6 -A INPUT --jump input___act
#
$I6 -F OUTPUT
$I6 -A OUTPUT -o lo -j ACCEPT
$I6 -A OUTPUT --jump output__act
#
$I6 -F FORWARD
$I6 -A FORWARD -m rt --rt-type 0 -j LOG --log-prefix "rt-0: " -m limit --limit 3/second --limit-burst 6
$I6 -A FORWARD -m rt --rt-type 0 -j DROP
$I6 -A FORWARD --jump forward_act
#
for chain in $CHAINS
do
/sbin/ip6tables -F "${chain}_old"
/sbin/ip6tables -X "${chain}_old"
done
$I6 -F logdrop >/dev/null 2>/dev/null
$I6 -X logdrop >/dev/null 2>/dev/null
$I6 -N logdrop
$I6 -A INPUT --jump logdrop
$I6 -A OUTPUT --jump logdrop
$I6 -A FORWARD --jump logdrop
$I6 -A logdrop -j LOG --log-prefix "drp: " -m limit --limit 3/second --limit-burst 6
$I6 -A logdrop -j DROP
#
/sbin/ip6tables-save -c >/root/last-filter
echo "**********************************************************************"
echo "**********************************************************************"
echo "## ##"
echo "## End of generated filter-rules ##"
echo "## ##"
echo "**********************************************************************"
echo "**********************************************************************"
# EOF
"""
expect = temp.replace("HOME_DIR", home_dir_replacement)
value_len = len(value)
expect_len = len(expect)
self.assertEquals(expect_len, value_len)
self.assertEquals(expect, value)
def test_15_IP6_Filter_mach_output_as_real_file(self):
"""
ft-15 IP6 Filter mach_output as real file
"""
debug = True
name = "adm6"
mach_dir = "~/adm6/desc/%s" % (name)
path = homedir(mach_dir)
os = "Debian GNU/Linux"
fwd = False
asym = True
ofilename = None
fi = IP6_Filter(debug, path, name, os, fwd, asym, None)
self.assertIsInstance(fi, IP6_Filter)
rule = []
rule.append("should be RuleText") # RuleText
rule.append(True) # System-Fwd
rule.append(1) # Rule-Nr.
rule.append(1) # Pair-Nr.
rule.append(False) # i_am_s
rule.append(True) # i_am_d
rule.append(IPv6Network('2001:db8:1::1')) # source
rule.append(IPv6Network('2001:db8:2::11')) # destin
rule.append('eth0') # source-if
rule.append(1) # source-rn
rule.append('eth1') # destin-if
rule.append(3) # destin-rn
rule.append('udp') # protocol
rule.append('4711') # dport
rule.append('accept') # action
rule.append('NONEW NOIF INSEC') # options at last
fi.rules.append(rule)
fi.mach_output(ofilename)
value = fi.msg
temp = """#!/bin/bash
#
echo "**********************************************************************"
echo "**********************************************************************"
echo "## ##"
echo "## a d m 6 - A Device Manager for IPv6 packetfiltering ##"
echo "## ##"
echo "## version: 0.2 ##"
echo "## ##"
echo "## device-name: adm6 ##"
echo "## device-type: Debian GNU/Linux ##"
echo "## ##"
echo "## date: 2013-03-18 23:38 ##"
echo "## author: Johannes Hubertz, hubertz-it-consulting GmbH ##"
echo "## ##"
echo "## license: GNU general public license version 3 ##"
echo "## or any later version ##"
echo "## ##"
echo "**********************************************************************"
echo "**********************************************************************"
echo "## ##"
echo "## some magic abbreviations follow ##"
echo "## ##"
#
#POLICY_A='ACCEPT'
POLICY_D='DROP'
#
I6='/sbin/ip6tables '
IP6I='/sbin/ip6tables -A input___new '
IP6O='/sbin/ip6tables -A output__new '
IP6F='/sbin/ip6tables -A forward_new '
#
CHAINS="$CHAINS input__"
CHAINS="$CHAINS output_"
CHAINS="$CHAINS forward"
for chain in $CHAINS
do
/sbin/ip6tables -N ${chain}_act >/dev/null 2>/dev/null
/sbin/ip6tables -N ${chain}_new
done
# but ignore all the boring fault-messages
$I6 -P INPUT $POLICY_D
$I6 -P OUTPUT $POLICY_D
$I6 -P FORWARD $POLICY_D
#
# some things need to pass,
# even if you don't like them
# do local and multicast on every interface
LOCAL="fe80::/10"
MCAST="ff02::/10"
#
$IP6I -p ipv6-icmp -s ${LOCAL} -d ${LOCAL} -j ACCEPT
$IP6O -p ipv6-icmp -s ${LOCAL} -d ${LOCAL} -j ACCEPT
#
$IP6I -p ipv6-icmp -s ${MCAST} -j ACCEPT
$IP6I -p ipv6-icmp -d ${MCAST} -j ACCEPT
$IP6O -p ipv6-icmp -s ${MCAST} -j ACCEPT
#
# all prepared now, individual mangling and rules following
#
# failed reading mangle-file: HOME_DIR/adm6/desc/adm6/mangle-startup, but OK
# ---------------------------------------------------------------------------- #
# Rule-Nr : 1 #
# Pair-Nr : 1 #
# System-Name : adm6 #
# System-Forward : True #
# OS : Debian #
# Asymmetric : True #
# RuleText : should be RuleText #
# Source : 2001:db8:1::1/128 #
# Destin : 2001:db8:2::11/128 #
# Protocol : udp #
# sport : 1024: #
# dport : 4711 #
# Action : accept #
# nonew : True #
# noif : True #
# nostate : True #
# insec : True #
# i_am_s : False #
# i_am_d : True #
# travers : False #
# source-if : eth0 #
# source-rn : 1 #
# src-linklocal : False #
# src-multicast : False #
# destin-if : eth1 #
# destin-rn : 3 #
# dst-linklocal : False #
# dst-multicast : False #
/sbin/ip6tables -A input___new -s 2001:db8:1::1/128 -d 2001:db8:2::11/128 -p udp --sport 0: --dport 4711 -j ACCEPT -m comment --comment "1,1"
/sbin/ip6tables -A output__new -d 2001:db8:1::1/128 -s 2001:db8:2::11/128 -p udp --dport 0: --sport 4711 -j ACCEPT -m comment --comment "1,1"
echo -n ".";# failed reading mangle-file: HOME_DIR/adm6/desc/adm6/mangle-endup, but OK#
#$IP6I -p tcp --dport 22 -j ACCEPT
#$IP6O -p tcp --sport 22 -j ACCEPT
#
# allow ping and pong always (al gusto)
#$IP6O -p ipv6-icmp --icmpv6-type echo-request -j ACCEPT
#$IP6I -p ipv6-icmp --icmpv6-type echo-reply -j ACCEPT
##
#$IP6I -p ipv6-icmp --icmpv6-type echo-request -j ACCEPT
#$IP6O -p ipv6-icmp --icmpv6-type echo-reply -j ACCEPT
#
#ICMPv6types="${ICMPv6types} destination-unreachable"
ICMPv6types="${ICMPv6types} echo-request"
ICMPv6types="${ICMPv6types} echo-reply"
ICMPv6types="${ICMPv6types} neighbour-solicitation"
ICMPv6types="${ICMPv6types} neighbour-advertisement"
ICMPv6types="${ICMPv6types} router-solicitation"
ICMPv6types="${ICMPv6types} router-advertisement"
for icmptype in $ICMPv6types
do
$IP6I -p ipv6-icmp --icmpv6-type $icmptype -j ACCEPT
$IP6O -p ipv6-icmp --icmpv6-type $icmptype -j ACCEPT
done
$IP6I -p ipv6-icmp --icmpv6-type destination-unreachable -j LOG --log-prefix "unreach: " -m limit --limit 30/second --limit-burst 60
$IP6I -p ipv6-icmp --icmpv6-type destination-unreachable -j ACCEPT
#
CHAINS=""
CHAINS="$CHAINS input__"
CHAINS="$CHAINS output_"
CHAINS="$CHAINS forward"
#set -x
for chain in $CHAINS
do
/sbin/ip6tables -E "${chain}_act" "${chain}_old"
/sbin/ip6tables -E "${chain}_new" "${chain}_act"
done
#
$I6 -F INPUT
$I6 -A INPUT -m rt --rt-type 0 -j LOG --log-prefix "rt-0: " -m limit --limit 3/second --limit-burst 6
$I6 -A INPUT -m rt --rt-type 0 -j DROP
$I6 -A INPUT -m rt --rt-type 2 -j LOG --log-prefix "rt-2: " -m limit --limit 3/second --limit-burst 6
$I6 -A INPUT -m rt --rt-type 2 -j DROP
$I6 -A INPUT -i lo -j ACCEPT
$I6 -A INPUT --jump input___act
#
$I6 -F OUTPUT
$I6 -A OUTPUT -o lo -j ACCEPT
$I6 -A OUTPUT --jump output__act
#
$I6 -F FORWARD
$I6 -A FORWARD -m rt --rt-type 0 -j LOG --log-prefix "rt-0: " -m limit --limit 3/second --limit-burst 6
$I6 -A FORWARD -m rt --rt-type 0 -j DROP
$I6 -A FORWARD --jump forward_act
#
for chain in $CHAINS
do
/sbin/ip6tables -F "${chain}_old"
/sbin/ip6tables -X "${chain}_old"
done
$I6 -F logdrop >/dev/null 2>/dev/null
$I6 -X logdrop >/dev/null 2>/dev/null
$I6 -N logdrop
$I6 -A INPUT --jump logdrop
$I6 -A OUTPUT --jump logdrop
$I6 -A FORWARD --jump logdrop
$I6 -A logdrop -j LOG --log-prefix "drp: " -m limit --limit 3/second --limit-burst 6
$I6 -A logdrop -j DROP
#
/sbin/ip6tables-save -c >/root/last-filter
echo "**********************************************************************"
echo "**********************************************************************"
echo "## ##"
echo "## End of generated filter-rules ##"
echo "## ##"
echo "**********************************************************************"
echo "**********************************************************************"
# EOF
"""
expect = temp.replace("HOME_DIR", home_dir_replacement)
value_len = len(value)
expect_len = len(expect)
self.assertEquals(expect_len, value_len)
if __name__ == "__main__":
unittest.main()<|fim▁end|> | fr['Destin'] = "2001:db8:2::1"
fr['Protocol'] = "ip6"
fr['dport'] = "all"
fr['System-Forward'] = True |
<|file_name|>DebianPackageManagerData.cpp<|end_file_name|><|fim▁begin|>//%2005////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development
// Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems.
// Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation, The Open Group.
// Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group.
// Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.;
// EMC Corporation; VERITAS Software Corporation; The Open Group.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN
// ALL COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE. THE SOFTWARE IS PROVIDED
// "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//==============================================================================
//
// Author: Christopher Neufeld <[email protected]>
// David Kennedy <[email protected]>
//
// Modified By: David Kennedy <[email protected]>
// Christopher Neufeld <[email protected]>
// Al Stone <[email protected]>
//
//%////////////////////////////////////////////////////////////////////////////
#include <Pegasus/Common/System.h>
#include <Pegasus/Common/Logger.h>
#include "DebianPackageManagerData.h"
#include <strings.h>
PEGASUS_NAMESPACE_BEGIN
#define DEBUG(X) Logger::put(Logger::DEBUG_LOG, "DebianPackageManagerData", Logger::INFORMATION, "$0", X)
DebianPackageManagerData::DebianPackageManagerData(void)
{
statusFile=NULL;
databaseDirectory=DEFAULT_DEBIAN_DIRECTORY;
}
DebianPackageManagerData::DebianPackageManagerData(const String &inDatabaseDirectory)
{
statusFile=NULL;
databaseDirectory=inDatabaseDirectory;
}
DebianPackageManagerData::~DebianPackageManagerData(void)
{
if(statusFile)
CloseStatusFile(statusFile);
statusFile=NULL;
}
int DebianPackageManagerData::initialize(void)
{
return 0;
}
void DebianPackageManagerData::terminate(void)
{
}
/* Get all the packages and put them in an array */
Array <PackageInformation *> DebianPackageManagerData::GetAllPackages(void)
{
DebianPackageInformation *package;
Array <PackageInformation *> packages;
package = (DebianPackageInformation *) GetFirstPackage();
while(package&&package->isValid()){
packages.append((PackageInformation *)package);
/* Need to keep packages lingering because we are using an
array of pointers to objects */
package=(DebianPackageInformation *)GetNextPackage();
}
EndGetPackage();
return packages;
}
/* Get the first package in the database */
PackageInformation * DebianPackageManagerData::GetFirstPackage(void)
{
String statusFilename(databaseDirectory);
if(statusFile!=NULL){
CloseStatusFile(statusFile);
statusFile=NULL;
}
statusFilename.append('/');
statusFilename.append(DEBIAN_STATUS_FILENAME);
statusFile=OpenStatusFile(statusFilename);
if(statusFile==NULL){
return NULL;
}
return(GetNextPackage());
}
/* Get the next package in the database */
PackageInformation * DebianPackageManagerData::GetNextPackage(void)
{
/*
The select file is in the form of:
Package: syslinux
Status: install ok installed
Priority: optional
Section: base
Installed-Size: 206
Maintainer: Juan Cespedes <[email protected]>
Version: 1.63-1
Depends: libc6 (>= 2.2.3-7)
Suggests: lilo (>= 20)
Description: Bootloader for Linux/i386 using MS-DOS floppies
SYSLINUX is a boot loader for the Linux/i386 operating system which
operates off an MS-DOS/Windows FAT filesystem. It is intended to
simplify first-time installation of Linux, and for creation of rescue
and other special-purpose boot disks.
.
SYSLINUX is probably not suitable as a general purpose boot loader.
However, SYSLINUX has shown itself to be quite useful in a number of
special-purpose applications.
.
You will need support for `msdos' filesystem in order to use this program
To get packages: search for any line that starts with 'Package'
*/
/* Parse the file looking for the keys (delimited by ':') */
return(ReadStatusPackage(statusFile));
}
void DebianPackageManagerData::EndGetPackage(void)
{
if(statusFile)
CloseStatusFile(statusFile);
statusFile=NULL;
}
PackageInformation * DebianPackageManagerData::GetPackage(const String &inName, const String &inVersion)
{
DebianPackageInformation * curPackage;
String junk;
junk = "dpmd-> look for package " + inName + ", version " + inVersion;
DEBUG(junk);
curPackage=(DebianPackageInformation *)GetFirstPackage();
while(curPackage&&curPackage->isValid()){
if (String::equal(curPackage->GetName(), inName) &&
String::equal(curPackage->GetVersion(), inVersion))
{
EndGetPackage();
DEBUG("dpmd-> FOUND package " + curPackage->GetName());
return curPackage;
}
junk = "dpmd-> not package " + curPackage->GetName();
junk.append(", version " + curPackage->GetVersion());
DEBUG(junk);
delete curPackage;
curPackage=(DebianPackageInformation *)GetNextPackage();
}
if (curPackage) {
delete curPackage;
curPackage = NULL;
}
EndGetPackage();
return NULL;
}
FILE * DebianPackageManagerData::OpenStatusFile(const String &filename){
FILE * retval;
retval= fopen(filename.getCString(),"r");
return retval;
}
int DebianPackageManagerData::CloseStatusFile(FILE * handle){
int retval=0;
if(handle)
retval=fclose(handle);
handle=NULL;
return retval;
}
String DebianPackageManagerData::ReadStatusLine(FILE * handle){
char *result;
char *returnLoc;
static char buffer[BUFSIZ];
String resultString;
/* Assume that no line is longer than BUFSIZ */
result=fgets(buffer,BUFSIZ,handle);
if(result==NULL){
return String::EMPTY;
}
/* Remove the trailing whitespace */
returnLoc=rindex(buffer,'\n');
if(returnLoc){
*returnLoc='\0';
}
resultString.assign(buffer);
return resultString;
}
/* Read in an entire package and return it */
DebianPackageInformation * DebianPackageManagerData::ReadStatusPackage(FILE * handle){
String nextLine;
enum parseStatus {NONE, LINE, DESCRIPTION } parser = LINE;
unsigned int colonLocation;
DebianPackageInformation *curPackage;
String curKey;
/* Assume that we are at the beginning of a package */
nextLine=ReadStatusLine(handle);
curPackage=new DebianPackageInformation;
while((nextLine!=String::EMPTY)&&(nextLine!="")&&(nextLine!="\n")){
/* Parse up the line */
switch(parser){
case LINE:
/* We are doing line by line reading */
if(nextLine[0]!=' '){ /* If this is a description, let if fall through */
colonLocation=nextLine.find(':');
if(colonLocation==PEG_NOT_FOUND){
/* parse error */
delete curPackage;
return NULL;
}
curKey=nextLine.subString(0,colonLocation);
curPackage->add(curKey,nextLine.subString(colonLocation+2));
break;
}
/* No break because the if falls through */
case DESCRIPTION:
/* We are reading in the description (multi line) */
parser=DESCRIPTION;
if(nextLine!="\n"){
curPackage->add(curKey,nextLine);
}
else {
parser=LINE;
return curPackage;
}
break;
default:
/* A parsing error occurred */
delete curPackage;
return NULL;
}
nextLine=ReadStatusLine(handle);
}
return curPackage;
}<|fim▁hole|><|fim▁end|> |
PEGASUS_NAMESPACE_END |
<|file_name|>SpellAuras.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2005-2013 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Common.h"
#include "Database/DatabaseEnv.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "Opcodes.h"
#include "Log.h"
#include "UpdateMask.h"
#include "World.h"
#include "ObjectMgr.h"
#include "SpellMgr.h"
#include "Player.h"
#include "Unit.h"
#include "Spell.h"
#include "DynamicObject.h"
#include "Group.h"
#include "UpdateData.h"
#include "ObjectAccessor.h"
#include "Policies/Singleton.h"
#include "Totem.h"
#include "Creature.h"
#include "Formulas.h"
#include "BattleGround/BattleGround.h"
#include "OutdoorPvP/OutdoorPvP.h"
#include "CreatureAI.h"
#include "ScriptMgr.h"
#include "Util.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "CellImpl.h"
#include "MapManager.h"
#define NULL_AURA_SLOT 0xFF
pAuraHandler AuraHandler[TOTAL_AURAS] =
{
&Aura::HandleNULL, // 0 SPELL_AURA_NONE
&Aura::HandleBindSight, // 1 SPELL_AURA_BIND_SIGHT
&Aura::HandleModPossess, // 2 SPELL_AURA_MOD_POSSESS
&Aura::HandlePeriodicDamage, // 3 SPELL_AURA_PERIODIC_DAMAGE
&Aura::HandleAuraDummy, // 4 SPELL_AURA_DUMMY
&Aura::HandleModConfuse, // 5 SPELL_AURA_MOD_CONFUSE
&Aura::HandleModCharm, // 6 SPELL_AURA_MOD_CHARM
&Aura::HandleModFear, // 7 SPELL_AURA_MOD_FEAR
&Aura::HandlePeriodicHeal, // 8 SPELL_AURA_PERIODIC_HEAL
&Aura::HandleModAttackSpeed, // 9 SPELL_AURA_MOD_ATTACKSPEED
&Aura::HandleModThreat, // 10 SPELL_AURA_MOD_THREAT
&Aura::HandleModTaunt, // 11 SPELL_AURA_MOD_TAUNT
&Aura::HandleAuraModStun, // 12 SPELL_AURA_MOD_STUN
&Aura::HandleModDamageDone, // 13 SPELL_AURA_MOD_DAMAGE_DONE
&Aura::HandleNoImmediateEffect, // 14 SPELL_AURA_MOD_DAMAGE_TAKEN implemented in Unit::MeleeDamageBonusTaken and Unit::SpellBaseDamageBonusTaken
&Aura::HandleNoImmediateEffect, // 15 SPELL_AURA_DAMAGE_SHIELD implemented in Unit::DealMeleeDamage
&Aura::HandleModStealth, // 16 SPELL_AURA_MOD_STEALTH
&Aura::HandleNoImmediateEffect, // 17 SPELL_AURA_MOD_STEALTH_DETECT implemented in Unit::isVisibleForOrDetect
&Aura::HandleInvisibility, // 18 SPELL_AURA_MOD_INVISIBILITY
&Aura::HandleInvisibilityDetect, // 19 SPELL_AURA_MOD_INVISIBILITY_DETECTION
&Aura::HandleAuraModTotalHealthPercentRegen, // 20 SPELL_AURA_OBS_MOD_HEALTH
&Aura::HandleAuraModTotalManaPercentRegen, // 21 SPELL_AURA_OBS_MOD_MANA
&Aura::HandleAuraModResistance, // 22 SPELL_AURA_MOD_RESISTANCE
&Aura::HandlePeriodicTriggerSpell, // 23 SPELL_AURA_PERIODIC_TRIGGER_SPELL
&Aura::HandlePeriodicEnergize, // 24 SPELL_AURA_PERIODIC_ENERGIZE
&Aura::HandleAuraModPacify, // 25 SPELL_AURA_MOD_PACIFY
&Aura::HandleAuraModRoot, // 26 SPELL_AURA_MOD_ROOT
&Aura::HandleAuraModSilence, // 27 SPELL_AURA_MOD_SILENCE
&Aura::HandleNoImmediateEffect, // 28 SPELL_AURA_REFLECT_SPELLS implement in Unit::SpellHitResult
&Aura::HandleAuraModStat, // 29 SPELL_AURA_MOD_STAT
&Aura::HandleAuraModSkill, // 30 SPELL_AURA_MOD_SKILL
&Aura::HandleAuraModIncreaseSpeed, // 31 SPELL_AURA_MOD_INCREASE_SPEED
&Aura::HandleAuraModIncreaseMountedSpeed, // 32 SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED
&Aura::HandleAuraModDecreaseSpeed, // 33 SPELL_AURA_MOD_DECREASE_SPEED
&Aura::HandleAuraModIncreaseHealth, // 34 SPELL_AURA_MOD_INCREASE_HEALTH
&Aura::HandleAuraModIncreaseEnergy, // 35 SPELL_AURA_MOD_INCREASE_ENERGY
&Aura::HandleAuraModShapeshift, // 36 SPELL_AURA_MOD_SHAPESHIFT
&Aura::HandleAuraModEffectImmunity, // 37 SPELL_AURA_EFFECT_IMMUNITY
&Aura::HandleAuraModStateImmunity, // 38 SPELL_AURA_STATE_IMMUNITY
&Aura::HandleAuraModSchoolImmunity, // 39 SPELL_AURA_SCHOOL_IMMUNITY
&Aura::HandleAuraModDmgImmunity, // 40 SPELL_AURA_DAMAGE_IMMUNITY
&Aura::HandleAuraModDispelImmunity, // 41 SPELL_AURA_DISPEL_IMMUNITY
&Aura::HandleAuraProcTriggerSpell, // 42 SPELL_AURA_PROC_TRIGGER_SPELL implemented in Unit::ProcDamageAndSpellFor and Unit::HandleProcTriggerSpell
&Aura::HandleNoImmediateEffect, // 43 SPELL_AURA_PROC_TRIGGER_DAMAGE implemented in Unit::ProcDamageAndSpellFor
&Aura::HandleAuraTrackCreatures, // 44 SPELL_AURA_TRACK_CREATURES
&Aura::HandleAuraTrackResources, // 45 SPELL_AURA_TRACK_RESOURCES
&Aura::HandleUnused, // 46 SPELL_AURA_46
&Aura::HandleAuraModParryPercent, // 47 SPELL_AURA_MOD_PARRY_PERCENT
&Aura::HandleUnused, // 48 SPELL_AURA_48
&Aura::HandleAuraModDodgePercent, // 49 SPELL_AURA_MOD_DODGE_PERCENT
&Aura::HandleUnused, // 50 SPELL_AURA_MOD_BLOCK_SKILL obsolete?
&Aura::HandleAuraModBlockPercent, // 51 SPELL_AURA_MOD_BLOCK_PERCENT
&Aura::HandleAuraModCritPercent, // 52 SPELL_AURA_MOD_CRIT_PERCENT
&Aura::HandlePeriodicLeech, // 53 SPELL_AURA_PERIODIC_LEECH
&Aura::HandleModHitChance, // 54 SPELL_AURA_MOD_HIT_CHANCE
&Aura::HandleModSpellHitChance, // 55 SPELL_AURA_MOD_SPELL_HIT_CHANCE
&Aura::HandleAuraTransform, // 56 SPELL_AURA_TRANSFORM
&Aura::HandleModSpellCritChance, // 57 SPELL_AURA_MOD_SPELL_CRIT_CHANCE
&Aura::HandleAuraModIncreaseSwimSpeed, // 58 SPELL_AURA_MOD_INCREASE_SWIM_SPEED
&Aura::HandleNoImmediateEffect, // 59 SPELL_AURA_MOD_DAMAGE_DONE_CREATURE implemented in Unit::MeleeDamageBonusDone and Unit::SpellDamageBonusDone
&Aura::HandleAuraModPacifyAndSilence, // 60 SPELL_AURA_MOD_PACIFY_SILENCE
&Aura::HandleAuraModScale, // 61 SPELL_AURA_MOD_SCALE
&Aura::HandlePeriodicHealthFunnel, // 62 SPELL_AURA_PERIODIC_HEALTH_FUNNEL
&Aura::HandleUnused, // 63 SPELL_AURA_PERIODIC_MANA_FUNNEL obsolete?
&Aura::HandlePeriodicManaLeech, // 64 SPELL_AURA_PERIODIC_MANA_LEECH
&Aura::HandleModCastingSpeed, // 65 SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK
&Aura::HandleFeignDeath, // 66 SPELL_AURA_FEIGN_DEATH
&Aura::HandleAuraModDisarm, // 67 SPELL_AURA_MOD_DISARM
&Aura::HandleAuraModStalked, // 68 SPELL_AURA_MOD_STALKED
&Aura::HandleSchoolAbsorb, // 69 SPELL_AURA_SCHOOL_ABSORB implemented in Unit::CalculateAbsorbAndResist
&Aura::HandleUnused, // 70 SPELL_AURA_EXTRA_ATTACKS Useless, used by only one spell that has only visual effect
&Aura::HandleModSpellCritChanceShool, // 71 SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL
&Aura::HandleModPowerCostPCT, // 72 SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT
&Aura::HandleModPowerCost, // 73 SPELL_AURA_MOD_POWER_COST_SCHOOL
&Aura::HandleNoImmediateEffect, // 74 SPELL_AURA_REFLECT_SPELLS_SCHOOL implemented in Unit::SpellHitResult
&Aura::HandleNoImmediateEffect, // 75 SPELL_AURA_MOD_LANGUAGE implemented in WorldSession::HandleMessagechatOpcode
&Aura::HandleFarSight, // 76 SPELL_AURA_FAR_SIGHT
&Aura::HandleModMechanicImmunity, // 77 SPELL_AURA_MECHANIC_IMMUNITY
&Aura::HandleAuraMounted, // 78 SPELL_AURA_MOUNTED
&Aura::HandleModDamagePercentDone, // 79 SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
&Aura::HandleModPercentStat, // 80 SPELL_AURA_MOD_PERCENT_STAT
&Aura::HandleNoImmediateEffect, // 81 SPELL_AURA_SPLIT_DAMAGE_PCT implemented in Unit::CalculateAbsorbAndResist
&Aura::HandleWaterBreathing, // 82 SPELL_AURA_WATER_BREATHING
&Aura::HandleModBaseResistance, // 83 SPELL_AURA_MOD_BASE_RESISTANCE
&Aura::HandleModRegen, // 84 SPELL_AURA_MOD_REGEN
&Aura::HandleModPowerRegen, // 85 SPELL_AURA_MOD_POWER_REGEN
&Aura::HandleChannelDeathItem, // 86 SPELL_AURA_CHANNEL_DEATH_ITEM
&Aura::HandleNoImmediateEffect, // 87 SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN implemented in Unit::MeleeDamageBonusTaken and Unit::SpellDamageBonusTaken
&Aura::HandleNoImmediateEffect, // 88 SPELL_AURA_MOD_HEALTH_REGEN_PERCENT implemented in Player::RegenerateHealth
&Aura::HandlePeriodicDamagePCT, // 89 SPELL_AURA_PERIODIC_DAMAGE_PERCENT
&Aura::HandleUnused, // 90 SPELL_AURA_MOD_RESIST_CHANCE Useless
&Aura::HandleNoImmediateEffect, // 91 SPELL_AURA_MOD_DETECT_RANGE implemented in Creature::GetAttackDistance
&Aura::HandlePreventFleeing, // 92 SPELL_AURA_PREVENTS_FLEEING
&Aura::HandleModUnattackable, // 93 SPELL_AURA_MOD_UNATTACKABLE
&Aura::HandleNoImmediateEffect, // 94 SPELL_AURA_INTERRUPT_REGEN implemented in Player::RegenerateAll
&Aura::HandleAuraGhost, // 95 SPELL_AURA_GHOST
&Aura::HandleNoImmediateEffect, // 96 SPELL_AURA_SPELL_MAGNET implemented in Unit::SelectMagnetTarget
&Aura::HandleManaShield, // 97 SPELL_AURA_MANA_SHIELD implemented in Unit::CalculateAbsorbAndResist
&Aura::HandleAuraModSkill, // 98 SPELL_AURA_MOD_SKILL_TALENT
&Aura::HandleAuraModAttackPower, // 99 SPELL_AURA_MOD_ATTACK_POWER
&Aura::HandleUnused, //100 SPELL_AURA_AURAS_VISIBLE obsolete? all player can see all auras now
&Aura::HandleModResistancePercent, //101 SPELL_AURA_MOD_RESISTANCE_PCT
&Aura::HandleNoImmediateEffect, //102 SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS implemented in Unit::MeleeDamageBonusDone
&Aura::HandleAuraModTotalThreat, //103 SPELL_AURA_MOD_TOTAL_THREAT
&Aura::HandleAuraWaterWalk, //104 SPELL_AURA_WATER_WALK
&Aura::HandleAuraFeatherFall, //105 SPELL_AURA_FEATHER_FALL
&Aura::HandleAuraHover, //106 SPELL_AURA_HOVER
&Aura::HandleAddModifier, //107 SPELL_AURA_ADD_FLAT_MODIFIER
&Aura::HandleAddModifier, //108 SPELL_AURA_ADD_PCT_MODIFIER
&Aura::HandleNoImmediateEffect, //109 SPELL_AURA_ADD_TARGET_TRIGGER
&Aura::HandleModPowerRegenPCT, //110 SPELL_AURA_MOD_POWER_REGEN_PERCENT
&Aura::HandleNoImmediateEffect, //111 SPELL_AURA_ADD_CASTER_HIT_TRIGGER implemented in Unit::SelectMagnetTarget
&Aura::HandleNoImmediateEffect, //112 SPELL_AURA_OVERRIDE_CLASS_SCRIPTS implemented in diff functions.
&Aura::HandleNoImmediateEffect, //113 SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN implemented in Unit::MeleeDamageBonusTaken
&Aura::HandleNoImmediateEffect, //114 SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT implemented in Unit::MeleeDamageBonusTaken
&Aura::HandleNoImmediateEffect, //115 SPELL_AURA_MOD_HEALING implemented in Unit::SpellBaseHealingBonusTaken
&Aura::HandleNoImmediateEffect, //116 SPELL_AURA_MOD_REGEN_DURING_COMBAT imppemented in Player::RegenerateAll and Player::RegenerateHealth
&Aura::HandleNoImmediateEffect, //117 SPELL_AURA_MOD_MECHANIC_RESISTANCE implemented in Unit::MagicSpellHitResult
&Aura::HandleNoImmediateEffect, //118 SPELL_AURA_MOD_HEALING_PCT implemented in Unit::SpellHealingBonusTaken
&Aura::HandleUnused, //119 SPELL_AURA_SHARE_PET_TRACKING useless
&Aura::HandleAuraUntrackable, //120 SPELL_AURA_UNTRACKABLE
&Aura::HandleAuraEmpathy, //121 SPELL_AURA_EMPATHY
&Aura::HandleModOffhandDamagePercent, //122 SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT
&Aura::HandleModTargetResistance, //123 SPELL_AURA_MOD_TARGET_RESISTANCE
&Aura::HandleAuraModRangedAttackPower, //124 SPELL_AURA_MOD_RANGED_ATTACK_POWER
&Aura::HandleNoImmediateEffect, //125 SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN implemented in Unit::MeleeDamageBonusTaken
&Aura::HandleNoImmediateEffect, //126 SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT implemented in Unit::MeleeDamageBonusTaken
&Aura::HandleNoImmediateEffect, //127 SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS implemented in Unit::MeleeDamageBonusDone
&Aura::HandleModPossessPet, //128 SPELL_AURA_MOD_POSSESS_PET
&Aura::HandleAuraModIncreaseSpeed, //129 SPELL_AURA_MOD_SPEED_ALWAYS
&Aura::HandleAuraModIncreaseMountedSpeed, //130 SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS
&Aura::HandleNoImmediateEffect, //131 SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS implemented in Unit::MeleeDamageBonusDone
&Aura::HandleAuraModIncreaseEnergyPercent, //132 SPELL_AURA_MOD_INCREASE_ENERGY_PERCENT
&Aura::HandleAuraModIncreaseHealthPercent, //133 SPELL_AURA_MOD_INCREASE_HEALTH_PERCENT
&Aura::HandleAuraModRegenInterrupt, //134 SPELL_AURA_MOD_MANA_REGEN_INTERRUPT
&Aura::HandleModHealingDone, //135 SPELL_AURA_MOD_HEALING_DONE
&Aura::HandleNoImmediateEffect, //136 SPELL_AURA_MOD_HEALING_DONE_PERCENT implemented in Unit::SpellHealingBonusDone
&Aura::HandleModTotalPercentStat, //137 SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE
&Aura::HandleModMeleeSpeedPct, //138 SPELL_AURA_MOD_MELEE_HASTE
&Aura::HandleForceReaction, //139 SPELL_AURA_FORCE_REACTION
&Aura::HandleAuraModRangedHaste, //140 SPELL_AURA_MOD_RANGED_HASTE
&Aura::HandleRangedAmmoHaste, //141 SPELL_AURA_MOD_RANGED_AMMO_HASTE
&Aura::HandleAuraModBaseResistancePCT, //142 SPELL_AURA_MOD_BASE_RESISTANCE_PCT
&Aura::HandleAuraModResistanceExclusive, //143 SPELL_AURA_MOD_RESISTANCE_EXCLUSIVE
&Aura::HandleAuraSafeFall, //144 SPELL_AURA_SAFE_FALL implemented in WorldSession::HandleMovementOpcodes
&Aura::HandleUnused, //145 SPELL_AURA_CHARISMA obsolete?
&Aura::HandleUnused, //146 SPELL_AURA_PERSUADED obsolete?
&Aura::HandleModMechanicImmunityMask, //147 SPELL_AURA_MECHANIC_IMMUNITY_MASK implemented in Unit::IsImmuneToSpell and Unit::IsImmuneToSpellEffect (check part)
&Aura::HandleAuraRetainComboPoints, //148 SPELL_AURA_RETAIN_COMBO_POINTS
&Aura::HandleNoImmediateEffect, //149 SPELL_AURA_RESIST_PUSHBACK implemented in Spell::Delayed and Spell::DelayedChannel
&Aura::HandleShieldBlockValue, //150 SPELL_AURA_MOD_SHIELD_BLOCKVALUE_PCT
&Aura::HandleAuraTrackStealthed, //151 SPELL_AURA_TRACK_STEALTHED
&Aura::HandleNoImmediateEffect, //152 SPELL_AURA_MOD_DETECTED_RANGE implemented in Creature::GetAttackDistance
&Aura::HandleNoImmediateEffect, //153 SPELL_AURA_SPLIT_DAMAGE_FLAT implemented in Unit::CalculateAbsorbAndResist
&Aura::HandleNoImmediateEffect, //154 SPELL_AURA_MOD_STEALTH_LEVEL implemented in Unit::isVisibleForOrDetect
&Aura::HandleNoImmediateEffect, //155 SPELL_AURA_MOD_WATER_BREATHING implemented in Player::getMaxTimer
&Aura::HandleNoImmediateEffect, //156 SPELL_AURA_MOD_REPUTATION_GAIN implemented in Player::CalculateReputationGain
&Aura::HandleUnused, //157 SPELL_AURA_PET_DAMAGE_MULTI (single test like spell 20782, also single for 214 aura)
&Aura::HandleShieldBlockValue, //158 SPELL_AURA_MOD_SHIELD_BLOCKVALUE
&Aura::HandleNoImmediateEffect, //159 SPELL_AURA_NO_PVP_CREDIT implemented in Player::RewardHonor
&Aura::HandleNoImmediateEffect, //160 SPELL_AURA_MOD_AOE_AVOIDANCE implemented in Unit::MagicSpellHitResult
&Aura::HandleNoImmediateEffect, //161 SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT implemented in Player::RegenerateAll and Player::RegenerateHealth
&Aura::HandleAuraPowerBurn, //162 SPELL_AURA_POWER_BURN_MANA
&Aura::HandleNoImmediateEffect, //163 SPELL_AURA_MOD_CRIT_DAMAGE_BONUS implemented in Unit::CalculateMeleeDamage and Unit::SpellCriticalDamageBonus
&Aura::HandleUnused, //164 useless, only one test spell
&Aura::HandleNoImmediateEffect, //165 SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS implemented in Unit::MeleeDamageBonusDone
&Aura::HandleAuraModAttackPowerPercent, //166 SPELL_AURA_MOD_ATTACK_POWER_PCT
&Aura::HandleAuraModRangedAttackPowerPercent, //167 SPELL_AURA_MOD_RANGED_ATTACK_POWER_PCT
&Aura::HandleNoImmediateEffect, //168 SPELL_AURA_MOD_DAMAGE_DONE_VERSUS implemented in Unit::SpellDamageBonusDone, Unit::MeleeDamageBonusDone
&Aura::HandleNoImmediateEffect, //169 SPELL_AURA_MOD_CRIT_PERCENT_VERSUS implemented in Unit::DealDamageBySchool, Unit::DoAttackDamage, Unit::SpellCriticalBonus
&Aura::HandleDetectAmore, //170 SPELL_AURA_DETECT_AMORE only for Detect Amore spell
&Aura::HandleAuraModIncreaseSpeed, //171 SPELL_AURA_MOD_SPEED_NOT_STACK
&Aura::HandleAuraModIncreaseMountedSpeed, //172 SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK
&Aura::HandleUnused, //173 SPELL_AURA_ALLOW_CHAMPION_SPELLS only for Proclaim Champion spell
&Aura::HandleModSpellDamagePercentFromStat, //174 SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT implemented in Unit::SpellBaseDamageBonusDone
&Aura::HandleModSpellHealingPercentFromStat, //175 SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT implemented in Unit::SpellBaseHealingBonusDone
&Aura::HandleSpiritOfRedemption, //176 SPELL_AURA_SPIRIT_OF_REDEMPTION only for Spirit of Redemption spell, die at aura end
&Aura::HandleNULL, //177 SPELL_AURA_AOE_CHARM
&Aura::HandleNoImmediateEffect, //178 SPELL_AURA_MOD_DEBUFF_RESISTANCE implemented in Unit::MagicSpellHitResult
&Aura::HandleNoImmediateEffect, //179 SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE implemented in Unit::SpellCriticalBonus
&Aura::HandleNoImmediateEffect, //180 SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS implemented in Unit::SpellDamageBonusDone
&Aura::HandleUnused, //181 SPELL_AURA_MOD_FLAT_SPELL_CRIT_DAMAGE_VERSUS unused
&Aura::HandleAuraModResistenceOfStatPercent, //182 SPELL_AURA_MOD_RESISTANCE_OF_STAT_PERCENT
&Aura::HandleNoImmediateEffect, //183 SPELL_AURA_MOD_CRITICAL_THREAT only used in 28746, implemented in ThreatCalcHelper::CalcThreat
&Aura::HandleNoImmediateEffect, //184 SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE implemented in Unit::RollMeleeOutcomeAgainst
&Aura::HandleNoImmediateEffect, //185 SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE implemented in Unit::RollMeleeOutcomeAgainst
&Aura::HandleNoImmediateEffect, //186 SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE implemented in Unit::MagicSpellHitResult
&Aura::HandleNoImmediateEffect, //187 SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE implemented in Unit::GetUnitCriticalChance
&Aura::HandleNoImmediateEffect, //188 SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE implemented in Unit::GetUnitCriticalChance
&Aura::HandleModRating, //189 SPELL_AURA_MOD_RATING
&Aura::HandleNoImmediateEffect, //190 SPELL_AURA_MOD_FACTION_REPUTATION_GAIN implemented in Player::CalculateReputationGain
&Aura::HandleAuraModUseNormalSpeed, //191 SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED
&Aura::HandleModMeleeRangedSpeedPct, //192 SPELL_AURA_MOD_MELEE_RANGED_HASTE
&Aura::HandleModCombatSpeedPct, //193 SPELL_AURA_HASTE_ALL (in fact combat (any type attack) speed pct)
&Aura::HandleUnused, //194 SPELL_AURA_MOD_DEPRICATED_1 not used now (old SPELL_AURA_MOD_SPELL_DAMAGE_OF_INTELLECT)
&Aura::HandleUnused, //195 SPELL_AURA_MOD_DEPRICATED_2 not used now (old SPELL_AURA_MOD_SPELL_HEALING_OF_INTELLECT)
&Aura::HandleNULL, //196 SPELL_AURA_MOD_COOLDOWN
&Aura::HandleNoImmediateEffect, //197 SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE implemented in Unit::SpellCriticalBonus Unit::GetUnitCriticalChance
&Aura::HandleUnused, //198 SPELL_AURA_MOD_ALL_WEAPON_SKILLS
&Aura::HandleNoImmediateEffect, //199 SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT implemented in Unit::MagicSpellHitResult
&Aura::HandleNoImmediateEffect, //200 SPELL_AURA_MOD_XP_PCT implemented in Player::GiveXP
&Aura::HandleAuraAllowFlight, //201 SPELL_AURA_FLY this aura enable flight mode...
&Aura::HandleNoImmediateEffect, //202 SPELL_AURA_IGNORE_COMBAT_RESULT implemented in Unit::MeleeSpellHitResult
&Aura::HandleNoImmediateEffect, //203 SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE implemented in Unit::CalculateMeleeDamage and Unit::SpellCriticalDamageBonus
&Aura::HandleNoImmediateEffect, //204 SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE implemented in Unit::CalculateMeleeDamage and Unit::SpellCriticalDamageBonus
&Aura::HandleNoImmediateEffect, //205 SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_DAMAGE implemented in Unit::SpellCriticalDamageBonus
&Aura::HandleAuraModIncreaseFlightSpeed, //206 SPELL_AURA_MOD_FLIGHT_SPEED
&Aura::HandleAuraModIncreaseFlightSpeed, //207 SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED
&Aura::HandleAuraModIncreaseFlightSpeed, //208 SPELL_AURA_MOD_FLIGHT_SPEED_STACKING
&Aura::HandleAuraModIncreaseFlightSpeed, //209 SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED_STACKING
&Aura::HandleAuraModIncreaseFlightSpeed, //210 SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACKING
&Aura::HandleAuraModIncreaseFlightSpeed, //211 SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED_NOT_STACKING
&Aura::HandleAuraModRangedAttackPowerOfStatPercent, //212 SPELL_AURA_MOD_RANGED_ATTACK_POWER_OF_STAT_PERCENT
&Aura::HandleNoImmediateEffect, //213 SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT implemented in Player::RewardRage
&Aura::HandleNULL, //214 Tamed Pet Passive
&Aura::HandleArenaPreparation, //215 SPELL_AURA_ARENA_PREPARATION
&Aura::HandleModCastingSpeed, //216 SPELL_AURA_HASTE_SPELLS
&Aura::HandleUnused, //217 unused
&Aura::HandleAuraModRangedHaste, //218 SPELL_AURA_HASTE_RANGED
&Aura::HandleModManaRegen, //219 SPELL_AURA_MOD_MANA_REGEN_FROM_STAT
&Aura::HandleUnused, //220 SPELL_AURA_MOD_RATING_FROM_STAT
&Aura::HandleNULL, //221 ignored
&Aura::HandleUnused, //222 unused
&Aura::HandleNULL, //223 Cold Stare
&Aura::HandleUnused, //224 unused
&Aura::HandleNoImmediateEffect, //225 SPELL_AURA_PRAYER_OF_MENDING
&Aura::HandleAuraPeriodicDummy, //226 SPELL_AURA_PERIODIC_DUMMY
&Aura::HandlePeriodicTriggerSpellWithValue, //227 SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE
&Aura::HandleNoImmediateEffect, //228 SPELL_AURA_DETECT_STEALTH
&Aura::HandleNoImmediateEffect, //229 SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE implemented in Unit::SpellDamageBonusTaken
&Aura::HandleAuraModIncreaseMaxHealth, //230 Commanding Shout
&Aura::HandleNoImmediateEffect, //231 SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE
&Aura::HandleNoImmediateEffect, //232 SPELL_AURA_MECHANIC_DURATION_MOD implement in Unit::CalculateAuraDuration
&Aura::HandleNULL, //233 set model id to the one of the creature with id m_modifier.m_miscvalue
&Aura::HandleNoImmediateEffect, //234 SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK implement in Unit::CalculateAuraDuration
&Aura::HandleAuraModDispelResist, //235 SPELL_AURA_MOD_DISPEL_RESIST implement in Unit::MagicSpellHitResult
&Aura::HandleUnused, //236 unused
&Aura::HandleModSpellDamagePercentFromAttackPower, //237 SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER implemented in Unit::SpellBaseDamageBonusDone
&Aura::HandleModSpellHealingPercentFromAttackPower, //238 SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER implemented in Unit::SpellBaseHealingBonusDone
&Aura::HandleAuraModScale, //239 SPELL_AURA_MOD_SCALE_2 only in Noggenfogger Elixir (16595) before 2.3.0 aura 61
&Aura::HandleAuraModExpertise, //240 SPELL_AURA_MOD_EXPERTISE
&Aura::HandleForceMoveForward, //241 Forces the caster to move forward
&Aura::HandleUnused, //242 unused
&Aura::HandleUnused, //243 used by two test spells
&Aura::HandleComprehendLanguage, //244 SPELL_AURA_COMPREHEND_LANGUAGE
&Aura::HandleUnused, //245 unused
&Aura::HandleUnused, //246 unused
&Aura::HandleAuraMirrorImage, //247 SPELL_AURA_MIRROR_IMAGE target to become a clone of the caster
&Aura::HandleNoImmediateEffect, //248 SPELL_AURA_MOD_COMBAT_RESULT_CHANCE implemented in Unit::RollMeleeOutcomeAgainst
&Aura::HandleNULL, //249
&Aura::HandleAuraModIncreaseHealth, //250 SPELL_AURA_MOD_INCREASE_HEALTH_2
&Aura::HandleNULL, //251 SPELL_AURA_MOD_ENEMY_DODGE
&Aura::HandleUnused, //252 unused
&Aura::HandleUnused, //253 unused
&Aura::HandleUnused, //254 unused
&Aura::HandleUnused, //255 unused
&Aura::HandleUnused, //256 unused
&Aura::HandleUnused, //257 unused
&Aura::HandleUnused, //258 unused
&Aura::HandleUnused, //259 unused
&Aura::HandleUnused, //260 unused
&Aura::HandleNULL //261 SPELL_AURA_261 some phased state (44856 spell)
};
static AuraType const frozenAuraTypes[] = { SPELL_AURA_MOD_ROOT, SPELL_AURA_MOD_STUN, SPELL_AURA_NONE };
Aura::Aura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target, Unit* caster, Item* castItem) :
m_spellmod(NULL), m_periodicTimer(0), m_periodicTick(0), m_removeMode(AURA_REMOVE_BY_DEFAULT),
m_effIndex(eff), m_positive(false), m_isPeriodic(false), m_isAreaAura(false),
m_isPersistent(false), m_in_use(0), m_spellAuraHolder(holder)
{
MANGOS_ASSERT(target);
MANGOS_ASSERT(spellproto && spellproto == sSpellStore.LookupEntry(spellproto->Id) && "`info` must be pointer to sSpellStore element");
m_currentBasePoints = currentBasePoints ? *currentBasePoints : spellproto->CalculateSimpleValue(eff);
m_positive = IsPositiveEffect(spellproto, m_effIndex);
m_applyTime = time(NULL);
int32 damage;
if (!caster)
damage = m_currentBasePoints;
else
{
damage = caster->CalculateSpellDamage(target, spellproto, m_effIndex, &m_currentBasePoints);
if (!damage && castItem && castItem->GetItemSuffixFactor())
{
ItemRandomSuffixEntry const* item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(castItem->GetItemRandomPropertyId()));
if (item_rand_suffix)
{
for (int k = 0; k < 3; ++k)
{
SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(item_rand_suffix->enchant_id[k]);
if (pEnchant)
{
for (int t = 0; t < 3; ++t)
{
if (pEnchant->spellid[t] != spellproto->Id)
continue;
damage = uint32((item_rand_suffix->prefix[k] * castItem->GetItemSuffixFactor()) / 10000);
break;
}
}
if (damage)
break;
}
}
}
}
DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "Aura: construct Spellid : %u, Aura : %u Target : %d Damage : %d", spellproto->Id, spellproto->EffectApplyAuraName[eff], spellproto->EffectImplicitTargetA[eff], damage);
SetModifier(AuraType(spellproto->EffectApplyAuraName[eff]), damage, spellproto->EffectAmplitude[eff], spellproto->EffectMiscValue[eff]);
Player* modOwner = caster ? caster->GetSpellModOwner() : NULL;
// Apply periodic time mod
if (modOwner && m_modifier.periodictime)
modOwner->ApplySpellMod(spellproto->Id, SPELLMOD_ACTIVATION_TIME, m_modifier.periodictime);
// Start periodic on next tick or at aura apply
if (!spellproto->HasAttribute(SPELL_ATTR_EX5_START_PERIODIC_AT_APPLY))
m_periodicTimer = m_modifier.periodictime;
}
Aura::~Aura()
{
}
AreaAura::AreaAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target,
Unit* caster, Item* castItem) : Aura(spellproto, eff, currentBasePoints, holder, target, caster, castItem)
{
m_isAreaAura = true;
// caster==NULL in constructor args if target==caster in fact
Unit* caster_ptr = caster ? caster : target;
m_radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellproto->EffectRadiusIndex[m_effIndex]));
if (Player* modOwner = caster_ptr->GetSpellModOwner())
modOwner->ApplySpellMod(spellproto->Id, SPELLMOD_RADIUS, m_radius);
switch (spellproto->Effect[eff])
{
case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
m_areaAuraType = AREA_AURA_PARTY;
break;
case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND:
m_areaAuraType = AREA_AURA_FRIEND;
break;
case SPELL_EFFECT_APPLY_AREA_AURA_ENEMY:
m_areaAuraType = AREA_AURA_ENEMY;
if (target == caster_ptr)
m_modifier.m_auraname = SPELL_AURA_NONE; // Do not do any effect on self
break;
case SPELL_EFFECT_APPLY_AREA_AURA_PET:
m_areaAuraType = AREA_AURA_PET;
break;
case SPELL_EFFECT_APPLY_AREA_AURA_OWNER:
m_areaAuraType = AREA_AURA_OWNER;
if (target == caster_ptr)
m_modifier.m_auraname = SPELL_AURA_NONE;
break;
default:
sLog.outError("Wrong spell effect in AreaAura constructor");
MANGOS_ASSERT(false);
break;
}
// totems are immune to any kind of area auras
if (target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->IsTotem())
m_modifier.m_auraname = SPELL_AURA_NONE;
}
AreaAura::~AreaAura()
{
}
PersistentAreaAura::PersistentAreaAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target,
Unit* caster, Item* castItem) : Aura(spellproto, eff, currentBasePoints, holder, target, caster, castItem)
{
m_isPersistent = true;
}
PersistentAreaAura::~PersistentAreaAura()
{
}
SingleEnemyTargetAura::SingleEnemyTargetAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target,
Unit* caster, Item* castItem) : Aura(spellproto, eff, currentBasePoints, holder, target, caster, castItem)
{
if (caster)
m_castersTargetGuid = caster->GetTypeId() == TYPEID_PLAYER ? ((Player*)caster)->GetSelectionGuid() : caster->GetTargetGuid();
}
SingleEnemyTargetAura::~SingleEnemyTargetAura()
{
}
Unit* SingleEnemyTargetAura::GetTriggerTarget() const
{
return ObjectAccessor::GetUnit(*(m_spellAuraHolder->GetTarget()), m_castersTargetGuid);
}
Aura* CreateAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target, Unit* caster, Item* castItem)
{
if (IsAreaAuraEffect(spellproto->Effect[eff]))
return new AreaAura(spellproto, eff, currentBasePoints, holder, target, caster, castItem);
uint32 triggeredSpellId = spellproto->EffectTriggerSpell[eff];
if (SpellEntry const* triggeredSpellInfo = sSpellStore.LookupEntry(triggeredSpellId))
for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
if (triggeredSpellInfo->EffectImplicitTargetA[i] == TARGET_SINGLE_ENEMY)
return new SingleEnemyTargetAura(spellproto, eff, currentBasePoints, holder, target, caster, castItem);
return new Aura(spellproto, eff, currentBasePoints, holder, target, caster, castItem);
}
SpellAuraHolder* CreateSpellAuraHolder(SpellEntry const* spellproto, Unit* target, WorldObject* caster, Item* castItem)
{
return new SpellAuraHolder(spellproto, target, caster, castItem);
}
void Aura::SetModifier(AuraType t, int32 a, uint32 pt, int32 miscValue)
{
m_modifier.m_auraname = t;
m_modifier.m_amount = a;
m_modifier.m_miscvalue = miscValue;
m_modifier.periodictime = pt;
}
void Aura::Update(uint32 diff)
{
if (m_isPeriodic)
{
m_periodicTimer -= diff;
if (m_periodicTimer <= 0) // tick also at m_periodicTimer==0 to prevent lost last tick in case max m_duration == (max m_periodicTimer)*N
{
// update before applying (aura can be removed in TriggerSpell or PeriodicTick calls)
m_periodicTimer += m_modifier.periodictime;
++m_periodicTick; // for some infinity auras in some cases can overflow and reset
PeriodicTick();
}
}
}
void AreaAura::Update(uint32 diff)
{
// update for the caster of the aura
if (GetCasterGuid() == GetTarget()->GetObjectGuid())
{
Unit* caster = GetTarget();
if (!caster->hasUnitState(UNIT_STAT_ISOLATED))
{
Unit* owner = caster->GetCharmerOrOwner();
if (!owner)
owner = caster;
Spell::UnitList targets;
switch (m_areaAuraType)
{
case AREA_AURA_PARTY:
{
Group* pGroup = NULL;
if (owner->GetTypeId() == TYPEID_PLAYER)
pGroup = ((Player*)owner)->GetGroup();
if (pGroup)
{
uint8 subgroup = ((Player*)owner)->GetSubGroup();
for (GroupReference* itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* Target = itr->getSource();
if (Target && Target->isAlive() && Target->GetSubGroup() == subgroup && caster->IsFriendlyTo(Target))
{
if (caster->IsWithinDistInMap(Target, m_radius))
targets.push_back(Target);
Pet* pet = Target->GetPet();
if (pet && pet->isAlive() && caster->IsWithinDistInMap(pet, m_radius))
targets.push_back(pet);
}
}
}
else
{
// add owner
if (owner != caster && caster->IsWithinDistInMap(owner, m_radius))
targets.push_back(owner);
// add caster's pet
Unit* pet = caster->GetPet();
if (pet && caster->IsWithinDistInMap(pet, m_radius))
targets.push_back(pet);
}
break;
}
case AREA_AURA_FRIEND:
{
MaNGOS::AnyFriendlyUnitInObjectRangeCheck u_check(caster, m_radius);
MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck> searcher(targets, u_check);
Cell::VisitAllObjects(caster, searcher, m_radius);
break;
}
case AREA_AURA_ENEMY:
{
MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(caster, m_radius); // No GetCharmer in searcher
MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(targets, u_check);
Cell::VisitAllObjects(caster, searcher, m_radius);
break;
}
case AREA_AURA_OWNER:
case AREA_AURA_PET:
{
if (owner != caster && caster->IsWithinDistInMap(owner, m_radius))
targets.push_back(owner);
break;
}
}
for (Spell::UnitList::iterator tIter = targets.begin(); tIter != targets.end(); ++tIter)
{
// flag for seelction is need apply aura to current iteration target
bool apply = true;
// we need ignore present caster self applied are auras sometime
// in cases if this only auras applied for spell effect
Unit::SpellAuraHolderBounds spair = (*tIter)->GetSpellAuraHolderBounds(GetId());
for (Unit::SpellAuraHolderMap::const_iterator i = spair.first; i != spair.second; ++i)
{
if (i->second->IsDeleted())
continue;
Aura* aur = i->second->GetAuraByEffectIndex(m_effIndex);
if (!aur)
continue;
switch (m_areaAuraType)
{
case AREA_AURA_ENEMY:
// non caster self-casted auras (non stacked)
if (aur->GetModifier()->m_auraname != SPELL_AURA_NONE)
apply = false;
break;
default:
// in generic case not allow stacking area auras
apply = false;
break;
}
if (!apply)
break;
}
if (!apply)
continue;
// Skip some targets (TODO: Might require better checks, also unclear how the actual caster must/can be handled)
if (GetSpellProto()->HasAttribute(SPELL_ATTR_EX3_TARGET_ONLY_PLAYER) && (*tIter)->GetTypeId() != TYPEID_PLAYER)
continue;
if (SpellEntry const* actualSpellInfo = sSpellMgr.SelectAuraRankForLevel(GetSpellProto(), (*tIter)->getLevel()))
{
int32 actualBasePoints = m_currentBasePoints;
// recalculate basepoints for lower rank (all AreaAura spell not use custom basepoints?)
if (actualSpellInfo != GetSpellProto())
actualBasePoints = actualSpellInfo->CalculateSimpleValue(m_effIndex);
SpellAuraHolder* holder = (*tIter)->GetSpellAuraHolder(actualSpellInfo->Id, GetCasterGuid());
bool addedToExisting = true;
if (!holder)
{
holder = CreateSpellAuraHolder(actualSpellInfo, (*tIter), caster);
addedToExisting = false;
}
holder->SetAuraDuration(GetAuraDuration());
AreaAura* aur = new AreaAura(actualSpellInfo, m_effIndex, &actualBasePoints, holder, (*tIter), caster, NULL);
holder->AddAura(aur, m_effIndex);
if (addedToExisting)
{
(*tIter)->AddAuraToModList(aur);
holder->SetInUse(true);
aur->ApplyModifier(true, true);
holder->SetInUse(false);
}
else
(*tIter)->AddSpellAuraHolder(holder);
}
}
}
Aura::Update(diff);
}
else // aura at non-caster
{
Unit* caster = GetCaster();
Unit* target = GetTarget();
Aura::Update(diff);
// remove aura if out-of-range from caster (after teleport for example)
// or caster is isolated or caster no longer has the aura
// or caster is (no longer) friendly
bool needFriendly = (m_areaAuraType == AREA_AURA_ENEMY ? false : true);
if (!caster || caster->hasUnitState(UNIT_STAT_ISOLATED) ||
!caster->IsWithinDistInMap(target, m_radius) ||
!caster->HasAura(GetId(), GetEffIndex()) ||
caster->IsFriendlyTo(target) != needFriendly
)
{
target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid());
}
else if (m_areaAuraType == AREA_AURA_PARTY) // check if in same sub group
{
// not check group if target == owner or target == pet
if (caster->GetCharmerOrOwnerGuid() != target->GetObjectGuid() && caster->GetObjectGuid() != target->GetCharmerOrOwnerGuid())
{
Player* check = caster->GetCharmerOrOwnerPlayerOrPlayerItself();
Group* pGroup = check ? check->GetGroup() : NULL;
if (pGroup)
{
Player* checkTarget = target->GetCharmerOrOwnerPlayerOrPlayerItself();
if (!checkTarget || !pGroup->SameSubGroup(check, checkTarget))
target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid());
}
else
target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid());
}
}
else if (m_areaAuraType == AREA_AURA_PET || m_areaAuraType == AREA_AURA_OWNER)
{
if (target->GetObjectGuid() != caster->GetCharmerOrOwnerGuid())
target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid());
}
}
}
void PersistentAreaAura::Update(uint32 diff)
{
bool remove = false;
// remove the aura if its caster or the dynamic object causing it was removed
// or if the target moves too far from the dynamic object
if (Unit* caster = GetCaster())
{
DynamicObject* dynObj = caster->GetDynObject(GetId(), GetEffIndex());
if (dynObj)
{
if (!GetTarget()->IsWithinDistInMap(dynObj, dynObj->GetRadius()))
{
remove = true;
dynObj->RemoveAffected(GetTarget()); // let later reapply if target return to range
}
}
else
remove = true;
}
else
remove = true;
Aura::Update(diff);
if (remove)
GetTarget()->RemoveAura(GetId(), GetEffIndex());
}
void Aura::ApplyModifier(bool apply, bool Real)
{
AuraType aura = m_modifier.m_auraname;
GetHolder()->SetInUse(true);
SetInUse(true);
if (aura < TOTAL_AURAS)
(*this.*AuraHandler [aura])(apply, Real);
SetInUse(false);
GetHolder()->SetInUse(false);
}
bool Aura::isAffectedOnSpell(SpellEntry const* spell) const
{
if (m_spellmod)
return m_spellmod->isAffectedOnSpell(spell);
// Check family name
if (spell->SpellFamilyName != GetSpellProto()->SpellFamilyName)
return false;
ClassFamilyMask mask = sSpellMgr.GetSpellAffectMask(GetId(), GetEffIndex());
return spell->IsFitToFamilyMask(mask);
}
bool Aura::CanProcFrom(SpellEntry const* spell, uint32 EventProcEx, uint32 procEx, bool active, bool useClassMask) const
{
// Check EffectClassMask (in pre-3.x stored in spell_affect in fact)
ClassFamilyMask mask = sSpellMgr.GetSpellAffectMask(GetId(), GetEffIndex());
// if no class mask defined, or spell_proc_event has SpellFamilyName=0 - allow proc
if (!useClassMask || !mask)
{
if (!(EventProcEx & PROC_EX_EX_TRIGGER_ALWAYS))
{
// Check for extra req (if none) and hit/crit
if (EventProcEx == PROC_EX_NONE)
{
// No extra req, so can trigger only for active (damage/healing present) and hit/crit
if ((procEx & (PROC_EX_NORMAL_HIT | PROC_EX_CRITICAL_HIT)) && active)
return true;
else
return false;
}
else // Passive spells hits here only if resist/reflect/immune/evade
{
// Passive spells can`t trigger if need hit (exclude cases when procExtra include non-active flags)
if ((EventProcEx & (PROC_EX_NORMAL_HIT | PROC_EX_CRITICAL_HIT) & procEx) && !active)
return false;
}
}
return true;
}
else
{
// SpellFamilyName check is performed in SpellMgr::IsSpellProcEventCanTriggeredBy and it is done once for whole holder
// note: SpellFamilyName is not checked if no spell_proc_event is defined
return mask.IsFitToFamilyMask(spell->SpellFamilyFlags);
}
}
void Aura::ReapplyAffectedPassiveAuras(Unit* target, bool owner_mode)
{
// we need store cast item guids for self casted spells
// expected that not exist permanent auras from stackable auras from different items
std::map<uint32, ObjectGuid> affectedSelf;
std::set<uint32> affectedAuraCaster;
for (Unit::SpellAuraHolderMap::const_iterator itr = target->GetSpellAuraHolderMap().begin(); itr != target->GetSpellAuraHolderMap().end(); ++itr)
{
// permanent passive or permanent area aura
// passive spells can be affected only by own or owner spell mods)
if ((itr->second->IsPermanent() && ((owner_mode && itr->second->IsPassive()) || itr->second->IsAreaAura())) &&
// non deleted and not same aura (any with same spell id)
!itr->second->IsDeleted() && itr->second->GetId() != GetId() &&
// and affected by aura
isAffectedOnSpell(itr->second->GetSpellProto()))
{
// only applied by self or aura caster
if (itr->second->GetCasterGuid() == target->GetObjectGuid())
affectedSelf[itr->second->GetId()] = itr->second->GetCastItemGuid();
else if (itr->second->GetCasterGuid() == GetCasterGuid())
affectedAuraCaster.insert(itr->second->GetId());
}
}
if (!affectedSelf.empty())
{
Player* pTarget = target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : NULL;
for (std::map<uint32, ObjectGuid>::const_iterator map_itr = affectedSelf.begin(); map_itr != affectedSelf.end(); ++map_itr)
{
Item* item = pTarget && map_itr->second ? pTarget->GetItemByGuid(map_itr->second) : NULL;
target->RemoveAurasDueToSpell(map_itr->first);
target->CastSpell(target, map_itr->first, true, item);
}
}
if (!affectedAuraCaster.empty())
{
Unit* caster = GetCaster();
for (std::set<uint32>::const_iterator set_itr = affectedAuraCaster.begin(); set_itr != affectedAuraCaster.end(); ++set_itr)
{
target->RemoveAurasDueToSpell(*set_itr);
if (caster)
caster->CastSpell(GetTarget(), *set_itr, true);
}
}
}
struct ReapplyAffectedPassiveAurasHelper
{
explicit ReapplyAffectedPassiveAurasHelper(Aura* _aura) : aura(_aura) {}
void operator()(Unit* unit) const { aura->ReapplyAffectedPassiveAuras(unit, true); }
Aura* aura;
};
void Aura::ReapplyAffectedPassiveAuras()
{
// not reapply spell mods with charges (use original value because processed and at remove)
if (GetSpellProto()->procCharges)
return;
// not reapply some spell mods ops (mostly speedup case)
switch (m_modifier.m_miscvalue)
{
case SPELLMOD_DURATION:
case SPELLMOD_CHARGES:
case SPELLMOD_NOT_LOSE_CASTING_TIME:
case SPELLMOD_CASTING_TIME:
case SPELLMOD_COOLDOWN:
case SPELLMOD_COST:
case SPELLMOD_ACTIVATION_TIME:
case SPELLMOD_CASTING_TIME_OLD:
return;
}
// reapply talents to own passive persistent auras
ReapplyAffectedPassiveAuras(GetTarget(), true);
// re-apply talents/passives/area auras applied to pet/totems (it affected by player spellmods)
GetTarget()->CallForAllControlledUnits(ReapplyAffectedPassiveAurasHelper(this), CONTROLLED_PET | CONTROLLED_TOTEMS);
// re-apply talents/passives/area auras applied to group members (it affected by player spellmods)
if (Group* group = ((Player*)GetTarget())->GetGroup())
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
if (Player* member = itr->getSource())
if (member != GetTarget() && member->IsInMap(GetTarget()))
ReapplyAffectedPassiveAuras(member, false);
}
/*********************************************************/
/*** BASIC AURA FUNCTION ***/
/*********************************************************/
void Aura::HandleAddModifier(bool apply, bool Real)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER || !Real)
return;
if (m_modifier.m_miscvalue >= MAX_SPELLMOD)
return;
if (apply)
{
SpellEntry const* spellProto = GetSpellProto();
// Add custom charges for some mod aura
switch (spellProto->Id)
{
case 17941: // Shadow Trance
case 22008: // Netherwind Focus
case 34936: // Backlash
GetHolder()->SetAuraCharges(1);
break;
}
m_spellmod = new SpellModifier(
SpellModOp(m_modifier.m_miscvalue),
SpellModType(m_modifier.m_auraname), // SpellModType value == spell aura types
m_modifier.m_amount,
this,
// prevent expire spell mods with (charges > 0 && m_stackAmount > 1)
// all this spell expected expire not at use but at spell proc event check
spellProto->StackAmount > 1 ? 0 : GetHolder()->GetAuraCharges());
}
((Player*)GetTarget())->AddSpellMod(m_spellmod, apply);
ReapplyAffectedPassiveAuras();
}
void Aura::TriggerSpell()
{
ObjectGuid casterGUID = GetCasterGuid();
Unit* triggerTarget = GetTriggerTarget();
if (!casterGUID || !triggerTarget)
return;
// generic casting code with custom spells and target/caster customs
uint32 trigger_spell_id = GetSpellProto()->EffectTriggerSpell[m_effIndex];
SpellEntry const* triggeredSpellInfo = sSpellStore.LookupEntry(trigger_spell_id);
SpellEntry const* auraSpellInfo = GetSpellProto();
uint32 auraId = auraSpellInfo->Id;
Unit* target = GetTarget();
Unit* triggerCaster = triggerTarget;
WorldObject* triggerTargetObject = NULL;
// specific code for cases with no trigger spell provided in field
if (triggeredSpellInfo == NULL)
{
switch (auraSpellInfo->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
switch (auraId)
{
// Firestone Passive (1-5 ranks)
case 758:
case 17945:
case 17947:
case 17949:
case 27252:
{
if (triggerTarget->GetTypeId() != TYPEID_PLAYER)
return;
Item* item = ((Player*)triggerTarget)->GetWeaponForAttack(BASE_ATTACK);
if (!item)
return;
uint32 enchant_id = 0;
switch (GetId())
{
case 758: enchant_id = 1803; break; // Rank 1
case 17945: enchant_id = 1823; break; // Rank 2
case 17947: enchant_id = 1824; break; // Rank 3
case 17949: enchant_id = 1825; break; // Rank 4
case 27252: enchant_id = 2645; break; // Rank 5
default:
return;
}
// remove old enchanting before applying new
((Player*)triggerTarget)->ApplyEnchantment(item, TEMP_ENCHANTMENT_SLOT, false);
item->SetEnchantment(TEMP_ENCHANTMENT_SLOT, enchant_id, m_modifier.periodictime + 1000, 0);
// add new enchanting
((Player*)triggerTarget)->ApplyEnchantment(item, TEMP_ENCHANTMENT_SLOT, true);
return;
}
case 812: // Periodic Mana Burn
{
trigger_spell_id = 25779; // Mana Burn
if (GetTarget()->GetTypeId() != TYPEID_UNIT)
return;
triggerTarget = ((Creature*)GetTarget())->SelectAttackingTarget(ATTACKING_TARGET_TOPAGGRO, 0, trigger_spell_id, SELECT_FLAG_POWER_MANA);
if (!triggerTarget)
return;
break;
}
// // Polymorphic Ray
// case 6965: break;
// // Fire Nova (1-7 ranks)
// case 8350:
// case 8508:
// case 8509:
// case 11312:
// case 11313:
// case 25540:
// case 25544:
// break;
case 9712: // Thaumaturgy Channel
trigger_spell_id = 21029;
break;
// // Egan's Blaster
// case 17368: break;
// // Haunted
// case 18347: break;
// // Ranshalla Waiting
// case 18953: break;
// // Inferno
// case 19695: break;
// // Frostwolf Muzzle DND
// case 21794: break;
// // Alterac Ram Collar DND
// case 21866: break;
// // Celebras Waiting
// case 21916: break;
case 23170: // Brood Affliction: Bronze
{
target->CastSpell(target, 23171, true, NULL, this);
return;
}
case 23184: // Mark of Frost
case 25041: // Mark of Nature
case 37125: // Mark of Death
{
std::list<Player*> targets;
// spells existed in 1.x.x; 23183 - mark of frost; 25042 - mark of nature; both had radius of 100.0 yards in 1.x.x DBC
// spells are used by Azuregos and the Emerald dragons in order to put a stun debuff on the players which resurrect during the encounter
// in order to implement the missing spells we need to make a grid search for hostile players and check their auras; if they are marked apply debuff
// spell 37127 used for the Mark of Death, is used server side, so it needs to be implemented here
uint32 markSpellId = 0;
uint32 debuffSpellId = 0;
switch (auraId)
{
case 23184:
markSpellId = 23182;
debuffSpellId = 23186;
break;
case 25041:
markSpellId = 25040;
debuffSpellId = 25043;
break;
case 37125:
markSpellId = 37128;
debuffSpellId = 37131;
break;
}
MaNGOS::AnyPlayerInObjectRangeWithAuraCheck u_check(GetTarget(), 100.0f, markSpellId);
MaNGOS::PlayerListSearcher<MaNGOS::AnyPlayerInObjectRangeWithAuraCheck > checker(targets, u_check);
Cell::VisitWorldObjects(GetTarget(), checker, 100.0f);
for (std::list<Player*>::iterator itr = targets.begin(); itr != targets.end(); ++itr)
(*itr)->CastSpell((*itr), debuffSpellId, true, NULL, NULL, casterGUID);
return;
}
case 23493: // Restoration
{
uint32 heal = triggerTarget->GetMaxHealth() / 10;
triggerTarget->DealHeal(triggerTarget, heal, auraSpellInfo);
if (int32 mana = triggerTarget->GetMaxPower(POWER_MANA))
{
mana /= 10;
triggerTarget->EnergizeBySpell(triggerTarget, 23493, mana, POWER_MANA);
}
return;
}
// // Stoneclaw Totem Passive TEST
// case 23792: break;
// // Axe Flurry
// case 24018: break;
case 24210: // Mark of Arlokk
{
// Replacement for (classic) spell 24211 (doesn't exist anymore)
std::list<Creature*> lList;
// Search for all Zulian Prowler in range
MaNGOS::AllCreaturesOfEntryInRangeCheck check(triggerTarget, 15101, 15.0f);
MaNGOS::CreatureListSearcher<MaNGOS::AllCreaturesOfEntryInRangeCheck> searcher(lList, check);
Cell::VisitGridObjects(triggerTarget, searcher, 15.0f);
for (std::list<Creature*>::const_iterator itr = lList.begin(); itr != lList.end(); ++itr)
if ((*itr)->isAlive())
(*itr)->AddThreat(triggerTarget, float(5000));
return;
}
// // Restoration
// case 24379: break;
// // Happy Pet
// case 24716: break;
case 24780: // Dream Fog
{
// Note: In 1.12 triggered spell 24781 still exists, need to script dummy effect for this spell then
// Select an unfriendly enemy in 100y range and attack it
if (target->GetTypeId() != TYPEID_UNIT)
return;
ThreatList const& tList = target->getThreatManager().getThreatList();
for (ThreatList::const_iterator itr = tList.begin(); itr != tList.end(); ++itr)
{
Unit* pUnit = target->GetMap()->GetUnit((*itr)->getUnitGuid());
if (pUnit && target->getThreatManager().getThreat(pUnit))
target->getThreatManager().modifyThreatPercent(pUnit, -100);
}
if (Unit* pEnemy = target->SelectRandomUnfriendlyTarget(target->getVictim(), 100.0f))
((Creature*)target)->AI()->AttackStart(pEnemy);
return;
}
// // Cannon Prep
// case 24832: break;
case 24834: // Shadow Bolt Whirl
{
uint32 spellForTick[8] = { 24820, 24821, 24822, 24823, 24835, 24836, 24837, 24838 };
uint32 tick = (GetAuraTicks() + 7/*-1*/) % 8;
// casted in left/right (but triggered spell have wide forward cone)
float forward = target->GetOrientation();
if (tick <= 3)
target->SetOrientation(forward + 0.75f * M_PI_F - tick * M_PI_F / 8); // Left
else
target->SetOrientation(forward - 0.75f * M_PI_F + (8 - tick) * M_PI_F / 8); // Right
triggerTarget->CastSpell(triggerTarget, spellForTick[tick], true, NULL, this, casterGUID);
target->SetOrientation(forward);
return;
}
// // Stink Trap
// case 24918: break;
// // Agro Drones
// case 25152: break;
case 25371: // Consume
{
int32 bpDamage = triggerTarget->GetMaxHealth() * 10 / 100;
triggerTarget->CastCustomSpell(triggerTarget, 25373, &bpDamage, NULL, NULL, true, NULL, this, casterGUID);
return;
}
// // Pain Spike
// case 25572: break;
case 26009: // Rotate 360
case 26136: // Rotate -360
{
float newAngle = target->GetOrientation();
if (auraId == 26009)
newAngle += M_PI_F / 40;
else
newAngle -= M_PI_F / 40;
newAngle = MapManager::NormalizeOrientation(newAngle);
target->SetFacingTo(newAngle);
target->CastSpell(target, 26029, true);
return;
}
// // Consume
// case 26196: break;
// // Berserk
// case 26615: break;
// // Defile
// case 27177: break;
// // Teleport: IF/UC
// case 27601: break;
// // Five Fat Finger Exploding Heart Technique
// case 27673: break;
// // Nitrous Boost
// case 27746: break;
// // Steam Tank Passive
// case 27747: break;
case 27808: // Frost Blast
{
int32 bpDamage = triggerTarget->GetMaxHealth() * 26 / 100;
triggerTarget->CastCustomSpell(triggerTarget, 29879, &bpDamage, NULL, NULL, true, NULL, this, casterGUID);
return;
}
// Detonate Mana
case 27819:
{
// 50% Mana Burn
int32 bpDamage = (int32)triggerTarget->GetPower(POWER_MANA) * 0.5f;
triggerTarget->ModifyPower(POWER_MANA, -bpDamage);
triggerTarget->CastCustomSpell(triggerTarget, 27820, &bpDamage, NULL, NULL, true, NULL, this, triggerTarget->GetObjectGuid());
return;
}
// // Controller Timer
// case 28095: break;
// Stalagg Chain and Feugen Chain
case 28096:
case 28111:
{
// X-Chain is casted by Tesla to X, so: caster == Tesla, target = X
Unit* pCaster = GetCaster();
if (pCaster && pCaster->GetTypeId() == TYPEID_UNIT && !pCaster->IsWithinDistInMap(target, 60.0f))
{
pCaster->InterruptNonMeleeSpells(true);
((Creature*)pCaster)->SetInCombatWithZone();
// Stalagg Tesla Passive or Feugen Tesla Passive
pCaster->CastSpell(pCaster, auraId == 28096 ? 28097 : 28109, true, NULL, NULL, target->GetObjectGuid());
}
return;
}
// Stalagg Tesla Passive and Feugen Tesla Passive
case 28097:
case 28109:
{
// X-Tesla-Passive is casted by Tesla on Tesla with original caster X, so: caster = X, target = Tesla
Unit* pCaster = GetCaster();
if (pCaster && pCaster->GetTypeId() == TYPEID_UNIT)
{
if (pCaster->getVictim() && !pCaster->IsWithinDistInMap(target, 60.0f))
{
if (Unit* pTarget = ((Creature*)pCaster)->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0))
target->CastSpell(pTarget, 28099, false);// Shock
}
else
{
// "Evade"
target->RemoveAurasDueToSpell(auraId);
target->DeleteThreatList();
target->CombatStop(true);
// Recast chain (Stalagg Chain or Feugen Chain
target->CastSpell(pCaster, auraId == 28097 ? 28096 : 28111, false);
}
}
return;
}
// // Mark of Didier
// case 28114: break;
// // Communique Timer, camp
// case 28346: break;
// // Icebolt
// case 28522: break;
// // Silithyst
// case 29519: break;
case 29528: // Inoculate Nestlewood Owlkin
// prevent error reports in case ignored player target
if (triggerTarget->GetTypeId() != TYPEID_UNIT)
return;
break;
// // Overload
// case 29768: break;
// // Return Fire
// case 29788: break;
// // Return Fire
// case 29793: break;
// // Return Fire
// case 29794: break;
// // Guardian of Icecrown Passive
// case 29897: break;
case 29917: // Feed Captured Animal
trigger_spell_id = 29916;
break;
// // Flame Wreath
// case 29946: break;
// // Flame Wreath
// case 29947: break;
// // Mind Exhaustion Passive
// case 30025: break;
// // Nether Beam - Serenity
// case 30401: break;
case 30427: // Extract Gas
{
Unit* caster = GetCaster();
if (!caster)
return;
// move loot to player inventory and despawn target
if (caster->GetTypeId() == TYPEID_PLAYER &&
triggerTarget->GetTypeId() == TYPEID_UNIT &&
((Creature*)triggerTarget)->GetCreatureInfo()->type == CREATURE_TYPE_GAS_CLOUD)
{
Player* player = (Player*)caster;
Creature* creature = (Creature*)triggerTarget;
// missing lootid has been reported on startup - just return
if (!creature->GetCreatureInfo()->SkinLootId)
return;
player->AutoStoreLoot(creature, creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, true);
creature->ForcedDespawn();
}
return;
}
case 30576: // Quake
trigger_spell_id = 30571;
break;
// // Burning Maul
// case 30598: break;
// // Regeneration
// case 30799:
// case 30800:
// case 30801:
// break;
// // Despawn Self - Smoke cloud
// case 31269: break;
// // Time Rift Periodic
// case 31320: break;
// // Corrupt Medivh
// case 31326: break;
case 31347: // Doom
{
target->CastSpell(target, 31350, true);
target->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
return;
}
case 31373: // Spellcloth
{
// Summon Elemental after create item
triggerTarget->SummonCreature(17870, 0.0f, 0.0f, 0.0f, triggerTarget->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 0);
return;
}
// // Bloodmyst Tesla
// case 31611: break;
case 31944: // Doomfire
{
int32 damage = m_modifier.m_amount * ((GetAuraDuration() + m_modifier.periodictime) / GetAuraMaxDuration());
triggerTarget->CastCustomSpell(triggerTarget, 31969, &damage, NULL, NULL, true, NULL, this, casterGUID);
return;
}
// // Teleport Test
// case 32236: break;
// // Earthquake
// case 32686: break;
// // Possess
// case 33401: break;
// // Draw Shadows
// case 33563: break;
// // Murmur's Touch
// case 33711: break;
case 34229: // Flame Quills
{
// cast 24 spells 34269-34289, 34314-34316
for (uint32 spell_id = 34269; spell_id != 34290; ++spell_id)
triggerTarget->CastSpell(triggerTarget, spell_id, true, NULL, this, casterGUID);
for (uint32 spell_id = 34314; spell_id != 34317; ++spell_id)
triggerTarget->CastSpell(triggerTarget, spell_id, true, NULL, this, casterGUID);
return;
}
// // Gravity Lapse
// case 34480: break;
// // Tornado
// case 34683: break;
// // Frostbite Rotate
// case 34748: break;
// // Arcane Flurry
// case 34821: break;
// // Interrupt Shutdown
// case 35016: break;
// // Interrupt Shutdown
// case 35176: break;
// // Inferno
// case 35268: break;
// // Salaadin's Tesla
// case 35515: break;
// // Ethereal Channel (Red)
// case 35518: break;
// // Nether Vapor
// case 35879: break;
// // Dark Portal Storm
// case 36018: break;
// // Burning Maul
// case 36056: break;
// // Living Grove Defender Lifespan
// case 36061: break;
// // Professor Dabiri Talks
// case 36064: break;
// // Kael Gaining Power
// case 36091: break;
// // They Must Burn Bomb Aura
// case 36344: break;
// // They Must Burn Bomb Aura (self)
// case 36350: break;
// // Stolen Ravenous Ravager Egg
// case 36401: break;
// // Activated Cannon
// case 36410: break;
// // Stolen Ravenous Ravager Egg
// case 36418: break;
// // Enchanted Weapons
// case 36510: break;
// // Cursed Scarab Periodic
// case 36556: break;
// // Cursed Scarab Despawn Periodic
// case 36561: break;
case 36573: // Vision Guide
{
if (GetAuraTicks() == 10 && target->GetTypeId() == TYPEID_PLAYER)
{
((Player*)target)->AreaExploredOrEventHappens(10525);
target->RemoveAurasDueToSpell(36573);
}
return;
}
// // Cannon Charging (platform)
// case 36785: break;
// // Cannon Charging (self)
// case 36860: break;
case 37027: // Remote Toy
trigger_spell_id = 37029;
break;
// // Mark of Death
// case 37125: break;
// // Arcane Flurry
// case 37268: break;
case 37429: // Spout (left)
case 37430: // Spout (right)
{
float newAngle = target->GetOrientation();
if (auraId == 37429)
newAngle += 2 * M_PI_F / 100;
else
newAngle -= 2 * M_PI_F / 100;
newAngle = MapManager::NormalizeOrientation(newAngle);
target->SetFacingTo(newAngle);
target->CastSpell(target, 37433, true);
return;
}
// // Karazhan - Chess NPC AI, Snapshot timer
// case 37440: break;
// // Karazhan - Chess NPC AI, action timer
// case 37504: break;
// // Karazhan - Chess: Is Square OCCUPIED aura (DND)
// case 39400: break;
// // Banish
// case 37546: break;
// // Shriveling Gaze
// case 37589: break;
// // Fake Aggro Radius (2 yd)
// case 37815: break;
// // Corrupt Medivh
// case 37853: break;
case 38495: // Eye of Grillok
{
target->CastSpell(target, 38530, true);
return;
}
case 38554: // Absorb Eye of Grillok (Zezzak's Shard)
{
if (target->GetTypeId() != TYPEID_UNIT)
return;
if (Unit* caster = GetCaster())
caster->CastSpell(caster, 38495, true, NULL, this);
else
return;
Creature* creatureTarget = (Creature*)target;
creatureTarget->ForcedDespawn();
return;
}
// // Magic Sucker Device timer
// case 38672: break;
// // Tomb Guarding Charging
// case 38751: break;
// // Murmur's Touch
// case 38794: break;
case 39105: // Activate Nether-wraith Beacon (31742 Nether-wraith Beacon item)
{
float fX, fY, fZ;
triggerTarget->GetClosePoint(fX, fY, fZ, triggerTarget->GetObjectBoundingRadius(), 20.0f);
triggerTarget->SummonCreature(22408, fX, fY, fZ, triggerTarget->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 0);
return;
}
// // Drain World Tree Visual
// case 39140: break;
// // Quest - Dustin's Undead Dragon Visual aura
// case 39259: break;
// // Hellfire - The Exorcism, Jules releases darkness, aura
// case 39306: break;
// // Inferno
// case 39346: break;
// // Enchanted Weapons
// case 39489: break;
// // Shadow Bolt Whirl
// case 39630: break;
// // Shadow Bolt Whirl
// case 39634: break;
// // Shadow Inferno
// case 39645: break;
case 39857: // Tear of Azzinoth Summon Channel - it's not really supposed to do anything,and this only prevents the console spam
trigger_spell_id = 39856;
break;
// // Soulgrinder Ritual Visual (Smashed)
// case 39974: break;
// // Simon Game Pre-game timer
// case 40041: break;
// // Knockdown Fel Cannon: The Aggro Check Aura
// case 40113: break;
// // Spirit Lance
// case 40157: break;
case 40398: // Demon Transform 2
switch (GetAuraTicks())
{
case 1:
if (target->HasAura(40506))
target->RemoveAurasDueToSpell(40506);
else
trigger_spell_id = 40506;
break;
case 2:
trigger_spell_id = 40510;
break;
}
break;
case 40511: // Demon Transform 1
trigger_spell_id = 40398;
break;
// // Ancient Flames
// case 40657: break;
// // Ethereal Ring Cannon: Cannon Aura
// case 40734: break;
// // Cage Trap
// case 40760: break;
// // Random Periodic
// case 40867: break;
// // Prismatic Shield
// case 40879: break;
// // Aura of Desire
// case 41350: break;
// // Dementia
// case 41404: break;
// // Chaos Form
// case 41629: break;
// // Alert Drums
// case 42177: break;
// // Spout
// case 42581: break;
// // Spout
// case 42582: break;
// // Return to the Spirit Realm
// case 44035: break;
// // Curse of Boundless Agony
// case 45050: break;
// // Earthquake
// case 46240: break;
case 46736: // Personalized Weather
trigger_spell_id = 46737;
break;
// // Stay Submerged
// case 46981: break;
// // Dragonblight Ram
// case 47015: break;
// // Party G.R.E.N.A.D.E.
// case 51510: break;
default:
break;
}
break;
}
case SPELLFAMILY_MAGE:
{
switch (auraId)
{
case 66: // Invisibility
// Here need periodic trigger reducing threat spell (or do it manually)
return;
default:
break;
}
break;
}
// case SPELLFAMILY_WARRIOR:
// {
// switch(auraId)
// {
// // Wild Magic
// case 23410: break;
// // Corrupted Totems
// case 23425: break;
// default:
// break;
// }
// break;
// }
// case SPELLFAMILY_PRIEST:
// {
// switch(auraId)
// {
// // Blue Beam
// case 32930: break;
// // Fury of the Dreghood Elders
// case 35460: break;
// default:
// break;
// }
// break;
// }
case SPELLFAMILY_DRUID:
{
switch (auraId)
{
case 768: // Cat Form
// trigger_spell_id not set and unknown effect triggered in this case, ignoring for while
return;
case 22842: // Frenzied Regeneration
case 22895:
case 22896:
case 26999:
{
int32 LifePerRage = GetModifier()->m_amount;
int32 lRage = target->GetPower(POWER_RAGE);
if (lRage > 100) // rage stored as rage*10
lRage = 100;
target->ModifyPower(POWER_RAGE, -lRage);
int32 FRTriggerBasePoints = int32(lRage * LifePerRage / 10);
target->CastCustomSpell(target, 22845, &FRTriggerBasePoints, NULL, NULL, true, NULL, this);
return;
}
default:
break;
}
break;
}
// case SPELLFAMILY_HUNTER:
// {
// switch(auraId)
// {
// // Frost Trap Aura
// case 13810:
// return;
// // Rizzle's Frost Trap
// case 39900:
// return;
// // Tame spells
// case 19597: // Tame Ice Claw Bear
// case 19676: // Tame Snow Leopard
// case 19677: // Tame Large Crag Boar
// case 19678: // Tame Adult Plainstrider
// case 19679: // Tame Prairie Stalker
// case 19680: // Tame Swoop
// case 19681: // Tame Dire Mottled Boar
// case 19682: // Tame Surf Crawler
// case 19683: // Tame Armored Scorpid
// case 19684: // Tame Webwood Lurker
// case 19685: // Tame Nightsaber Stalker
// case 19686: // Tame Strigid Screecher
// case 30100: // Tame Crazed Dragonhawk
// case 30103: // Tame Elder Springpaw
// case 30104: // Tame Mistbat
// case 30647: // Tame Barbed Crawler
// case 30648: // Tame Greater Timberstrider
// case 30652: // Tame Nightstalker
// return;
// default:
// break;
// }
// break;
// }
case SPELLFAMILY_SHAMAN:
{
switch (auraId)
{
case 28820: // Lightning Shield (The Earthshatterer set trigger after cast Lighting Shield)
{
// Need remove self if Lightning Shield not active
Unit::SpellAuraHolderMap const& auras = triggerTarget->GetSpellAuraHolderMap();
for (Unit::SpellAuraHolderMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
{
SpellEntry const* spell = itr->second->GetSpellProto();
if (spell->SpellFamilyName == SPELLFAMILY_SHAMAN &&
(spell->SpellFamilyFlags & UI64LIT(0x0000000000000400)))
return;
}
triggerTarget->RemoveAurasDueToSpell(28820);
return;
}
case 38443: // Totemic Mastery (Skyshatter Regalia (Shaman Tier 6) - bonus)
{
if (triggerTarget->IsAllTotemSlotsUsed())
triggerTarget->CastSpell(triggerTarget, 38437, true, NULL, this);
else
triggerTarget->RemoveAurasDueToSpell(38437);
return;
}
default:
break;
}
break;
}
default:
break;
}
// Reget trigger spell proto
triggeredSpellInfo = sSpellStore.LookupEntry(trigger_spell_id);
}
else // initial triggeredSpellInfo != NULL
{
// for channeled spell cast applied from aura owner to channel target (persistent aura affects already applied to true target)
// come periodic casts applied to targets, so need seelct proper caster (ex. 15790)
if (IsChanneledSpell(GetSpellProto()) && GetSpellProto()->Effect[GetEffIndex()] != SPELL_EFFECT_PERSISTENT_AREA_AURA)
{
// interesting 2 cases: periodic aura at caster of channeled spell
if (target->GetObjectGuid() == casterGUID)
{
triggerCaster = target;
if (WorldObject* channelTarget = target->GetMap()->GetWorldObject(target->GetChannelObjectGuid()))
{
if (channelTarget->isType(TYPEMASK_UNIT))
triggerTarget = (Unit*)channelTarget;
else
triggerTargetObject = channelTarget;
}
}
// or periodic aura at caster channel target
else if (Unit* caster = GetCaster())
{
if (target->GetObjectGuid() == caster->GetChannelObjectGuid())
{
triggerCaster = caster;
triggerTarget = target;
}
}
}
// Spell exist but require custom code
switch (auraId)
{
case 9347: // Mortal Strike
{
if (target->GetTypeId() != TYPEID_UNIT)
return;
// expected selection current fight target
triggerTarget = ((Creature*)target)->SelectAttackingTarget(ATTACKING_TARGET_TOPAGGRO, 0, triggeredSpellInfo);
if (!triggerTarget)
return;
break;
}
case 1010: // Curse of Idiocy
{
// TODO: spell casted by result in correct way mostly
// BUT:
// 1) target show casting at each triggered cast: target don't must show casting animation for any triggered spell
// but must show affect apply like item casting
// 2) maybe aura must be replace by new with accumulative stat mods instead stacking
// prevent cast by triggered auras
if (casterGUID == triggerTarget->GetObjectGuid())
return;
// stop triggering after each affected stats lost > 90
int32 intelectLoss = 0;
int32 spiritLoss = 0;
Unit::AuraList const& mModStat = triggerTarget->GetAurasByType(SPELL_AURA_MOD_STAT);
for (Unit::AuraList::const_iterator i = mModStat.begin(); i != mModStat.end(); ++i)
{
if ((*i)->GetId() == 1010)
{
switch ((*i)->GetModifier()->m_miscvalue)
{
case STAT_INTELLECT: intelectLoss += (*i)->GetModifier()->m_amount; break;
case STAT_SPIRIT: spiritLoss += (*i)->GetModifier()->m_amount; break;
default: break;
}
}
}
if (intelectLoss <= -90 && spiritLoss <= -90)
return;
break;
}
case 16191: // Mana Tide
{
triggerTarget->CastCustomSpell(triggerTarget, trigger_spell_id, &m_modifier.m_amount, NULL, NULL, true, NULL, this);
return;
}
case 33525: // Ground Slam
triggerTarget->CastSpell(triggerTarget, trigger_spell_id, true, NULL, this, casterGUID);
return;
case 38736: // Rod of Purification - for quest 10839 (Veil Skith: Darkstone of Terokk)
{
if (Unit* caster = GetCaster())
caster->CastSpell(triggerTarget, trigger_spell_id, true, NULL, this);
return;
}
case 44883: // Encapsulate
{
// Self cast spell, hence overwrite caster (only channeled spell where the triggered spell deals dmg to SELF)
triggerCaster = triggerTarget;
break;
}
}
}
// All ok cast by default case
if (triggeredSpellInfo)
{
if (triggerTargetObject)
triggerCaster->CastSpell(triggerTargetObject->GetPositionX(), triggerTargetObject->GetPositionY(), triggerTargetObject->GetPositionZ(),
triggeredSpellInfo, true, NULL, this, casterGUID);
else
triggerCaster->CastSpell(triggerTarget, triggeredSpellInfo, true, NULL, this, casterGUID);
}
else
{
if (Unit* caster = GetCaster())
{
if (triggerTarget->GetTypeId() != TYPEID_UNIT || !sScriptMgr.OnEffectDummy(caster, GetId(), GetEffIndex(), (Creature*)triggerTarget))
sLog.outError("Aura::TriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?", GetId(), GetEffIndex());
}
}
}
void Aura::TriggerSpellWithValue()
{
ObjectGuid casterGuid = GetCasterGuid();
Unit* target = GetTriggerTarget();
if (!casterGuid || !target)
return;
// generic casting code with custom spells and target/caster customs
uint32 trigger_spell_id = GetSpellProto()->EffectTriggerSpell[m_effIndex];
int32 basepoints0 = GetModifier()->m_amount;
target->CastCustomSpell(target, trigger_spell_id, &basepoints0, NULL, NULL, true, NULL, this, casterGuid);
}
/*********************************************************/
/*** AURA EFFECTS ***/
/*********************************************************/
void Aura::HandleAuraDummy(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
Unit* target = GetTarget();
// AT APPLY
if (apply)
{
switch (GetSpellProto()->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
switch (GetId())
{
case 1515: // Tame beast
// FIX_ME: this is 2.0.12 threat effect replaced in 2.1.x by dummy aura, must be checked for correctness
if (target->CanHaveThreatList())
if (Unit* caster = GetCaster())
target->AddThreat(caster, 10.0f, false, GetSpellSchoolMask(GetSpellProto()), GetSpellProto());
return;
case 7057: // Haunting Spirits
// expected to tick with 30 sec period (tick part see in Aura::PeriodicTick)
m_isPeriodic = true;
m_modifier.periodictime = 30 * IN_MILLISECONDS;
m_periodicTimer = m_modifier.periodictime;
return;
case 10255: // Stoned
{
if (Unit* caster = GetCaster())
{
if (caster->GetTypeId() != TYPEID_UNIT)
return;
caster->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
caster->addUnitState(UNIT_STAT_ROOT);
}
return;
}
case 13139: // net-o-matic
// root to self part of (root_target->charge->root_self sequence
if (Unit* caster = GetCaster())
caster->CastSpell(caster, 13138, true, NULL, this);
return;
case 28832: // Mark of Korth'azz
case 28833: // Mark of Blaumeux
case 28834: // Mark of Rivendare
case 28835: // Mark of Zeliek
{
int32 damage = 0;
switch (GetStackAmount())
{
case 1:
return;
case 2: damage = 500; break;
case 3: damage = 1500; break;
case 4: damage = 4000; break;
case 5: damage = 12500; break;
default:
damage = 14000 + 1000 * GetStackAmount();
break;
}
if (Unit* caster = GetCaster())
caster->CastCustomSpell(target, 28836, &damage, NULL, NULL, true, NULL, this);
return;
}
case 31606: // Stormcrow Amulet
{
CreatureInfo const* cInfo = ObjectMgr::GetCreatureTemplate(17970);
// we must assume db or script set display id to native at ending flight (if not, target is stuck with this model)
if (cInfo)
target->SetDisplayId(Creature::ChooseDisplayId(cInfo));
return;
}
case 32045: // Soul Charge
case 32051:
case 32052:
{
// max duration is 2 minutes, but expected to be random duration
// real time randomness is unclear, using max 30 seconds here
// see further down for expire of this aura
GetHolder()->SetAuraDuration(urand(1, 30)*IN_MILLISECONDS);
return;
}
case 33326: // Stolen Soul Dispel
{
target->RemoveAurasDueToSpell(32346);
return;
}
case 36587: // Vision Guide
{
target->CastSpell(target, 36573, true, NULL, this);
return;
}
// Gender spells
case 38224: // Illidari Agent Illusion
case 37096: // Blood Elf Illusion
case 46354: // Blood Elf Illusion
{
uint8 gender = target->getGender();
uint32 spellId;
switch (GetId())
{
case 38224: spellId = (gender == GENDER_MALE ? 38225 : 38227); break;
case 37096: spellId = (gender == GENDER_MALE ? 37092 : 37094); break;
case 46354: spellId = (gender == GENDER_MALE ? 46355 : 46356); break;
default: return;
}
target->CastSpell(target, spellId, true, NULL, this);
return;
}
case 39850: // Rocket Blast
if (roll_chance_i(20)) // backfire stun
target->CastSpell(target, 51581, true, NULL, this);
return;
case 43873: // Headless Horseman Laugh
target->PlayDistanceSound(11965);
return;
case 46699: // Requires No Ammo
if (target->GetTypeId() == TYPEID_PLAYER)
// not use ammo and not allow use
((Player*)target)->RemoveAmmo();
return;
case 48025: // Headless Horseman's Mount
Spell::SelectMountByAreaAndSkill(target, GetSpellProto(), 51621, 48024, 51617, 48023, 0);
return;
}
break;
}
case SPELLFAMILY_WARRIOR:
{
switch (GetId())
{
case 41099: // Battle Stance
{
if (target->GetTypeId() != TYPEID_UNIT)
return;
// Stance Cooldown
target->CastSpell(target, 41102, true, NULL, this);
// Battle Aura
target->CastSpell(target, 41106, true, NULL, this);
// equipment
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_0, 32614);
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_1, 0);
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_2, 0);
return;
}
case 41100: // Berserker Stance
{
if (target->GetTypeId() != TYPEID_UNIT)
return;
// Stance Cooldown
target->CastSpell(target, 41102, true, NULL, this);
// Berserker Aura
target->CastSpell(target, 41107, true, NULL, this);
// equipment
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_0, 32614);
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_1, 0);
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_2, 0);
return;
}
case 41101: // Defensive Stance
{
if (target->GetTypeId() != TYPEID_UNIT)
return;
// Stance Cooldown
target->CastSpell(target, 41102, true, NULL, this);
// Defensive Aura
target->CastSpell(target, 41105, true, NULL, this);
// equipment
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_0, 32604);
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_1, 31467);
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_2, 0);
return;
}
}
break;
}
case SPELLFAMILY_SHAMAN:
{
// Earth Shield
if ((GetSpellProto()->SpellFamilyFlags & UI64LIT(0x40000000000)))
{
// prevent double apply bonuses
if (target->GetTypeId() != TYPEID_PLAYER || !((Player*)target)->GetSession()->PlayerLoading())
{
if (Unit* caster = GetCaster())
{
m_modifier.m_amount = caster->SpellHealingBonusDone(target, GetSpellProto(), m_modifier.m_amount, SPELL_DIRECT_DAMAGE);
m_modifier.m_amount = target->SpellHealingBonusTaken(caster, GetSpellProto(), m_modifier.m_amount, SPELL_DIRECT_DAMAGE);
}
}
return;
}
break;
}
}
}
// AT REMOVE
else
{
if (IsQuestTameSpell(GetId()) && target->isAlive())
{
Unit* caster = GetCaster();
if (!caster || !caster->isAlive())
return;
uint32 finalSpellId = 0;
switch (GetId())
{
case 19548: finalSpellId = 19597; break;
case 19674: finalSpellId = 19677; break;
case 19687: finalSpellId = 19676; break;
case 19688: finalSpellId = 19678; break;
case 19689: finalSpellId = 19679; break;
case 19692: finalSpellId = 19680; break;
case 19693: finalSpellId = 19684; break;
case 19694: finalSpellId = 19681; break;
case 19696: finalSpellId = 19682; break;
case 19697: finalSpellId = 19683; break;
case 19699: finalSpellId = 19685; break;
case 19700: finalSpellId = 19686; break;
case 30646: finalSpellId = 30647; break;
case 30653: finalSpellId = 30648; break;
case 30654: finalSpellId = 30652; break;
case 30099: finalSpellId = 30100; break;
case 30102: finalSpellId = 30103; break;
case 30105: finalSpellId = 30104; break;
}
if (finalSpellId)
caster->CastSpell(target, finalSpellId, true, NULL, this);
return;
}
switch (GetId())
{
case 10255: // Stoned
{
if (Unit* caster = GetCaster())
{
if (caster->GetTypeId() != TYPEID_UNIT)
return;
// see dummy effect of spell 10254 for removal of flags etc
caster->CastSpell(caster, 10254, true);
}
return;
}
case 12479: // Hex of Jammal'an
target->CastSpell(target, 12480, true, NULL, this);
return;
case 12774: // (DND) Belnistrasz Idol Shutdown Visual
{
if (m_removeMode == AURA_REMOVE_BY_DEATH)
return;
// Idom Rool Camera Shake <- wtf, don't drink while making spellnames?
if (Unit* caster = GetCaster())
caster->CastSpell(caster, 12816, true);
return;
}
case 28169: // Mutating Injection
{
// Mutagen Explosion
target->CastSpell(target, 28206, true, NULL, this);
// Poison Cloud
target->CastSpell(target, 28240, true, NULL, this);
return;
}
case 32045: // Soul Charge
{
if (m_removeMode == AURA_REMOVE_BY_EXPIRE)
target->CastSpell(target, 32054, true, NULL, this);
return;
}
case 32051: // Soul Charge
{
if (m_removeMode == AURA_REMOVE_BY_EXPIRE)
target->CastSpell(target, 32057, true, NULL, this);
return;
}
case 32052: // Soul Charge
{
if (m_removeMode == AURA_REMOVE_BY_EXPIRE)
target->CastSpell(target, 32053, true, NULL, this);
return;
}
case 32286: // Focus Target Visual
{
if (m_removeMode == AURA_REMOVE_BY_EXPIRE)
target->CastSpell(target, 32301, true, NULL, this);
return;
}
case 35079: // Misdirection, triggered buff
{
if (Unit* pCaster = GetCaster())
pCaster->RemoveAurasDueToSpell(34477);
return;
}
case 36730: // Flame Strike
{
target->CastSpell(target, 36731, true, NULL, this);
return;
}
case 41099: // Battle Stance
{
// Battle Aura
target->RemoveAurasDueToSpell(41106);
return;
}
case 41100: // Berserker Stance
{
// Berserker Aura
target->RemoveAurasDueToSpell(41107);
return;
}
case 41101: // Defensive Stance
{
// Defensive Aura
target->RemoveAurasDueToSpell(41105);
return;
}
case 42385: // Alcaz Survey Aura
{
target->CastSpell(target, 42316, true, NULL, this);
return;
}
case 42454: // Captured Totem
{
if (m_removeMode == AURA_REMOVE_BY_DEFAULT)
{
if (target->getDeathState() != CORPSE)
return;
Unit* pCaster = GetCaster();
if (!pCaster)
return;
// Captured Totem Test Credit
if (Player* pPlayer = pCaster->GetCharmerOrOwnerPlayerOrPlayerItself())
pPlayer->CastSpell(pPlayer, 42455, true);
}
return;
}
case 42517: // Beam to Zelfrax
{
// expecting target to be a dummy creature
Creature* pSummon = target->SummonCreature(23864, 0.0f, 0.0f, 0.0f, target->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 0);
Unit* pCaster = GetCaster();
if (pSummon && pCaster)
pSummon->GetMotionMaster()->MovePoint(0, pCaster->GetPositionX(), pCaster->GetPositionY(), pCaster->GetPositionZ());
return;
}
case 44191: // Flame Strike
{
if (target->GetMap()->IsDungeon())
{
uint32 spellId = target->GetMap()->IsRegularDifficulty() ? 44190 : 46163;
target->CastSpell(target, spellId, true, NULL, this);
}
return;
}
case 45934: // Dark Fiend
{
// Kill target if dispelled
if (m_removeMode == AURA_REMOVE_BY_DISPEL)
target->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
return;
}
case 46308: // Burning Winds
{
// casted only at creatures at spawn
target->CastSpell(target, 47287, true, NULL, this);
return;
}
}
}
// AT APPLY & REMOVE
switch (GetSpellProto()->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
switch (GetId())
{
case 6606: // Self Visual - Sleep Until Cancelled (DND)
{
if (apply)
{
target->SetStandState(UNIT_STAND_STATE_SLEEP);
target->addUnitState(UNIT_STAT_ROOT);
}
else
{
target->clearUnitState(UNIT_STAT_ROOT);
target->SetStandState(UNIT_STAND_STATE_STAND);
}
return;
}
case 24658: // Unstable Power
{
if (apply)
{
Unit* caster = GetCaster();
if (!caster)
return;
caster->CastSpell(target, 24659, true, NULL, NULL, GetCasterGuid());
}
else
target->RemoveAurasDueToSpell(24659);
return;
}
case 24661: // Restless Strength
{
if (apply)
{
Unit* caster = GetCaster();
if (!caster)
return;
caster->CastSpell(target, 24662, true, NULL, NULL, GetCasterGuid());
}
else
target->RemoveAurasDueToSpell(24662);
return;
}
case 29266: // Permanent Feign Death
case 31261: // Permanent Feign Death (Root)
case 37493: // Feign Death
{
// Unclear what the difference really is between them.
// Some has effect1 that makes the difference, however not all.
// Some appear to be used depending on creature location, in water, at solid ground, in air/suspended, etc
// For now, just handle all the same way
if (target->GetTypeId() == TYPEID_UNIT)
target->SetFeignDeath(apply);
return;
}
case 32216: // Victorious
if (target->getClass() == CLASS_WARRIOR)
target->ModifyAuraState(AURA_STATE_WARRIOR_VICTORY_RUSH, apply);
return;
case 35356: // Spawn Feign Death
case 35357: // Spawn Feign Death
{
if (target->GetTypeId() == TYPEID_UNIT)
{
// Flags not set like it's done in SetFeignDeath()
// UNIT_DYNFLAG_DEAD does not appear with these spells.
// All of the spells appear to be present at spawn and not used to feign in combat or similar.
if (apply)
{
target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29);
target->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH);
target->addUnitState(UNIT_STAT_DIED);
}
else
{
target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29);
target->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH);
target->clearUnitState(UNIT_STAT_DIED);
}
}
return;
}
case 40133: // Summon Fire Elemental
{
Unit* caster = GetCaster();
if (!caster)
return;
Unit* owner = caster->GetOwner();
if (owner && owner->GetTypeId() == TYPEID_PLAYER)
{
if (apply)
owner->CastSpell(owner, 8985, true);
else
((Player*)owner)->RemovePet(PET_SAVE_REAGENTS);
}
return;
}
case 40132: // Summon Earth Elemental
{
Unit* caster = GetCaster();
if (!caster)
return;
Unit* owner = caster->GetOwner();
if (owner && owner->GetTypeId() == TYPEID_PLAYER)
{
if (apply)
owner->CastSpell(owner, 19704, true);
else
((Player*)owner)->RemovePet(PET_SAVE_REAGENTS);
}
return;
}
case 40214: // Dragonmaw Illusion
{
if (apply)
{
target->CastSpell(target, 40216, true);
target->CastSpell(target, 42016, true);
}
else
{
target->RemoveAurasDueToSpell(40216);
target->RemoveAurasDueToSpell(42016);
}
return;
}
case 42515: // Jarl Beam
{
// aura animate dead (fainted) state for the duration, but we need to animate the death itself (correct way below?)
if (Unit* pCaster = GetCaster())
pCaster->ApplyModFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH, apply);
// Beam to Zelfrax at remove
if (!apply)
target->CastSpell(target, 42517, true);
return;
}
case 27978:
case 40131:
if (apply)
target->m_AuraFlags |= UNIT_AURAFLAG_ALIVE_INVISIBLE;
else
target->m_AuraFlags |= ~UNIT_AURAFLAG_ALIVE_INVISIBLE;
return;
}
break;
}
case SPELLFAMILY_MAGE:
{
// Hypothermia
if (GetId() == 41425)
{
target->ModifyAuraState(AURA_STATE_HYPOTHERMIA, apply);
return;
}
break;
}
case SPELLFAMILY_DRUID:
{
switch (GetId())
{
case 34246: // Idol of the Emerald Queen
{
if (target->GetTypeId() != TYPEID_PLAYER)
return;
if (apply)
// dummy not have proper effectclassmask
m_spellmod = new SpellModifier(SPELLMOD_DOT, SPELLMOD_FLAT, m_modifier.m_amount / 7, GetId(), UI64LIT(0x001000000000));
((Player*)target)->AddSpellMod(m_spellmod, apply);
return;
}
}
// Lifebloom
if (GetSpellProto()->SpellFamilyFlags & UI64LIT(0x1000000000))
{
if (apply)
{
if (Unit* caster = GetCaster())
{
// prevent double apply bonuses
if (target->GetTypeId() != TYPEID_PLAYER || !((Player*)target)->GetSession()->PlayerLoading())
{
// Lifebloom ignore stack amount
m_modifier.m_amount /= GetStackAmount();
m_modifier.m_amount = caster->SpellHealingBonusDone(target, GetSpellProto(), m_modifier.m_amount, SPELL_DIRECT_DAMAGE);
m_modifier.m_amount = target->SpellHealingBonusTaken(caster, GetSpellProto(), m_modifier.m_amount, SPELL_DIRECT_DAMAGE);
}
}
}
else
{
// Final heal on duration end
if (m_removeMode != AURA_REMOVE_BY_EXPIRE)
return;
// final heal
if (target->IsInWorld() && GetStackAmount() > 0)
{
// Lifebloom dummy store single stack amount always
int32 amount = m_modifier.m_amount;
target->CastCustomSpell(target, 33778, &amount, NULL, NULL, true, NULL, this, GetCasterGuid());
}
}
return;
}
// Predatory Strikes
if (target->GetTypeId() == TYPEID_PLAYER && GetSpellProto()->SpellIconID == 1563)
{
((Player*)target)->UpdateAttackPowerAndDamage();
return;
}
break;
}
case SPELLFAMILY_ROGUE:
break;
case SPELLFAMILY_HUNTER:
{
switch (GetId())
{
// Improved Aspect of the Viper
case 38390:
{
if (target->GetTypeId() == TYPEID_PLAYER)
{
if (apply)
// + effect value for Aspect of the Viper
m_spellmod = new SpellModifier(SPELLMOD_EFFECT1, SPELLMOD_FLAT, m_modifier.m_amount, GetId(), UI64LIT(0x4000000000000));
((Player*)target)->AddSpellMod(m_spellmod, apply);
}
return;
}
}
break;
}
case SPELLFAMILY_SHAMAN:
{
switch (GetId())
{
case 6495: // Sentry Totem
{
if (target->GetTypeId() != TYPEID_PLAYER)
return;
Totem* totem = target->GetTotem(TOTEM_SLOT_AIR);
if (totem && apply)
((Player*)target)->GetCamera().SetView(totem);
else
((Player*)target)->GetCamera().ResetView();
return;
}
}
// Improved Weapon Totems
if (GetSpellProto()->SpellIconID == 57 && target->GetTypeId() == TYPEID_PLAYER)
{
if (apply)
{
switch (m_effIndex)
{
case 0:
// Windfury Totem
m_spellmod = new SpellModifier(SPELLMOD_EFFECT1, SPELLMOD_PCT, m_modifier.m_amount, GetId(), UI64LIT(0x00200000000));
break;
case 1:
// Flametongue Totem
m_spellmod = new SpellModifier(SPELLMOD_EFFECT1, SPELLMOD_PCT, m_modifier.m_amount, GetId(), UI64LIT(0x00400000000));
break;
default: return;
}
}
((Player*)target)->AddSpellMod(m_spellmod, apply);
return;
}
break;
}
}
// pet auras
if (PetAura const* petSpell = sSpellMgr.GetPetAura(GetId()))
{
if (apply)
target->AddPetAura(petSpell);
else
target->RemovePetAura(petSpell);
return;
}
if (GetEffIndex() == EFFECT_INDEX_0 && target->GetTypeId() == TYPEID_PLAYER)
{
SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAuraMapBounds(GetId());
if (saBounds.first != saBounds.second)
{
uint32 zone, area;
target->GetZoneAndAreaId(zone, area);
for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
{
// some auras remove at aura remove
if (!itr->second->IsFitToRequirements((Player*)target, zone, area))
target->RemoveAurasDueToSpell(itr->second->spellId);
// some auras applied at aura apply
else if (itr->second->autocast)
{
if (!target->HasAura(itr->second->spellId, EFFECT_INDEX_0))
target->CastSpell(target, itr->second->spellId, true);
}
}
}
}
// script has to "handle with care", only use where data are not ok to use in the above code.
if (target->GetTypeId() == TYPEID_UNIT)
sScriptMgr.OnAuraDummy(this, apply);
}
void Aura::HandleAuraMounted(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
Unit* target = GetTarget();
if (apply)
{
CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(m_modifier.m_miscvalue);
if (!ci)
{
sLog.outErrorDb("AuraMounted: `creature_template`='%u' not found in database (only need it modelid)", m_modifier.m_miscvalue);
return;
}
uint32 display_id = Creature::ChooseDisplayId(ci);
CreatureModelInfo const* minfo = sObjectMgr.GetCreatureModelRandomGender(display_id);
if (minfo)
display_id = minfo->modelid;
target->Mount(display_id, GetId());
}
else
{
target->Unmount(true);
}
}
void Aura::HandleAuraWaterWalk(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
GetTarget()->SetWaterWalk(apply);
}
void Aura::HandleAuraFeatherFall(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
Unit* target = GetTarget();
WorldPacket data;
if (apply)
data.Initialize(SMSG_MOVE_FEATHER_FALL, 8 + 4);
else
data.Initialize(SMSG_MOVE_NORMAL_FALL, 8 + 4);
data << target->GetPackGUID();
data << uint32(0);
target->SendMessageToSet(&data, true);
// start fall from current height
if (!apply && target->GetTypeId() == TYPEID_PLAYER)
((Player*)target)->SetFallInformation(0, target->GetPositionZ());
}
void Aura::HandleAuraHover(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
WorldPacket data;
if (apply)
data.Initialize(SMSG_MOVE_SET_HOVER, 8 + 4);
else
data.Initialize(SMSG_MOVE_UNSET_HOVER, 8 + 4);
data << GetTarget()->GetPackGUID();
data << uint32(0);
GetTarget()->SendMessageToSet(&data, true);
}
void Aura::HandleWaterBreathing(bool /*apply*/, bool /*Real*/)
{
// update timers in client
if (GetTarget()->GetTypeId() == TYPEID_PLAYER)
((Player*)GetTarget())->UpdateMirrorTimers();
}
void Aura::HandleAuraModShapeshift(bool apply, bool Real)
{
if (!Real)
return;
ShapeshiftForm form = ShapeshiftForm(m_modifier.m_miscvalue);
SpellShapeshiftFormEntry const* ssEntry = sSpellShapeshiftFormStore.LookupEntry(form);
if (!ssEntry)
{
sLog.outError("Unknown shapeshift form %u in spell %u", form, GetId());
return;
}
uint32 modelid = 0;
Powers PowerType = POWER_MANA;
Unit* target = GetTarget();
if (ssEntry->modelID_A)
{
// i will asume that creatures will always take the defined model from the dbc
// since no field in creature_templates describes wether an alliance or
// horde modelid should be used at shapeshifting
if (target->GetTypeId() != TYPEID_PLAYER)
modelid = ssEntry->modelID_A;
else
{
// players are a bit different since the dbc has seldomly an horde modelid
if (Player::TeamForRace(target->getRace()) == HORDE)
{
// get model for race ( in 2.2.4 no horde models in dbc field, only 0 in it
modelid = sObjectMgr.GetModelForRace(ssEntry->modelID_A, target->getRaceMask());
}
// nothing found in above, so use default
if (!modelid)
modelid = ssEntry->modelID_A;
}
}
// remove polymorph before changing display id to keep new display id
switch (form)
{
case FORM_CAT:
case FORM_TREE:
case FORM_TRAVEL:
case FORM_AQUA:
case FORM_BEAR:
case FORM_DIREBEAR:
case FORM_FLIGHT_EPIC:
case FORM_FLIGHT:
case FORM_MOONKIN:
{
// remove movement affects
target->RemoveSpellsCausingAura(SPELL_AURA_MOD_ROOT, GetHolder());
Unit::AuraList const& slowingAuras = target->GetAurasByType(SPELL_AURA_MOD_DECREASE_SPEED);
for (Unit::AuraList::const_iterator iter = slowingAuras.begin(); iter != slowingAuras.end();)
{
SpellEntry const* aurSpellInfo = (*iter)->GetSpellProto();
uint32 aurMechMask = GetAllSpellMechanicMask(aurSpellInfo);
// If spell that caused this aura has Croud Control or Daze effect
if ((aurMechMask & MECHANIC_NOT_REMOVED_BY_SHAPESHIFT) ||
// some Daze spells have these parameters instead of MECHANIC_DAZE (skip snare spells)
(aurSpellInfo->SpellIconID == 15 && aurSpellInfo->Dispel == 0 &&
(aurMechMask & (1 << (MECHANIC_SNARE - 1))) == 0))
{
++iter;
continue;
}
// All OK, remove aura now
target->RemoveAurasDueToSpellByCancel(aurSpellInfo->Id);
iter = slowingAuras.begin();
}
// and polymorphic affects
if (target->IsPolymorphed())
target->RemoveAurasDueToSpell(target->getTransForm());
break;
}
default:
break;
}
if (apply)
{
// remove other shapeshift before applying a new one
target->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT, GetHolder());
if (modelid > 0)
target->SetDisplayId(modelid);
// now only powertype must be set
switch (form)
{
case FORM_CAT:
PowerType = POWER_ENERGY;
break;
case FORM_BEAR:
case FORM_DIREBEAR:
case FORM_BATTLESTANCE:
case FORM_BERSERKERSTANCE:
case FORM_DEFENSIVESTANCE:
PowerType = POWER_RAGE;
break;
default:
break;
}
if (PowerType != POWER_MANA)
{
// reset power to default values only at power change
if (target->getPowerType() != PowerType)
target->setPowerType(PowerType);
switch (form)
{
case FORM_CAT:
case FORM_BEAR:
case FORM_DIREBEAR:
{
// get furor proc chance
int32 furorChance = 0;
Unit::AuraList const& mDummy = target->GetAurasByType(SPELL_AURA_DUMMY);
for (Unit::AuraList::const_iterator i = mDummy.begin(); i != mDummy.end(); ++i)
{
if ((*i)->GetSpellProto()->SpellIconID == 238)
{
furorChance = (*i)->GetModifier()->m_amount;
break;
}
}
if (m_modifier.m_miscvalue == FORM_CAT)
{
target->SetPower(POWER_ENERGY, 0);
if (irand(1, 100) <= furorChance)
target->CastSpell(target, 17099, true, NULL, this);
}
else
{
target->SetPower(POWER_RAGE, 0);
if (irand(1, 100) <= furorChance)
target->CastSpell(target, 17057, true, NULL, this);
}
break;
}
case FORM_BATTLESTANCE:
case FORM_DEFENSIVESTANCE:
case FORM_BERSERKERSTANCE:
{
uint32 Rage_val = 0;
// Stance mastery + Tactical mastery (both passive, and last have aura only in defense stance, but need apply at any stance switch)
if (target->GetTypeId() == TYPEID_PLAYER)
{
PlayerSpellMap const& sp_list = ((Player*)target)->GetSpellMap();
for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
{
if (itr->second.state == PLAYERSPELL_REMOVED)
continue;
SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
if (spellInfo && spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && spellInfo->SpellIconID == 139)
Rage_val += target->CalculateSpellDamage(target, spellInfo, EFFECT_INDEX_0) * 10;
}
}
if (target->GetPower(POWER_RAGE) > Rage_val)
target->SetPower(POWER_RAGE, Rage_val);
break;
}
default:
break;
}
}
target->SetShapeshiftForm(form);
// a form can give the player a new castbar with some spells.. this is a clientside process..
// serverside just needs to register the new spells so that player isn't kicked as cheater
if (target->GetTypeId() == TYPEID_PLAYER)
for (uint32 i = 0; i < 8; ++i)
if (ssEntry->spellId[i])
((Player*)target)->addSpell(ssEntry->spellId[i], true, false, false, false);
}
else
{
if (modelid > 0)
target->SetDisplayId(target->GetNativeDisplayId());
if (target->getClass() == CLASS_DRUID)
target->setPowerType(POWER_MANA);
target->SetShapeshiftForm(FORM_NONE);
switch (form)
{
// Nordrassil Harness - bonus
case FORM_BEAR:
case FORM_DIREBEAR:
case FORM_CAT:
if (Aura* dummy = target->GetDummyAura(37315))
target->CastSpell(target, 37316, true, NULL, dummy);
break;
// Nordrassil Regalia - bonus
case FORM_MOONKIN:
if (Aura* dummy = target->GetDummyAura(37324))
target->CastSpell(target, 37325, true, NULL, dummy);
break;
default:
break;
}
// look at the comment in apply-part
if (target->GetTypeId() == TYPEID_PLAYER)
for (uint32 i = 0; i < 8; ++i)
if (ssEntry->spellId[i])
((Player*)target)->removeSpell(ssEntry->spellId[i], false, false, false);
}
// adding/removing linked auras
// add/remove the shapeshift aura's boosts
HandleShapeshiftBoosts(apply);
if (target->GetTypeId() == TYPEID_PLAYER)
((Player*)target)->InitDataForForm();
}
void Aura::HandleAuraTransform(bool apply, bool Real)
{
Unit* target = GetTarget();
if (apply)
{
// special case (spell specific functionality)
if (m_modifier.m_miscvalue == 0)
{
switch (GetId())
{
case 16739: // Orb of Deception
{
uint32 orb_model = target->GetNativeDisplayId();
switch (orb_model)
{
// Troll Female
case 1479: target->SetDisplayId(10134); break;
// Troll Male
case 1478: target->SetDisplayId(10135); break;
// Tauren Male
case 59: target->SetDisplayId(10136); break;
// Human Male
case 49: target->SetDisplayId(10137); break;
// Human Female
case 50: target->SetDisplayId(10138); break;
// Orc Male
case 51: target->SetDisplayId(10139); break;
// Orc Female
case 52: target->SetDisplayId(10140); break;
// Dwarf Male
case 53: target->SetDisplayId(10141); break;
// Dwarf Female
case 54: target->SetDisplayId(10142); break;
// NightElf Male
case 55: target->SetDisplayId(10143); break;
// NightElf Female
case 56: target->SetDisplayId(10144); break;
// Undead Female
case 58: target->SetDisplayId(10145); break;
// Undead Male
case 57: target->SetDisplayId(10146); break;
// Tauren Female
case 60: target->SetDisplayId(10147); break;
// Gnome Male
case 1563: target->SetDisplayId(10148); break;
// Gnome Female
case 1564: target->SetDisplayId(10149); break;
// BloodElf Female
case 15475: target->SetDisplayId(17830); break;
// BloodElf Male
case 15476: target->SetDisplayId(17829); break;
// Dranei Female
case 16126: target->SetDisplayId(17828); break;
// Dranei Male
case 16125: target->SetDisplayId(17827); break;
default: break;
}
break;
}
case 42365: // Murloc costume
target->SetDisplayId(21723);
break;
// case 44186: // Gossip NPC Appearance - All, Brewfest
// break;
// case 48305: // Gossip NPC Appearance - All, Spirit of Competition
// break;
case 50517: // Dread Corsair
case 51926: // Corsair Costume
{
// expected for players
uint32 race = target->getRace();
switch (race)
{
case RACE_HUMAN:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25037 : 25048);
break;
case RACE_ORC:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25039 : 25050);
break;
case RACE_DWARF:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25034 : 25045);
break;
case RACE_NIGHTELF:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25038 : 25049);
break;
case RACE_UNDEAD:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25042 : 25053);
break;
case RACE_TAUREN:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25040 : 25051);
break;
case RACE_GNOME:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25035 : 25046);
break;
case RACE_TROLL:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25041 : 25052);
break;
case RACE_GOBLIN: // not really player race (3.x), but model exist
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25036 : 25047);
break;
case RACE_BLOODELF:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25032 : 25043);
break;
case RACE_DRAENEI:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25033 : 25044);
break;
}
break;
}
// case 50531: // Gossip NPC Appearance - All, Pirate Day
// break;
// case 51010: // Dire Brew
// break;
default:
sLog.outError("Aura::HandleAuraTransform, spell %u does not have creature entry defined, need custom defined model.", GetId());
break;
}
}
else // m_modifier.m_miscvalue != 0
{
uint32 model_id;
CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(m_modifier.m_miscvalue);
if (!ci)
{
model_id = 16358; // pig pink ^_^
sLog.outError("Auras: unknown creature id = %d (only need its modelid) Form Spell Aura Transform in Spell ID = %d", m_modifier.m_miscvalue, GetId());
}
else
model_id = Creature::ChooseDisplayId(ci); // Will use the default model here
target->SetDisplayId(model_id);
// creature case, need to update equipment if additional provided
if (ci && target->GetTypeId() == TYPEID_UNIT)
((Creature*)target)->LoadEquipment(ci->equipmentId, false);
// Dragonmaw Illusion (set mount model also)
if (GetId() == 42016 && target->GetMountID() && !target->GetAurasByType(SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED).empty())
target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 16314);
}
// update active transform spell only not set or not overwriting negative by positive case
if (!target->getTransForm() || !IsPositiveSpell(GetId()) || IsPositiveSpell(target->getTransForm()))
target->setTransForm(GetId());
// polymorph case
if (Real && target->GetTypeId() == TYPEID_PLAYER && target->IsPolymorphed())
{
// for players, start regeneration after 1s (in polymorph fast regeneration case)
// only if caster is Player (after patch 2.4.2)
if (GetCasterGuid().IsPlayer())
((Player*)target)->setRegenTimer(1 * IN_MILLISECONDS);
// dismount polymorphed target (after patch 2.4.2)
if (target->IsMounted())
target->RemoveSpellsCausingAura(SPELL_AURA_MOUNTED, GetHolder());
}
}
else // !apply
{
// ApplyModifier(true) will reapply it if need
target->setTransForm(0);
target->SetDisplayId(target->GetNativeDisplayId());
// apply default equipment for creature case
if (target->GetTypeId() == TYPEID_UNIT)
((Creature*)target)->LoadEquipment(((Creature*)target)->GetCreatureInfo()->equipmentId, true);
// re-apply some from still active with preference negative cases
Unit::AuraList const& otherTransforms = target->GetAurasByType(SPELL_AURA_TRANSFORM);
if (!otherTransforms.empty())
{
// look for other transform auras
Aura* handledAura = *otherTransforms.begin();
for (Unit::AuraList::const_iterator i = otherTransforms.begin(); i != otherTransforms.end(); ++i)
{
// negative auras are preferred
if (!IsPositiveSpell((*i)->GetSpellProto()->Id))
{
handledAura = *i;
break;
}
}
handledAura->ApplyModifier(true);
}
// Dragonmaw Illusion (restore mount model)
if (GetId() == 42016 && target->GetMountID() == 16314)
{
if (!target->GetAurasByType(SPELL_AURA_MOUNTED).empty())
{
uint32 cr_id = target->GetAurasByType(SPELL_AURA_MOUNTED).front()->GetModifier()->m_miscvalue;
if (CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(cr_id))
{
uint32 display_id = Creature::ChooseDisplayId(ci);
CreatureModelInfo const* minfo = sObjectMgr.GetCreatureModelRandomGender(display_id);
if (minfo)
display_id = minfo->modelid;
target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, display_id);
}
}
}
}
}
void Aura::HandleForceReaction(bool apply, bool Real)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
if (!Real)
return;
Player* player = (Player*)GetTarget();
uint32 faction_id = m_modifier.m_miscvalue;
ReputationRank faction_rank = ReputationRank(m_modifier.m_amount);
player->GetReputationMgr().ApplyForceReaction(faction_id, faction_rank, apply);
player->GetReputationMgr().SendForceReactions();
// stop fighting if at apply forced rank friendly or at remove real rank friendly
if ((apply && faction_rank >= REP_FRIENDLY) || (!apply && player->GetReputationRank(faction_id) >= REP_FRIENDLY))
player->StopAttackFaction(faction_id);
}
void Aura::HandleAuraModSkill(bool apply, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
uint32 prot = GetSpellProto()->EffectMiscValue[m_effIndex];
int32 points = GetModifier()->m_amount;
((Player*)GetTarget())->ModifySkillBonus(prot, (apply ? points : -points), m_modifier.m_auraname == SPELL_AURA_MOD_SKILL_TALENT);
if (prot == SKILL_DEFENSE)
((Player*)GetTarget())->UpdateDefenseBonusesMod();
}
void Aura::HandleChannelDeathItem(bool apply, bool Real)
{
if (Real && !apply)
{
if (m_removeMode != AURA_REMOVE_BY_DEATH)
return;
// Item amount
if (m_modifier.m_amount <= 0)
return;
SpellEntry const* spellInfo = GetSpellProto();
if (spellInfo->EffectItemType[m_effIndex] == 0)
return;
Unit* victim = GetTarget();
Unit* caster = GetCaster();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
// Soul Shard (target req.)
if (spellInfo->EffectItemType[m_effIndex] == 6265)
{
// Only from non-grey units
if (!((Player*)caster)->isHonorOrXPTarget(victim) ||
(victim->GetTypeId() == TYPEID_UNIT && !((Player*)caster)->isAllowedToLoot((Creature*)victim)))
return;
}
// Adding items
uint32 noSpaceForCount = 0;
uint32 count = m_modifier.m_amount;
ItemPosCountVec dest;
InventoryResult msg = ((Player*)caster)->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, spellInfo->EffectItemType[m_effIndex], count, &noSpaceForCount);
if (msg != EQUIP_ERR_OK)
{
count -= noSpaceForCount;
((Player*)caster)->SendEquipError(msg, NULL, NULL, spellInfo->EffectItemType[m_effIndex]);
if (count == 0)
return;
}
Item* newitem = ((Player*)caster)->StoreNewItem(dest, spellInfo->EffectItemType[m_effIndex], true);
((Player*)caster)->SendNewItem(newitem, count, true, true);
}
}
void Aura::HandleBindSight(bool apply, bool /*Real*/)
{
Unit* caster = GetCaster();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
Camera& camera = ((Player*)caster)->GetCamera();
if (apply)
camera.SetView(GetTarget());
else
camera.ResetView();
}
void Aura::HandleFarSight(bool apply, bool /*Real*/)
{
Unit* caster = GetCaster();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
Camera& camera = ((Player*)caster)->GetCamera();
if (apply)
camera.SetView(GetTarget());
else
camera.ResetView();
}
void Aura::HandleAuraTrackCreatures(bool apply, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
if (apply)
GetTarget()->RemoveNoStackAurasDueToAuraHolder(GetHolder());
if (apply)
GetTarget()->SetFlag(PLAYER_TRACK_CREATURES, uint32(1) << (m_modifier.m_miscvalue - 1));
else
GetTarget()->RemoveFlag(PLAYER_TRACK_CREATURES, uint32(1) << (m_modifier.m_miscvalue - 1));
}
void Aura::HandleAuraTrackResources(bool apply, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
if (apply)
GetTarget()->RemoveNoStackAurasDueToAuraHolder(GetHolder());
if (apply)
GetTarget()->SetFlag(PLAYER_TRACK_RESOURCES, uint32(1) << (m_modifier.m_miscvalue - 1));
else
GetTarget()->RemoveFlag(PLAYER_TRACK_RESOURCES, uint32(1) << (m_modifier.m_miscvalue - 1));
}
void Aura::HandleAuraTrackStealthed(bool apply, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
if (apply)
GetTarget()->RemoveNoStackAurasDueToAuraHolder(GetHolder());
GetTarget()->ApplyModByteFlag(PLAYER_FIELD_BYTES, 0, PLAYER_FIELD_BYTE_TRACK_STEALTHED, apply);
}
void Aura::HandleAuraModScale(bool apply, bool /*Real*/)
{
GetTarget()->ApplyPercentModFloatValue(OBJECT_FIELD_SCALE_X, float(m_modifier.m_amount), apply);
GetTarget()->UpdateModelData();
}
void Aura::HandleModPossess(bool apply, bool Real)
{
if (!Real)
return;
Unit* target = GetTarget();
// not possess yourself
if (GetCasterGuid() == target->GetObjectGuid())
return;
Unit* caster = GetCaster();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
Player* p_caster = (Player*)caster;
Camera& camera = p_caster->GetCamera();
if (apply)
{
target->addUnitState(UNIT_STAT_CONTROLLED);
target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
target->SetCharmerGuid(p_caster->GetObjectGuid());
target->setFaction(p_caster->getFaction());
// target should became visible at SetView call(if not visible before):
// otherwise client\p_caster will ignore packets from the target(SetClientControl for example)
camera.SetView(target);
p_caster->SetCharm(target);
p_caster->SetClientControl(target, 1);
p_caster->SetMover(target);
target->CombatStop(true);
target->DeleteThreatList();
target->getHostileRefManager().deleteReferences();
if (CharmInfo* charmInfo = target->InitCharmInfo(target))
{
charmInfo->InitPossessCreateSpells();
charmInfo->SetReactState(REACT_PASSIVE);
charmInfo->SetCommandState(COMMAND_STAY);
}
p_caster->PossessSpellInitialize();
if (target->GetTypeId() == TYPEID_UNIT)
{
((Creature*)target)->AIM_Initialize();
}
else if (target->GetTypeId() == TYPEID_PLAYER)
{
((Player*)target)->SetClientControl(target, 0);
}
}
else
{
p_caster->SetCharm(NULL);
p_caster->SetClientControl(target, 0);
p_caster->SetMover(NULL);
// there is a possibility that target became invisible for client\p_caster at ResetView call:
// it must be called after movement control unapplying, not before! the reason is same as at aura applying
camera.ResetView();
p_caster->RemovePetActionBar();
// on delete only do caster related effects
if (m_removeMode == AURA_REMOVE_BY_DELETE)
return;
target->clearUnitState(UNIT_STAT_CONTROLLED);
target->CombatStop(true);
target->DeleteThreatList();
target->getHostileRefManager().deleteReferences();
target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
target->SetCharmerGuid(ObjectGuid());
if (target->GetTypeId() == TYPEID_PLAYER)
{
((Player*)target)->setFactionForRace(target->getRace());
((Player*)target)->SetClientControl(target, 1);
}
else if (target->GetTypeId() == TYPEID_UNIT)
{
CreatureInfo const* cinfo = ((Creature*)target)->GetCreatureInfo();
target->setFaction(cinfo->faction_A);
}
if (target->GetTypeId() == TYPEID_UNIT)
{
((Creature*)target)->AIM_Initialize();
target->AttackedBy(caster);
}
}
}
void Aura::HandleModPossessPet(bool apply, bool Real)
{
if (!Real)
return;
Unit* caster = GetCaster();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
Unit* target = GetTarget();
if (target->GetTypeId() != TYPEID_UNIT || !((Creature*)target)->IsPet())
return;
Pet* pet = (Pet*)target;
Player* p_caster = (Player*)caster;
Camera& camera = p_caster->GetCamera();
if (apply)
{
pet->addUnitState(UNIT_STAT_CONTROLLED);
// target should became visible at SetView call(if not visible before):
// otherwise client\p_caster will ignore packets from the target(SetClientControl for example)
camera.SetView(pet);
p_caster->SetCharm(pet);
p_caster->SetClientControl(pet, 1);
((Player*)caster)->SetMover(pet);
pet->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
pet->StopMoving();
pet->GetMotionMaster()->Clear(false);
pet->GetMotionMaster()->MoveIdle();
}
else
{
p_caster->SetCharm(NULL);
p_caster->SetClientControl(pet, 0);
p_caster->SetMover(NULL);
// there is a possibility that target became invisible for client\p_caster at ResetView call:
// it must be called after movement control unapplying, not before! the reason is same as at aura applying
camera.ResetView();
// on delete only do caster related effects
if (m_removeMode == AURA_REMOVE_BY_DELETE)
return;
pet->clearUnitState(UNIT_STAT_CONTROLLED);
pet->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
pet->AttackStop();
// out of range pet dismissed
if (!pet->IsWithinDistInMap(p_caster, pet->GetMap()->GetVisibilityDistance()))
{
p_caster->RemovePet(PET_SAVE_REAGENTS);
}
else
{
pet->GetMotionMaster()->MoveFollow(caster, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE);
}
}
}
void Aura::HandleModCharm(bool apply, bool Real)
{
if (!Real)
return;
Unit* target = GetTarget();
// not charm yourself
if (GetCasterGuid() == target->GetObjectGuid())
return;
Unit* caster = GetCaster();
if (!caster)
return;
if (apply)
{
// is it really need after spell check checks?
target->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM, GetHolder());
target->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS, GetHolder());
target->SetCharmerGuid(GetCasterGuid());
target->setFaction(caster->getFaction());
target->CastStop(target == caster ? GetId() : 0);
caster->SetCharm(target);
target->CombatStop(true);
target->DeleteThreatList();
target->getHostileRefManager().deleteReferences();
if (target->GetTypeId() == TYPEID_UNIT)
{
((Creature*)target)->AIM_Initialize();
CharmInfo* charmInfo = target->InitCharmInfo(target);
charmInfo->InitCharmCreateSpells();
charmInfo->SetReactState(REACT_DEFENSIVE);
if (caster->GetTypeId() == TYPEID_PLAYER && caster->getClass() == CLASS_WARLOCK)
{
CreatureInfo const* cinfo = ((Creature*)target)->GetCreatureInfo();
if (cinfo && cinfo->type == CREATURE_TYPE_DEMON)
{
// creature with pet number expected have class set
if (target->GetByteValue(UNIT_FIELD_BYTES_0, 1) == 0)
{
if (cinfo->unit_class == 0)
sLog.outErrorDb("Creature (Entry: %u) have unit_class = 0 but used in charmed spell, that will be result client crash.", cinfo->Entry);
else
sLog.outError("Creature (Entry: %u) have unit_class = %u but at charming have class 0!!! that will be result client crash.", cinfo->Entry, cinfo->unit_class);
target->SetByteValue(UNIT_FIELD_BYTES_0, 1, CLASS_MAGE);
}
// just to enable stat window
charmInfo->SetPetNumber(sObjectMgr.GeneratePetNumber(), true);
// if charmed two demons the same session, the 2nd gets the 1st one's name
target->SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(NULL)));
}
}
}
if (caster->GetTypeId() == TYPEID_PLAYER)
((Player*)caster)->CharmSpellInitialize();
}
else
{
target->SetCharmerGuid(ObjectGuid());
if (target->GetTypeId() == TYPEID_PLAYER)
((Player*)target)->setFactionForRace(target->getRace());
else
{
CreatureInfo const* cinfo = ((Creature*)target)->GetCreatureInfo();
// restore faction
if (((Creature*)target)->IsPet())
{
if (Unit* owner = target->GetOwner())
target->setFaction(owner->getFaction());
else if (cinfo)
target->setFaction(cinfo->faction_A);
}
else if (cinfo) // normal creature
target->setFaction(cinfo->faction_A);
// restore UNIT_FIELD_BYTES_0
if (cinfo && caster->GetTypeId() == TYPEID_PLAYER && caster->getClass() == CLASS_WARLOCK && cinfo->type == CREATURE_TYPE_DEMON)
{
// DB must have proper class set in field at loading, not req. restore, including workaround case at apply
// m_target->SetByteValue(UNIT_FIELD_BYTES_0, 1, cinfo->unit_class);
if (target->GetCharmInfo())
target->GetCharmInfo()->SetPetNumber(0, true);
else
sLog.outError("Aura::HandleModCharm: target (GUID: %u TypeId: %u) has a charm aura but no charm info!", target->GetGUIDLow(), target->GetTypeId());
}
}
caster->SetCharm(NULL);
if (caster->GetTypeId() == TYPEID_PLAYER)
((Player*)caster)->RemovePetActionBar();
target->CombatStop(true);
target->DeleteThreatList();
target->getHostileRefManager().deleteReferences();
if (target->GetTypeId() == TYPEID_UNIT)
{
((Creature*)target)->AIM_Initialize();
target->AttackedBy(caster);
}
}
}
void Aura::HandleModConfuse(bool apply, bool Real)
{
if (!Real)
return;
GetTarget()->SetConfused(apply, GetCasterGuid(), GetId());
}
void Aura::HandleModFear(bool apply, bool Real)
{
if (!Real)
return;
GetTarget()->SetFeared(apply, GetCasterGuid(), GetId());
}
void Aura::HandleFeignDeath(bool apply, bool Real)
{
if (!Real)
return;
GetTarget()->SetFeignDeath(apply, GetCasterGuid(), GetId());
}
void Aura::HandleAuraModDisarm(bool apply, bool Real)
{
if (!Real)
return;
Unit* target = GetTarget();
if (!apply && target->HasAuraType(GetModifier()->m_auraname))
return;
target->ApplyModFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISARMED, apply);<|fim▁hole|> return;
// main-hand attack speed already set to special value for feral form already and don't must change and reset at remove.
if (target->IsInFeralForm())
return;
if (apply)
target->SetAttackTime(BASE_ATTACK, BASE_ATTACK_TIME);
else
((Player*)target)->SetRegularAttackTime();
target->UpdateDamagePhysical(BASE_ATTACK);
}
void Aura::HandleAuraModStun(bool apply, bool Real)
{
if (!Real)
return;
Unit* target = GetTarget();
if (apply)
{
// Frost stun aura -> freeze/unfreeze target
if (GetSpellSchoolMask(GetSpellProto()) & SPELL_SCHOOL_MASK_FROST)
target->ModifyAuraState(AURA_STATE_FROZEN, apply);
target->addUnitState(UNIT_STAT_STUNNED);
target->SetTargetGuid(ObjectGuid());
target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
target->CastStop(target->GetObjectGuid() == GetCasterGuid() ? GetId() : 0);
// Creature specific
if (target->GetTypeId() != TYPEID_PLAYER)
target->StopMoving();
else
{
((Player*)target)->m_movementInfo.SetMovementFlags(MOVEFLAG_NONE);
target->SetStandState(UNIT_STAND_STATE_STAND);// in 1.5 client
}
target->SetRoot(true);
// Summon the Naj'entus Spine GameObject on target if spell is Impaling Spine
if (GetId() == 39837)
{
GameObject* pObj = new GameObject;
if (pObj->Create(target->GetMap()->GenerateLocalLowGuid(HIGHGUID_GAMEOBJECT), 185584, target->GetMap(),
target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation()))
{
pObj->SetRespawnTime(GetAuraDuration() / IN_MILLISECONDS);
pObj->SetSpellId(GetId());
target->AddGameObject(pObj);
target->GetMap()->Add(pObj);
}
else
delete pObj;
}
}
else
{
// Frost stun aura -> freeze/unfreeze target
if (GetSpellSchoolMask(GetSpellProto()) & SPELL_SCHOOL_MASK_FROST)
{
bool found_another = false;
for (AuraType const* itr = &frozenAuraTypes[0]; *itr != SPELL_AURA_NONE; ++itr)
{
Unit::AuraList const& auras = target->GetAurasByType(*itr);
for (Unit::AuraList::const_iterator i = auras.begin(); i != auras.end(); ++i)
{
if (GetSpellSchoolMask((*i)->GetSpellProto()) & SPELL_SCHOOL_MASK_FROST)
{
found_another = true;
break;
}
}
if (found_another)
break;
}
if (!found_another)
target->ModifyAuraState(AURA_STATE_FROZEN, apply);
}
// Real remove called after current aura remove from lists, check if other similar auras active
if (target->HasAuraType(SPELL_AURA_MOD_STUN))
return;
target->clearUnitState(UNIT_STAT_STUNNED);
target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
if (!target->hasUnitState(UNIT_STAT_ROOT)) // prevent allow move if have also root effect
{
if (target->getVictim() && target->isAlive())
target->SetTargetGuid(target->getVictim()->GetObjectGuid());
target->SetRoot(false);
}
// Wyvern Sting
if (GetSpellProto()->SpellFamilyName == SPELLFAMILY_HUNTER && GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000100000000000))
{
Unit* caster = GetCaster();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
uint32 spell_id = 0;
switch (GetId())
{
case 19386: spell_id = 24131; break;
case 24132: spell_id = 24134; break;
case 24133: spell_id = 24135; break;
case 27068: spell_id = 27069; break;
default:
sLog.outError("Spell selection called for unexpected original spell %u, new spell for this spell family?", GetId());
return;
}
SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell_id);
if (!spellInfo)
return;
caster->CastSpell(target, spellInfo, true, NULL, this);
return;
}
}
}
void Aura::HandleModStealth(bool apply, bool Real)
{
Unit* target = GetTarget();
if (apply)
{
// drop flag at stealth in bg
target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
// only at real aura add
if (Real)
{
target->SetStandFlags(UNIT_STAND_FLAGS_CREEP);
if (target->GetTypeId() == TYPEID_PLAYER)
target->SetByteFlag(PLAYER_FIELD_BYTES2, 1, PLAYER_FIELD_BYTE2_STEALTH);
// apply only if not in GM invisibility (and overwrite invisibility state)
if (target->GetVisibility() != VISIBILITY_OFF)
{
target->SetVisibility(VISIBILITY_GROUP_NO_DETECT);
target->SetVisibility(VISIBILITY_GROUP_STEALTH);
}
// for RACE_NIGHTELF stealth
if (target->GetTypeId() == TYPEID_PLAYER && GetId() == 20580)
target->CastSpell(target, 21009, true, NULL, this);
// apply full stealth period bonuses only at first stealth aura in stack
if (target->GetAurasByType(SPELL_AURA_MOD_STEALTH).size() <= 1)
{
Unit::AuraList const& mDummyAuras = target->GetAurasByType(SPELL_AURA_DUMMY);
for (Unit::AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
{
// Master of Subtlety
if ((*i)->GetSpellProto()->SpellIconID == 2114)
{
target->RemoveAurasDueToSpell(31666);
int32 bp = (*i)->GetModifier()->m_amount;
target->CastCustomSpell(target, 31665, &bp, NULL, NULL, true);
break;
}
}
}
}
}
else
{
// for RACE_NIGHTELF stealth
if (Real && target->GetTypeId() == TYPEID_PLAYER && GetId() == 20580)
target->RemoveAurasDueToSpell(21009);
// only at real aura remove of _last_ SPELL_AURA_MOD_STEALTH
if (Real && !target->HasAuraType(SPELL_AURA_MOD_STEALTH))
{
// if no GM invisibility
if (target->GetVisibility() != VISIBILITY_OFF)
{
target->RemoveStandFlags(UNIT_STAND_FLAGS_CREEP);
if (target->GetTypeId() == TYPEID_PLAYER)
target->RemoveByteFlag(PLAYER_FIELD_BYTES2, 1, PLAYER_FIELD_BYTE2_STEALTH);
// restore invisibility if any
if (target->HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
{
target->SetVisibility(VISIBILITY_GROUP_NO_DETECT);
target->SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
}
else
target->SetVisibility(VISIBILITY_ON);
}
// apply delayed talent bonus remover at last stealth aura remove
Unit::AuraList const& mDummyAuras = target->GetAurasByType(SPELL_AURA_DUMMY);
for (Unit::AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
{
// Master of Subtlety
if ((*i)->GetSpellProto()->SpellIconID == 2114)
{
target->CastSpell(target, 31666, true);
break;
}
}
}
}
}
void Aura::HandleInvisibility(bool apply, bool Real)
{
Unit* target = GetTarget();
if (apply)
{
target->m_invisibilityMask |= (1 << m_modifier.m_miscvalue);
target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
if (Real && target->GetTypeId() == TYPEID_PLAYER)
{
// apply glow vision
target->SetByteFlag(PLAYER_FIELD_BYTES2, 1, PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW);
}
// apply only if not in GM invisibility and not stealth
if (target->GetVisibility() == VISIBILITY_ON)
{
// Aura not added yet but visibility code expect temporary add aura
target->SetVisibility(VISIBILITY_GROUP_NO_DETECT);
target->SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
}
}
else
{
// recalculate value at modifier remove (current aura already removed)
target->m_invisibilityMask = 0;
Unit::AuraList const& auras = target->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY);
for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
target->m_invisibilityMask |= (1 << (*itr)->GetModifier()->m_miscvalue);
// only at real aura remove and if not have different invisibility auras.
if (Real && target->m_invisibilityMask == 0)
{
// remove glow vision
if (target->GetTypeId() == TYPEID_PLAYER)
target->RemoveByteFlag(PLAYER_FIELD_BYTES2, 1, PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW);
// apply only if not in GM invisibility & not stealthed while invisible
if (target->GetVisibility() != VISIBILITY_OFF)
{
// if have stealth aura then already have stealth visibility
if (!target->HasAuraType(SPELL_AURA_MOD_STEALTH))
target->SetVisibility(VISIBILITY_ON);
}
}
}
}
void Aura::HandleInvisibilityDetect(bool apply, bool Real)
{
Unit* target = GetTarget();
if (apply)
{
target->m_detectInvisibilityMask |= (1 << m_modifier.m_miscvalue);
}
else
{
// recalculate value at modifier remove (current aura already removed)
target->m_detectInvisibilityMask = 0;
Unit::AuraList const& auras = target->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
target->m_detectInvisibilityMask |= (1 << (*itr)->GetModifier()->m_miscvalue);
}
if (Real && target->GetTypeId() == TYPEID_PLAYER)
((Player*)target)->GetCamera().UpdateVisibilityForOwner();
}
void Aura::HandleDetectAmore(bool apply, bool /*real*/)
{
GetTarget()->ApplyModByteFlag(PLAYER_FIELD_BYTES2, 1, (PLAYER_FIELD_BYTE2_DETECT_AMORE_0 << m_modifier.m_amount), apply);
}
void Aura::HandleAuraModRoot(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
Unit* target = GetTarget();
if (apply)
{
// Frost root aura -> freeze/unfreeze target
if (GetSpellSchoolMask(GetSpellProto()) & SPELL_SCHOOL_MASK_FROST)
target->ModifyAuraState(AURA_STATE_FROZEN, apply);
target->addUnitState(UNIT_STAT_ROOT);
target->SetTargetGuid(ObjectGuid());
// Save last orientation
if (target->getVictim())
target->SetOrientation(target->GetAngle(target->getVictim()));
if (target->GetTypeId() == TYPEID_PLAYER)
{
target->SetRoot(true);
// Clear unit movement flags
((Player*)target)->m_movementInfo.SetMovementFlags(MOVEFLAG_NONE);
}
else
target->StopMoving();
}
else
{
// Frost root aura -> freeze/unfreeze target
if (GetSpellSchoolMask(GetSpellProto()) & SPELL_SCHOOL_MASK_FROST)
{
bool found_another = false;
for (AuraType const* itr = &frozenAuraTypes[0]; *itr != SPELL_AURA_NONE; ++itr)
{
Unit::AuraList const& auras = target->GetAurasByType(*itr);
for (Unit::AuraList::const_iterator i = auras.begin(); i != auras.end(); ++i)
{
if (GetSpellSchoolMask((*i)->GetSpellProto()) & SPELL_SCHOOL_MASK_FROST)
{
found_another = true;
break;
}
}
if (found_another)
break;
}
if (!found_another)
target->ModifyAuraState(AURA_STATE_FROZEN, apply);
}
// Real remove called after current aura remove from lists, check if other similar auras active
if (target->HasAuraType(SPELL_AURA_MOD_ROOT))
return;
target->clearUnitState(UNIT_STAT_ROOT);
if (!target->hasUnitState(UNIT_STAT_STUNNED)) // prevent allow move if have also stun effect
{
if (target->getVictim() && target->isAlive())
target->SetTargetGuid(target->getVictim()->GetObjectGuid());
if (target->GetTypeId() == TYPEID_PLAYER)
target->SetRoot(false);
}
}
}
void Aura::HandleAuraModSilence(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
Unit* target = GetTarget();
if (apply)
{
target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED);
// Stop cast only spells vs PreventionType == SPELL_PREVENTION_TYPE_SILENCE
for (uint32 i = CURRENT_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
if (Spell* spell = target->GetCurrentSpell(CurrentSpellTypes(i)))
if (spell->m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE)
// Stop spells on prepare or casting state
target->InterruptSpell(CurrentSpellTypes(i), false);
switch (GetId())
{
// Arcane Torrent (Energy)
case 25046:
{
Unit* caster = GetCaster();
if (!caster)
return;
// Search Mana Tap auras on caster
Aura* dummy = caster->GetDummyAura(28734);
if (dummy)
{
int32 bp = dummy->GetStackAmount() * 10;
caster->CastCustomSpell(caster, 25048, &bp, NULL, NULL, true);
caster->RemoveAurasDueToSpell(28734);
}
}
}
}
else
{
// Real remove called after current aura remove from lists, check if other similar auras active
if (target->HasAuraType(SPELL_AURA_MOD_SILENCE))
return;
target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED);
}
}
void Aura::HandleModThreat(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
Unit* target = GetTarget();
if (!target->isAlive())
return;
int level_diff = 0;
int multiplier = 0;
switch (GetId())
{
// Arcane Shroud
case 26400:
level_diff = target->getLevel() - 60;
multiplier = 2;
break;
// The Eye of Diminution
case 28862:
level_diff = target->getLevel() - 60;
multiplier = 1;
break;
}
if (level_diff > 0)
m_modifier.m_amount += multiplier * level_diff;
if (target->GetTypeId() == TYPEID_PLAYER)
for (int8 x = 0; x < MAX_SPELL_SCHOOL; ++x)
if (m_modifier.m_miscvalue & int32(1 << x))
ApplyPercentModFloatVar(target->m_threatModifier[x], float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModTotalThreat(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
Unit* target = GetTarget();
if (!target->isAlive() || target->GetTypeId() != TYPEID_PLAYER)
return;
Unit* caster = GetCaster();
if (!caster || !caster->isAlive())
return;
float threatMod = apply ? float(m_modifier.m_amount) : float(-m_modifier.m_amount);
target->getHostileRefManager().threatAssist(caster, threatMod, GetSpellProto());
}
void Aura::HandleModTaunt(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
Unit* target = GetTarget();
if (!target->isAlive() || !target->CanHaveThreatList())
return;
Unit* caster = GetCaster();
if (!caster || !caster->isAlive())
return;
if (apply)
target->TauntApply(caster);
else
{
// When taunt aura fades out, mob will switch to previous target if current has less than 1.1 * secondthreat
target->TauntFadeOut(caster);
}
}
/*********************************************************/
/*** MODIFY SPEED ***/
/*********************************************************/
void Aura::HandleAuraModIncreaseSpeed(bool /*apply*/, bool Real)
{
// all applied/removed only at real aura add/remove
if (!Real)
return;
GetTarget()->UpdateSpeed(MOVE_RUN, true);
}
void Aura::HandleAuraModIncreaseMountedSpeed(bool /*apply*/, bool Real)
{
// all applied/removed only at real aura add/remove
if (!Real)
return;
GetTarget()->UpdateSpeed(MOVE_RUN, true);
}
void Aura::HandleAuraModIncreaseFlightSpeed(bool apply, bool Real)
{
// all applied/removed only at real aura add/remove
if (!Real)
return;
Unit* target = GetTarget();
// Enable Fly mode for flying mounts
if (m_modifier.m_auraname == SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED)
{
WorldPacket data;
if (apply)
data.Initialize(SMSG_MOVE_SET_CAN_FLY, 12);
else
data.Initialize(SMSG_MOVE_UNSET_CAN_FLY, 12);
data << target->GetPackGUID();
data << uint32(0); // unknown
target->SendMessageToSet(&data, true);
// Players on flying mounts must be immune to polymorph
if (target->GetTypeId() == TYPEID_PLAYER)
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply);
// Dragonmaw Illusion (overwrite mount model, mounted aura already applied)
if (apply && target->HasAura(42016, EFFECT_INDEX_0) && target->GetMountID())
target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 16314);
}
target->UpdateSpeed(MOVE_FLIGHT, true);
}
void Aura::HandleAuraModIncreaseSwimSpeed(bool /*apply*/, bool Real)
{
// all applied/removed only at real aura add/remove
if (!Real)
return;
GetTarget()->UpdateSpeed(MOVE_SWIM, true);
}
void Aura::HandleAuraModDecreaseSpeed(bool apply, bool Real)
{
// all applied/removed only at real aura add/remove
if (!Real)
return;
Unit* target = GetTarget();
if (apply)
{
// Gronn Lord's Grasp, becomes stoned
if (GetId() == 33572)
{
if (GetStackAmount() >= 5 && !target->HasAura(33652))
target->CastSpell(target, 33652, true);
}
}
target->UpdateSpeed(MOVE_RUN, true);
target->UpdateSpeed(MOVE_SWIM, true);
target->UpdateSpeed(MOVE_FLIGHT, true);
}
void Aura::HandleAuraModUseNormalSpeed(bool /*apply*/, bool Real)
{
// all applied/removed only at real aura add/remove
if (!Real)
return;
Unit* target = GetTarget();
target->UpdateSpeed(MOVE_RUN, true);
target->UpdateSpeed(MOVE_SWIM, true);
target->UpdateSpeed(MOVE_FLIGHT, true);
}
/*********************************************************/
/*** IMMUNITY ***/
/*********************************************************/
void Aura::HandleModMechanicImmunity(bool apply, bool /*Real*/)
{
uint32 misc = m_modifier.m_miscvalue;
Unit* target = GetTarget();
if (apply && GetSpellProto()->HasAttribute(SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY))
{
uint32 mechanic = 1 << (misc - 1);
// immune movement impairment and loss of control (spell data have special structure for mark this case)
if (IsSpellRemoveAllMovementAndControlLossEffects(GetSpellProto()))
mechanic = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
target->RemoveAurasAtMechanicImmunity(mechanic, GetId());
}
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, misc, apply);
// special cases
switch (misc)
{
case MECHANIC_INVULNERABILITY:
target->ModifyAuraState(AURA_STATE_FORBEARANCE, apply);
break;
case MECHANIC_SHIELD:
target->ModifyAuraState(AURA_STATE_WEAKENED_SOUL, apply);
break;
}
// Bestial Wrath
if (GetSpellProto()->SpellFamilyName == SPELLFAMILY_HUNTER && GetSpellProto()->SpellIconID == 1680)
{
// The Beast Within cast on owner if talent present
if (Unit* owner = target->GetOwner())
{
// Search talent The Beast Within
Unit::AuraList const& dummyAuras = owner->GetAurasByType(SPELL_AURA_DUMMY);
for (Unit::AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i)
{
if ((*i)->GetSpellProto()->SpellIconID == 2229)
{
if (apply)
owner->CastSpell(owner, 34471, true, NULL, this);
else
owner->RemoveAurasDueToSpell(34471);
break;
}
}
}
}
}
void Aura::HandleModMechanicImmunityMask(bool apply, bool /*Real*/)
{
uint32 mechanic = m_modifier.m_miscvalue;
if (apply && GetSpellProto()->HasAttribute(SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY))
GetTarget()->RemoveAurasAtMechanicImmunity(mechanic, GetId());
// check implemented in Unit::IsImmuneToSpell and Unit::IsImmuneToSpellEffect
}
// this method is called whenever we add / remove aura which gives m_target some imunity to some spell effect
void Aura::HandleAuraModEffectImmunity(bool apply, bool /*Real*/)
{
Unit* target = GetTarget();
// when removing flag aura, handle flag drop
if (!apply && target->GetTypeId() == TYPEID_PLAYER
&& (GetSpellProto()->AuraInterruptFlags & AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION))
{
Player* player = (Player*)target;
if (BattleGround* bg = player->GetBattleGround())
bg->EventPlayerDroppedFlag(player);
else if (OutdoorPvP* outdoorPvP = sOutdoorPvPMgr.GetScript(player->GetCachedZoneId()))
outdoorPvP->HandleDropFlag(player, GetSpellProto()->Id);
}
target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, m_modifier.m_miscvalue, apply);
}
void Aura::HandleAuraModStateImmunity(bool apply, bool Real)
{
if (apply && Real && GetSpellProto()->HasAttribute(SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY))
{
Unit::AuraList const& auraList = GetTarget()->GetAurasByType(AuraType(m_modifier.m_miscvalue));
for (Unit::AuraList::const_iterator itr = auraList.begin(); itr != auraList.end();)
{
if (auraList.front() != this) // skip itself aura (it already added)
{
GetTarget()->RemoveAurasDueToSpell(auraList.front()->GetId());
itr = auraList.begin();
}
else
++itr;
}
}
GetTarget()->ApplySpellImmune(GetId(), IMMUNITY_STATE, m_modifier.m_miscvalue, apply);
}
void Aura::HandleAuraModSchoolImmunity(bool apply, bool Real)
{
Unit* target = GetTarget();
target->ApplySpellImmune(GetId(), IMMUNITY_SCHOOL, m_modifier.m_miscvalue, apply);
// remove all flag auras (they are positive, but they must be removed when you are immune)
if (GetSpellProto()->HasAttribute(SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY) && GetSpellProto()->HasAttribute(SPELL_ATTR_EX2_DAMAGE_REDUCED_SHIELD))
target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
// TODO: optimalize this cycle - use RemoveAurasWithInterruptFlags call or something else
if (Real && apply
&& GetSpellProto()->HasAttribute(SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
&& IsPositiveSpell(GetId())) // Only positive immunity removes auras
{
uint32 school_mask = m_modifier.m_miscvalue;
Unit::SpellAuraHolderMap& Auras = target->GetSpellAuraHolderMap();
for (Unit::SpellAuraHolderMap::iterator iter = Auras.begin(), next; iter != Auras.end(); iter = next)
{
next = iter;
++next;
SpellEntry const* spell = iter->second->GetSpellProto();
if ((GetSpellSchoolMask(spell) & school_mask) // Check for school mask
&& !spell->HasAttribute(SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY) // Spells unaffected by invulnerability
&& !iter->second->IsPositive() // Don't remove positive spells
&& spell->Id != GetId()) // Don't remove self
{
target->RemoveAurasDueToSpell(spell->Id);
if (Auras.empty())
break;
else
next = Auras.begin();
}
}
}
if (Real && GetSpellProto()->Mechanic == MECHANIC_BANISH)
{
if (apply)
target->addUnitState(UNIT_STAT_ISOLATED);
else
target->clearUnitState(UNIT_STAT_ISOLATED);
}
}
void Aura::HandleAuraModDmgImmunity(bool apply, bool /*Real*/)
{
GetTarget()->ApplySpellImmune(GetId(), IMMUNITY_DAMAGE, m_modifier.m_miscvalue, apply);
}
void Aura::HandleAuraModDispelImmunity(bool apply, bool Real)
{
// all applied/removed only at real aura add/remove
if (!Real)
return;
GetTarget()->ApplySpellDispelImmunity(GetSpellProto(), DispelType(m_modifier.m_miscvalue), apply);
}
void Aura::HandleAuraProcTriggerSpell(bool apply, bool Real)
{
if (!Real)
return;
Unit* target = GetTarget();
switch (GetId())
{
// some spell have charges by functionality not have its in spell data
case 28200: // Ascendance (Talisman of Ascendance trinket)
if (apply)
GetHolder()->SetAuraCharges(6);
break;
default:
break;
}
}
void Aura::HandleAuraModStalked(bool apply, bool /*Real*/)
{
// used by spells: Hunter's Mark, Mind Vision, Syndicate Tracker (MURP) DND
if (apply)
GetTarget()->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TRACK_UNIT);
else
GetTarget()->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TRACK_UNIT);
}
/*********************************************************/
/*** PERIODIC ***/
/*********************************************************/
void Aura::HandlePeriodicTriggerSpell(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
Unit* target = GetTarget();
if (!apply)
{
switch (GetId())
{
case 66: // Invisibility
if (m_removeMode == AURA_REMOVE_BY_EXPIRE)
target->CastSpell(target, 32612, true, NULL, this);
return;
case 29213: // Curse of the Plaguebringer
if (m_removeMode != AURA_REMOVE_BY_DISPEL)
// Cast Wrath of the Plaguebringer if not dispelled
target->CastSpell(target, 29214, true, 0, this);
return;
case 42783: // Wrath of the Astrom...
if (m_removeMode == AURA_REMOVE_BY_EXPIRE && GetEffIndex() + 1 < MAX_EFFECT_INDEX)
target->CastSpell(target, GetSpellProto()->CalculateSimpleValue(SpellEffectIndex(GetEffIndex() + 1)), true);
return;
default:
break;
}
}
}
void Aura::HandlePeriodicTriggerSpellWithValue(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
}
void Aura::HandlePeriodicEnergize(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
}
void Aura::HandleAuraPowerBurn(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
}
void Aura::HandleAuraPeriodicDummy(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
Unit* target = GetTarget();
// For prevent double apply bonuses
bool loading = (target->GetTypeId() == TYPEID_PLAYER && ((Player*)target)->GetSession()->PlayerLoading());
SpellEntry const* spell = GetSpellProto();
switch (spell->SpellFamilyName)
{
case SPELLFAMILY_ROGUE:
{
// Master of Subtlety
if (spell->Id == 31666 && !apply)
{
target->RemoveAurasDueToSpell(31665);
break;
}
break;
}
case SPELLFAMILY_HUNTER:
{
// Aspect of the Viper
if (spell->SpellFamilyFlags & UI64LIT(0x0004000000000000))
{
// Update regen on remove
if (!apply && target->GetTypeId() == TYPEID_PLAYER)
((Player*)target)->UpdateManaRegen();
break;
}
break;
}
}
m_isPeriodic = apply;
}
void Aura::HandlePeriodicHeal(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
Unit* target = GetTarget();
// For prevent double apply bonuses
bool loading = (target->GetTypeId() == TYPEID_PLAYER && ((Player*)target)->GetSession()->PlayerLoading());
// Custom damage calculation after
if (apply)
{
if (loading)
return;
Unit* caster = GetCaster();
if (!caster)
return;
m_modifier.m_amount = caster->SpellHealingBonusDone(target, GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount());
}
}
void Aura::HandlePeriodicDamage(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
m_isPeriodic = apply;
Unit* target = GetTarget();
SpellEntry const* spellProto = GetSpellProto();
// For prevent double apply bonuses
bool loading = (target->GetTypeId() == TYPEID_PLAYER && ((Player*)target)->GetSession()->PlayerLoading());
// Custom damage calculation after
if (apply)
{
if (loading)
return;
Unit* caster = GetCaster();
if (!caster)
return;
switch (spellProto->SpellFamilyName)
{
case SPELLFAMILY_WARRIOR:
{
// Rend
if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000020))
{
// 0.00743*(($MWB+$mwb)/2+$AP/14*$MWS) bonus per tick
float ap = caster->GetTotalAttackPowerValue(BASE_ATTACK);
int32 mws = caster->GetAttackTime(BASE_ATTACK);
float mwb_min = caster->GetWeaponDamageRange(BASE_ATTACK, MINDAMAGE);
float mwb_max = caster->GetWeaponDamageRange(BASE_ATTACK, MAXDAMAGE);
m_modifier.m_amount += int32(((mwb_min + mwb_max) / 2 + ap * mws / 14000) * 0.00743f);
}
break;
}
case SPELLFAMILY_DRUID:
{
// Rip
if (spellProto->SpellFamilyFlags & UI64LIT(0x000000000000800000))
{
if (caster->GetTypeId() != TYPEID_PLAYER)
break;
// $AP * min(0.06*$cp, 0.24)/6 [Yes, there is no difference, whether 4 or 5 CPs are being used]
uint8 cp = ((Player*)caster)->GetComboPoints();
// Idol of Feral Shadows. Cant be handled as SpellMod in SpellAura:Dummy due its dependency from CPs
Unit::AuraList const& dummyAuras = caster->GetAurasByType(SPELL_AURA_DUMMY);
for (Unit::AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
{
if ((*itr)->GetId() == 34241)
{
m_modifier.m_amount += cp * (*itr)->GetModifier()->m_amount;
break;
}
}
if (cp > 4) cp = 4;
m_modifier.m_amount += int32(caster->GetTotalAttackPowerValue(BASE_ATTACK) * cp / 100);
}
break;
}
case SPELLFAMILY_ROGUE:
{
// Rupture
if (spellProto->SpellFamilyFlags & UI64LIT(0x000000000000100000))
{
if (caster->GetTypeId() != TYPEID_PLAYER)
break;
// Dmg/tick = $AP*min(0.01*$cp, 0.03) [Like Rip: only the first three CP increase the contribution from AP]
uint8 cp = ((Player*)caster)->GetComboPoints();
if (cp > 3) cp = 3;
m_modifier.m_amount += int32(caster->GetTotalAttackPowerValue(BASE_ATTACK) * cp / 100);
}
break;
}
default:
break;
}
if (m_modifier.m_auraname == SPELL_AURA_PERIODIC_DAMAGE)
{
// SpellDamageBonusDone for magic spells
if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellProto->DmgClass == SPELL_DAMAGE_CLASS_MAGIC)
m_modifier.m_amount = caster->SpellDamageBonusDone(target, GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount());
// MeleeDamagebonusDone for weapon based spells
else
{
WeaponAttackType attackType = GetWeaponAttackType(GetSpellProto());
m_modifier.m_amount = caster->MeleeDamageBonusDone(target, m_modifier.m_amount, attackType, GetSpellProto(), DOT, GetStackAmount());
}
}
}
// remove time effects
else
{
// Parasitic Shadowfiend - handle summoning of two Shadowfiends on DoT expire
if (spellProto->Id == 41917)
target->CastSpell(target, 41915, true);
}
}
void Aura::HandlePeriodicDamagePCT(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
}
void Aura::HandlePeriodicLeech(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
// For prevent double apply bonuses
bool loading = (GetTarget()->GetTypeId() == TYPEID_PLAYER && ((Player*)GetTarget())->GetSession()->PlayerLoading());
// Custom damage calculation after
if (apply)
{
if (loading)
return;
Unit* caster = GetCaster();
if (!caster)
return;
m_modifier.m_amount = caster->SpellDamageBonusDone(GetTarget(), GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount());
}
}
void Aura::HandlePeriodicManaLeech(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
}
void Aura::HandlePeriodicHealthFunnel(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
// For prevent double apply bonuses
bool loading = (GetTarget()->GetTypeId() == TYPEID_PLAYER && ((Player*)GetTarget())->GetSession()->PlayerLoading());
// Custom damage calculation after
if (apply)
{
if (loading)
return;
Unit* caster = GetCaster();
if (!caster)
return;
m_modifier.m_amount = caster->SpellDamageBonusDone(GetTarget(), GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount());
}
}
/*********************************************************/
/*** MODIFY STATS ***/
/*********************************************************/
/********************************/
/*** RESISTANCE ***/
/********************************/
void Aura::HandleAuraModResistanceExclusive(bool apply, bool /*Real*/)
{
for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; ++x)
{
if (m_modifier.m_miscvalue & int32(1 << x))
{
GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + x), BASE_VALUE, float(m_modifier.m_amount), apply);
if (GetTarget()->GetTypeId() == TYPEID_PLAYER)
GetTarget()->ApplyResistanceBuffModsMod(SpellSchools(x), m_positive, float(m_modifier.m_amount), apply);
}
}
}
void Aura::HandleAuraModResistance(bool apply, bool /*Real*/)
{
for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; ++x)
{
if (m_modifier.m_miscvalue & int32(1 << x))
{
GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + x), TOTAL_VALUE, float(m_modifier.m_amount), apply);
if (GetTarget()->GetTypeId() == TYPEID_PLAYER || ((Creature*)GetTarget())->IsPet())
GetTarget()->ApplyResistanceBuffModsMod(SpellSchools(x), m_positive, float(m_modifier.m_amount), apply);
}
}
}
void Aura::HandleAuraModBaseResistancePCT(bool apply, bool /*Real*/)
{
// only players have base stats
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
{
// pets only have base armor
if (((Creature*)GetTarget())->IsPet() && (m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_NORMAL))
GetTarget()->HandleStatModifier(UNIT_MOD_ARMOR, BASE_PCT, float(m_modifier.m_amount), apply);
}
else
{
for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; ++x)
{
if (m_modifier.m_miscvalue & int32(1 << x))
GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + x), BASE_PCT, float(m_modifier.m_amount), apply);
}
}
}
void Aura::HandleModResistancePercent(bool apply, bool /*Real*/)
{
Unit* target = GetTarget();
for (int8 i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; ++i)
{
if (m_modifier.m_miscvalue & int32(1 << i))
{
target->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + i), TOTAL_PCT, float(m_modifier.m_amount), apply);
if (target->GetTypeId() == TYPEID_PLAYER || ((Creature*)target)->IsPet())
{
target->ApplyResistanceBuffModsPercentMod(SpellSchools(i), true, float(m_modifier.m_amount), apply);
target->ApplyResistanceBuffModsPercentMod(SpellSchools(i), false, float(m_modifier.m_amount), apply);
}
}
}
}
void Aura::HandleModBaseResistance(bool apply, bool /*Real*/)
{
// only players have base stats
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
{
// only pets have base stats
if (((Creature*)GetTarget())->IsPet() && (m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_NORMAL))
GetTarget()->HandleStatModifier(UNIT_MOD_ARMOR, TOTAL_VALUE, float(m_modifier.m_amount), apply);
}
else
{
for (int i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; ++i)
if (m_modifier.m_miscvalue & (1 << i))
GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + i), TOTAL_VALUE, float(m_modifier.m_amount), apply);
}
}
/********************************/
/*** STAT ***/
/********************************/
void Aura::HandleAuraModStat(bool apply, bool /*Real*/)
{
if (m_modifier.m_miscvalue < -2 || m_modifier.m_miscvalue > 4)
{
sLog.outError("WARNING: Spell %u effect %u have unsupported misc value (%i) for SPELL_AURA_MOD_STAT ", GetId(), GetEffIndex(), m_modifier.m_miscvalue);
return;
}
for (int32 i = STAT_STRENGTH; i < MAX_STATS; ++i)
{
// -1 or -2 is all stats ( misc < -2 checked in function beginning )
if (m_modifier.m_miscvalue < 0 || m_modifier.m_miscvalue == i)
{
// m_target->ApplyStatMod(Stats(i), m_modifier.m_amount,apply);
GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), TOTAL_VALUE, float(m_modifier.m_amount), apply);
if (GetTarget()->GetTypeId() == TYPEID_PLAYER || ((Creature*)GetTarget())->IsPet())
GetTarget()->ApplyStatBuffMod(Stats(i), float(m_modifier.m_amount), apply);
}
}
}
void Aura::HandleModPercentStat(bool apply, bool /*Real*/)
{
if (m_modifier.m_miscvalue < -1 || m_modifier.m_miscvalue > 4)
{
sLog.outError("WARNING: Misc Value for SPELL_AURA_MOD_PERCENT_STAT not valid");
return;
}
// only players have base stats
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
for (int32 i = STAT_STRENGTH; i < MAX_STATS; ++i)
{
if (m_modifier.m_miscvalue == i || m_modifier.m_miscvalue == -1)
GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), BASE_PCT, float(m_modifier.m_amount), apply);
}
}
void Aura::HandleModSpellDamagePercentFromStat(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
// Magic damage modifiers implemented in Unit::SpellDamageBonusDone
// This information for client side use only
// Recalculate bonus
((Player*)GetTarget())->UpdateSpellDamageAndHealingBonus();
}
void Aura::HandleModSpellHealingPercentFromStat(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
// Recalculate bonus
((Player*)GetTarget())->UpdateSpellDamageAndHealingBonus();
}
void Aura::HandleAuraModDispelResist(bool apply, bool Real)
{
if (!Real || !apply)
return;
if (GetId() == 33206)
GetTarget()->CastSpell(GetTarget(), 44416, true, NULL, this, GetCasterGuid());
}
void Aura::HandleModSpellDamagePercentFromAttackPower(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
// Magic damage modifiers implemented in Unit::SpellDamageBonusDone
// This information for client side use only
// Recalculate bonus
((Player*)GetTarget())->UpdateSpellDamageAndHealingBonus();
}
void Aura::HandleModSpellHealingPercentFromAttackPower(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
// Recalculate bonus
((Player*)GetTarget())->UpdateSpellDamageAndHealingBonus();
}
void Aura::HandleModHealingDone(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
// implemented in Unit::SpellHealingBonusDone
// this information is for client side only
((Player*)GetTarget())->UpdateSpellDamageAndHealingBonus();
}
void Aura::HandleModTotalPercentStat(bool apply, bool /*Real*/)
{
if (m_modifier.m_miscvalue < -1 || m_modifier.m_miscvalue > 4)
{
sLog.outError("WARNING: Misc Value for SPELL_AURA_MOD_PERCENT_STAT not valid");
return;
}
Unit* target = GetTarget();
// save current and max HP before applying aura
uint32 curHPValue = target->GetHealth();
uint32 maxHPValue = target->GetMaxHealth();
for (int32 i = STAT_STRENGTH; i < MAX_STATS; ++i)
{
if (m_modifier.m_miscvalue == i || m_modifier.m_miscvalue == -1)
{
target->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), TOTAL_PCT, float(m_modifier.m_amount), apply);
if (target->GetTypeId() == TYPEID_PLAYER || ((Creature*)target)->IsPet())
target->ApplyStatPercentBuffMod(Stats(i), float(m_modifier.m_amount), apply);
}
}
// recalculate current HP/MP after applying aura modifications (only for spells with 0x10 flag)
if (m_modifier.m_miscvalue == STAT_STAMINA && maxHPValue > 0 && GetSpellProto()->HasAttribute(SPELL_ATTR_UNK4))
{
// newHP = (curHP / maxHP) * newMaxHP = (newMaxHP * curHP) / maxHP -> which is better because no int -> double -> int conversion is needed
uint32 newHPValue = (target->GetMaxHealth() * curHPValue) / maxHPValue;
target->SetHealth(newHPValue);
}
}
void Aura::HandleAuraModResistenceOfStatPercent(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
if (m_modifier.m_miscvalue != SPELL_SCHOOL_MASK_NORMAL)
{
// support required adding replace UpdateArmor by loop by UpdateResistence at intellect update
// and include in UpdateResistence same code as in UpdateArmor for aura mod apply.
sLog.outError("Aura SPELL_AURA_MOD_RESISTANCE_OF_STAT_PERCENT(182) need adding support for non-armor resistances!");
return;
}
// Recalculate Armor
GetTarget()->UpdateArmor();
}
/********************************/
/*** HEAL & ENERGIZE ***/
/********************************/
void Aura::HandleAuraModTotalHealthPercentRegen(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
}
void Aura::HandleAuraModTotalManaPercentRegen(bool apply, bool /*Real*/)
{
if (m_modifier.periodictime == 0)
m_modifier.periodictime = 1000;
m_periodicTimer = m_modifier.periodictime;
m_isPeriodic = apply;
}
void Aura::HandleModRegen(bool apply, bool /*Real*/) // eating
{
if (m_modifier.periodictime == 0)
m_modifier.periodictime = 5000;
m_periodicTimer = 5000;
m_isPeriodic = apply;
}
void Aura::HandleModPowerRegen(bool apply, bool Real) // drinking
{
if (!Real)
return;
Powers pt = GetTarget()->getPowerType();
if (m_modifier.periodictime == 0)
{
// Anger Management (only spell use this aura for rage)
if (pt == POWER_RAGE)
m_modifier.periodictime = 3000;
else
m_modifier.periodictime = 2000;
}
m_periodicTimer = 5000;
if (GetTarget()->GetTypeId() == TYPEID_PLAYER && m_modifier.m_miscvalue == POWER_MANA)
((Player*)GetTarget())->UpdateManaRegen();
m_isPeriodic = apply;
}
void Aura::HandleModPowerRegenPCT(bool /*apply*/, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
// Update manaregen value
if (m_modifier.m_miscvalue == POWER_MANA)
((Player*)GetTarget())->UpdateManaRegen();
}
void Aura::HandleModManaRegen(bool /*apply*/, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
// Note: an increase in regen does NOT cause threat.
((Player*)GetTarget())->UpdateManaRegen();
}
void Aura::HandleComprehendLanguage(bool apply, bool /*Real*/)
{
if (apply)
GetTarget()->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_COMPREHEND_LANG);
else
GetTarget()->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_COMPREHEND_LANG);
}
void Aura::HandleAuraModIncreaseHealth(bool apply, bool Real)
{
Unit* target = GetTarget();
// Special case with temporary increase max/current health
switch (GetId())
{
case 12976: // Warrior Last Stand triggered spell
case 28726: // Nightmare Seed ( Nightmare Seed )
case 34511: // Valor (Bulwark of Kings, Bulwark of the Ancient Kings)
case 44055: // Tremendous Fortitude (Battlemaster's Alacrity)
{
if (Real)
{
if (apply)
{
target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(m_modifier.m_amount), apply);
target->ModifyHealth(m_modifier.m_amount);
}
else
{
if (int32(target->GetHealth()) > m_modifier.m_amount)
target->ModifyHealth(-m_modifier.m_amount);
else
target->SetHealth(1);
target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(m_modifier.m_amount), apply);
}
}
return;
}
}
// generic case
target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModIncreaseMaxHealth(bool apply, bool /*Real*/)
{
Unit* target = GetTarget();
uint32 oldhealth = target->GetHealth();
double healthPercentage = (double)oldhealth / (double)target->GetMaxHealth();
target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(m_modifier.m_amount), apply);
// refresh percentage
if (oldhealth > 0)
{
uint32 newhealth = uint32(ceil((double)target->GetMaxHealth() * healthPercentage));
if (newhealth == 0)
newhealth = 1;
target->SetHealth(newhealth);
}
}
void Aura::HandleAuraModIncreaseEnergy(bool apply, bool /*Real*/)
{
Unit* target = GetTarget();
Powers powerType = target->getPowerType();
if (int32(powerType) != m_modifier.m_miscvalue)
return;
UnitMods unitMod = UnitMods(UNIT_MOD_POWER_START + powerType);
target->HandleStatModifier(unitMod, TOTAL_VALUE, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModIncreaseEnergyPercent(bool apply, bool /*Real*/)
{
Powers powerType = GetTarget()->getPowerType();
if (int32(powerType) != m_modifier.m_miscvalue)
return;
UnitMods unitMod = UnitMods(UNIT_MOD_POWER_START + powerType);
GetTarget()->HandleStatModifier(unitMod, TOTAL_PCT, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModIncreaseHealthPercent(bool apply, bool /*Real*/)
{
GetTarget()->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_PCT, float(m_modifier.m_amount), apply);
}
/********************************/
/*** FIGHT ***/
/********************************/
void Aura::HandleAuraModParryPercent(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
((Player*)GetTarget())->UpdateParryPercentage();
}
void Aura::HandleAuraModDodgePercent(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
((Player*)GetTarget())->UpdateDodgePercentage();
// sLog.outError("BONUS DODGE CHANCE: + %f", float(m_modifier.m_amount));
}
void Aura::HandleAuraModBlockPercent(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
((Player*)GetTarget())->UpdateBlockPercentage();
// sLog.outError("BONUS BLOCK CHANCE: + %f", float(m_modifier.m_amount));
}
void Aura::HandleAuraModRegenInterrupt(bool /*apply*/, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
((Player*)GetTarget())->UpdateManaRegen();
}
void Aura::HandleAuraModCritPercent(bool apply, bool Real)
{
Unit* target = GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// apply item specific bonuses for already equipped weapon
if (Real)
{
for (int i = 0; i < MAX_ATTACK; ++i)
if (Item* pItem = ((Player*)target)->GetWeaponForAttack(WeaponAttackType(i), true, false))
((Player*)target)->_ApplyWeaponDependentAuraCritMod(pItem, WeaponAttackType(i), this, apply);
}
// mods must be applied base at equipped weapon class and subclass comparison
// with spell->EquippedItemClass and EquippedItemSubClassMask and EquippedItemInventoryTypeMask
// m_modifier.m_miscvalue comparison with item generated damage types
if (GetSpellProto()->EquippedItemClass == -1)
{
((Player*)target)->HandleBaseModValue(CRIT_PERCENTAGE, FLAT_MOD, float(m_modifier.m_amount), apply);
((Player*)target)->HandleBaseModValue(OFFHAND_CRIT_PERCENTAGE, FLAT_MOD, float(m_modifier.m_amount), apply);
((Player*)target)->HandleBaseModValue(RANGED_CRIT_PERCENTAGE, FLAT_MOD, float(m_modifier.m_amount), apply);
}
else
{
// done in Player::_ApplyWeaponDependentAuraMods
}
}
void Aura::HandleModHitChance(bool apply, bool /*Real*/)
{
Unit* target = GetTarget();
if (target->GetTypeId() == TYPEID_PLAYER)
{
((Player*)target)->UpdateMeleeHitChances();
((Player*)target)->UpdateRangedHitChances();
}
else
{
target->m_modMeleeHitChance += apply ? m_modifier.m_amount : (-m_modifier.m_amount);
target->m_modRangedHitChance += apply ? m_modifier.m_amount : (-m_modifier.m_amount);
}
}
void Aura::HandleModSpellHitChance(bool apply, bool /*Real*/)
{
if (GetTarget()->GetTypeId() == TYPEID_PLAYER)
{
((Player*)GetTarget())->UpdateSpellHitChances();
}
else
{
GetTarget()->m_modSpellHitChance += apply ? m_modifier.m_amount : (-m_modifier.m_amount);
}
}
void Aura::HandleModSpellCritChance(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
if (GetTarget()->GetTypeId() == TYPEID_PLAYER)
{
((Player*)GetTarget())->UpdateAllSpellCritChances();
}
else
{
GetTarget()->m_baseSpellCritChance += apply ? m_modifier.m_amount : (-m_modifier.m_amount);
}
}
void Aura::HandleModSpellCritChanceShool(bool /*apply*/, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
for (int school = SPELL_SCHOOL_NORMAL; school < MAX_SPELL_SCHOOL; ++school)
if (m_modifier.m_miscvalue & (1 << school))
((Player*)GetTarget())->UpdateSpellCritChance(school);
}
/********************************/
/*** ATTACK SPEED ***/
/********************************/
void Aura::HandleModCastingSpeed(bool apply, bool /*Real*/)
{
GetTarget()->ApplyCastTimePercentMod(float(m_modifier.m_amount), apply);
}
void Aura::HandleModMeleeRangedSpeedPct(bool apply, bool /*Real*/)
{
Unit* target = GetTarget();
target->ApplyAttackTimePercentMod(BASE_ATTACK, float(m_modifier.m_amount), apply);
target->ApplyAttackTimePercentMod(OFF_ATTACK, float(m_modifier.m_amount), apply);
target->ApplyAttackTimePercentMod(RANGED_ATTACK, float(m_modifier.m_amount), apply);
}
void Aura::HandleModCombatSpeedPct(bool apply, bool /*Real*/)
{
Unit* target = GetTarget();
target->ApplyCastTimePercentMod(float(m_modifier.m_amount), apply);
target->ApplyAttackTimePercentMod(BASE_ATTACK, float(m_modifier.m_amount), apply);
target->ApplyAttackTimePercentMod(OFF_ATTACK, float(m_modifier.m_amount), apply);
target->ApplyAttackTimePercentMod(RANGED_ATTACK, float(m_modifier.m_amount), apply);
}
void Aura::HandleModAttackSpeed(bool apply, bool /*Real*/)
{
GetTarget()->ApplyAttackTimePercentMod(BASE_ATTACK, float(m_modifier.m_amount), apply);
}
void Aura::HandleModMeleeSpeedPct(bool apply, bool /*Real*/)
{
Unit* target = GetTarget();
target->ApplyAttackTimePercentMod(BASE_ATTACK, float(m_modifier.m_amount), apply);
target->ApplyAttackTimePercentMod(OFF_ATTACK, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModRangedHaste(bool apply, bool /*Real*/)
{
GetTarget()->ApplyAttackTimePercentMod(RANGED_ATTACK, float(m_modifier.m_amount), apply);
}
void Aura::HandleRangedAmmoHaste(bool apply, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
GetTarget()->ApplyAttackTimePercentMod(RANGED_ATTACK, float(m_modifier.m_amount), apply);
}
/********************************/
/*** ATTACK POWER ***/
/********************************/
void Aura::HandleAuraModAttackPower(bool apply, bool /*Real*/)
{
GetTarget()->HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModRangedAttackPower(bool apply, bool /*Real*/)
{
if ((GetTarget()->getClassMask() & CLASSMASK_WAND_USERS) != 0)
return;
GetTarget()->HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModAttackPowerPercent(bool apply, bool /*Real*/)
{
// UNIT_FIELD_ATTACK_POWER_MULTIPLIER = multiplier - 1
GetTarget()->HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_PCT, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModRangedAttackPowerPercent(bool apply, bool /*Real*/)
{
if ((GetTarget()->getClassMask() & CLASSMASK_WAND_USERS) != 0)
return;
// UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER = multiplier - 1
GetTarget()->HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_PCT, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModRangedAttackPowerOfStatPercent(bool /*apply*/, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
// Recalculate bonus
if (GetTarget()->GetTypeId() == TYPEID_PLAYER && !(GetTarget()->getClassMask() & CLASSMASK_WAND_USERS))
((Player*)GetTarget())->UpdateAttackPowerAndDamage(true);
}
/********************************/
/*** DAMAGE BONUS ***/
/********************************/
void Aura::HandleModDamageDone(bool apply, bool Real)
{
Unit* target = GetTarget();
// apply item specific bonuses for already equipped weapon
if (Real && target->GetTypeId() == TYPEID_PLAYER)
{
for (int i = 0; i < MAX_ATTACK; ++i)
if (Item* pItem = ((Player*)target)->GetWeaponForAttack(WeaponAttackType(i), true, false))
((Player*)target)->_ApplyWeaponDependentAuraDamageMod(pItem, WeaponAttackType(i), this, apply);
}
// m_modifier.m_miscvalue is bitmask of spell schools
// 1 ( 0-bit ) - normal school damage (SPELL_SCHOOL_MASK_NORMAL)
// 126 - full bitmask all magic damages (SPELL_SCHOOL_MASK_MAGIC) including wands
// 127 - full bitmask any damages
//
// mods must be applied base at equipped weapon class and subclass comparison
// with spell->EquippedItemClass and EquippedItemSubClassMask and EquippedItemInventoryTypeMask
// m_modifier.m_miscvalue comparison with item generated damage types
if ((m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_NORMAL) != 0)
{
// apply generic physical damage bonuses including wand case
if (GetSpellProto()->EquippedItemClass == -1 || target->GetTypeId() != TYPEID_PLAYER)
{
target->HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(m_modifier.m_amount), apply);
target->HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(m_modifier.m_amount), apply);
target->HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(m_modifier.m_amount), apply);
}
else
{
// done in Player::_ApplyWeaponDependentAuraMods
}
if (target->GetTypeId() == TYPEID_PLAYER)
{
if (m_positive)
target->ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS, m_modifier.m_amount, apply);
else
target->ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG, m_modifier.m_amount, apply);
}
}
// Skip non magic case for speedup
if ((m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_MAGIC) == 0)
return;
if (GetSpellProto()->EquippedItemClass != -1 || GetSpellProto()->EquippedItemInventoryTypeMask != 0)
{
// wand magic case (skip generic to all item spell bonuses)
// done in Player::_ApplyWeaponDependentAuraMods
// Skip item specific requirements for not wand magic damage
return;
}
// Magic damage modifiers implemented in Unit::SpellDamageBonusDone
// This information for client side use only
if (target->GetTypeId() == TYPEID_PLAYER)
{
if (m_positive)
{
for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i)
{
if ((m_modifier.m_miscvalue & (1 << i)) != 0)
target->ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + i, m_modifier.m_amount, apply);
}
}
else
{
for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i)
{
if ((m_modifier.m_miscvalue & (1 << i)) != 0)
target->ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + i, m_modifier.m_amount, apply);
}
}
Pet* pet = target->GetPet();
if (pet)
pet->UpdateAttackPowerAndDamage();
}
}
void Aura::HandleModDamagePercentDone(bool apply, bool Real)
{
DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "AURA MOD DAMAGE type:%u negative:%u", m_modifier.m_miscvalue, m_positive ? 0 : 1);
Unit* target = GetTarget();
// apply item specific bonuses for already equipped weapon
if (Real && target->GetTypeId() == TYPEID_PLAYER)
{
for (int i = 0; i < MAX_ATTACK; ++i)
if (Item* pItem = ((Player*)target)->GetWeaponForAttack(WeaponAttackType(i), true, false))
((Player*)target)->_ApplyWeaponDependentAuraDamageMod(pItem, WeaponAttackType(i), this, apply);
}
// m_modifier.m_miscvalue is bitmask of spell schools
// 1 ( 0-bit ) - normal school damage (SPELL_SCHOOL_MASK_NORMAL)
// 126 - full bitmask all magic damages (SPELL_SCHOOL_MASK_MAGIC) including wand
// 127 - full bitmask any damages
//
// mods must be applied base at equipped weapon class and subclass comparison
// with spell->EquippedItemClass and EquippedItemSubClassMask and EquippedItemInventoryTypeMask
// m_modifier.m_miscvalue comparison with item generated damage types
if ((m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_NORMAL) != 0)
{
// apply generic physical damage bonuses including wand case
if (GetSpellProto()->EquippedItemClass == -1 || target->GetTypeId() != TYPEID_PLAYER)
{
target->HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_PCT, float(m_modifier.m_amount), apply);
target->HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_PCT, float(m_modifier.m_amount), apply);
target->HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_PCT, float(m_modifier.m_amount), apply);
}
else
{
// done in Player::_ApplyWeaponDependentAuraMods
}
// For show in client
if (target->GetTypeId() == TYPEID_PLAYER)
target->ApplyModSignedFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT, m_modifier.m_amount / 100.0f, apply);
}
// Skip non magic case for speedup
if ((m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_MAGIC) == 0)
return;
if (GetSpellProto()->EquippedItemClass != -1 || GetSpellProto()->EquippedItemInventoryTypeMask != 0)
{
// wand magic case (skip generic to all item spell bonuses)
// done in Player::_ApplyWeaponDependentAuraMods
// Skip item specific requirements for not wand magic damage
return;
}
// Magic damage percent modifiers implemented in Unit::SpellDamageBonusDone
// Send info to client
if (target->GetTypeId() == TYPEID_PLAYER)
for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i)
target->ApplyModSignedFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT + i, m_modifier.m_amount / 100.0f, apply);
}
void Aura::HandleModOffhandDamagePercent(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "AURA MOD OFFHAND DAMAGE");
GetTarget()->HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_PCT, float(m_modifier.m_amount), apply);
}
/********************************/
/*** POWER COST ***/
/********************************/
void Aura::HandleModPowerCostPCT(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
float amount = m_modifier.m_amount / 100.0f;
for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
if (m_modifier.m_miscvalue & (1 << i))
GetTarget()->ApplyModSignedFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER + i, amount, apply);
}
void Aura::HandleModPowerCost(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
if (m_modifier.m_miscvalue & (1 << i))
GetTarget()->ApplyModInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + i, m_modifier.m_amount, apply);
}
/*********************************************************/
/*** OTHERS ***/
/*********************************************************/
void Aura::HandleShapeshiftBoosts(bool apply)
{
uint32 spellId1 = 0;
uint32 spellId2 = 0;
uint32 HotWSpellId = 0;
ShapeshiftForm form = ShapeshiftForm(GetModifier()->m_miscvalue);
Unit* target = GetTarget();
switch (form)
{
case FORM_CAT:
spellId1 = 3025;
HotWSpellId = 24900;
break;
case FORM_TREE:
spellId1 = 5420;
break;
case FORM_TRAVEL:
spellId1 = 5419;
break;
case FORM_AQUA:
spellId1 = 5421;
break;
case FORM_BEAR:
spellId1 = 1178;
spellId2 = 21178;
HotWSpellId = 24899;
break;
case FORM_DIREBEAR:
spellId1 = 9635;
spellId2 = 21178;
HotWSpellId = 24899;
break;
case FORM_BATTLESTANCE:
spellId1 = 21156;
break;
case FORM_DEFENSIVESTANCE:
spellId1 = 7376;
break;
case FORM_BERSERKERSTANCE:
spellId1 = 7381;
break;
case FORM_MOONKIN:
spellId1 = 24905;
break;
case FORM_FLIGHT:
spellId1 = 33948;
spellId2 = 34764;
break;
case FORM_FLIGHT_EPIC:
spellId1 = 40122;
spellId2 = 40121;
break;
case FORM_SPIRITOFREDEMPTION:
spellId1 = 27792;
spellId2 = 27795; // must be second, this important at aura remove to prevent to early iterator invalidation.
break;
case FORM_GHOSTWOLF:
case FORM_AMBIENT:
case FORM_GHOUL:
case FORM_SHADOW:
case FORM_STEALTH:
case FORM_CREATURECAT:
case FORM_CREATUREBEAR:
break;
}
if (apply)
{
if (spellId1)
target->CastSpell(target, spellId1, true, NULL, this);
if (spellId2)
target->CastSpell(target, spellId2, true, NULL, this);
if (target->GetTypeId() == TYPEID_PLAYER)
{
const PlayerSpellMap& sp_list = ((Player*)target)->GetSpellMap();
for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
{
if (itr->second.state == PLAYERSPELL_REMOVED) continue;
if (itr->first == spellId1 || itr->first == spellId2) continue;
SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
if (!spellInfo || !IsNeedCastSpellAtFormApply(spellInfo, form))
continue;
target->CastSpell(target, itr->first, true, NULL, this);
}
// Leader of the Pack
if (((Player*)target)->HasSpell(17007))
{
SpellEntry const* spellInfo = sSpellStore.LookupEntry(24932);
if (spellInfo && spellInfo->Stances & (1 << (form - 1)))
target->CastSpell(target, 24932, true, NULL, this);
}
// Heart of the Wild
if (HotWSpellId)
{
Unit::AuraList const& mModTotalStatPct = target->GetAurasByType(SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE);
for (Unit::AuraList::const_iterator i = mModTotalStatPct.begin(); i != mModTotalStatPct.end(); ++i)
{
if ((*i)->GetSpellProto()->SpellIconID == 240 && (*i)->GetModifier()->m_miscvalue == 3)
{
int32 HotWMod = (*i)->GetModifier()->m_amount;
if (GetModifier()->m_miscvalue == FORM_CAT)
HotWMod /= 2;
target->CastCustomSpell(target, HotWSpellId, &HotWMod, NULL, NULL, true, NULL, this);
break;
}
}
}
}
}
else
{
if (spellId1)
target->RemoveAurasDueToSpell(spellId1);
if (spellId2)
target->RemoveAurasDueToSpell(spellId2);
Unit::SpellAuraHolderMap& tAuras = target->GetSpellAuraHolderMap();
for (Unit::SpellAuraHolderMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
{
if (itr->second->IsRemovedOnShapeLost())
{
target->RemoveAurasDueToSpell(itr->second->GetId());
itr = tAuras.begin();
}
else
++itr;
}
}
}
void Aura::HandleAuraEmpathy(bool apply, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_UNIT)
return;
CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(GetTarget()->GetEntry());
if (ci && ci->type == CREATURE_TYPE_BEAST)
GetTarget()->ApplyModUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_SPECIALINFO, apply);
}
void Aura::HandleAuraUntrackable(bool apply, bool /*Real*/)
{
if (apply)
GetTarget()->SetByteFlag(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_UNTRACKABLE);
else
GetTarget()->RemoveByteFlag(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_UNTRACKABLE);
}
void Aura::HandleAuraModPacify(bool apply, bool /*Real*/)
{
if (apply)
GetTarget()->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED);
else
GetTarget()->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED);
}
void Aura::HandleAuraModPacifyAndSilence(bool apply, bool Real)
{
HandleAuraModPacify(apply, Real);
HandleAuraModSilence(apply, Real);
}
void Aura::HandleAuraGhost(bool apply, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
if (apply)
{
GetTarget()->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST);
}
else
{
GetTarget()->RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST);
}
}
void Aura::HandleAuraAllowFlight(bool apply, bool Real)
{
// all applied/removed only at real aura add/remove
if (!Real)
return;
// allow fly
WorldPacket data;
if (apply)
data.Initialize(SMSG_MOVE_SET_CAN_FLY, 12);
else
data.Initialize(SMSG_MOVE_UNSET_CAN_FLY, 12);
data << GetTarget()->GetPackGUID();
data << uint32(0); // unk
GetTarget()->SendMessageToSet(&data, true);
}
void Aura::HandleModRating(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
for (uint32 rating = 0; rating < MAX_COMBAT_RATING; ++rating)
if (m_modifier.m_miscvalue & (1 << rating))
((Player*)GetTarget())->ApplyRatingMod(CombatRating(rating), m_modifier.m_amount, apply);
}
void Aura::HandleForceMoveForward(bool apply, bool Real)
{
if (!Real)
return;
if (apply)
GetTarget()->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE);
else
GetTarget()->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE);
}
void Aura::HandleAuraModExpertise(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
((Player*)GetTarget())->UpdateExpertise(BASE_ATTACK);
((Player*)GetTarget())->UpdateExpertise(OFF_ATTACK);
}
void Aura::HandleModTargetResistance(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
Unit* target = GetTarget();
// applied to damage as HandleNoImmediateEffect in Unit::CalculateAbsorbAndResist and Unit::CalcArmorReducedDamage
// show armor penetration
if (target->GetTypeId() == TYPEID_PLAYER && (m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_NORMAL))
target->ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE, m_modifier.m_amount, apply);
// show as spell penetration only full spell penetration bonuses (all resistances except armor and holy
if (target->GetTypeId() == TYPEID_PLAYER && (m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_SPELL) == SPELL_SCHOOL_MASK_SPELL)
target->ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE, m_modifier.m_amount, apply);
}
void Aura::HandleShieldBlockValue(bool apply, bool /*Real*/)
{
BaseModType modType = FLAT_MOD;
if (m_modifier.m_auraname == SPELL_AURA_MOD_SHIELD_BLOCKVALUE_PCT)
modType = PCT_MOD;
if (GetTarget()->GetTypeId() == TYPEID_PLAYER)
((Player*)GetTarget())->HandleBaseModValue(SHIELD_BLOCK_VALUE, modType, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraRetainComboPoints(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
Player* target = (Player*)GetTarget();
// combo points was added in SPELL_EFFECT_ADD_COMBO_POINTS handler
// remove only if aura expire by time (in case combo points amount change aura removed without combo points lost)
if (!apply && m_removeMode == AURA_REMOVE_BY_EXPIRE && target->GetComboTargetGuid())
if (Unit* unit = ObjectAccessor::GetUnit(*GetTarget(), target->GetComboTargetGuid()))
target->AddComboPoints(unit, -m_modifier.m_amount);
}
void Aura::HandleModUnattackable(bool Apply, bool Real)
{
if (Real && Apply)
{
GetTarget()->CombatStop();
GetTarget()->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
}
GetTarget()->ApplyModFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE, Apply);
}
void Aura::HandleSpiritOfRedemption(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
Unit* target = GetTarget();
// prepare spirit state
if (apply)
{
if (target->GetTypeId() == TYPEID_PLAYER)
{
// disable breath/etc timers
((Player*)target)->StopMirrorTimers();
// set stand state (expected in this form)
if (!target->IsStandState())
target->SetStandState(UNIT_STAND_STATE_STAND);
}
target->SetHealth(1);
}
// die at aura end
else
target->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, GetSpellProto(), false);
}
void Aura::HandleSchoolAbsorb(bool apply, bool Real)
{
if (!Real)
return;
Unit* caster = GetCaster();
if (!caster)
return;
Unit* target = GetTarget();
SpellEntry const* spellProto = GetSpellProto();
if (apply)
{
// prevent double apply bonuses
if (target->GetTypeId() != TYPEID_PLAYER || !((Player*)target)->GetSession()->PlayerLoading())
{
float DoneActualBenefit = 0.0f;
switch (spellProto->SpellFamilyName)
{
case SPELLFAMILY_PRIEST:
// Power Word: Shield
if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000001))
{
//+30% from +healing bonus
DoneActualBenefit = caster->SpellBaseHealingBonusDone(GetSpellSchoolMask(spellProto)) * 0.3f;
break;
}
break;
case SPELLFAMILY_MAGE:
// Frost Ward, Fire Ward
if (spellProto->IsFitToFamilyMask(UI64LIT(0x0000000100080108)))
//+10% from +spell bonus
DoneActualBenefit = caster->SpellBaseDamageBonusDone(GetSpellSchoolMask(spellProto)) * 0.1f;
break;
case SPELLFAMILY_WARLOCK:
// Shadow Ward
if (spellProto->SpellFamilyFlags == UI64LIT(0x00))
//+10% from +spell bonus
DoneActualBenefit = caster->SpellBaseDamageBonusDone(GetSpellSchoolMask(spellProto)) * 0.1f;
break;
default:
break;
}
DoneActualBenefit *= caster->CalculateLevelPenalty(GetSpellProto());
m_modifier.m_amount += (int32)DoneActualBenefit;
}
}
}
void Aura::PeriodicTick()
{
Unit* target = GetTarget();
SpellEntry const* spellProto = GetSpellProto();
switch (m_modifier.m_auraname)
{
case SPELL_AURA_PERIODIC_DAMAGE:
case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
{
// don't damage target if not alive, possible death persistent effects
if (!target->isAlive())
return;
Unit* pCaster = GetCaster();
if (!pCaster)
return;
if (spellProto->Effect[GetEffIndex()] == SPELL_EFFECT_PERSISTENT_AREA_AURA &&
pCaster->SpellHitResult(target, spellProto, false) != SPELL_MISS_NONE)
return;
// Check for immune (not use charges)
if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto)))
return;
// some auras remove at specific health level or more
if (m_modifier.m_auraname == SPELL_AURA_PERIODIC_DAMAGE)
{
switch (GetId())
{
case 43093: case 31956: case 38801:
case 35321: case 38363: case 39215:
case 48920:
{
if (target->GetHealth() == target->GetMaxHealth())
{
target->RemoveAurasDueToSpell(GetId());
return;
}
break;
}
case 38772:
{
uint32 percent =
GetEffIndex() < EFFECT_INDEX_2 && spellProto->Effect[GetEffIndex()] == SPELL_EFFECT_DUMMY ?
pCaster->CalculateSpellDamage(target, spellProto, SpellEffectIndex(GetEffIndex() + 1)) :
100;
if (target->GetHealth() * 100 >= target->GetMaxHealth() * percent)
{
target->RemoveAurasDueToSpell(GetId());
return;
}
break;
}
default:
break;
}
}
uint32 absorb = 0;
uint32 resist = 0;
CleanDamage cleanDamage = CleanDamage(0, BASE_ATTACK, MELEE_HIT_NORMAL);
// ignore non positive values (can be result apply spellmods to aura damage
uint32 amount = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0;
uint32 pdamage;
if (m_modifier.m_auraname == SPELL_AURA_PERIODIC_DAMAGE)
pdamage = amount;
else
pdamage = uint32(target->GetMaxHealth() * amount / 100);
// SpellDamageBonus for magic spells
if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellProto->DmgClass == SPELL_DAMAGE_CLASS_MAGIC)
pdamage = target->SpellDamageBonusTaken(pCaster, spellProto, pdamage, DOT, GetStackAmount());
// MeleeDamagebonus for weapon based spells
else
{
WeaponAttackType attackType = GetWeaponAttackType(spellProto);
pdamage = target->MeleeDamageBonusTaken(pCaster, pdamage, attackType, spellProto, DOT, GetStackAmount());
}
// Calculate armor mitigation if it is a physical spell
// But not for bleed mechanic spells
if (GetSpellSchoolMask(spellProto) & SPELL_SCHOOL_MASK_NORMAL &&
GetEffectMechanic(spellProto, m_effIndex) != MECHANIC_BLEED)
{
uint32 pdamageReductedArmor = pCaster->CalcArmorReducedDamage(target, pdamage);
cleanDamage.damage += pdamage - pdamageReductedArmor;
pdamage = pdamageReductedArmor;
}
// Curse of Agony damage-per-tick calculation
if (spellProto->SpellFamilyName == SPELLFAMILY_WARLOCK && (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000400)) && spellProto->SpellIconID == 544)
{
// 1..4 ticks, 1/2 from normal tick damage
if (GetAuraTicks() <= 4)
pdamage = pdamage / 2;
// 9..12 ticks, 3/2 from normal tick damage
else if (GetAuraTicks() >= 9)
pdamage += (pdamage + 1) / 2; // +1 prevent 0.5 damage possible lost at 1..4 ticks
// 5..8 ticks have normal tick damage
}
// As of 2.2 resilience reduces damage from DoT ticks as much as the chance to not be critically hit
// Reduce dot damage from resilience for players
if (target->GetTypeId() == TYPEID_PLAYER)
pdamage -= ((Player*)target)->GetDotDamageReduction(pdamage);
target->CalculateDamageAbsorbAndResist(pCaster, GetSpellSchoolMask(spellProto), DOT, pdamage, &absorb, &resist, !GetSpellProto()->HasAttribute(SPELL_ATTR_EX2_CANT_REFLECTED));
DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s attacked %s for %u dmg inflicted by %u",
GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId());
pCaster->DealDamageMods(target, pdamage, &absorb);
// Set trigger flag
uint32 procAttacker = PROC_FLAG_ON_DO_PERIODIC; // | PROC_FLAG_SUCCESSFUL_HARMFUL_SPELL_HIT;
uint32 procVictim = PROC_FLAG_ON_TAKE_PERIODIC;// | PROC_FLAG_TAKEN_HARMFUL_SPELL_HIT;
pdamage = (pdamage <= absorb + resist) ? 0 : (pdamage - absorb - resist);
SpellPeriodicAuraLogInfo pInfo(this, pdamage, absorb, resist, 0.0f);
target->SendPeriodicAuraLog(&pInfo);
if (pdamage)
procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
pCaster->ProcDamageAndSpell(target, procAttacker, procVictim, PROC_EX_NORMAL_HIT, pdamage, BASE_ATTACK, spellProto);
pCaster->DealDamage(target, pdamage, &cleanDamage, DOT, GetSpellSchoolMask(spellProto), spellProto, true);
break;
}
case SPELL_AURA_PERIODIC_LEECH:
case SPELL_AURA_PERIODIC_HEALTH_FUNNEL:
{
// don't damage target if not alive, possible death persistent effects
if (!target->isAlive())
return;
Unit* pCaster = GetCaster();
if (!pCaster)
return;
if (!pCaster->isAlive())
return;
if (spellProto->Effect[GetEffIndex()] == SPELL_EFFECT_PERSISTENT_AREA_AURA &&
pCaster->SpellHitResult(target, spellProto, false) != SPELL_MISS_NONE)
return;
// Check for immune
if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto)))
return;
uint32 absorb = 0;
uint32 resist = 0;
CleanDamage cleanDamage = CleanDamage(0, BASE_ATTACK, MELEE_HIT_NORMAL);
uint32 pdamage = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0;
// Calculate armor mitigation if it is a physical spell
if (GetSpellSchoolMask(spellProto) & SPELL_SCHOOL_MASK_NORMAL)
{
uint32 pdamageReductedArmor = pCaster->CalcArmorReducedDamage(target, pdamage);
cleanDamage.damage += pdamage - pdamageReductedArmor;
pdamage = pdamageReductedArmor;
}
pdamage = target->SpellDamageBonusTaken(pCaster, spellProto, pdamage, DOT, GetStackAmount());
// As of 2.2 resilience reduces damage from DoT ticks as much as the chance to not be critically hit
// Reduce dot damage from resilience for players
if (target->GetTypeId() == TYPEID_PLAYER)
pdamage -= ((Player*)target)->GetDotDamageReduction(pdamage);
target->CalculateDamageAbsorbAndResist(pCaster, GetSpellSchoolMask(spellProto), DOT, pdamage, &absorb, &resist, !spellProto->HasAttribute(SPELL_ATTR_EX2_CANT_REFLECTED));
if (target->GetHealth() < pdamage)
pdamage = uint32(target->GetHealth());
DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s health leech of %s for %u dmg inflicted by %u abs is %u",
GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId(), absorb);
pCaster->DealDamageMods(target, pdamage, &absorb);
pCaster->SendSpellNonMeleeDamageLog(target, GetId(), pdamage, GetSpellSchoolMask(spellProto), absorb, resist, false, 0);
float multiplier = spellProto->EffectMultipleValue[GetEffIndex()] > 0 ? spellProto->EffectMultipleValue[GetEffIndex()] : 1;
// Set trigger flag
uint32 procAttacker = PROC_FLAG_ON_DO_PERIODIC; // | PROC_FLAG_SUCCESSFUL_HARMFUL_SPELL_HIT;
uint32 procVictim = PROC_FLAG_ON_TAKE_PERIODIC;// | PROC_FLAG_TAKEN_HARMFUL_SPELL_HIT;
pdamage = (pdamage <= absorb + resist) ? 0 : (pdamage - absorb - resist);
if (pdamage)
procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
pCaster->ProcDamageAndSpell(target, procAttacker, procVictim, PROC_EX_NORMAL_HIT, pdamage, BASE_ATTACK, spellProto);
int32 new_damage = pCaster->DealDamage(target, pdamage, &cleanDamage, DOT, GetSpellSchoolMask(spellProto), spellProto, false);
if (!target->isAlive() && pCaster->IsNonMeleeSpellCasted(false))
for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
if (Spell* spell = pCaster->GetCurrentSpell(CurrentSpellTypes(i)))
if (spell->m_spellInfo->Id == GetId())
spell->cancel();
if (Player* modOwner = pCaster->GetSpellModOwner())
modOwner->ApplySpellMod(GetId(), SPELLMOD_MULTIPLE_VALUE, multiplier);
uint32 heal = pCaster->SpellHealingBonusTaken(pCaster, spellProto, int32(new_damage * multiplier), DOT, GetStackAmount());
int32 gain = pCaster->DealHeal(pCaster, heal, spellProto);
pCaster->getHostileRefManager().threatAssist(pCaster, gain * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto);
break;
}
case SPELL_AURA_PERIODIC_HEAL:
case SPELL_AURA_OBS_MOD_HEALTH:
{
// don't heal target if not alive, mostly death persistent effects from items
if (!target->isAlive())
return;
Unit* pCaster = GetCaster();
if (!pCaster)
return;
// heal for caster damage (must be alive)
if (target != pCaster && spellProto->SpellVisual == 163 && !pCaster->isAlive())
return;
// ignore non positive values (can be result apply spellmods to aura damage
uint32 amount = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0;
uint32 pdamage;
if (m_modifier.m_auraname == SPELL_AURA_OBS_MOD_HEALTH)
pdamage = uint32(target->GetMaxHealth() * amount / 100);
else
pdamage = amount;
pdamage = target->SpellHealingBonusTaken(pCaster, spellProto, pdamage, DOT, GetStackAmount());
DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s heal of %s for %u health inflicted by %u",
GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId());
int32 gain = target->ModifyHealth(pdamage);
SpellPeriodicAuraLogInfo pInfo(this, pdamage, 0, 0, 0.0f);
target->SendPeriodicAuraLog(&pInfo);
// Set trigger flag
uint32 procAttacker = PROC_FLAG_ON_DO_PERIODIC;
uint32 procVictim = PROC_FLAG_ON_TAKE_PERIODIC;
uint32 procEx = PROC_EX_NORMAL_HIT | PROC_EX_PERIODIC_POSITIVE;
pCaster->ProcDamageAndSpell(target, procAttacker, procVictim, procEx, gain, BASE_ATTACK, spellProto);
// add HoTs to amount healed in bgs
if (pCaster->GetTypeId() == TYPEID_PLAYER)
if (BattleGround* bg = ((Player*)pCaster)->GetBattleGround())
bg->UpdatePlayerScore(((Player*)pCaster), SCORE_HEALING_DONE, gain);
target->getHostileRefManager().threatAssist(pCaster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto);
// heal for caster damage
if (target != pCaster && spellProto->SpellVisual == 163)
{
uint32 dmg = spellProto->manaPerSecond;
if (pCaster->GetHealth() <= dmg && pCaster->GetTypeId() == TYPEID_PLAYER)
{
pCaster->RemoveAurasDueToSpell(GetId());
// finish current generic/channeling spells, don't affect autorepeat
pCaster->FinishSpell(CURRENT_GENERIC_SPELL);
pCaster->FinishSpell(CURRENT_CHANNELED_SPELL);
}
else
{
uint32 damage = gain;
uint32 absorb = 0;
pCaster->DealDamageMods(pCaster, damage, &absorb);
pCaster->SendSpellNonMeleeDamageLog(pCaster, GetId(), damage, GetSpellSchoolMask(spellProto), absorb, 0, false, 0, false);
CleanDamage cleanDamage = CleanDamage(0, BASE_ATTACK, MELEE_HIT_NORMAL);
pCaster->DealDamage(pCaster, damage, &cleanDamage, NODAMAGE, GetSpellSchoolMask(spellProto), spellProto, true);
}
}
break;
}
case SPELL_AURA_PERIODIC_MANA_LEECH:
{
// don't damage target if not alive, possible death persistent effects
if (!target->isAlive())
return;
if (m_modifier.m_miscvalue < 0 || m_modifier.m_miscvalue >= MAX_POWERS)
return;
Powers power = Powers(m_modifier.m_miscvalue);
// power type might have changed between aura applying and tick (druid's shapeshift)
if (target->getPowerType() != power)
return;
Unit* pCaster = GetCaster();
if (!pCaster)
return;
if (!pCaster->isAlive())
return;
if (GetSpellProto()->Effect[GetEffIndex()] == SPELL_EFFECT_PERSISTENT_AREA_AURA &&
pCaster->SpellHitResult(target, spellProto, false) != SPELL_MISS_NONE)
return;
// Check for immune (not use charges)
if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto)))
return;
// ignore non positive values (can be result apply spellmods to aura damage
uint32 pdamage = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0;
DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s power leech of %s for %u dmg inflicted by %u",
GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId());
int32 drain_amount = target->GetPower(power) > pdamage ? pdamage : target->GetPower(power);
// resilience reduce mana draining effect at spell crit damage reduction (added in 2.4)
if (power == POWER_MANA && target->GetTypeId() == TYPEID_PLAYER)
drain_amount -= ((Player*)target)->GetSpellCritDamageReduction(drain_amount);
target->ModifyPower(power, -drain_amount);
float gain_multiplier = 0.0f;
if (pCaster->GetMaxPower(power) > 0)
{
gain_multiplier = spellProto->EffectMultipleValue[GetEffIndex()];
if (Player* modOwner = pCaster->GetSpellModOwner())
modOwner->ApplySpellMod(GetId(), SPELLMOD_MULTIPLE_VALUE, gain_multiplier);
}
SpellPeriodicAuraLogInfo pInfo(this, drain_amount, 0, 0, gain_multiplier);
target->SendPeriodicAuraLog(&pInfo);
if (int32 gain_amount = int32(drain_amount * gain_multiplier))
{
int32 gain = pCaster->ModifyPower(power, gain_amount);
if (GetId() == 5138) // Drain Mana
if (Aura* petPart = GetHolder()->GetAuraByEffectIndex(EFFECT_INDEX_1))
if (int pet_gain = gain_amount * petPart->GetModifier()->m_amount / 100)
pCaster->CastCustomSpell(pCaster, 32554, &pet_gain, NULL, NULL, true);
target->AddThreat(pCaster, float(gain) * 0.5f, false, GetSpellSchoolMask(spellProto), spellProto);
}
// Some special cases
switch (GetId())
{
case 32960: // Mark of Kazzak
{
if (target->GetTypeId() == TYPEID_PLAYER && target->getPowerType() == POWER_MANA)
{
// Drain 5% of target's mana
pdamage = target->GetMaxPower(POWER_MANA) * 5 / 100;
drain_amount = target->GetPower(POWER_MANA) > pdamage ? pdamage : target->GetPower(POWER_MANA);
target->ModifyPower(POWER_MANA, -drain_amount);
SpellPeriodicAuraLogInfo pInfo(this, drain_amount, 0, 0, 0.0f);
target->SendPeriodicAuraLog(&pInfo);
}
// no break here
}
case 21056: // Mark of Kazzak
case 31447: // Mark of Kaz'rogal
{
uint32 triggerSpell = 0;
switch (GetId())
{
case 21056: triggerSpell = 21058; break;
case 31447: triggerSpell = 31463; break;
case 32960: triggerSpell = 32961; break;
}
if (target->GetTypeId() == TYPEID_PLAYER && target->GetPower(power) == 0)
{
target->CastSpell(target, triggerSpell, true, NULL, this);
target->RemoveAurasDueToSpell(GetId());
}
break;
}
}
break;
}
case SPELL_AURA_PERIODIC_ENERGIZE:
{
// don't energize target if not alive, possible death persistent effects
if (!target->isAlive())
return;
// ignore non positive values (can be result apply spellmods to aura damage
uint32 pdamage = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0;
DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s energize %s for %u dmg inflicted by %u",
GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId());
if (m_modifier.m_miscvalue < 0 || m_modifier.m_miscvalue >= MAX_POWERS)
break;
Powers power = Powers(m_modifier.m_miscvalue);
if (target->GetMaxPower(power) == 0)
break;
SpellPeriodicAuraLogInfo pInfo(this, pdamage, 0, 0, 0.0f);
target->SendPeriodicAuraLog(&pInfo);
int32 gain = target->ModifyPower(power, pdamage);
if (Unit* pCaster = GetCaster())
target->getHostileRefManager().threatAssist(pCaster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto);
break;
}
case SPELL_AURA_OBS_MOD_MANA:
{
// don't energize target if not alive, possible death persistent effects
if (!target->isAlive())
return;
// ignore non positive values (can be result apply spellmods to aura damage
uint32 amount = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0;
uint32 pdamage = uint32(target->GetMaxPower(POWER_MANA) * amount / 100);
DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s energize %s for %u mana inflicted by %u",
GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId());
if (target->GetMaxPower(POWER_MANA) == 0)
break;
SpellPeriodicAuraLogInfo pInfo(this, pdamage, 0, 0, 0.0f);
target->SendPeriodicAuraLog(&pInfo);
int32 gain = target->ModifyPower(POWER_MANA, pdamage);
if (Unit* pCaster = GetCaster())
target->getHostileRefManager().threatAssist(pCaster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto);
break;
}
case SPELL_AURA_POWER_BURN_MANA:
{
// don't mana burn target if not alive, possible death persistent effects
if (!target->isAlive())
return;
Unit* pCaster = GetCaster();
if (!pCaster)
return;
// Check for immune (not use charges)
if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto)))
return;
int32 pdamage = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0;
Powers powerType = Powers(m_modifier.m_miscvalue);
if (!target->isAlive() || target->getPowerType() != powerType)
return;
// resilience reduce mana draining effect at spell crit damage reduction (added in 2.4)
if (powerType == POWER_MANA && target->GetTypeId() == TYPEID_PLAYER)
pdamage -= ((Player*)target)->GetSpellCritDamageReduction(pdamage);
uint32 gain = uint32(-target->ModifyPower(powerType, -pdamage));
gain = uint32(gain * spellProto->EffectMultipleValue[GetEffIndex()]);
// maybe has to be sent different to client, but not by SMSG_PERIODICAURALOG
SpellNonMeleeDamage damageInfo(pCaster, target, spellProto->Id, SpellSchoolMask(spellProto->SchoolMask));
pCaster->CalculateSpellDamage(&damageInfo, gain, spellProto);
damageInfo.target->CalculateAbsorbResistBlock(pCaster, &damageInfo, spellProto);
pCaster->DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb);
pCaster->SendSpellNonMeleeDamageLog(&damageInfo);
// Set trigger flag
uint32 procAttacker = PROC_FLAG_ON_DO_PERIODIC; // | PROC_FLAG_SUCCESSFUL_HARMFUL_SPELL_HIT;
uint32 procVictim = PROC_FLAG_ON_TAKE_PERIODIC;// | PROC_FLAG_TAKEN_HARMFUL_SPELL_HIT;
uint32 procEx = createProcExtendMask(&damageInfo, SPELL_MISS_NONE);
if (damageInfo.damage)
procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
pCaster->ProcDamageAndSpell(damageInfo.target, procAttacker, procVictim, procEx, damageInfo.damage, BASE_ATTACK, spellProto);
pCaster->DealSpellDamage(&damageInfo, true);
break;
}
case SPELL_AURA_MOD_REGEN:
{
// don't heal target if not alive, possible death persistent effects
if (!target->isAlive())
return;
int32 gain = target->ModifyHealth(m_modifier.m_amount);
if (Unit* caster = GetCaster())
target->getHostileRefManager().threatAssist(caster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto);
break;
}
case SPELL_AURA_MOD_POWER_REGEN:
{
// don't energize target if not alive, possible death persistent effects
if (!target->isAlive())
return;
Powers pt = target->getPowerType();
if (int32(pt) != m_modifier.m_miscvalue)
return;
if (spellProto->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED)
{
// eating anim
target->HandleEmoteCommand(EMOTE_ONESHOT_EAT);
}
else if (GetId() == 20577)
{
// cannibalize anim
target->HandleEmoteCommand(EMOTE_STATE_CANNIBALIZE);
}
// Anger Management
// amount = 1+ 16 = 17 = 3,4*5 = 10,2*5/3
// so 17 is rounded amount for 5 sec tick grow ~ 1 range grow in 3 sec
if (pt == POWER_RAGE)
target->ModifyPower(pt, m_modifier.m_amount * 3 / 5);
break;
}
// Here tick dummy auras
case SPELL_AURA_DUMMY: // some spells have dummy aura
case SPELL_AURA_PERIODIC_DUMMY:
{
PeriodicDummyTick();
break;
}
case SPELL_AURA_PERIODIC_TRIGGER_SPELL:
{
TriggerSpell();
break;
}
case SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE:
{
TriggerSpellWithValue();
break;
}
default:
break;
}
}
void Aura::PeriodicDummyTick()
{
SpellEntry const* spell = GetSpellProto();
Unit* target = GetTarget();
switch (spell->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
switch (spell->Id)
{
// Forsaken Skills
case 7054:
{
// Possibly need cast one of them (but
// 7038 Forsaken Skill: Swords
// 7039 Forsaken Skill: Axes
// 7040 Forsaken Skill: Daggers
// 7041 Forsaken Skill: Maces
// 7042 Forsaken Skill: Staves
// 7043 Forsaken Skill: Bows
// 7044 Forsaken Skill: Guns
// 7045 Forsaken Skill: 2H Axes
// 7046 Forsaken Skill: 2H Maces
// 7047 Forsaken Skill: 2H Swords
// 7048 Forsaken Skill: Defense
// 7049 Forsaken Skill: Fire
// 7050 Forsaken Skill: Frost
// 7051 Forsaken Skill: Holy
// 7053 Forsaken Skill: Shadow
return;
}
case 7057: // Haunting Spirits
if (roll_chance_i(33))
target->CastSpell(target, m_modifier.m_amount, true, NULL, this);
return;
// // Panda
// case 19230: break;
// // Gossip NPC Periodic - Talk
// case 33208: break;
// // Gossip NPC Periodic - Despawn
// case 33209: break;
// // Steal Weapon
// case 36207: break;
// // Simon Game START timer, (DND)
// case 39993: break;
// // Harpooner's Mark
// case 40084: break;
// // Old Mount Spell
// case 40154: break;
// // Magnetic Pull
// case 40581: break;
// // Ethereal Ring: break; The Bolt Burst
// case 40801: break;
// // Crystal Prison
// case 40846: break;
// // Copy Weapon
// case 41054: break;
// // Ethereal Ring Visual, Lightning Aura
// case 41477: break;
// // Ethereal Ring Visual, Lightning Aura (Fork)
// case 41525: break;
// // Ethereal Ring Visual, Lightning Jumper Aura
// case 41567: break;
// // No Man's Land
// case 41955: break;
// // Headless Horseman - Fire
// case 42074: break;
// // Headless Horseman - Visual - Large Fire
// case 42075: break;
// // Headless Horseman - Start Fire, Periodic Aura
// case 42140: break;
// // Ram Speed Boost
// case 42152: break;
// // Headless Horseman - Fires Out Victory Aura
// case 42235: break;
// // Pumpkin Life Cycle
// case 42280: break;
// // Brewfest Request Chick Chuck Mug Aura
// case 42537: break;
// // Squashling
// case 42596: break;
// // Headless Horseman Climax, Head: Periodic
// case 42603: break;
case 42621: // Fire Bomb
{
// Cast the summon spells (42622 to 42627) with increasing chance
uint32 rand = urand(0, 99);
for (uint32 i = 1; i <= 6; ++i)
{
if (rand < i * (i + 1) / 2 * 5)
{
target->CastSpell(target, spell->Id + i, true);
break;
}
}
break;
}
// // Headless Horseman - Conflagrate, Periodic Aura
// case 42637: break;
// // Headless Horseman - Create Pumpkin Treats Aura
// case 42774: break;
// // Headless Horseman Climax - Summoning Rhyme Aura
// case 42879: break;
// // Tricky Treat
// case 42919: break;
// // Giddyup!
// case 42924: break;
// // Ram - Trot
// case 42992: break;
// // Ram - Canter
// case 42993: break;
// // Ram - Gallop
// case 42994: break;
// // Ram Level - Neutral
// case 43310: break;
// // Headless Horseman - Maniacal Laugh, Maniacal, Delayed 17
// case 43884: break;
// // Headless Horseman - Maniacal Laugh, Maniacal, other, Delayed 17
// case 44000: break;
// // Energy Feedback
// case 44328: break;
// // Romantic Picnic
// case 45102: break;
// // Romantic Picnic
// case 45123: break;
// // Looking for Love
// case 45124: break;
// // Kite - Lightning Strike Kite Aura
// case 45197: break;
// // Rocket Chicken
// case 45202: break;
// // Copy Offhand Weapon
// case 45205: break;
// // Upper Deck - Kite - Lightning Periodic Aura
// case 45207: break;
// // Kite -Sky Lightning Strike Kite Aura
// case 45251: break;
// // Ribbon Pole Dancer Check Aura
// case 45390: break;
// // Holiday - Midsummer, Ribbon Pole Periodic Visual
// case 45406: break;
// // Alliance Flag, Extra Damage Debuff
// case 45898: break;
// // Horde Flag, Extra Damage Debuff
// case 45899: break;
// // Ahune - Summoning Rhyme Aura
// case 45926: break;
// // Ahune - Slippery Floor
// case 45945: break;
// // Ahune's Shield
// case 45954: break;
// // Nether Vapor Lightning
// case 45960: break;
// // Darkness
// case 45996: break;
case 46041: // Summon Blood Elves Periodic
target->CastSpell(target, 46037, true, NULL, this);
target->CastSpell(target, roll_chance_i(50) ? 46038 : 46039, true, NULL, this);
target->CastSpell(target, 46040, true, NULL, this);
return;
// // Transform Visual Missile Periodic
// case 46205: break;
// // Find Opening Beam End
// case 46333: break;
// // Ice Spear Control Aura
// case 46371: break;
// // Hailstone Chill
// case 46458: break;
// // Hailstone Chill, Internal
// case 46465: break;
// // Chill, Internal Shifter
// case 46549: break;
// // Summon Ice Spear Knockback Delayer
// case 46878: break;
// // Send Mug Control Aura
// case 47369: break;
// // Direbrew's Disarm (precast)
// case 47407: break;
// // Mole Machine Port Schedule
// case 47489: break;
// // Mole Machine Portal Schedule
// case 49466: break;
// // Drink Coffee
// case 49472: break;
// // Listening to Music
// case 50493: break;
// // Love Rocket Barrage
// case 50530: break;
// Exist more after, need add later
default:
break;
}
// Drink (item drink spells)
if (GetEffIndex() > EFFECT_INDEX_0 && spell->EffectApplyAuraName[GetEffIndex()-1] == SPELL_AURA_MOD_POWER_REGEN)
{
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// Search SPELL_AURA_MOD_POWER_REGEN aura for this spell and add bonus
if (Aura* aura = GetHolder()->GetAuraByEffectIndex(SpellEffectIndex(GetEffIndex() - 1)))
{
aura->GetModifier()->m_amount = m_modifier.m_amount;
((Player*)target)->UpdateManaRegen();
// Disable continue
m_isPeriodic = false;
return;
}
return;
}
break;
}
case SPELLFAMILY_HUNTER:
{
// Aspect of the Viper
switch (spell->Id)
{
case 34074:
{
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// Should be manauser
if (target->getPowerType() != POWER_MANA)
return;
Unit* caster = GetCaster();
if (!caster)
return;
// Regen amount is max (100% from spell) on 21% or less mana and min on 92.5% or greater mana (20% from spell)
int mana = target->GetPower(POWER_MANA);
int max_mana = target->GetMaxPower(POWER_MANA);
int32 base_regen = caster->CalculateSpellDamage(target, GetSpellProto(), m_effIndex, &m_currentBasePoints);
float regen_pct = 1.20f - 1.1f * mana / max_mana;
if (regen_pct > 1.0f) regen_pct = 1.0f;
else if (regen_pct < 0.2f) regen_pct = 0.2f;
m_modifier.m_amount = int32(base_regen * regen_pct);
((Player*)target)->UpdateManaRegen();
return;
}
// // Knockdown Fel Cannon: break; The Aggro Burst
// case 40119: break;
}
break;
}
default:
break;
}
}
void Aura::HandlePreventFleeing(bool apply, bool Real)
{
if (!Real)
return;
Unit::AuraList const& fearAuras = GetTarget()->GetAurasByType(SPELL_AURA_MOD_FEAR);
if (!fearAuras.empty())
{
if (apply)
GetTarget()->SetFeared(false, fearAuras.front()->GetCasterGuid());
else
GetTarget()->SetFeared(true);
}
}
void Aura::HandleManaShield(bool apply, bool Real)
{
if (!Real)
return;
// prevent double apply bonuses
if (apply && (GetTarget()->GetTypeId() != TYPEID_PLAYER || !((Player*)GetTarget())->GetSession()->PlayerLoading()))
{
if (Unit* caster = GetCaster())
{
float DoneActualBenefit = 0.0f;
switch (GetSpellProto()->SpellFamilyName)
{
case SPELLFAMILY_MAGE:
if (GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000008000))
{
// Mana Shield
// +50% from +spd bonus
DoneActualBenefit = caster->SpellBaseDamageBonusDone(GetSpellSchoolMask(GetSpellProto())) * 0.5f;
break;
}
break;
default:
break;
}
DoneActualBenefit *= caster->CalculateLevelPenalty(GetSpellProto());
m_modifier.m_amount += (int32)DoneActualBenefit;
}
}
}
void Aura::HandleArenaPreparation(bool apply, bool Real)
{
if (!Real)
return;
Unit* target = GetTarget();
target->ApplyModFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION, apply);
if (apply)
{
// max regen powers at start preparation
target->SetHealth(target->GetMaxHealth());
target->SetPower(POWER_MANA, target->GetMaxPower(POWER_MANA));
target->SetPower(POWER_ENERGY, target->GetMaxPower(POWER_ENERGY));
}
else
{
// reset originally 0 powers at start/leave
target->SetPower(POWER_RAGE, 0);
}
}
void Aura::HandleAuraMirrorImage(bool apply, bool Real)
{
if (!Real)
return;
// Target of aura should always be creature (ref Spell::CheckCast)
Creature* pCreature = (Creature*)GetTarget();
if (apply)
{
// Caster can be player or creature, the unit who pCreature will become an clone of.
Unit* caster = GetCaster();
pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 0, caster->getRace());
pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 1, caster->getClass());
pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 2, caster->getGender());
pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 3, caster->getPowerType());
pCreature->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_CLONED);
pCreature->SetDisplayId(caster->GetNativeDisplayId());
}
else
{
const CreatureInfo* cinfo = pCreature->GetCreatureInfo();
const CreatureModelInfo* minfo = sObjectMgr.GetCreatureModelInfo(pCreature->GetNativeDisplayId());
pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 0, 0);
pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 1, cinfo->unit_class);
pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 3, 0);
pCreature->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_CLONED);
pCreature->SetDisplayId(pCreature->GetNativeDisplayId());
}
}
void Aura::HandleAuraSafeFall(bool Apply, bool Real)
{
// implemented in WorldSession::HandleMovementOpcodes
// only special case
if (Apply && Real && GetId() == 32474 && GetTarget()->GetTypeId() == TYPEID_PLAYER)
((Player*)GetTarget())->ActivateTaxiPathTo(506, GetId());
}
bool Aura::IsLastAuraOnHolder()
{
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (i != GetEffIndex() && GetHolder()->m_auras[i])
return false;
return true;
}
bool Aura::HasMechanic(uint32 mechanic) const
{
return GetSpellProto()->Mechanic == mechanic ||
GetSpellProto()->EffectMechanic[m_effIndex] == mechanic;
}
SpellAuraHolder::SpellAuraHolder(SpellEntry const* spellproto, Unit* target, WorldObject* caster, Item* castItem) :
m_spellProto(spellproto),
m_target(target), m_castItemGuid(castItem ? castItem->GetObjectGuid() : ObjectGuid()),
m_auraSlot(MAX_AURAS), m_auraLevel(1),
m_procCharges(0), m_stackAmount(1),
m_timeCla(1000), m_removeMode(AURA_REMOVE_BY_DEFAULT), m_AuraDRGroup(DIMINISHING_NONE),
m_permanent(false), m_isRemovedOnShapeLost(true), m_deleted(false), m_in_use(0)
{
MANGOS_ASSERT(target);
MANGOS_ASSERT(spellproto && spellproto == sSpellStore.LookupEntry(spellproto->Id) && "`info` must be pointer to sSpellStore element");
if (!caster)
m_casterGuid = target->GetObjectGuid();
else
{
// remove this assert when not unit casters will be supported
MANGOS_ASSERT(caster->isType(TYPEMASK_UNIT))
m_casterGuid = caster->GetObjectGuid();
}
m_applyTime = time(NULL);
m_isPassive = IsPassiveSpell(spellproto);
m_isDeathPersist = IsDeathPersistentSpell(spellproto);
m_trackedAuraType= IsSingleTargetSpell(spellproto) ? TRACK_AURA_TYPE_SINGLE_TARGET : TRACK_AURA_TYPE_NOT_TRACKED;
m_procCharges = spellproto->procCharges;
m_isRemovedOnShapeLost = (GetCasterGuid() == m_target->GetObjectGuid() &&
m_spellProto->Stances &&
!m_spellProto->HasAttribute(SPELL_ATTR_EX2_NOT_NEED_SHAPESHIFT) &&
!m_spellProto->HasAttribute(SPELL_ATTR_NOT_SHAPESHIFT));
Unit* unitCaster = caster && caster->isType(TYPEMASK_UNIT) ? (Unit*)caster : NULL;
m_duration = m_maxDuration = CalculateSpellDuration(spellproto, unitCaster);
if (m_maxDuration == -1 || (m_isPassive && spellproto->DurationIndex == 0))
m_permanent = true;
if (unitCaster)
{
if (Player* modOwner = unitCaster->GetSpellModOwner())
modOwner->ApplySpellMod(GetId(), SPELLMOD_CHARGES, m_procCharges);
}
// some custom stack values at aura holder create
switch (m_spellProto->Id)
{
// some auras applied with max stack
case 24575: // Brittle Armor
case 24659: // Unstable Power
case 24662: // Restless Strength
case 26464: // Mercurial Shield
m_stackAmount = m_spellProto->StackAmount;
break;
}
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
m_auras[i] = NULL;
}
void SpellAuraHolder::AddAura(Aura* aura, SpellEffectIndex index)
{
m_auras[index] = aura;
}
void SpellAuraHolder::RemoveAura(SpellEffectIndex index)
{
m_auras[index] = NULL;
}
void SpellAuraHolder::ApplyAuraModifiers(bool apply, bool real)
{
for (int32 i = 0; i < MAX_EFFECT_INDEX && !IsDeleted(); ++i)
if (Aura* aur = GetAuraByEffectIndex(SpellEffectIndex(i)))
aur->ApplyModifier(apply, real);
}
void SpellAuraHolder::_AddSpellAuraHolder()
{
if (!GetId())
return;
if (!m_target)
return;
// Try find slot for aura
uint8 slot = NULL_AURA_SLOT;
Unit* caster = GetCaster();
// Lookup free slot
// will be < MAX_AURAS slot (if find free) with !secondaura
if (IsNeedVisibleSlot(caster))
{
if (IsPositive()) // empty positive slot
{
for (uint8 i = 0; i < MAX_POSITIVE_AURAS; i++)
{
if (m_target->GetUInt32Value((uint16)(UNIT_FIELD_AURA + i)) == 0)
{
slot = i;
break;
}
}
}
else // empty negative slot
{
for (uint8 i = MAX_POSITIVE_AURAS; i < MAX_AURAS; i++)
{
if (m_target->GetUInt32Value((uint16)(UNIT_FIELD_AURA + i)) == 0)
{
slot = i;
break;
}
}
}
}
// set infinity cooldown state for spells
if (caster && caster->GetTypeId() == TYPEID_PLAYER)
{
if (m_spellProto->HasAttribute(SPELL_ATTR_DISABLED_WHILE_ACTIVE))
{
Item* castItem = m_castItemGuid ? ((Player*)caster)->GetItemByGuid(m_castItemGuid) : NULL;
((Player*)caster)->AddSpellAndCategoryCooldowns(m_spellProto, castItem ? castItem->GetEntry() : 0, NULL, true);
}
}
SetAuraSlot(slot);
// Not update fields for not first spell's aura, all data already in fields
if (slot < MAX_AURAS) // slot found
{
SetAura(slot, false);
SetAuraFlag(slot, true);
SetAuraLevel(slot, caster ? caster->getLevel() : sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL));
UpdateAuraApplication();
// update for out of range group members
m_target->UpdateAuraForGroup(slot);
UpdateAuraDuration();
}
//*****************************************************
// Update target aura state flag (at 1 aura apply)
// TODO: Make it easer
//*****************************************************
// Sitdown on apply aura req seated
if (m_spellProto->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED && !m_target->IsSitState())
m_target->SetStandState(UNIT_STAND_STATE_SIT);
// register aura diminishing on apply
if (getDiminishGroup() != DIMINISHING_NONE)
m_target->ApplyDiminishingAura(getDiminishGroup(), true);
// Update Seals information
if (IsSealSpell(GetSpellProto()))
m_target->ModifyAuraState(AURA_STATE_JUDGEMENT, true);
// Conflagrate aura state
if (GetSpellProto()->IsFitToFamily(SPELLFAMILY_WARLOCK, UI64LIT(0x0000000000000004)))
m_target->ModifyAuraState(AURA_STATE_CONFLAGRATE, true);
// Faerie Fire (druid versions)
if (m_spellProto->IsFitToFamily(SPELLFAMILY_DRUID, UI64LIT(0x0000000000000400)))
m_target->ModifyAuraState(AURA_STATE_FAERIE_FIRE, true);
// Swiftmend state on Regrowth & Rejuvenation
if (m_spellProto->IsFitToFamily(SPELLFAMILY_DRUID, UI64LIT(0x0000000000000050)))
m_target->ModifyAuraState(AURA_STATE_SWIFTMEND, true);
// Deadly poison aura state
if (m_spellProto->IsFitToFamily(SPELLFAMILY_ROGUE, UI64LIT(0x0000000000010000)))
m_target->ModifyAuraState(AURA_STATE_DEADLY_POISON, true);
}
void SpellAuraHolder::_RemoveSpellAuraHolder()
{
// Remove all triggered by aura spells vs unlimited duration
// except same aura replace case
if (m_removeMode != AURA_REMOVE_BY_STACK)
CleanupTriggeredSpells();
Unit* caster = GetCaster();
if (caster && IsPersistent())
if (DynamicObject* dynObj = caster->GetDynObject(GetId()))
dynObj->RemoveAffected(m_target);
// remove at-store spell cast items (for all remove modes?)
if (m_target->GetTypeId() == TYPEID_PLAYER && m_removeMode != AURA_REMOVE_BY_DEFAULT && m_removeMode != AURA_REMOVE_BY_DELETE)
if (ObjectGuid castItemGuid = GetCastItemGuid())
if (Item* castItem = ((Player*)m_target)->GetItemByGuid(castItemGuid))
((Player*)m_target)->DestroyItemWithOnStoreSpell(castItem, GetId());
// passive auras do not get put in slots - said who? ;)
// Note: but totem can be not accessible for aura target in time remove (to far for find in grid)
// if(m_isPassive && !(caster && caster->GetTypeId() == TYPEID_UNIT && ((Creature*)caster)->IsTotem()))
// return;
uint8 slot = GetAuraSlot();
if (slot >= MAX_AURAS) // slot not set
return;
if (m_target->GetUInt32Value((uint16)(UNIT_FIELD_AURA + slot)) == 0)
return;
// unregister aura diminishing (and store last time)
if (getDiminishGroup() != DIMINISHING_NONE)
m_target->ApplyDiminishingAura(getDiminishGroup(), false);
SetAura(slot, true);
SetAuraFlag(slot, false);
SetAuraLevel(slot, caster ? caster->getLevel() : sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL));
m_procCharges = 0;
m_stackAmount = 1;
UpdateAuraApplication();
if (m_removeMode != AURA_REMOVE_BY_DELETE)
{
// update for out of range group members
m_target->UpdateAuraForGroup(slot);
//*****************************************************
// Update target aura state flag (at last aura remove)
//*****************************************************
uint32 removeState = 0;
ClassFamilyMask removeFamilyFlag = m_spellProto->SpellFamilyFlags;
switch (m_spellProto->SpellFamilyName)
{
case SPELLFAMILY_PALADIN:
if (IsSealSpell(m_spellProto))
removeState = AURA_STATE_JUDGEMENT; // Update Seals information
break;
case SPELLFAMILY_WARLOCK:
if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000000004)))
removeState = AURA_STATE_CONFLAGRATE; // Conflagrate aura state
break;
case SPELLFAMILY_DRUID:
if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000000400)))
removeState = AURA_STATE_FAERIE_FIRE; // Faerie Fire (druid versions)
else if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000000050)))
{
removeFamilyFlag = ClassFamilyMask(UI64LIT(0x00000000000050));
removeState = AURA_STATE_SWIFTMEND; // Swiftmend aura state
}
break;
case SPELLFAMILY_ROGUE:
if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000010000)))
removeState = AURA_STATE_DEADLY_POISON; // Deadly poison aura state
break;
}
// Remove state (but need check other auras for it)
if (removeState)
{
bool found = false;
Unit::SpellAuraHolderMap const& holders = m_target->GetSpellAuraHolderMap();
for (Unit::SpellAuraHolderMap::const_iterator i = holders.begin(); i != holders.end(); ++i)
{
SpellEntry const* auraSpellInfo = (*i).second->GetSpellProto();
if (auraSpellInfo->IsFitToFamily(SpellFamily(m_spellProto->SpellFamilyName), removeFamilyFlag))
{
found = true;
break;
}
}
// this has been last aura
if (!found)
m_target->ModifyAuraState(AuraState(removeState), false);
}
// reset cooldown state for spells
if (caster && caster->GetTypeId() == TYPEID_PLAYER)
{
if (GetSpellProto()->HasAttribute(SPELL_ATTR_DISABLED_WHILE_ACTIVE))
// note: item based cooldowns and cooldown spell mods with charges ignored (unknown existing cases)
((Player*)caster)->SendCooldownEvent(GetSpellProto());
}
}
}
void SpellAuraHolder::CleanupTriggeredSpells()
{
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if (!m_spellProto->EffectApplyAuraName[i])
continue;
uint32 tSpellId = m_spellProto->EffectTriggerSpell[i];
if (!tSpellId)
continue;
SpellEntry const* tProto = sSpellStore.LookupEntry(tSpellId);
if (!tProto)
continue;
if (GetSpellDuration(tProto) != -1)
continue;
// needed for spell 43680, maybe others
// TODO: is there a spell flag, which can solve this in a more sophisticated way?
if (m_spellProto->EffectApplyAuraName[i] == SPELL_AURA_PERIODIC_TRIGGER_SPELL &&
GetSpellDuration(m_spellProto) == int32(m_spellProto->EffectAmplitude[i]))
continue;
m_target->RemoveAurasDueToSpell(tSpellId);
}
}
bool SpellAuraHolder::ModStackAmount(int32 num)
{
uint32 protoStackAmount = m_spellProto->StackAmount;
// Can`t mod
if (!protoStackAmount)
return true;
// Modify stack but limit it
int32 stackAmount = m_stackAmount + num;
if (stackAmount > (int32)protoStackAmount)
stackAmount = protoStackAmount;
else if (stackAmount <= 0) // Last aura from stack removed
{
m_stackAmount = 0;
return true; // need remove aura
}
// Update stack amount
SetStackAmount(stackAmount);
return false;
}
void SpellAuraHolder::SetStackAmount(uint32 stackAmount)
{
Unit* target = GetTarget();
Unit* caster = GetCaster();
if (!target || !caster)
return;
bool refresh = stackAmount >= m_stackAmount;
if (stackAmount != m_stackAmount)
{
m_stackAmount = stackAmount;
UpdateAuraApplication();
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if (Aura* aur = m_auras[i])
{
int32 bp = aur->GetBasePoints();
int32 amount = m_stackAmount * caster->CalculateSpellDamage(target, m_spellProto, SpellEffectIndex(i), &bp);
// Reapply if amount change
if (amount != aur->GetModifier()->m_amount)
{
aur->ApplyModifier(false, true);
aur->GetModifier()->m_amount = amount;
aur->ApplyModifier(true, true);
}
}
}
}
if (refresh)
// Stack increased refresh duration
RefreshHolder();
}
Unit* SpellAuraHolder::GetCaster() const
{
if (GetCasterGuid() == m_target->GetObjectGuid())
return m_target;
return ObjectAccessor::GetUnit(*m_target, m_casterGuid);// player will search at any maps
}
bool SpellAuraHolder::IsWeaponBuffCoexistableWith(SpellAuraHolder const* ref) const
{
// only item casted spells
if (!GetCastItemGuid())
return false;
// Exclude Debuffs
if (!IsPositive())
return false;
// Exclude Non-generic Buffs and Executioner-Enchant
if (GetSpellProto()->SpellFamilyName != SPELLFAMILY_GENERIC || GetId() == 42976)
return false;
// Exclude Stackable Buffs [ie: Blood Reserve]
if (GetSpellProto()->StackAmount)
return false;
// only self applied player buffs
if (m_target->GetTypeId() != TYPEID_PLAYER || m_target->GetObjectGuid() != GetCasterGuid())
return false;
Item* castItem = ((Player*)m_target)->GetItemByGuid(GetCastItemGuid());
if (!castItem)
return false;
// Limit to Weapon-Slots
if (!castItem->IsEquipped() ||
(castItem->GetSlot() != EQUIPMENT_SLOT_MAINHAND && castItem->GetSlot() != EQUIPMENT_SLOT_OFFHAND))
return false;
// form different weapons
return ref->GetCastItemGuid() && ref->GetCastItemGuid() != GetCastItemGuid();
}
bool SpellAuraHolder::IsNeedVisibleSlot(Unit const* caster) const
{
bool totemAura = caster && caster->GetTypeId() == TYPEID_UNIT && ((Creature*)caster)->IsTotem();
for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if (!m_auras[i])
continue;
// special area auras cases
switch (m_spellProto->Effect[i])
{
case SPELL_EFFECT_APPLY_AREA_AURA_ENEMY:
return m_target != caster;
case SPELL_EFFECT_APPLY_AREA_AURA_PET:
case SPELL_EFFECT_APPLY_AREA_AURA_OWNER:
case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND:
case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
// passive auras (except totem auras) do not get placed in caster slot
return (m_target != caster || totemAura || !m_isPassive) && m_auras[i]->GetModifier()->m_auraname != SPELL_AURA_NONE;
default:
break;
}
}
// passive auras (except totem auras) do not get placed in the slots
return !m_isPassive || totemAura;
}
void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply)
{
uint32 spellId1 = 0;
uint32 spellId2 = 0;
uint32 spellId3 = 0;
uint32 spellId4 = 0;
switch (GetSpellProto()->SpellFamilyName)
{
case SPELLFAMILY_MAGE:
{
switch (GetId())
{
case 11189: // Frost Warding
case 28332:
{
if (m_target->GetTypeId() == TYPEID_PLAYER && !apply)
{
// reflection chance (effect 1) of Frost Ward, applied in dummy effect
if (SpellModifier* mod = ((Player*)m_target)->GetSpellMod(SPELLMOD_EFFECT2, GetId()))
((Player*)m_target)->AddSpellMod(mod, false);
}
return;
}
default:
return;
}
break;
}
case SPELLFAMILY_WARRIOR:
{
if (!apply)
{
// Remove Blood Frenzy only if target no longer has any Deep Wound or Rend (applying is handled by procs)
if (GetSpellProto()->Mechanic != MECHANIC_BLEED)
return;
// If target still has one of Warrior's bleeds, do nothing
Unit::AuraList const& PeriodicDamage = m_target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
for (Unit::AuraList::const_iterator i = PeriodicDamage.begin(); i != PeriodicDamage.end(); ++i)
if ((*i)->GetCasterGuid() == GetCasterGuid() &&
(*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARRIOR &&
(*i)->GetSpellProto()->Mechanic == MECHANIC_BLEED)
return;
spellId1 = 30069; // Blood Frenzy (Rank 1)
spellId2 = 30070; // Blood Frenzy (Rank 2)
}
else
return;
break;
}
case SPELLFAMILY_HUNTER:
{
switch (GetId())
{
// The Beast Within and Bestial Wrath - immunity
case 19574:
case 34471:
{
spellId1 = 24395;
spellId2 = 24396;
spellId3 = 24397;
spellId4 = 26592;
break;
}
// Misdirection, main spell
case 34477:
{
if (!apply)
m_target->getHostileRefManager().ResetThreatRedirection();
return;
}
default:
return;
}
break;
}
default:
return;
}
// prevent aura deletion, specially in multi-boost case
SetInUse(true);
if (apply)
{
if (spellId1)
m_target->CastSpell(m_target, spellId1, true, NULL, NULL, GetCasterGuid());
if (spellId2 && !IsDeleted())
m_target->CastSpell(m_target, spellId2, true, NULL, NULL, GetCasterGuid());
if (spellId3 && !IsDeleted())
m_target->CastSpell(m_target, spellId3, true, NULL, NULL, GetCasterGuid());
if (spellId4 && !IsDeleted())
m_target->CastSpell(m_target, spellId4, true, NULL, NULL, GetCasterGuid());
}
else
{
if (spellId1)
m_target->RemoveAurasByCasterSpell(spellId1, GetCasterGuid());
if (spellId2)
m_target->RemoveAurasByCasterSpell(spellId2, GetCasterGuid());
if (spellId3)
m_target->RemoveAurasByCasterSpell(spellId3, GetCasterGuid());
if (spellId4)
m_target->RemoveAurasByCasterSpell(spellId4, GetCasterGuid());
}
SetInUse(false);
}
SpellAuraHolder::~SpellAuraHolder()
{
// note: auras in delete list won't be affected since they clear themselves from holder when adding to deletedAuraslist
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (Aura* aur = m_auras[i])
delete aur;
}
void SpellAuraHolder::Update(uint32 diff)
{
if (m_duration > 0)
{
m_duration -= diff;
if (m_duration < 0)
m_duration = 0;
m_timeCla -= diff;
if (m_timeCla <= 0)
{
if (Unit* caster = GetCaster())
{
Powers powertype = Powers(GetSpellProto()->powerType);
int32 manaPerSecond = GetSpellProto()->manaPerSecond + GetSpellProto()->manaPerSecondPerLevel * caster->getLevel();
m_timeCla = 1 * IN_MILLISECONDS;
if (manaPerSecond)
{
if (powertype == POWER_HEALTH)
caster->ModifyHealth(-manaPerSecond);
else
caster->ModifyPower(powertype, -manaPerSecond);
}
}
}
}
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (Aura* aura = m_auras[i])
aura->UpdateAura(diff);
// Channeled aura required check distance from caster
if (IsChanneledSpell(m_spellProto) && GetCasterGuid() != m_target->GetObjectGuid())
{
Unit* caster = GetCaster();
if (!caster)
{
m_target->RemoveAurasByCasterSpell(GetId(), GetCasterGuid());
return;
}
// need check distance for channeled target only
if (caster->GetChannelObjectGuid() == m_target->GetObjectGuid())
{
// Get spell range
float max_range = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellProto->rangeIndex));
if (Player* modOwner = caster->GetSpellModOwner())
modOwner->ApplySpellMod(GetId(), SPELLMOD_RANGE, max_range, NULL);
if (!caster->IsWithinDistInMap(m_target, max_range))
{
caster->InterruptSpell(CURRENT_CHANNELED_SPELL);
return;
}
}
}
}
void SpellAuraHolder::RefreshHolder()
{
SetAuraDuration(GetAuraMaxDuration());
UpdateAuraDuration();
}
void SpellAuraHolder::SetAuraMaxDuration(int32 duration)
{
m_maxDuration = duration;
// possible overwrite persistent state
if (duration > 0)
{
if (!(IsPassive() && GetSpellProto()->DurationIndex == 0))
SetPermanent(false);
}
}
bool SpellAuraHolder::HasMechanic(uint32 mechanic) const
{
if (mechanic == m_spellProto->Mechanic)
return true;
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (m_auras[i] && m_spellProto->EffectMechanic[i] == mechanic)
return true;
return false;
}
bool SpellAuraHolder::HasMechanicMask(uint32 mechanicMask) const
{
if (mechanicMask & (1 << (m_spellProto->Mechanic - 1)))
return true;
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (m_auras[i] && m_spellProto->EffectMechanic[i] && ((1 << (m_spellProto->EffectMechanic[i] - 1)) & mechanicMask))
return true;
return false;
}
bool SpellAuraHolder::IsPersistent() const
{
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (Aura* aur = m_auras[i])
if (aur->IsPersistent())
return true;
return false;
}
bool SpellAuraHolder::IsAreaAura() const
{
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (Aura* aur = m_auras[i])
if (aur->IsAreaAura())
return true;
return false;
}
bool SpellAuraHolder::IsPositive() const
{
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (Aura* aur = m_auras[i])
if (!aur->IsPositive())
return false;
return true;
}
bool SpellAuraHolder::IsEmptyHolder() const
{
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (m_auras[i])
return false;
return true;
}
void SpellAuraHolder::UnregisterAndCleanupTrackedAuras()
{
TrackedAuraType trackedType = GetTrackedAuraType();
if (!trackedType)
return;
if (trackedType == TRACK_AURA_TYPE_SINGLE_TARGET)
{
if (Unit* caster = GetCaster())
caster->GetTrackedAuraTargets(trackedType).erase(GetSpellProto());
}
m_trackedAuraType = TRACK_AURA_TYPE_NOT_TRACKED;
}
void SpellAuraHolder::SetAuraFlag(uint32 slot, bool add)
{
uint32 index = slot / 4;
uint32 byte = (slot % 4) * 8;
uint32 val = m_target->GetUInt32Value(UNIT_FIELD_AURAFLAGS + index);
val &= ~((uint32)AFLAG_MASK << byte);
if (add)
{
if (IsPositive())
val |= ((uint32)AFLAG_POSITIVE << byte);
else
val |= ((uint32)AFLAG_NEGATIVE << byte);
}
m_target->SetUInt32Value(UNIT_FIELD_AURAFLAGS + index, val);
}
void SpellAuraHolder::SetAuraLevel(uint32 slot, uint32 level)
{
uint32 index = slot / 4;
uint32 byte = (slot % 4) * 8;
uint32 val = m_target->GetUInt32Value(UNIT_FIELD_AURALEVELS + index);
val &= ~(0xFF << byte);
val |= (level << byte);
m_target->SetUInt32Value(UNIT_FIELD_AURALEVELS + index, val);
}
void SpellAuraHolder::UpdateAuraApplication()
{
if (m_auraSlot >= MAX_AURAS)
return;
uint32 stackCount = m_procCharges > 0 ? m_procCharges * m_stackAmount : m_stackAmount;
uint32 index = m_auraSlot / 4;
uint32 byte = (m_auraSlot % 4) * 8;
uint32 val = m_target->GetUInt32Value(UNIT_FIELD_AURAAPPLICATIONS + index);
val &= ~(0xFF << byte);
// field expect count-1 for proper amount show, also prevent overflow at client side
val |= ((uint8(stackCount <= 255 ? stackCount - 1 : 255 - 1)) << byte);
m_target->SetUInt32Value(UNIT_FIELD_AURAAPPLICATIONS + index, val);
}
void SpellAuraHolder::UpdateAuraDuration()
{
if (GetAuraSlot() >= MAX_AURAS || m_isPassive)
return;
if (m_target->GetTypeId() == TYPEID_PLAYER)
{
WorldPacket data(SMSG_UPDATE_AURA_DURATION, 5);
data << uint8(GetAuraSlot());
data << uint32(GetAuraDuration());
((Player*)m_target)->SendDirectMessage(&data);
data.Initialize(SMSG_SET_EXTRA_AURA_INFO, (8 + 1 + 4 + 4 + 4));
data << m_target->GetPackGUID();
data << uint8(GetAuraSlot());
data << uint32(GetId());
data << uint32(GetAuraMaxDuration());
data << uint32(GetAuraDuration());
((Player*)m_target)->SendDirectMessage(&data);
}
// not send in case player loading (will not work anyway until player not added to map), sent in visibility change code
if (m_target->GetTypeId() == TYPEID_PLAYER && ((Player*)m_target)->GetSession()->PlayerLoading())
return;
Unit* caster = GetCaster();
if (caster && caster->GetTypeId() == TYPEID_PLAYER && caster != m_target)
SendAuraDurationForCaster((Player*)caster);
}
void SpellAuraHolder::SendAuraDurationForCaster(Player* caster)
{
WorldPacket data(SMSG_SET_EXTRA_AURA_INFO_NEED_UPDATE, (8 + 1 + 4 + 4 + 4));
data << m_target->GetPackGUID();
data << uint8(GetAuraSlot());
data << uint32(GetId());
data << uint32(GetAuraMaxDuration()); // full
data << uint32(GetAuraDuration()); // remain
caster->GetSession()->SendPacket(&data);
}<|fim▁end|> |
if (target->GetTypeId() != TYPEID_PLAYER) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.