prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>failure.go<|end_file_name|><|fim▁begin|>package history
import (
"bytes"
"encoding/json"
"fmt"
"os"
"sync"
"github.com/admpub/spider/app/downloader/request"
"github.com/admpub/spider/common/mgo"
"github.com/admpub/spider/common/mysql"
"github.com/admpub/spider/common/pool"
"github.com/admpub/spider/config"
)
type Failure struct {
tabName string
fileName string
list map[string]*request.Request //key:url
inheritable bool
sync.RWMutex
}
func (self *Failure) PullFailure() map[string]*request.Request {
list := self.list
self.list = make(map[string]*request.Request)
return list
}
// 更新或加入失败记录,
// 对比是否已存在,不存在就记录,
// 返回值表示是否有插入操作。
func (self *Failure) UpsertFailure(req *request.Request) bool {
self.RWMutex.Lock()
defer self.RWMutex.Unlock()
if self.list[req.Unique()] != nil {
return false
}
self.list[req.Unique()] = req
return true
}
<|fim▁hole|> self.RWMutex.Lock()
delete(self.list, req.Unique())
self.RWMutex.Unlock()
}
// 先清空历史失败记录再更新
func (self *Failure) flush(provider string) (fLen int, err error) {
self.RWMutex.Lock()
defer self.RWMutex.Unlock()
fLen = len(self.list)
switch provider {
case "mgo":
if mgo.Error() != nil {
err = fmt.Errorf(" * Fail [添加失败记录][mgo]: %v 条 [ERROR] %v\n", fLen, mgo.Error())
return
}
mgo.Call(func(src pool.Src) error {
c := src.(*mgo.MgoSrc).DB(config.DB_NAME).C(self.tabName)
// 删除失败记录文件
c.DropCollection()
if fLen == 0 {
return nil
}
var docs = []interface{}{}
for key, req := range self.list {
docs = append(docs, map[string]interface{}{"_id": key, "failure": req.Serialize()})
}
c.Insert(docs...)
return nil
})
case "mysql":
_, err := mysql.DB()
if err != nil {
return fLen, fmt.Errorf(" * Fail [添加失败记录][mysql]: %v 条 [PING] %v\n", fLen, err)
}
table, ok := getWriteMysqlTable(self.tabName)
if !ok {
table = mysql.New()
table.SetTableName(self.tabName).CustomPrimaryKey(`id VARCHAR(255) NOT NULL PRIMARY KEY`).AddColumn(`failure MEDIUMTEXT`)
setWriteMysqlTable(self.tabName, table)
// 创建失败记录表
err = table.Create()
if err != nil {
return fLen, fmt.Errorf(" * Fail [添加失败记录][mysql]: %v 条 [CREATE] %v\n", fLen, err)
}
} else {
// 清空失败记录表
err = table.Truncate()
if err != nil {
return fLen, fmt.Errorf(" * Fail [添加失败记录][mysql]: %v 条 [TRUNCATE] %v\n", fLen, err)
}
}
// 添加失败记录
for key, req := range self.list {
table.AutoInsert([]string{key, req.Serialize()})
err = table.FlushInsert()
if err != nil {
fLen--
}
}
default:
// 删除失败记录文件
os.Remove(self.fileName)
if fLen == 0 {
return
}
f, _ := os.OpenFile(self.fileName, os.O_CREATE|os.O_WRONLY, 0777)
docs := make(map[string]string, len(self.list))
for key, req := range self.list {
docs[key] = req.Serialize()
}
b, _ := json.Marshal(docs)
b = bytes.Replace(b, []byte(`\u0026`), []byte(`&`), -1)
f.Write(b)
f.Close()
}
return
}<|fim▁end|> | // 删除失败记录
func (self *Failure) DeleteFailure(req *request.Request) { |
<|file_name|>test_output.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015-2022, Exa Analytics Development Team
# Distributed under the terms of the Apache License 2.0
from unittest import TestCase
import numpy as np
import pandas as pd
import h5py<|fim▁hole|>
# TODO : change df.shape[0] == num to len(df.index) == num everywhere
class TestOutput(TestCase):
"""Test the Molcas output file editor."""
def setUp(self):
self.cdz = Output(resource('mol-carbon-dz.out'))
self.uo2sp = Output(resource('mol-uo2-anomb.out'))
self.mamcart = Output(resource('mol-ch3nh2-631g.out'))
self.mamsphr = Output(resource('mol-ch3nh2-anovdzp.out'))
self.c2h6 = Output(resource('mol-c2h6-basis.out'))
def test_add_orb(self):
"""Test adding orbital file functionality."""
self.mamcart.add_orb(resource('mol-ch3nh2-631g.scforb'))
self.assertTrue(hasattr(self.mamcart, 'momatrix'))
self.assertTrue(hasattr(self.mamcart, 'orbital'))
with self.assertRaises(ValueError):
self.mamcart.add_orb(resource('mol-ch3nh2-631g.scforb'))
self.mamcart.add_orb(resource('mol-ch3nh2-631g.scforb'),
mocoefs='same')
self.assertTrue('same' in self.mamcart.momatrix.columns)
self.assertTrue('same' in self.mamcart.orbital.columns)
self.mamcart.add_orb(resource('mol-ch3nh2-631g.scforb'),
mocoefs='diff', orbocc='diffocc')
self.assertTrue('diff' in self.mamcart.momatrix.columns)
self.assertTrue('diffocc' in self.mamcart.orbital.columns)
uni = self.mamcart.to_universe()
self.assertTrue(hasattr(uni, 'momatrix'))
self.assertTrue(hasattr(uni, 'orbital'))
def test_add_overlap(self):
"""Test adding an overlap matrix."""
self.cdz.add_overlap(resource('mol-carbon-dz.overlap'))
self.assertTrue(hasattr(self.cdz, 'overlap'))
uni = self.cdz.to_universe()
self.assertTrue(hasattr(uni, 'overlap'))
def test_parse_atom(self):
"""Test the atom table parser."""
self.uo2sp.parse_atom()
self.assertEqual(self.uo2sp.atom.shape[0], 3)
self.assertTrue(np.all(pd.notnull(pd.DataFrame(self.uo2sp.atom))))
self.mamcart.parse_atom()
self.assertEqual(self.mamcart.atom.shape[0], 7)
self.assertTrue(np.all(pd.notnull(pd.DataFrame(self.mamcart.atom))))
self.mamsphr.parse_atom()
self.assertEqual(self.mamsphr.atom.shape[0], 7)
self.assertTrue(np.all(pd.notnull(pd.DataFrame(self.mamsphr.atom))))
def test_parse_basis_set_order(self):
"""Test the basis set order table parser."""
self.uo2sp.parse_basis_set_order()
self.assertEqual(self.uo2sp.basis_set_order.shape[0], 69)
cols = list(set(self.uo2sp.basis_set_order._columns))
test = pd.DataFrame(self.uo2sp.basis_set_order[cols])
self.assertTrue(np.all(pd.notnull(test)))
self.mamcart.parse_basis_set_order()
self.assertEqual(self.mamcart.basis_set_order.shape[0], 28)
cols = list(set(self.mamcart.basis_set_order._columns))
test = pd.DataFrame(self.mamcart.basis_set_order[cols])
self.assertTrue(np.all(pd.notnull(test)))
self.mamsphr.parse_basis_set_order()
self.assertEqual(self.mamsphr.basis_set_order.shape[0], 53)
cols = list(set(self.mamsphr.basis_set_order._columns))
test = pd.DataFrame(self.mamsphr.basis_set_order[cols])
self.assertTrue(np.all(pd.notnull(test)))
def test_parse_basis_set(self):
"""Test the gaussian basis set table parser."""
self.uo2sp.parse_basis_set()
self.assertEqual(self.uo2sp.basis_set.shape[0], 451)
self.assertTrue(np.all(pd.notnull(pd.DataFrame(self.uo2sp.basis_set))))
self.mamcart.parse_basis_set()
self.assertEqual(self.mamcart.basis_set.shape[0], 84)
self.assertTrue(np.all(pd.notnull(pd.DataFrame(self.mamcart.basis_set))))
self.mamsphr.parse_basis_set()
self.assertEqual(self.mamsphr.basis_set.shape[0], 148)
self.assertTrue(np.all(pd.notnull(pd.DataFrame(self.mamsphr.basis_set))))
self.c2h6.parse_basis_set()
self.assertTrue(hasattr(self.c2h6, 'basis_set'))
def test_to_universe(self):
"""Test that the Outputs can be converted to universes."""
uni = self.uo2sp.to_universe()
self.assertIs(type(uni), Universe)
uni = self.mamcart.to_universe()
self.assertIs(type(uni), Universe)
uni = self.mamsphr.to_universe()
self.assertIs(type(uni), Universe)
class TestOrb(TestCase):
"""Test the Molcas Orb file parser."""
def test_parse_old_uhf(self):
sym = Orb(resource('mol-c2h6-old-sym.uhforb'))
nym = Orb(resource('mol-c2h6-old-nosym.uhforb'))
sym.parse_momatrix()
nym.parse_momatrix()
self.assertTrue(sym.momatrix.shape[0] == 274)
self.assertTrue(nym.momatrix.shape[0] == 900)
def test_parse_old_orb(self):
sym = Orb(resource('mol-c2h6-old-sym.scforb'))
nym = Orb(resource('mol-c2h6-old-nosym.scforb'))
sym.parse_momatrix()
nym.parse_momatrix()
self.assertTrue(sym.momatrix.shape[0] == 274)
self.assertTrue(nym.momatrix.shape[0] == 900)
def test_parse_uhf(self):
sym = Orb(resource('mol-c2h6-sym.uhforb'))
nym = Orb(resource('mol-c2h6-nosym.uhforb'))
sym.parse_momatrix()
nym.parse_momatrix()
self.assertTrue(sym.momatrix.shape[0] == 274)
self.assertTrue(nym.momatrix.shape[0] == 900)
def test_parse_orb(self):
sym = Orb(resource('mol-c2h6-sym.scforb'))
nym = Orb(resource('mol-c2h6-nosym.scforb'))
sym.parse_momatrix()
nym.parse_momatrix()
self.assertTrue(sym.momatrix.shape[0] == 274)
self.assertTrue(nym.momatrix.shape[0] == 900)
def test_parse_momatrix(self):
"""Test the momatrix table parser."""
uo2sp = Orb(resource('mol-uo2-anomb.scforb'))
uo2sp.parse_momatrix()
self.assertEqual(uo2sp.momatrix.shape[0], 4761)
self.assertTrue(np.all(pd.notnull(pd.DataFrame(uo2sp.momatrix))))
self.assertTrue(np.all(pd.notnull(pd.DataFrame(uo2sp.orbital))))
mamcart = Orb(resource('mol-ch3nh2-631g.scforb'))
mamcart.parse_momatrix()
self.assertEqual(mamcart.momatrix.shape[0], 784)
self.assertTrue(np.all(pd.notnull(pd.DataFrame(mamcart.momatrix))))
self.assertTrue(np.all(pd.notnull(pd.DataFrame(mamcart.orbital))))
mamsphr = Orb(resource('mol-ch3nh2-anovdzp.scforb'))
mamsphr.parse_momatrix()
self.assertEqual(mamsphr.momatrix.shape[0], 2809)
self.assertTrue(np.all(pd.notnull(pd.DataFrame(mamsphr.momatrix))))
self.assertTrue(np.all(pd.notnull(pd.DataFrame(mamsphr.orbital))))
class TestHDF(TestCase):
def setUp(self):
self.nym = HDF(resource('mol-c2h6-nosym-scf.hdf5'))
self.sym = HDF(resource('mol-c2h6-sym-scf.hdf5'))
def test_parse_atom(self):
self.sym.parse_atom()
self.nym.parse_atom()
self.assertTrue(self.sym.atom.shape[0] == 8)
self.assertTrue(self.nym.atom.shape[0] == 8)
def test_parse_basis_set_order(self):
self.sym.parse_basis_set_order()
self.nym.parse_basis_set_order()
self.assertTrue(self.sym.basis_set_order.shape[0] == 30)
self.assertTrue(self.nym.basis_set_order.shape[0] == 30)
def test_parse_orbital(self):
self.sym.parse_orbital()
self.nym.parse_orbital()
self.assertTrue(self.sym.orbital.shape[0] == 30)
self.assertTrue(self.nym.orbital.shape[0] == 30)
def test_parse_overlap(self):
self.sym.parse_overlap()
self.nym.parse_overlap()
self.assertTrue(self.sym.overlap.shape[0])
self.assertTrue(self.nym.overlap.shape[0])
def test_parse_momatrix(self):
self.sym.parse_momatrix()
self.nym.parse_momatrix()
self.assertTrue(self.nym.momatrix.shape[0] == 900)
with self.assertRaises(AttributeError):
self.assertTrue(self.sym.momatrix)
def test_to_universe(self):
self.sym.to_universe()
self.nym.to_universe()<|fim▁end|> | from exatomic import Universe
from exatomic.base import resource
from exatomic.molcas.output import Output, Orb, HDF |
<|file_name|>2_photos.js<|end_file_name|><|fim▁begin|>Photos = new orion.collection('photos', {
singularName: 'photo',
pluralName: 'photos',
link: {
title: 'Photos'
},
tabular: {
columns: [
{data: 'title', title: 'Title'},
{data: 'state', title: 'State'},
//ToDo: Thumbnail
orion.attributeColumn('markdown', 'body', 'Content'),
orion.attributeColumn('createdAt', 'createdAt', 'Created At'),
orion.attributeColumn('createdBy', 'createdBy', 'Created By')
]
}
});
Photos.attachSchema(new SimpleSchema({
title: {type: String},
state: {
type: String,
allowedValues: [
"draft",
"published",
"archived"
],
label: "State"
},
userId: orion.attribute('hasOne', {
type: String,
label: 'Author',
optional: false
}, {
collection: Meteor.users,
// the key whose value you want to show for each Post document on the Update form
titleField: 'profile.name',
publicationName: 'PB_Photos_Author',
}),
image: orion.attribute('image', {
optional: true,
label: 'Image'
}),
body: orion.attribute('markdown', {
label: 'Body'
}),
createdBy: orion.attribute('createdBy', {
label: 'Created By'
}),
createdAt: orion.attribute('createdAt', {
label: 'Created At'
}),
lockedBy: {<|fim▁hole|> type: 'hidden'
},
optional: true
}
}));<|fim▁end|> | type: String,
autoform: { |
<|file_name|>store.rs<|end_file_name|><|fim▁begin|>pub struct StoreStats {
pub num_keys: u64,
pub total_memory_in_bytes: u64,
}
impl StoreStats {
pub fn new() -> StoreStats {
StoreStats {
num_keys: 0,
total_memory_in_bytes: 0,
}
}
}
pub trait ValueStore<K, V> {
fn get(&self, key: &K) -> Option<&V>;
fn set(&mut self, key: K, value: V);
fn delete(&mut self, key: &K) -> bool;
fn delete_many(&mut self, keys: &Vec<K>);
fn clear(&mut self);
fn stats(&self) -> &StoreStats;
}<|fim▁hole|>pub trait EvictionPolicy<K, V> {
// Metadata management
fn update_metadata_on_get(&mut self, key: K);
fn update_metadata_on_set(&mut self, key: K, value: V);
fn delete_metadata(&mut self, keys: &Vec<K>);
fn clear_metadata(&mut self);
// Eviction polict logic
fn should_evict_keys(&self, store_stats: &StoreStats) -> bool;
fn choose_keys_to_evict(&self) -> Vec<K>;
}
pub struct Store<K: Clone,
V: Clone,
KVStore: ValueStore<K, V>,
EvPolicy: EvictionPolicy<K, V>>
{
value_store: KVStore,
eviction_policy: EvPolicy,
// Hack to allow this struct to take the ValueStore and EvictionPolicy
// traits and constrain them to having the same types for the keys (K) and
// the values (V).
// TODO: find a better way to achieve this
__hack1: Option<K>,
__hack2: Option<V>,
}
impl<K: Clone,
V: Clone,
KVStore: ValueStore<K, V>,
EvPolicy: EvictionPolicy<K, V>>
Store<K, V, KVStore, EvPolicy>
{
pub fn new(value_store: KVStore,
eviction_policy: EvPolicy) -> Store<K, V, KVStore, EvPolicy>
{
Store {
value_store: value_store,
eviction_policy: eviction_policy,
__hack1: None,
__hack2: None,
}
}
pub fn get(&mut self, key: &K) -> Option<&V> {
self.evict_keys_if_necessary();
self.eviction_policy.update_metadata_on_get(key.clone());
self.value_store.get(key)
}
pub fn set(&mut self, key: K, value: V) {
self.evict_keys_if_necessary();
self.eviction_policy.update_metadata_on_set(key.clone(), value.clone());
self.value_store.set(key, value);
}
fn evict_keys_if_necessary(&mut self) {
let should_evict = self.eviction_policy.should_evict_keys(
self.value_store.stats());
if should_evict {
let keys_to_evict = self.eviction_policy.choose_keys_to_evict();
self.value_store.delete_many(&keys_to_evict);
self.eviction_policy.delete_metadata(&keys_to_evict);
}
}
}<|fim▁end|> | |
<|file_name|>BookService.java<|end_file_name|><|fim▁begin|>package by.itransition.dpm.service;
import by.itransition.dpm.dao.BookDao;
import by.itransition.dpm.dao.UserDao;
import by.itransition.dpm.entity.Book;
import by.itransition.dpm.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class BookService {
@Autowired
private BookDao bookDao;
@Autowired
private UserDao userDao;
@Autowired
private UserService userService;
public void setBookDao(BookDao bookDao) {<|fim▁hole|> this.bookDao = bookDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Transactional
public void addBook(Book book){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String name = authentication.getName();
User user = userDao.getUserByLogin(name);
book.setUser(user);
bookDao.saveBook(book);
userService.addBook(user, book);
}
@Transactional
public List<Book> getAllBooks() {
return bookDao.getAllBooks();
}
@Transactional
public List<Book> getUserBooks(User user) {
return user.getBooks();
}
@Transactional
public void deleteBookById(Integer id) {
bookDao.deleteBookById(id);
}
@Transactional
public Book getBookById (Integer id){
return bookDao.getBookById(id);
}
}<|fim▁end|> | |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>//
// Copyright (C) 2017 Kubos Corporation
//
// 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<|fim▁hole|>// 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.
//
#[macro_use]
extern crate juniper;
extern crate juniper_iron;
extern crate iron;
extern crate mount;
extern crate logger;
use iron::prelude::*;
use juniper_iron::{GraphQLHandler, GraphiQLHandler};
mod model;
mod schema;
use std::env;
/// A context object is used in Juniper to provide out-of-band access to global
/// data when resolving fields. We will use it here to provide a Subsystem structure
/// with recently fetched data.
///
/// Since this function is called once for every request, it will fetch new
/// data with each request.
fn context_factory(_: &mut Request) -> schema::Context {
schema::Context { subsystem: model::Subsystem::new() }
}
fn main() {
let graphql_endpoint =
GraphQLHandler::new(context_factory, schema::QueryRoot, schema::MutationRoot);
let graphiql_endpoint = GraphiQLHandler::new("/grapihql");
let mut mount = mount::Mount::new();
mount.mount("/", graphql_endpoint);
mount.mount("/graphiql", graphiql_endpoint);
let (logger_before, logger_after) = logger::Logger::new(None);
let mut chain = Chain::new(mount);
chain.link_before(logger_before);
chain.link_after(logger_after);
let host = env::var("LISTEN").unwrap_or("0.0.0.0:8080".to_owned());
println!("GraphQL server started on {}", host);
Iron::new(chain).http(host.as_str()).unwrap();
}<|fim▁end|> | // distributed under the License is distributed on an "AS IS" BASIS, |
<|file_name|>tomltree_write_test.go<|end_file_name|><|fim▁begin|>package toml
import (
"bytes"
"errors"
"fmt"
"reflect"
"strings"
"testing"
"time"
)
type failingWriter struct {
failAt int
written int
buffer bytes.Buffer
}
func (f failingWriter) Write(p []byte) (n int, err error) {
count := len(p)
toWrite := f.failAt - count + f.written
if toWrite < 0 {
toWrite = 0
}
if toWrite > count {
f.written += count
f.buffer.WriteString(string(p))
return count, nil
}
f.buffer.WriteString(string(p[:toWrite]))
f.written = f.failAt
return f.written, fmt.Errorf("failingWriter failed after writting %d bytes", f.written)
}
func assertErrorString(t *testing.T, expected string, err error) {
expectedErr := errors.New(expected)
if err.Error() != expectedErr.Error() {
t.Errorf("expecting error %s, but got %s instead", expected, err)
}
}
func TestTreeWriteToEmptyTable(t *testing.T) {
doc := `[[empty-tables]]
[[empty-tables]]`
toml, err := Load(doc)
if err != nil {
t.Fatal("Unexpected Load error:", err)
}
tomlString, err := toml.ToTomlString()
if err != nil {
t.Fatal("Unexpected ToTomlString error:", err)
}
expected := `
[[empty-tables]]
[[empty-tables]]
`
if tomlString != expected {
t.Fatalf("Expected:\n%s\nGot:\n%s", expected, tomlString)
}
}
func TestTreeWriteToTomlString(t *testing.T) {
toml, err := Load(`name = { first = "Tom", last = "Preston-Werner" }
points = { x = 1, y = 2 }`)
if err != nil {
t.Fatal("Unexpected error:", err)
}
tomlString, _ := toml.ToTomlString()
reparsedTree, err := Load(tomlString)
assertTree(t, reparsedTree, err, map[string]interface{}{
"name": map[string]interface{}{
"first": "Tom",
"last": "Preston-Werner",
},
"points": map[string]interface{}{
"x": int64(1),
"y": int64(2),
},
})
}
func TestTreeWriteToTomlStringSimple(t *testing.T) {
tree, err := Load("[foo]\n\n[[foo.bar]]\na = 42\n\n[[foo.bar]]\na = 69\n")
if err != nil {
t.Errorf("Test failed to parse: %v", err)
return
}
result, err := tree.ToTomlString()
if err != nil {
t.Errorf("Unexpected error: %s", err)
}
expected := "\n[foo]\n\n [[foo.bar]]\n a = 42\n\n [[foo.bar]]\n a = 69\n"
if result != expected {
t.Errorf("Expected got '%s', expected '%s'", result, expected)
}
}
func TestTreeWriteToTomlStringKeysOrders(t *testing.T) {
for i := 0; i < 100; i++ {
tree, _ := Load(`
foobar = true
bar = "baz"
foo = 1
[qux]
foo = 1
bar = "baz2"`)
stringRepr, _ := tree.ToTomlString()
t.Log("Intermediate string representation:")
t.Log(stringRepr)
r := strings.NewReader(stringRepr)
toml, err := LoadReader(r)
if err != nil {
t.Fatal("Unexpected error:", err)
}
assertTree(t, toml, err, map[string]interface{}{
"foobar": true,
"bar": "baz",
"foo": 1,
"qux": map[string]interface{}{
"foo": 1,
"bar": "baz2",
},
})
}
}
func testMaps(t *testing.T, actual, expected map[string]interface{}) {
if !reflect.DeepEqual(actual, expected) {
t.Fatal("trees aren't equal.\n", "Expected:\n", expected, "\nActual:\n", actual)
}
}
func TestTreeWriteToMapSimple(t *testing.T) {
tree, _ := Load("a = 42\nb = 17")
expected := map[string]interface{}{
"a": int64(42),
"b": int64(17),
}
testMaps(t, tree.ToMap(), expected)
}
func TestTreeWriteToInvalidTreeSimpleValue(t *testing.T) {
tree := Tree{values: map[string]interface{}{"foo": int8(1)}}
_, err := tree.ToTomlString()
assertErrorString(t, "invalid value type at foo: int8", err)
}
func TestTreeWriteToInvalidTreeTomlValue(t *testing.T) {
tree := Tree{values: map[string]interface{}{"foo": &tomlValue{int8(1), Position{}}}}
_, err := tree.ToTomlString()
assertErrorString(t, "unsupported value type int8: 1", err)
}
func TestTreeWriteToInvalidTreeTomlValueArray(t *testing.T) {
tree := Tree{values: map[string]interface{}{"foo": &tomlValue{[]interface{}{int8(1)}, Position{}}}}
_, err := tree.ToTomlString()
assertErrorString(t, "unsupported value type int8: 1", err)
}
func TestTreeWriteToFailingWriterInSimpleValue(t *testing.T) {
toml, _ := Load(`a = 2`)
writer := failingWriter{failAt: 0, written: 0}
_, err := toml.WriteTo(writer)
assertErrorString(t, "failingWriter failed after writting 0 bytes", err)
}
func TestTreeWriteToFailingWriterInTable(t *testing.T) {
toml, _ := Load(`
[b]
a = 2`)
writer := failingWriter{failAt: 2, written: 0}
_, err := toml.WriteTo(writer)
assertErrorString(t, "failingWriter failed after writting 2 bytes", err)
writer = failingWriter{failAt: 13, written: 0}
_, err = toml.WriteTo(writer)
assertErrorString(t, "failingWriter failed after writting 13 bytes", err)
}
func TestTreeWriteToFailingWriterInArray(t *testing.T) {
toml, _ := Load(`
[[b]]
a = 2`)
writer := failingWriter{failAt: 2, written: 0}
_, err := toml.WriteTo(writer)
assertErrorString(t, "failingWriter failed after writting 2 bytes", err)
writer = failingWriter{failAt: 15, written: 0}
_, err = toml.WriteTo(writer)
assertErrorString(t, "failingWriter failed after writting 15 bytes", err)
}
func TestTreeWriteToMapExampleFile(t *testing.T) {
tree, _ := LoadFile("example.toml")<|fim▁hole|> "name": "Tom Preston-Werner",
"organization": "GitHub",
"bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.",
"dob": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC),
},
"database": map[string]interface{}{
"server": "192.168.1.1",
"ports": []interface{}{int64(8001), int64(8001), int64(8002)},
"connection_max": int64(5000),
"enabled": true,
},
"servers": map[string]interface{}{
"alpha": map[string]interface{}{
"ip": "10.0.0.1",
"dc": "eqdc10",
},
"beta": map[string]interface{}{
"ip": "10.0.0.2",
"dc": "eqdc10",
},
},
"clients": map[string]interface{}{
"data": []interface{}{
[]interface{}{"gamma", "delta"},
[]interface{}{int64(1), int64(2)},
},
},
}
testMaps(t, tree.ToMap(), expected)
}
func TestTreeWriteToMapWithTablesInMultipleChunks(t *testing.T) {
tree, _ := Load(`
[[menu.main]]
a = "menu 1"
b = "menu 2"
[[menu.main]]
c = "menu 3"
d = "menu 4"`)
expected := map[string]interface{}{
"menu": map[string]interface{}{
"main": []interface{}{
map[string]interface{}{"a": "menu 1", "b": "menu 2"},
map[string]interface{}{"c": "menu 3", "d": "menu 4"},
},
},
}
treeMap := tree.ToMap()
testMaps(t, treeMap, expected)
}
func TestTreeWriteToMapWithArrayOfInlineTables(t *testing.T) {
tree, _ := Load(`
[params]
language_tabs = [
{ key = "shell", name = "Shell" },
{ key = "ruby", name = "Ruby" },
{ key = "python", name = "Python" }
]`)
expected := map[string]interface{}{
"params": map[string]interface{}{
"language_tabs": []interface{}{
map[string]interface{}{
"key": "shell",
"name": "Shell",
},
map[string]interface{}{
"key": "ruby",
"name": "Ruby",
},
map[string]interface{}{
"key": "python",
"name": "Python",
},
},
},
}
treeMap := tree.ToMap()
testMaps(t, treeMap, expected)
}<|fim▁end|> | expected := map[string]interface{}{
"title": "TOML Example",
"owner": map[string]interface{}{ |
<|file_name|>test_consoles.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-2011 OpenStack LLC.
# Copyright 2011 Piston Cloud Computing, 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.
import datetime
from lxml import etree
import webob
from nova.api.openstack.compute import consoles
from nova.compute import vm_states
from nova import console
from nova import db
from nova import exception
from nova import flags
from nova import test
from nova.tests.api.openstack import fakes
from nova import utils
FLAGS = flags.FLAGS
FAKE_UUID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
class FakeInstanceDB(object):
def __init__(self):
self.instances_by_id = {}
self.ids_by_uuid = {}
self.max_id = 0
def return_server_by_id(self, context, id):
if id not in self.instances_by_id:
self._add_server(id=id)
return dict(self.instances_by_id[id])
def return_server_by_uuid(self, context, uuid):
if uuid not in self.ids_by_uuid:
self._add_server(uuid=uuid)
return dict(self.instances_by_id[self.ids_by_uuid[uuid]])
def _add_server(self, id=None, uuid=None):
if id is None:
id = self.max_id + 1
if uuid is None:
uuid = str(utils.gen_uuid())
instance = stub_instance(id, uuid=uuid)
self.instances_by_id[id] = instance
self.ids_by_uuid[uuid] = id
if id > self.max_id:
self.max_id = id
def stub_instance(id, user_id='fake', project_id='fake', host=None,
vm_state=None, task_state=None,
reservation_id="", uuid=FAKE_UUID, image_ref="10",
flavor_id="1", name=None, key_name='',
access_ipv4=None, access_ipv6=None, progress=0):
if host is not None:
host = str(host)
if key_name:
key_data = 'FAKE'
else:
key_data = ''
# ReservationID isn't sent back, hack it in there.
server_name = name or "server%s" % id
if reservation_id != "":
server_name = "reservation_%s" % (reservation_id, )
instance = {
"id": int(id),
"created_at": datetime.datetime(2010, 10, 10, 12, 0, 0),
"updated_at": datetime.datetime(2010, 11, 11, 11, 0, 0),
"admin_pass": "",
"user_id": user_id,
"project_id": project_id,
"image_ref": image_ref,
"kernel_id": "",
"ramdisk_id": "",
"launch_index": 0,
"key_name": key_name,
"key_data": key_data,
"vm_state": vm_state or vm_states.BUILDING,
"task_state": task_state,
"memory_mb": 0,
"vcpus": 0,
"root_gb": 0,
"hostname": "",
"host": host,
"instance_type": {},
"user_data": "",
"reservation_id": reservation_id,
"mac_address": "",
"scheduled_at": utils.utcnow(),
"launched_at": utils.utcnow(),
"terminated_at": utils.utcnow(),
"availability_zone": "",
"display_name": server_name,
"display_description": "",
"locked": False,
"metadata": [],
"access_ip_v4": access_ipv4,
"access_ip_v6": access_ipv6,
"uuid": uuid,
"progress": progress}
return instance
class ConsolesControllerTest(test.TestCase):
def setUp(self):
super(ConsolesControllerTest, self).setUp()
self.flags(verbose=True)
self.instance_db = FakeInstanceDB()
self.stubs.Set(db, 'instance_get',
self.instance_db.return_server_by_id)
self.stubs.Set(db, 'instance_get_by_uuid',
self.instance_db.return_server_by_uuid)
self.uuid = str(utils.gen_uuid())
self.url = '/v2/fake/servers/%s/consoles' % self.uuid
self.controller = consoles.Controller()
def test_create_console(self):
def fake_create_console(cons_self, context, instance_id):
self.assertEqual(instance_id, self.uuid)
return {}
self.stubs.Set(console.api.API, 'create_console', fake_create_console)
req = fakes.HTTPRequest.blank(self.url)
self.controller.create(req, self.uuid)
def test_show_console(self):
def fake_get_console(cons_self, context, instance_id, console_id):
self.assertEqual(instance_id, self.uuid)
self.assertEqual(console_id, 20)
pool = dict(console_type='fake_type',
public_hostname='fake_hostname')
return dict(id=console_id, password='fake_password',
port='fake_port', pool=pool, instance_name='inst-0001')
expected = {'console': {'id': 20,
'port': 'fake_port',<|fim▁hole|> 'host': 'fake_hostname',
'password': 'fake_password',
'instance_name': 'inst-0001',
'console_type': 'fake_type'}}
self.stubs.Set(console.api.API, 'get_console', fake_get_console)
req = fakes.HTTPRequest.blank(self.url + '/20')
res_dict = self.controller.show(req, self.uuid, '20')
self.assertDictMatch(res_dict, expected)
def test_show_console_unknown_console(self):
def fake_get_console(cons_self, context, instance_id, console_id):
raise exception.ConsoleNotFound(console_id=console_id)
self.stubs.Set(console.api.API, 'get_console', fake_get_console)
req = fakes.HTTPRequest.blank(self.url + '/20')
self.assertRaises(webob.exc.HTTPNotFound, self.controller.show,
req, self.uuid, '20')
def test_show_console_unknown_instance(self):
def fake_get_console(cons_self, context, instance_id, console_id):
raise exception.InstanceNotFound(instance_id=instance_id)
self.stubs.Set(console.api.API, 'get_console', fake_get_console)
req = fakes.HTTPRequest.blank(self.url + '/20')
self.assertRaises(webob.exc.HTTPNotFound, self.controller.show,
req, self.uuid, '20')
def test_list_consoles(self):
def fake_get_consoles(cons_self, context, instance_id):
self.assertEqual(instance_id, self.uuid)
pool1 = dict(console_type='fake_type',
public_hostname='fake_hostname')
cons1 = dict(id=10, password='fake_password',
port='fake_port', pool=pool1)
pool2 = dict(console_type='fake_type2',
public_hostname='fake_hostname2')
cons2 = dict(id=11, password='fake_password2',
port='fake_port2', pool=pool2)
return [cons1, cons2]
expected = {'consoles':
[{'console': {'id': 10, 'console_type': 'fake_type'}},
{'console': {'id': 11, 'console_type': 'fake_type2'}}]}
self.stubs.Set(console.api.API, 'get_consoles', fake_get_consoles)
req = fakes.HTTPRequest.blank(self.url)
res_dict = self.controller.index(req, self.uuid)
self.assertDictMatch(res_dict, expected)
def test_delete_console(self):
def fake_get_console(cons_self, context, instance_id, console_id):
self.assertEqual(instance_id, self.uuid)
self.assertEqual(console_id, 20)
pool = dict(console_type='fake_type',
public_hostname='fake_hostname')
return dict(id=console_id, password='fake_password',
port='fake_port', pool=pool)
def fake_delete_console(cons_self, context, instance_id, console_id):
self.assertEqual(instance_id, self.uuid)
self.assertEqual(console_id, 20)
self.stubs.Set(console.api.API, 'get_console', fake_get_console)
self.stubs.Set(console.api.API, 'delete_console', fake_delete_console)
req = fakes.HTTPRequest.blank(self.url + '/20')
self.controller.delete(req, self.uuid, '20')
def test_delete_console_unknown_console(self):
def fake_delete_console(cons_self, context, instance_id, console_id):
raise exception.ConsoleNotFound(console_id=console_id)
self.stubs.Set(console.api.API, 'delete_console', fake_delete_console)
req = fakes.HTTPRequest.blank(self.url + '/20')
self.assertRaises(webob.exc.HTTPNotFound, self.controller.delete,
req, self.uuid, '20')
def test_delete_console_unknown_instance(self):
def fake_delete_console(cons_self, context, instance_id, console_id):
raise exception.InstanceNotFound(instance_id=instance_id)
self.stubs.Set(console.api.API, 'delete_console', fake_delete_console)
req = fakes.HTTPRequest.blank(self.url + '/20')
self.assertRaises(webob.exc.HTTPNotFound, self.controller.delete,
req, self.uuid, '20')
class TestConsolesXMLSerializer(test.TestCase):
def test_show(self):
fixture = {'console': {'id': 20,
'password': 'fake_password',
'port': 'fake_port',
'host': 'fake_hostname',
'console_type': 'fake_type'}}
output = consoles.ConsoleTemplate().serialize(fixture)
res_tree = etree.XML(output)
self.assertEqual(res_tree.tag, 'console')
self.assertEqual(res_tree.xpath('id')[0].text, '20')
self.assertEqual(res_tree.xpath('port')[0].text, 'fake_port')
self.assertEqual(res_tree.xpath('host')[0].text, 'fake_hostname')
self.assertEqual(res_tree.xpath('password')[0].text, 'fake_password')
self.assertEqual(res_tree.xpath('console_type')[0].text, 'fake_type')
def test_index(self):
fixture = {'consoles': [{'console': {'id': 10,
'console_type': 'fake_type'}},
{'console': {'id': 11,
'console_type': 'fake_type2'}}]}
output = consoles.ConsolesTemplate().serialize(fixture)
res_tree = etree.XML(output)
self.assertEqual(res_tree.tag, 'consoles')
self.assertEqual(len(res_tree), 2)
self.assertEqual(res_tree[0].tag, 'console')
self.assertEqual(res_tree[1].tag, 'console')
self.assertEqual(len(res_tree[0]), 1)
self.assertEqual(res_tree[0][0].tag, 'console')
self.assertEqual(len(res_tree[1]), 1)
self.assertEqual(res_tree[1][0].tag, 'console')
self.assertEqual(res_tree[0][0].xpath('id')[0].text, '10')
self.assertEqual(res_tree[1][0].xpath('id')[0].text, '11')
self.assertEqual(res_tree[0][0].xpath('console_type')[0].text,
'fake_type')
self.assertEqual(res_tree[1][0].xpath('console_type')[0].text,
'fake_type2')<|fim▁end|> | |
<|file_name|>app_chooser.rs<|end_file_name|><|fim▁begin|>// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
use glib::translate::{FromGlibPtr};
use gtk::{self, ffi};
use gtk::cast::GTK_APP_CHOOSER;<|fim▁hole|>pub trait AppChooserTrait: gtk::WidgetTrait {
fn get_app_info(&self) -> Option<gtk::AppInfo> {
let tmp_pointer = unsafe { ffi::gtk_app_chooser_get_app_info(GTK_APP_CHOOSER(self.unwrap_widget())) };
if tmp_pointer.is_null() {
None
} else {
Some(gtk::FFIWidget::wrap_widget(tmp_pointer as *mut ffi::C_GtkWidget))
}
}
fn get_content_info(&self) -> Option<String> {
unsafe {
FromGlibPtr::borrow(
ffi::gtk_app_chooser_get_content_type(GTK_APP_CHOOSER(self.unwrap_widget())))
}
}
fn refresh(&self) -> () {
unsafe { ffi::gtk_app_chooser_refresh(GTK_APP_CHOOSER(self.unwrap_widget())) }
}
}<|fim▁end|> | |
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | class AbortAction(RuntimeError):
pass |
<|file_name|>test_experiment.py<|end_file_name|><|fim▁begin|>import pytest
from everest.repositories.rdb.testing import check_attributes
from everest.repositories.rdb.testing import persist
from thelma.tests.entity.conftest import TestEntityBase
class TestExperimentEntity(TestEntityBase):
def test_init(self, experiment_fac):
exp = experiment_fac()
check_attributes(exp, experiment_fac.init_kw)
assert len(exp.experiment_racks) == 0
@pytest.mark.parametrize('kw1,kw2,result',
[(dict(id=-1), dict(id=-1), True),
(dict(id=-1), dict(id=-2), False)])
def test_equality(self, experiment_fac, experiment_design_fac, plate_fac,
kw1, kw2, result):
ed1 = experiment_design_fac(**kw1)
ed2 = experiment_design_fac(**kw2)
rack1 = plate_fac(**kw1)
rack2 = plate_fac(**kw2)
exp1 = experiment_fac(experiment_design=ed1, source_rack=rack1)
exp2 = experiment_fac(experiment_design=ed2, source_rack=rack2)
exp3 = experiment_fac(experiment_design=ed2, source_rack=rack1)
exp4 = experiment_fac(experiment_design=ed1, source_rack=rack2)
assert (exp1 == exp2) is result
assert (exp1 == exp3) is result
assert (exp1 == exp4) is result
def test_persist(self, nested_session, experiment_fac,
experiment_job_fac):
exp = experiment_fac()<|fim▁hole|> kw['job'] = exp.job
exp.job = exp_job
persist(nested_session, exp, kw, True)
class TestExperimentRackEntity(TestEntityBase):
def test_init(self, experiment_rack_fac):
exp_r = experiment_rack_fac()
check_attributes(exp_r, experiment_rack_fac.init_kw)
class TestExperimentDesignEntity(TestEntityBase):
def test_init(self, experiment_design_fac):
exp_dsgn = experiment_design_fac()
check_attributes(exp_dsgn, experiment_design_fac.init_kw)
def test_persist(self, nested_session, experiment_design_fac):
exp_design = experiment_design_fac()
persist(nested_session, exp_design, experiment_design_fac.init_kw,
True)
class TestExperimentDesignRackEntity(TestEntityBase):
def test_init(self, experiment_design_rack_fac):
exp_dr = experiment_design_rack_fac()
check_attributes(exp_dr, experiment_design_rack_fac.init_kw)
class TestExperimentMetadataEntity(TestEntityBase):
def test_init(self, experiment_metadata_fac):
em = experiment_metadata_fac()
check_attributes(em, experiment_metadata_fac.init_kw)
@pytest.mark.parametrize('kw1,kw2,result',
[(dict(label='em1'), dict(label='em1'), True),
(dict(label='em1'), dict(label='em2'), False)])
def test_equality(self, subproject_fac, experiment_metadata_fac,
kw1, kw2, result):
sp1 = subproject_fac(**kw1)
sp2 = subproject_fac(**kw2)
em1 = experiment_metadata_fac(subproject=sp1, **kw1)
em2 = experiment_metadata_fac(subproject=sp2, **kw2)
assert (em1 == em2) is result
def test_persist(self, nested_session, experiment_metadata_fac):
exp_metadata = experiment_metadata_fac()
persist(nested_session, exp_metadata, experiment_metadata_fac.init_kw,
True)<|fim▁end|> | # FIXME: Working around the circular dependency of experiment and
# experiment job here.
exp_job = experiment_job_fac(experiments=[exp])
kw = experiment_fac.init_kw |
<|file_name|>search-box.component.spec.ts<|end_file_name|><|fim▁begin|>import { Component } from '@angular/core';
import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { SearchBoxComponent } from './search-box.component';
import { LocationService } from 'app/shared/location.service';
import { MockLocationService } from 'testing/location.service';
@Component({
template: '<aio-search-box (onSearch)="searchHandler($event)" (onFocus)="focusHandler($event)"></aio-search-box>'
})
class HostComponent {
searchHandler = jasmine.createSpy('searchHandler');
focusHandler = jasmine.createSpy('focusHandler');
}
describe('SearchBoxComponent', () => {
let component: SearchBoxComponent;
let host: HostComponent;
let fixture: ComponentFixture<HostComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ SearchBoxComponent, HostComponent ],
providers: [
{ provide: LocationService, useFactory: () => new MockLocationService('') }
]
});
});
beforeEach(() => {
fixture = TestBed.createComponent(HostComponent);
host = fixture.componentInstance;
component = fixture.debugElement.query(By.directive(SearchBoxComponent)).componentInstance;
fixture.detectChanges();
});
<|fim▁hole|> component.ngOnInit();
expect(location.search).toHaveBeenCalled();
tick(300);
expect(host.searchHandler).toHaveBeenCalledWith('initial search');
expect(component.searchBox.nativeElement.value).toEqual('initial search');
})));
});
describe('onSearch', () => {
it('should debounce by 300ms', fakeAsync(() => {
component.doSearch();
expect(host.searchHandler).not.toHaveBeenCalled();
tick(300);
expect(host.searchHandler).toHaveBeenCalled();
}));
it('should pass through the value of the input box', fakeAsync(() => {
const input = fixture.debugElement.query(By.css('input'));
input.nativeElement.value = 'some query (input)';
component.doSearch();
tick(300);
expect(host.searchHandler).toHaveBeenCalledWith('some query (input)');
}));
it('should only send events if the search value has changed', fakeAsync(() => {
const input = fixture.debugElement.query(By.css('input'));
input.nativeElement.value = 'some query';
component.doSearch();
tick(300);
expect(host.searchHandler).toHaveBeenCalledTimes(1);
component.doSearch();
tick(300);
expect(host.searchHandler).toHaveBeenCalledTimes(1);
input.nativeElement.value = 'some other query';
component.doSearch();
tick(300);
expect(host.searchHandler).toHaveBeenCalledTimes(2);
}));
});
describe('on input', () => {
it('should trigger a search', () => {
const input = fixture.debugElement.query(By.css('input'));
spyOn(component, 'doSearch');
input.triggerEventHandler('input', { });
expect(component.doSearch).toHaveBeenCalled();
});
});
describe('on keyup', () => {
it('should trigger a search', () => {
const input = fixture.debugElement.query(By.css('input'));
spyOn(component, 'doSearch');
input.triggerEventHandler('keyup', { });
expect(component.doSearch).toHaveBeenCalled();
});
});
describe('on focus', () => {
it('should trigger the onFocus event', () => {
const input = fixture.debugElement.query(By.css('input'));
input.nativeElement.value = 'some query (focus)';
input.triggerEventHandler('focus', { });
expect(host.focusHandler).toHaveBeenCalledWith('some query (focus)');
});
});
describe('on click', () => {
it('should trigger a search', () => {
const input = fixture.debugElement.query(By.css('input'));
spyOn(component, 'doSearch');
input.triggerEventHandler('click', { });
expect(component.doSearch).toHaveBeenCalled();
});
});
describe('focus', () => {
it('should set the focus to the input box', () => {
const input = fixture.debugElement.query(By.css('input'));
component.focus();
expect(document.activeElement).toBe(input.nativeElement);
});
});
});<|fim▁end|> | describe('initialisation', () => {
it('should get the current search query from the location service',
inject([LocationService], (location: MockLocationService) => fakeAsync(() => {
location.search.and.returnValue({ search: 'initial search' }); |
<|file_name|>number.rs<|end_file_name|><|fim▁begin|>use front::stdlib::value::{Value, ResultValue, VNumber, VInteger, to_value, from_value};
use front::stdlib::function::Function;
use std::f64::{NAN, MAX_VALUE, MIN_VALUE, INFINITY, NEG_INFINITY, EPSILON};
/// Parse a float into a value
pub fn parse_float(args:Vec<Value>, _:Value, _:Value, _:Value) -> ResultValue {
let parsed = from_str::<f64>(from_value::<String>(args[0]).unwrap().as_slice());
return Ok(to_value(match parsed {
Some(v) => v,
None => NAN
}));
}
/// Parse an int into a value
pub fn parse_int(args:Vec<Value>, _:Value, _:Value, _:Value) -> ResultValue {<|fim▁hole|> None => to_value(NAN)
});
}
/// Check if a value when converted to a number is finite
pub fn is_finite(args:Vec<Value>, _:Value, _:Value, _:Value) -> ResultValue {
Ok(to_value(if args.len() == 0 {
false
} else {
from_value::<f64>(args[0]).unwrap().is_finite()
}))
}
/// Check if a number is finite
pub fn strict_is_finite(args:Vec<Value>, _:Value, _:Value, _:Value) -> ResultValue {
Ok(to_value(if args.len() == 0 {
false
} else {
match *args[0] {
VNumber(v) => v.is_finite(),
VInteger(_) => true, // integers can't be infinite
_ => false
}
}))
}
/// Check if a value when converted to a number is equal to NaN
pub fn is_nan(args:Vec<Value>, _:Value, _:Value, _:Value) -> ResultValue {
Ok(to_value(if args.len() == 0 {
false
} else {
from_value::<f64>(args[0]).unwrap().is_nan()
}))
}
/// Check if a number is equal to NaN
pub fn strict_is_nan(args:Vec<Value>, _:Value, _:Value, _:Value) -> ResultValue {
Ok(to_value(if args.len() == 0 {
false
} else {
match *args[0] {
VNumber(v) => v.is_nan(),
_ => false
}
}))
}
/// Create a new `Number` object
pub fn _create(global:Value) -> Value {
js!(global, {
"NaN": NAN,
"MAX_VALUE": MAX_VALUE,
"MIN_VALUE": MIN_VALUE,
"POSITIVE_INFINITY": INFINITY,
"NEGATIVE_INFINITY": NEG_INFINITY,
"EPSILON": EPSILON,
"parseFloat": Function::make(parse_float, ["string"]),
"parseInt": Function::make(parse_int, ["string"]),
"isFinite": Function::make(strict_is_finite, ["num"]),
"isNaN": Function::make(strict_is_nan, ["num"])
})
}
/// Initialise the parse functions and `Number` on the global object
pub fn init(global:Value) {
js_extend!(global, {
"NaN": NAN,
"Infinity": INFINITY,
"parseFloat": Function::make(parse_float, ["string"]),
"parseInt": Function::make(parse_int, ["string"]),
"isFinite": Function::make(is_finite, ["number"]),
"isNaN": Function::make(is_nan, ["num"]),
"Number": _create(global)
});
}<|fim▁end|> | let parsed = from_str::<i32>(from_value::<String>(args[0]).unwrap().as_slice());
return Ok(match parsed {
Some(v) => to_value(v), |
<|file_name|>consul.go<|end_file_name|><|fim▁begin|>package veneur
import (
"errors"
"fmt"
"github.com/hashicorp/consul/api"
)
// Consul is a Discoverer that uses Consul to find
// healthy instances of a given name.
type Consul struct {<|fim▁hole|> ConsulHealth *api.Health
}
// NewConsul creates a new instance of a Consul Discoverer
func NewConsul(config *api.Config) (*Consul, error) {
consulClient, err := api.NewClient(config)
if err != nil {
return nil, err
}
return &Consul{
ConsulHealth: consulClient.Health(),
}, nil
}
// GetDestinationsForService updates the list of destinations based on healthy nodes
// found via Consul. It returns destinations in the form "<host>:<port>".
func (c *Consul) GetDestinationsForService(serviceName string) ([]string, error) {
serviceEntries, _, err := c.ConsulHealth.Service(serviceName, "", true, &api.QueryOptions{})
if err != nil {
return nil, err
}
numHosts := len(serviceEntries)
if numHosts < 1 {
return nil, errors.New("Received no hosts from Consul")
}
// Make a slice to hold our returned hosts
hosts := make([]string, numHosts)
for index, se := range serviceEntries {
hosts[index] = fmt.Sprintf("%s:%d", se.Node.Address, se.Service.Port)
}
return hosts, nil
}<|fim▁end|> | |
<|file_name|>basic_operations_with_function.py<|end_file_name|><|fim▁begin|>#Author Emily Keiser
def addition(x,y):
return int(x)+int(y)
def subtraction (x,y) :
return int(x) -int(y)
def multiplication (x,y) :
return int(x) *int(y)
def module (x,y) :
return int(x) %int(y)
a=raw_input("Enter variable a: ")
b=raw_input("Enter variable b: ")
print addition (a,b)
print subtraction (a,b)
print multiplication (a,b)
print module (a,b)
#addition
#c=int(a)+int(b)
#Output?
#print(c)
#subtraction<|fim▁hole|>#d=int(a)-int(b)
#print(d)
#multiplication
#e=int(a)*int(b)
#print(e)
#module
#f=36%5
#print(f)<|fim▁end|> | |
<|file_name|>tools.py<|end_file_name|><|fim▁begin|>from oauth2_provider.settings import oauth2_settings
from oauthlib.common import generate_token
from django.http import JsonResponse
from oauth2_provider.models import AccessToken, Application, RefreshToken
from django.utils.timezone import now, timedelta
def get_token_json(access_token):
"""
Takes an AccessToken instance as an argument
and returns a JsonResponse instance from that
AccessToken
"""
token = {
'access_token': access_token.token,
'expires_in': oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS,
'token_type': 'Bearer',<|fim▁hole|> }
return JsonResponse(token)
def get_access_token(user):
"""
Takes a user instance and return an access_token as a JsonResponse
instance.
"""
# our oauth2 app
app = Application.objects.get(name="omics")
# We delete the old access_token and refresh_token
try:
old_access_token = AccessToken.objects.get(
user=user, application=app)
old_refresh_token = RefreshToken.objects.get(
user=user, access_token=old_access_token
)
except:
pass
else:
old_access_token.delete()
old_refresh_token.delete()
# we generate an access token
token = generate_token()
# we generate a refresh token
refresh_token = generate_token()
expires = now() + timedelta(seconds=oauth2_settings.
ACCESS_TOKEN_EXPIRE_SECONDS)
scope = "read write"
# we create the access token
access_token = AccessToken.objects.\
create(user=user,
application=app,
expires=expires,
token=token,
scope=scope)
# we create the refresh token
RefreshToken.objects.\
create(user=user,
application=app,
token=refresh_token,
access_token=access_token)
# we call get_token_json and returns the access token as json
return get_token_json(access_token)<|fim▁end|> | 'refresh_token': access_token.refresh_token.token,
'scope': access_token.scope |
<|file_name|>TaskView.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import
from Screens.Screen import Screen
from Components.ConfigList import ConfigListScreen
from Components.config import ConfigSubsection, ConfigSelection, getConfigListEntry
from Components.SystemInfo import SystemInfo
from Components.Task import job_manager
from Screens.InfoBarGenerics import InfoBarNotifications
import Screens.Standby
import Tools.Notifications
from boxbranding import getMachineBrand, getMachineName
class JobView(InfoBarNotifications, Screen, ConfigListScreen):
def __init__(self, session, job, parent=None, cancelable = True, backgroundable = True, afterEventChangeable = True , afterEvent="nothing"):
from Components.Sources.StaticText import StaticText
from Components.Sources.Progress import Progress
from Components.Sources.Boolean import Boolean
from Components.ActionMap import ActionMap
Screen.__init__(self, session, parent)
Screen.setTitle(self, _("Job View"))
InfoBarNotifications.__init__(self)
ConfigListScreen.__init__(self, [])
self.parent = parent
self.job = job
if afterEvent:
self.job.afterEvent = afterEvent
self["job_name"] = StaticText(job.name)
self["job_progress"] = Progress()
self["job_task"] = StaticText()
self["summary_job_name"] = StaticText(job.name)
self["summary_job_progress"] = Progress()
self["summary_job_task"] = StaticText()
self["job_status"] = StaticText()
self["finished"] = Boolean()
self["cancelable"] = Boolean(cancelable)
self["backgroundable"] = Boolean(backgroundable)
self["key_blue"] = StaticText(_("Background"))
self.onShow.append(self.windowShow)
self.onHide.append(self.windowHide)
self["setupActions"] = ActionMap(["ColorActions", "SetupActions"],
{
"green": self.ok,
"red": self.abort,
"blue": self.background,
"cancel": self.abort,
"ok": self.ok,
}, -2)
self.settings = ConfigSubsection()
if SystemInfo["DeepstandbySupport"]:
shutdownString = _("go to deep standby")
else:
shutdownString = _("shut down")
self.settings.afterEvent = ConfigSelection(choices = [("nothing", _("do nothing")), ("close", _("Close")), ("standby", _("go to standby")), ("deepstandby", shutdownString)], default = self.job.afterEvent or "nothing")
self.job.afterEvent = self.settings.afterEvent.value
self.afterEventChangeable = afterEventChangeable
self.setupList()
self.state_changed()
def setupList(self):
if self.afterEventChangeable:
self["config"].setList( [ getConfigListEntry(_("After event"), self.settings.afterEvent) ])
else:
self["config"].hide()
self.job.afterEvent = self.settings.afterEvent.value
def keyLeft(self):
ConfigListScreen.keyLeft(self)
self.setupList()
def keyRight(self):
ConfigListScreen.keyRight(self)
self.setupList()
def windowShow(self):
job_manager.visible = True
self.job.state_changed.append(self.state_changed)
def windowHide(self):
job_manager.visible = False
if len(self.job.state_changed) > 0:
self.job.state_changed.remove(self.state_changed)
def state_changed(self):
j = self.job
self["job_progress"].range = j.end
self["summary_job_progress"].range = j.end
self["job_progress"].value = j.progress
self["summary_job_progress"].value = j.progress
#print "JobView::state_changed:", j.end, j.progress
self["job_status"].text = j.getStatustext()
if j.status == j.IN_PROGRESS:
self["job_task"].text = j.tasks[j.current_task].name
self["summary_job_task"].text = j.tasks[j.current_task].name
else:
self["job_task"].text = ""
self["summary_job_task"].text = j.getStatustext()<|fim▁hole|> self["backgroundable"].boolean = False
if j.status == j.FINISHED:
self["finished"].boolean = True
self["cancelable"].boolean = False
elif j.status == j.FAILED:
self["cancelable"].boolean = True
def background(self):
if self["backgroundable"].boolean:
self.close(True)
def ok(self):
if self.job.status in (self.job.FINISHED, self.job.FAILED):
self.close(False)
else:
self.background()
def abort(self):
if self.job.status == self.job.NOT_STARTED:
job_manager.active_jobs.remove(self.job)
self.close(False)
elif self.job.status == self.job.IN_PROGRESS and self["cancelable"].boolean == True:
self.job.cancel()
else:
self.close(False)
def performAfterEvent(self):
self["config"].hide()
if self.settings.afterEvent.value == "nothing":
return
elif self.settings.afterEvent.value == "close" and self.job.status == self.job.FINISHED:
self.close(False)
from Screens.MessageBox import MessageBox
if self.settings.afterEvent.value == "deepstandby":
if not Screens.Standby.inTryQuitMainloop:
Tools.Notifications.AddNotificationWithCallback(self.sendTryQuitMainloopNotification, MessageBox, _("A sleep timer wants to shut down\nyour %s %s. Shutdown now?") % (getMachineBrand(), getMachineName()), timeout = 20)
elif self.settings.afterEvent.value == "standby":
if not Screens.Standby.inStandby:
Tools.Notifications.AddNotificationWithCallback(self.sendStandbyNotification, MessageBox, _("A sleep timer wants to set your\n%s %s to standby. Do that now?") % (getMachineBrand(), getMachineName()), timeout = 20)
def checkNotifications(self):
InfoBarNotifications.checkNotifications(self)
if not Tools.Notifications.notifications:
if self.settings.afterEvent.value == "close" and self.job.status == self.job.FAILED:
self.close(False)
def sendStandbyNotification(self, answer):
if answer:
Tools.Notifications.AddNotification(Screens.Standby.Standby)
def sendTryQuitMainloopNotification(self, answer):
if answer:
Tools.Notifications.AddNotification(Screens.Standby.TryQuitMainloop, 1)<|fim▁end|> | if j.status in (j.FINISHED, j.FAILED):
self.performAfterEvent() |
<|file_name|>Absorbers.d.ts<|end_file_name|><|fim▁begin|>import type { IContainerPlugin } from "../../Core/Interfaces/IContainerPlugin";
import { Absorber } from "./Absorber";
import { Container } from "../../Core/Container";
import type { Particle } from "../../Core/Particle";
import { ClickMode } from "../../Enums/Modes/ClickMode";
export declare class Absorbers implements IContainerPlugin {
readonly container: Container;
array: Absorber[];
constructor(container: Container);<|fim▁hole|> init(): void;
particleUpdate(particle: Particle, delta: number): void;
draw(context: CanvasRenderingContext2D): void;
stop(): void;
resize(): void;
handleClickMode(mode: ClickMode | string): void;
}<|fim▁end|> | |
<|file_name|>Lusher_Alexander_home_work_3_.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
def add(x, y):
a=1
while a>0:
a = x & y
b = x ^ y
x = b
y = a << 1
return b
def vowel_count(word):
vowels_counter = 0
for letter in word:
if letter.isalpha():
if letter.upper() in 'AEIOUY':
vowels_counter += 1
return vowels_counter
if __name__ == '__main__':
# Assignment N 1
text="Proin eget tortor risus. Cras ultricies ligula sed magna dictum porta. Proin eget tortor risus. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Donec rutrum congue leo eget malesuada."
<|fim▁hole|> list=text.split()
max_vowel_number=0
for i in range(0,len(list)-1):
print "word=",list[i]," number of vowels",vowel_count(list[i])
if vowel_count(list[i])>max_vowel_number:
max_vowel_number=vowel_count(list[i])
print "Maximum number of vowels is",max_vowel_number
# Assignment N 2
text="Proin eget tortor risus. Cras ultricies ligula sed magna dictum porta. Proin eget tortor risus. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Donec rutrum congue leo eget malesuada."
list=text.split()
length=len(list[0])
words=[]
words.append(list[0])
for i in range(1,len(list)-1):
if length<len(list[i]):
length=len(list[i])
words[:] = []
words.append(list[i])
elif length==len(list[i]):
words.append(list[i])
print "maximum length=",length,"words are",words
# Assignment N 3
text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla quis lorem ut libero malesuada feugiat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rutrum congue leo eget malesuada. Cras ultricies ligula sed magna dictum porta."
list=text.split()
i=len(text)-1
mirrored_text=''
while i>=0:
mirrored_text=mirrored_text+(text[i])
i-=1
print mirrored_text
# Assignment N 4
import os
content=dir(os)
content_len=len(content)
for k in range(0,content_len-1):
s="os"+"."+content[k]+".__doc__"
print(eval(s))
import sys
content=dir(sys)
content_len=len(content)
for k in range(0,content_len-1):
s="sys"+"."+content[k]+".__doc__"
print(eval(s))
# Assignment N 5
input=12345
a=str(input)
str_len=len(a)
i=0
total=int(a[i])
while i<str_len-1:
total=add(total,int(a[add(i,1)]))
i=add(i,1)
print total<|fim▁end|> | |
<|file_name|>gaussian_process.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Author: Vincent Dubourg <[email protected]>
# (mostly translation, see implementation details)
# License: BSD 3 clause
from __future__ import print_function
import numpy as np
from scipy import linalg, optimize
from ..base import BaseEstimator, RegressorMixin
from ..metrics.pairwise import manhattan_distances
from ..utils import check_random_state, check_array, check_X_y
from ..utils.validation import check_is_fitted
from . import regression_models as regression
from . import correlation_models as correlation
from ..utils import deprecated
MACHINE_EPSILON = np.finfo(np.double).eps
@deprecated("l1_cross_distances was deprecated in version 0.18 "
"and will be removed in 0.20.")
def l1_cross_distances(X):
"""
Computes the nonzero componentwise L1 cross-distances between the vectors
in X.
Parameters
----------
X: array_like
An array with shape (n_samples, n_features)
Returns
-------
D: array with shape (n_samples * (n_samples - 1) / 2, n_features)
The array of componentwise L1 cross-distances.
ij: arrays with shape (n_samples * (n_samples - 1) / 2, 2)
The indices i and j of the vectors in X associated to the cross-
distances in D: D[k] = np.abs(X[ij[k, 0]] - Y[ij[k, 1]]).
"""
X = check_array(X)
n_samples, n_features = X.shape
n_nonzero_cross_dist = n_samples * (n_samples - 1) // 2
ij = np.zeros((n_nonzero_cross_dist, 2), dtype=np.int)
D = np.zeros((n_nonzero_cross_dist, n_features))
ll_1 = 0
for k in range(n_samples - 1):
ll_0 = ll_1
ll_1 = ll_0 + n_samples - k - 1
ij[ll_0:ll_1, 0] = k
ij[ll_0:ll_1, 1] = np.arange(k + 1, n_samples)
D[ll_0:ll_1] = np.abs(X[k] - X[(k + 1):n_samples])
return D, ij
@deprecated("GaussianProcess was deprecated in version 0.18 and will be "
"removed in 0.20. Use the GaussianProcessRegressor instead.")
class GaussianProcess(BaseEstimator, RegressorMixin):
"""The legacy Gaussian Process model class.
Note that this class was deprecated in version 0.18 and will be
removed in 0.20. Use the GaussianProcessRegressor instead.
Read more in the :ref:`User Guide <gaussian_process>`.
Parameters
----------
regr : string or callable, optional
A regression function returning an array of outputs of the linear
regression functional basis. The number of observations n_samples
should be greater than the size p of this basis.
Default assumes a simple constant regression trend.
Available built-in regression models are::
'constant', 'linear', 'quadratic'
corr : string or callable, optional
A stationary autocorrelation function returning the autocorrelation
between two points x and x'.
Default assumes a squared-exponential autocorrelation model.
Built-in correlation models are::
'absolute_exponential', 'squared_exponential',
'generalized_exponential', 'cubic', 'linear'
beta0 : double array_like, optional
The regression weight vector to perform Ordinary Kriging (OK).
Default assumes Universal Kriging (UK) so that the vector beta of
regression weights is estimated using the maximum likelihood
principle.
storage_mode : string, optional
A string specifying whether the Cholesky decomposition of the
correlation matrix should be stored in the class (storage_mode =
'full') or not (storage_mode = 'light').
Default assumes storage_mode = 'full', so that the
Cholesky decomposition of the correlation matrix is stored.
This might be a useful parameter when one is not interested in the
MSE and only plan to estimate the BLUP, for which the correlation
matrix is not required.
verbose : boolean, optional
A boolean specifying the verbose level.
Default is verbose = False.
theta0 : double array_like, optional
An array with shape (n_features, ) or (1, ).
The parameters in the autocorrelation model.
If thetaL and thetaU are also specified, theta0 is considered as
the starting point for the maximum likelihood estimation of the
best set of parameters.
Default assumes isotropic autocorrelation model with theta0 = 1e-1.
thetaL : double array_like, optional
An array with shape matching theta0's.
Lower bound on the autocorrelation parameters for maximum
likelihood estimation.
Default is None, so that it skips maximum likelihood estimation and
it uses theta0.
thetaU : double array_like, optional
An array with shape matching theta0's.
Upper bound on the autocorrelation parameters for maximum
likelihood estimation.
Default is None, so that it skips maximum likelihood estimation and
it uses theta0.
normalize : boolean, optional
Input X and observations y are centered and reduced wrt
means and standard deviations estimated from the n_samples
observations provided.
Default is normalize = True so that data is normalized to ease
maximum likelihood estimation.
nugget : double or ndarray, optional
Introduce a nugget effect to allow smooth predictions from noisy
data. If nugget is an ndarray, it must be the same length as the
number of data points used for the fit.
The nugget is added to the diagonal of the assumed training covariance;
in this way it acts as a Tikhonov regularization in the problem. In
the special case of the squared exponential correlation function, the
nugget mathematically represents the variance of the input values.
Default assumes a nugget close to machine precision for the sake of
robustness (nugget = 10. * MACHINE_EPSILON).
optimizer : string, optional
A string specifying the optimization algorithm to be used.
Default uses 'fmin_cobyla' algorithm from scipy.optimize.
Available optimizers are::
'fmin_cobyla', 'Welch'
'Welch' optimizer is dued to Welch et al., see reference [WBSWM1992]_.
It consists in iterating over several one-dimensional optimizations
instead of running one single multi-dimensional optimization.<|fim▁hole|>
random_start : int, optional
The number of times the Maximum Likelihood Estimation should be
performed from a random starting point.
The first MLE always uses the specified starting point (theta0),
the next starting points are picked at random according to an
exponential distribution (log-uniform on [thetaL, thetaU]).
Default does not use random starting point (random_start = 1).
random_state: integer or numpy.RandomState, optional
The generator used to shuffle the sequence of coordinates of theta in
the Welch optimizer. If an integer is given, it fixes the seed.
Defaults to the global numpy random number generator.
Attributes
----------
theta_ : array
Specified theta OR the best set of autocorrelation parameters (the \
sought maximizer of the reduced likelihood function).
reduced_likelihood_function_value_ : array
The optimal reduced likelihood function value.
Examples
--------
>>> import numpy as np
>>> from sklearn.gaussian_process import GaussianProcess
>>> X = np.array([[1., 3., 5., 6., 7., 8.]]).T
>>> y = (X * np.sin(X)).ravel()
>>> gp = GaussianProcess(theta0=0.1, thetaL=.001, thetaU=1.)
>>> gp.fit(X, y) # doctest: +ELLIPSIS
GaussianProcess(beta0=None...
...
Notes
-----
The presentation implementation is based on a translation of the DACE
Matlab toolbox, see reference [NLNS2002]_.
References
----------
.. [NLNS2002] `H.B. Nielsen, S.N. Lophaven, H. B. Nielsen and J.
Sondergaard. DACE - A MATLAB Kriging Toolbox.` (2002)
http://imedea.uib-csic.es/master/cambioglobal/Modulo_V_cod101615/Lab/lab_maps/krigging/DACE-krigingsoft/dace/dace.pdf
.. [WBSWM1992] `W.J. Welch, R.J. Buck, J. Sacks, H.P. Wynn, T.J. Mitchell,
and M.D. Morris (1992). Screening, predicting, and computer
experiments. Technometrics, 34(1) 15--25.`
http://www.jstor.org/stable/1269548
"""
_regression_types = {
'constant': regression.constant,
'linear': regression.linear,
'quadratic': regression.quadratic}
_correlation_types = {
'absolute_exponential': correlation.absolute_exponential,
'squared_exponential': correlation.squared_exponential,
'generalized_exponential': correlation.generalized_exponential,
'cubic': correlation.cubic,
'linear': correlation.linear}
_optimizer_types = [
'fmin_cobyla',
'Welch']
def __init__(self, regr='constant', corr='squared_exponential', beta0=None,
storage_mode='full', verbose=False, theta0=1e-1,
thetaL=None, thetaU=None, optimizer='fmin_cobyla',
random_start=1, normalize=True,
nugget=10. * MACHINE_EPSILON, random_state=None):
self.regr = regr
self.corr = corr
self.beta0 = beta0
self.storage_mode = storage_mode
self.verbose = verbose
self.theta0 = theta0
self.thetaL = thetaL
self.thetaU = thetaU
self.normalize = normalize
self.nugget = nugget
self.optimizer = optimizer
self.random_start = random_start
self.random_state = random_state
def fit(self, X, y):
"""
The Gaussian Process model fitting method.
Parameters
----------
X : double array_like
An array with shape (n_samples, n_features) with the input at which
observations were made.
y : double array_like
An array with shape (n_samples, ) or shape (n_samples, n_targets)
with the observations of the output to be predicted.
Returns
-------
gp : self
A fitted Gaussian Process model object awaiting data to perform
predictions.
"""
# Run input checks
self._check_params()
self.random_state = check_random_state(self.random_state)
# Force data to 2D numpy.array
X, y = check_X_y(X, y, multi_output=True, y_numeric=True)
self.y_ndim_ = y.ndim
if y.ndim == 1:
y = y[:, np.newaxis]
# Check shapes of DOE & observations
n_samples, n_features = X.shape
_, n_targets = y.shape
# Run input checks
self._check_params(n_samples)
# Normalize data or don't
if self.normalize:
X_mean = np.mean(X, axis=0)
X_std = np.std(X, axis=0)
y_mean = np.mean(y, axis=0)
y_std = np.std(y, axis=0)
X_std[X_std == 0.] = 1.
y_std[y_std == 0.] = 1.
# center and scale X if necessary
X = (X - X_mean) / X_std
y = (y - y_mean) / y_std
else:
X_mean = np.zeros(1)
X_std = np.ones(1)
y_mean = np.zeros(1)
y_std = np.ones(1)
# Calculate matrix of distances D between samples
D, ij = l1_cross_distances(X)
if (np.min(np.sum(D, axis=1)) == 0.
and self.corr != correlation.pure_nugget):
raise Exception("Multiple input features cannot have the same"
" target value.")
# Regression matrix and parameters
F = self.regr(X)
n_samples_F = F.shape[0]
if F.ndim > 1:
p = F.shape[1]
else:
p = 1
if n_samples_F != n_samples:
raise Exception("Number of rows in F and X do not match. Most "
"likely something is going wrong with the "
"regression model.")
if p > n_samples_F:
raise Exception(("Ordinary least squares problem is undetermined "
"n_samples=%d must be greater than the "
"regression model size p=%d.") % (n_samples, p))
if self.beta0 is not None:
if self.beta0.shape[0] != p:
raise Exception("Shapes of beta0 and F do not match.")
# Set attributes
self.X = X
self.y = y
self.D = D
self.ij = ij
self.F = F
self.X_mean, self.X_std = X_mean, X_std
self.y_mean, self.y_std = y_mean, y_std
# Determine Gaussian Process model parameters
if self.thetaL is not None and self.thetaU is not None:
# Maximum Likelihood Estimation of the parameters
if self.verbose:
print("Performing Maximum Likelihood Estimation of the "
"autocorrelation parameters...")
self.theta_, self.reduced_likelihood_function_value_, par = \
self._arg_max_reduced_likelihood_function()
if np.isinf(self.reduced_likelihood_function_value_):
raise Exception("Bad parameter region. "
"Try increasing upper bound")
else:
# Given parameters
if self.verbose:
print("Given autocorrelation parameters. "
"Computing Gaussian Process model parameters...")
self.theta_ = self.theta0
self.reduced_likelihood_function_value_, par = \
self.reduced_likelihood_function()
if np.isinf(self.reduced_likelihood_function_value_):
raise Exception("Bad point. Try increasing theta0.")
self.beta = par['beta']
self.gamma = par['gamma']
self.sigma2 = par['sigma2']
self.C = par['C']
self.Ft = par['Ft']
self.G = par['G']
if self.storage_mode == 'light':
# Delete heavy data (it will be computed again if required)
# (it is required only when MSE is wanted in self.predict)
if self.verbose:
print("Light storage mode specified. "
"Flushing autocorrelation matrix...")
self.D = None
self.ij = None
self.F = None
self.C = None
self.Ft = None
self.G = None
return self
def predict(self, X, eval_MSE=False, batch_size=None):
"""
This function evaluates the Gaussian Process model at x.
Parameters
----------
X : array_like
An array with shape (n_eval, n_features) giving the point(s) at
which the prediction(s) should be made.
eval_MSE : boolean, optional
A boolean specifying whether the Mean Squared Error should be
evaluated or not.
Default assumes evalMSE = False and evaluates only the BLUP (mean
prediction).
batch_size : integer, optional
An integer giving the maximum number of points that can be
evaluated simultaneously (depending on the available memory).
Default is None so that all given points are evaluated at the same
time.
Returns
-------
y : array_like, shape (n_samples, ) or (n_samples, n_targets)
An array with shape (n_eval, ) if the Gaussian Process was trained
on an array of shape (n_samples, ) or an array with shape
(n_eval, n_targets) if the Gaussian Process was trained on an array
of shape (n_samples, n_targets) with the Best Linear Unbiased
Prediction at x.
MSE : array_like, optional (if eval_MSE == True)
An array with shape (n_eval, ) or (n_eval, n_targets) as with y,
with the Mean Squared Error at x.
"""
check_is_fitted(self, "X")
# Check input shapes
X = check_array(X)
n_eval, _ = X.shape
n_samples, n_features = self.X.shape
n_samples_y, n_targets = self.y.shape
# Run input checks
self._check_params(n_samples)
if X.shape[1] != n_features:
raise ValueError(("The number of features in X (X.shape[1] = %d) "
"should match the number of features used "
"for fit() "
"which is %d.") % (X.shape[1], n_features))
if batch_size is None:
# No memory management
# (evaluates all given points in a single batch run)
# Normalize input
X = (X - self.X_mean) / self.X_std
# Initialize output
y = np.zeros(n_eval)
if eval_MSE:
MSE = np.zeros(n_eval)
# Get pairwise componentwise L1-distances to the input training set
dx = manhattan_distances(X, Y=self.X, sum_over_features=False)
# Get regression function and correlation
f = self.regr(X)
r = self.corr(self.theta_, dx).reshape(n_eval, n_samples)
# Scaled predictor
y_ = np.dot(f, self.beta) + np.dot(r, self.gamma)
# Predictor
y = (self.y_mean + self.y_std * y_).reshape(n_eval, n_targets)
if self.y_ndim_ == 1:
y = y.ravel()
# Mean Squared Error
if eval_MSE:
C = self.C
if C is None:
# Light storage mode (need to recompute C, F, Ft and G)
if self.verbose:
print("This GaussianProcess used 'light' storage mode "
"at instantiation. Need to recompute "
"autocorrelation matrix...")
reduced_likelihood_function_value, par = \
self.reduced_likelihood_function()
self.C = par['C']
self.Ft = par['Ft']
self.G = par['G']
rt = linalg.solve_triangular(self.C, r.T, lower=True)
if self.beta0 is None:
# Universal Kriging
u = linalg.solve_triangular(self.G.T,
np.dot(self.Ft.T, rt) - f.T,
lower=True)
else:
# Ordinary Kriging
u = np.zeros((n_targets, n_eval))
MSE = np.dot(self.sigma2.reshape(n_targets, 1),
(1. - (rt ** 2.).sum(axis=0)
+ (u ** 2.).sum(axis=0))[np.newaxis, :])
MSE = np.sqrt((MSE ** 2.).sum(axis=0) / n_targets)
# Mean Squared Error might be slightly negative depending on
# machine precision: force to zero!
MSE[MSE < 0.] = 0.
if self.y_ndim_ == 1:
MSE = MSE.ravel()
return y, MSE
else:
return y
else:
# Memory management
if type(batch_size) is not int or batch_size <= 0:
raise Exception("batch_size must be a positive integer")
if eval_MSE:
y, MSE = np.zeros(n_eval), np.zeros(n_eval)
for k in range(max(1, n_eval / batch_size)):
batch_from = k * batch_size
batch_to = min([(k + 1) * batch_size + 1, n_eval + 1])
y[batch_from:batch_to], MSE[batch_from:batch_to] = \
self.predict(X[batch_from:batch_to],
eval_MSE=eval_MSE, batch_size=None)
return y, MSE
else:
y = np.zeros(n_eval)
for k in range(max(1, n_eval / batch_size)):
batch_from = k * batch_size
batch_to = min([(k + 1) * batch_size + 1, n_eval + 1])
y[batch_from:batch_to] = \
self.predict(X[batch_from:batch_to],
eval_MSE=eval_MSE, batch_size=None)
return y
def reduced_likelihood_function(self, theta=None):
"""
This function determines the BLUP parameters and evaluates the reduced
likelihood function for the given autocorrelation parameters theta.
Maximizing this function wrt the autocorrelation parameters theta is
equivalent to maximizing the likelihood of the assumed joint Gaussian
distribution of the observations y evaluated onto the design of
experiments X.
Parameters
----------
theta : array_like, optional
An array containing the autocorrelation parameters at which the
Gaussian Process model parameters should be determined.
Default uses the built-in autocorrelation parameters
(ie ``theta = self.theta_``).
Returns
-------
reduced_likelihood_function_value : double
The value of the reduced likelihood function associated to the
given autocorrelation parameters theta.
par : dict
A dictionary containing the requested Gaussian Process model
parameters:
sigma2
Gaussian Process variance.
beta
Generalized least-squares regression weights for
Universal Kriging or given beta0 for Ordinary
Kriging.
gamma
Gaussian Process weights.
C
Cholesky decomposition of the correlation matrix [R].
Ft
Solution of the linear equation system : [R] x Ft = F
G
QR decomposition of the matrix Ft.
"""
check_is_fitted(self, "X")
if theta is None:
# Use built-in autocorrelation parameters
theta = self.theta_
# Initialize output
reduced_likelihood_function_value = - np.inf
par = {}
# Retrieve data
n_samples = self.X.shape[0]
D = self.D
ij = self.ij
F = self.F
if D is None:
# Light storage mode (need to recompute D, ij and F)
D, ij = l1_cross_distances(self.X)
if (np.min(np.sum(D, axis=1)) == 0.
and self.corr != correlation.pure_nugget):
raise Exception("Multiple X are not allowed")
F = self.regr(self.X)
# Set up R
r = self.corr(theta, D)
R = np.eye(n_samples) * (1. + self.nugget)
R[ij[:, 0], ij[:, 1]] = r
R[ij[:, 1], ij[:, 0]] = r
# Cholesky decomposition of R
try:
C = linalg.cholesky(R, lower=True)
except linalg.LinAlgError:
return reduced_likelihood_function_value, par
# Get generalized least squares solution
Ft = linalg.solve_triangular(C, F, lower=True)
try:
Q, G = linalg.qr(Ft, econ=True)
except:
#/usr/lib/python2.6/dist-packages/scipy/linalg/decomp.py:1177:
# DeprecationWarning: qr econ argument will be removed after scipy
# 0.7. The economy transform will then be available through the
# mode='economic' argument.
Q, G = linalg.qr(Ft, mode='economic')
sv = linalg.svd(G, compute_uv=False)
rcondG = sv[-1] / sv[0]
if rcondG < 1e-10:
# Check F
sv = linalg.svd(F, compute_uv=False)
condF = sv[0] / sv[-1]
if condF > 1e15:
raise Exception("F is too ill conditioned. Poor combination "
"of regression model and observations.")
else:
# Ft is too ill conditioned, get out (try different theta)
return reduced_likelihood_function_value, par
Yt = linalg.solve_triangular(C, self.y, lower=True)
if self.beta0 is None:
# Universal Kriging
beta = linalg.solve_triangular(G, np.dot(Q.T, Yt))
else:
# Ordinary Kriging
beta = np.array(self.beta0)
rho = Yt - np.dot(Ft, beta)
sigma2 = (rho ** 2.).sum(axis=0) / n_samples
# The determinant of R is equal to the squared product of the diagonal
# elements of its Cholesky decomposition C
detR = (np.diag(C) ** (2. / n_samples)).prod()
# Compute/Organize output
reduced_likelihood_function_value = - sigma2.sum() * detR
par['sigma2'] = sigma2 * self.y_std ** 2.
par['beta'] = beta
par['gamma'] = linalg.solve_triangular(C.T, rho)
par['C'] = C
par['Ft'] = Ft
par['G'] = G
return reduced_likelihood_function_value, par
def _arg_max_reduced_likelihood_function(self):
"""
This function estimates the autocorrelation parameters theta as the
maximizer of the reduced likelihood function.
(Minimization of the opposite reduced likelihood function is used for
convenience)
Parameters
----------
self : All parameters are stored in the Gaussian Process model object.
Returns
-------
optimal_theta : array_like
The best set of autocorrelation parameters (the sought maximizer of
the reduced likelihood function).
optimal_reduced_likelihood_function_value : double
The optimal reduced likelihood function value.
optimal_par : dict
The BLUP parameters associated to thetaOpt.
"""
# Initialize output
best_optimal_theta = []
best_optimal_rlf_value = []
best_optimal_par = []
if self.verbose:
print("The chosen optimizer is: " + str(self.optimizer))
if self.random_start > 1:
print(str(self.random_start) + " random starts are required.")
percent_completed = 0.
# Force optimizer to fmin_cobyla if the model is meant to be isotropic
if self.optimizer == 'Welch' and self.theta0.size == 1:
self.optimizer = 'fmin_cobyla'
if self.optimizer == 'fmin_cobyla':
def minus_reduced_likelihood_function(log10t):
return - self.reduced_likelihood_function(
theta=10. ** log10t)[0]
constraints = []
for i in range(self.theta0.size):
constraints.append(lambda log10t, i=i:
log10t[i] - np.log10(self.thetaL[0, i]))
constraints.append(lambda log10t, i=i:
np.log10(self.thetaU[0, i]) - log10t[i])
for k in range(self.random_start):
if k == 0:
# Use specified starting point as first guess
theta0 = self.theta0
else:
# Generate a random starting point log10-uniformly
# distributed between bounds
log10theta0 = (np.log10(self.thetaL)
+ self.random_state.rand(*self.theta0.shape)
* np.log10(self.thetaU / self.thetaL))
theta0 = 10. ** log10theta0
# Run Cobyla
try:
log10_optimal_theta = \
optimize.fmin_cobyla(minus_reduced_likelihood_function,
np.log10(theta0).ravel(), constraints,
iprint=0)
except ValueError as ve:
print("Optimization failed. Try increasing the ``nugget``")
raise ve
optimal_theta = 10. ** log10_optimal_theta
optimal_rlf_value, optimal_par = \
self.reduced_likelihood_function(theta=optimal_theta)
# Compare the new optimizer to the best previous one
if k > 0:
if optimal_rlf_value > best_optimal_rlf_value:
best_optimal_rlf_value = optimal_rlf_value
best_optimal_par = optimal_par
best_optimal_theta = optimal_theta
else:
best_optimal_rlf_value = optimal_rlf_value
best_optimal_par = optimal_par
best_optimal_theta = optimal_theta
if self.verbose and self.random_start > 1:
if (20 * k) / self.random_start > percent_completed:
percent_completed = (20 * k) / self.random_start
print("%s completed" % (5 * percent_completed))
optimal_rlf_value = best_optimal_rlf_value
optimal_par = best_optimal_par
optimal_theta = best_optimal_theta
elif self.optimizer == 'Welch':
# Backup of the given attributes
theta0, thetaL, thetaU = self.theta0, self.thetaL, self.thetaU
corr = self.corr
verbose = self.verbose
# This will iterate over fmin_cobyla optimizer
self.optimizer = 'fmin_cobyla'
self.verbose = False
# Initialize under isotropy assumption
if verbose:
print("Initialize under isotropy assumption...")
self.theta0 = check_array(self.theta0.min())
self.thetaL = check_array(self.thetaL.min())
self.thetaU = check_array(self.thetaU.max())
theta_iso, optimal_rlf_value_iso, par_iso = \
self._arg_max_reduced_likelihood_function()
optimal_theta = theta_iso + np.zeros(theta0.shape)
# Iterate over all dimensions of theta allowing for anisotropy
if verbose:
print("Now improving allowing for anisotropy...")
for i in self.random_state.permutation(theta0.size):
if verbose:
print("Proceeding along dimension %d..." % (i + 1))
self.theta0 = check_array(theta_iso)
self.thetaL = check_array(thetaL[0, i])
self.thetaU = check_array(thetaU[0, i])
def corr_cut(t, d):
return corr(check_array(np.hstack([optimal_theta[0][0:i],
t[0],
optimal_theta[0][(i +
1)::]])),
d)
self.corr = corr_cut
optimal_theta[0, i], optimal_rlf_value, optimal_par = \
self._arg_max_reduced_likelihood_function()
# Restore the given attributes
self.theta0, self.thetaL, self.thetaU = theta0, thetaL, thetaU
self.corr = corr
self.optimizer = 'Welch'
self.verbose = verbose
else:
raise NotImplementedError("This optimizer ('%s') is not "
"implemented yet. Please contribute!"
% self.optimizer)
return optimal_theta, optimal_rlf_value, optimal_par
def _check_params(self, n_samples=None):
# Check regression model
if not callable(self.regr):
if self.regr in self._regression_types:
self.regr = self._regression_types[self.regr]
else:
raise ValueError("regr should be one of %s or callable, "
"%s was given."
% (self._regression_types.keys(), self.regr))
# Check regression weights if given (Ordinary Kriging)
if self.beta0 is not None:
self.beta0 = np.atleast_2d(self.beta0)
if self.beta0.shape[1] != 1:
# Force to column vector
self.beta0 = self.beta0.T
# Check correlation model
if not callable(self.corr):
if self.corr in self._correlation_types:
self.corr = self._correlation_types[self.corr]
else:
raise ValueError("corr should be one of %s or callable, "
"%s was given."
% (self._correlation_types.keys(), self.corr))
# Check storage mode
if self.storage_mode != 'full' and self.storage_mode != 'light':
raise ValueError("Storage mode should either be 'full' or "
"'light', %s was given." % self.storage_mode)
# Check correlation parameters
self.theta0 = np.atleast_2d(self.theta0)
lth = self.theta0.size
if self.thetaL is not None and self.thetaU is not None:
self.thetaL = np.atleast_2d(self.thetaL)
self.thetaU = np.atleast_2d(self.thetaU)
if self.thetaL.size != lth or self.thetaU.size != lth:
raise ValueError("theta0, thetaL and thetaU must have the "
"same length.")
if np.any(self.thetaL <= 0) or np.any(self.thetaU < self.thetaL):
raise ValueError("The bounds must satisfy O < thetaL <= "
"thetaU.")
elif self.thetaL is None and self.thetaU is None:
if np.any(self.theta0 <= 0):
raise ValueError("theta0 must be strictly positive.")
elif self.thetaL is None or self.thetaU is None:
raise ValueError("thetaL and thetaU should either be both or "
"neither specified.")
# Force verbose type to bool
self.verbose = bool(self.verbose)
# Force normalize type to bool
self.normalize = bool(self.normalize)
# Check nugget value
self.nugget = np.asarray(self.nugget)
if np.any(self.nugget) < 0.:
raise ValueError("nugget must be positive or zero.")
if (n_samples is not None
and self.nugget.shape not in [(), (n_samples,)]):
raise ValueError("nugget must be either a scalar "
"or array of length n_samples.")
# Check optimizer
if self.optimizer not in self._optimizer_types:
raise ValueError("optimizer should be one of %s"
% self._optimizer_types)
# Force random_start type to int
self.random_start = int(self.random_start)<|fim▁end|> | |
<|file_name|>show_top_players.py<|end_file_name|><|fim▁begin|>import sys
from django.core.management.base import BaseCommand, CommandError
import nflgame
from terminaltables import AsciiTable
from ...models import Player, Team, Season, Week, WeeklyStats
<|fim▁hole|>
class Command(BaseCommand):
help = 'takes option position, displays top players as table'
def add_arguments(self, parser):
# Named (optional) arguments
parser.add_argument('position', nargs=1)
def handle(self, *args, **options):
p = options['position']
if p:
Player.show_top_players(position=p[0])
else:
Player.show_top_players()<|fim▁end|> | |
<|file_name|>DkBygningDa.py<|end_file_name|><|fim▁begin|>from Monument import Monument, Dataset
import importer_utils as utils
import importer as importer
class DkBygningDa(Monument):
def set_adm_location(self):
if self.has_non_empty_attribute("kommune"):
if utils.count_wikilinks(self.kommune) == 1:
adm_location = utils.q_from_first_wikilink("da", self.kommune)
self.add_statement("located_adm", adm_location)
def set_location(self):
"""
Set location based on 'by' column.
If there's one wikilinked item, confirm that
the corresponding WD item is of a type that's
a subclass of 'human settlement', using query results
downloaded by importer.
If not wikilinked, check if there's a dawp article
with the same name and do the same check.
"""
place_item = None
if self.has_non_empty_attribute("by"):
place = self.by
if utils.count_wikilinks(place) == 1:<|fim▁hole|> if place_item:
place_item_ids = utils.get_P31(place_item, self.repo)
for p31_value in place_item_ids:
if p31_value in self.data_files["settlement"]:
self.add_statement("location", place_item)
# there can be more than one P31, but after first positive
# we can leave
return
def set_sagsnr(self):
"""Danish listed buildings case ID (P2783)."""
self.add_statement("listed_building_dk", str(self.sagsnr))
def update_labels(self):
self.add_label("da", utils.remove_markup(self.sagsnavn))
def set_address(self):
"""
Set address of object.
self.addresse is always streetname + number.
self.postnr is always zipcode
self.by is always placename.
"""
if self.has_non_empty_attribute("adresse"):
address = self.adresse + " " + self.postnr + " " + self.by
self.add_statement("located_street", address)
def set_inception(self):
if self.has_non_empty_attribute("opforelsesar"):
inception = utils.parse_year(self.opforelsesar)
if isinstance(inception, int):
self.add_statement(
"inception", utils.package_time({"year": inception}))
def set_monuments_all_id(self):
"""Map monuments_all ID to fields in this table."""
self.monuments_all_id = "{!s}-{!s}-{!s}".format(
self.kommunenr, self.ejendomsnr, self.bygningsnr)
def __init__(self, db_row_dict, mapping, data_files, existing):
Monument.__init__(self, db_row_dict, mapping, data_files, existing)
self.set_monuments_all_id()
self.update_labels()
self.exists("da")
self.set_commonscat()
self.set_image("billede")
self.set_coords(("lat", "lon"))
self.set_adm_location()
self.set_location()
self.set_sagsnr()
self.set_address()
self.set_inception()
self.exists_with_prop(mapping)
self.print_wd()
if __name__ == "__main__":
"""Point of entrance for importer."""
args = importer.handle_args()
dataset = Dataset("dk-bygninger", "da", DkBygningDa)
dataset.subclass_downloads = {"settlement": "Q486972"}
importer.main(args, dataset)<|fim▁end|> | place = utils.get_wikilinks(place)[0].title
if utils.wp_page_exists("da", place):
place_item = utils.q_from_wikipedia("da", place) |
<|file_name|>OptionGuiLogger.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2008 Google 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
*
* 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 com.google.gwt.dev.util.arg;
/**
* Option to set whether to use a GUI logger instead of stdout.<|fim▁hole|>public interface OptionGuiLogger {
/**
* Returns true if a GUI logger should be used.
*/
boolean isUseGuiLogger();
/**
* Sets whether or not to use a GUI logger.
*/
void setUseGuiLogger(boolean useGuiLogger);
}<|fim▁end|> | */ |
<|file_name|>__openerp__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Author: Yannick Vaucher
# Copyright 2013 Camptocamp SA
#
# 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/>.
#
##############################################################################
{'name': 'Report to printer - Paper tray selection',
'version': '8.0.1.0.1',
'category': 'Printer',
'author': "Camptocamp,Odoo Community Association (OCA)",
'maintainer': 'Camptocamp',
'website': 'http://www.camptocamp.com/',
'license': 'AGPL-3',
'depends': ['base_report_to_printer',
],
'data': [
'users_view.xml',
'ir_report_view.xml',
'printer_view.xml',
'report_xml_action_view.xml',<|fim▁hole|> 'external_dependencies': {
'python': ['cups'],
},
'installable': True,
'auto_install': False,
'application': True,
}<|fim▁end|> | 'security/ir.model.access.csv',
], |
<|file_name|>TransmissionCleanUp.py<|end_file_name|><|fim▁begin|>from datetime import datetime as dt
from functools import reduce
import transmissionrpc
from config import config
TRANSMISSION_ENABLED = config['TRANSMISSION_ENABLED']
TRANS_HOST = config['TRANS_HOST']
TRANS_PORT = config['TRANS_PORT']
TRANS_USER = config['TRANS_USER']
TRANS_PASS = config['TRANS_PASS']
TRANS_PUBLIC_RATIO_LIMIT = config['TRANS_PUBLIC_RATIO_LIMIT']
TRANS_ANIME_RATIO_LIMIT = config['TRANS_ANIME_RATIO_LIMIT']
def update_nyaa_torrents(host, port, user, password, ratio=TRANS_ANIME_RATIO_LIMIT):
tc = transmissionrpc.Client(host, port=port, user=user, password=password)
# All torrents
torrents = tc.get_torrents()
# Only public torrents
torrents = filter(lambda t: not t.isPrivate, torrents)
# Only torrents with matching trackers
trackers = ['nyaa', 'wakku']
torrents = list(filter(lambda t: reduce(lambda result, x: result or any(s in x['announce'] for s in trackers), t.trackers, False) is True, torrents))
# Torrent ids
ids = list(map(lambda t: t.id, torrents))
<|fim▁hole|> if ids:
tc.change_torrent(ids, seedRatioLimit=ratio, seedRatioMode=1)
return ids
def update_global_ratio_public_torrents(host, port, user, password, ratio):
tc = transmissionrpc.Client(host, port=port, user=user, password=password)
# All torrents
torrents = tc.get_torrents()
# Only public torrents with a global seed ratio mode
torrents = filter(lambda t: not t.isPrivate and t.seed_ratio_mode == 'global', torrents)
# Torrent ids
ids = list(map(lambda t: t.id, torrents))
# Update torrents seed ratio limit and mode
if ids:
tc.change_torrent(ids, seedRatioLimit=ratio, seedRatioMode=1)
return ids
def stop_completed_public_seeding_torrents(host, port, user, password):
tc = transmissionrpc.Client(host, port=port, user=user, password=password)
# All torrents
torrents = tc.get_torrents()
# Only public, seeding torrents
torrents = filter(lambda t: not t.isPrivate and t.status == 'seeding' and t.seed_ratio_mode == 'global', torrents)
# Torrent ids
ids = list(map(lambda t: t.id, torrents))
# Stop torrents
if ids:
tc.stop_torrent(ids)
return ids
def delete_completed_public_stopped_torrents(host, port, user, password):
tc = transmissionrpc.Client(host, port=port, user=user, password=password)
# All torrents
torrents = tc.get_torrents()
# Only public, seeding torrents
torrents = filter(lambda t: not t.isPrivate and t.status == 'stopped', torrents)
# Torrents that are at least 2 hours complete
torrents = filter(lambda t: (dt.now() - t.date_done).seconds > 7200, torrents)
# Torrent ids
ids = list(map(lambda t: t.id, torrents))
# Stop torrents
if ids:
tc.remove_torrent(ids, delete_data=True)
return ids
num_changed = len(update_global_ratio_public_torrents(TRANS_HOST, TRANS_PORT, TRANS_USER, TRANS_PASS, TRANS_PUBLIC_RATIO_LIMIT))
num_changed += len(update_nyaa_torrents(TRANS_HOST, TRANS_PORT, TRANS_USER, TRANS_PASS, TRANS_ANIME_RATIO_LIMIT))
num_stopped = len(stop_completed_public_seeding_torrents(TRANS_HOST, TRANS_PORT, TRANS_USER, TRANS_PASS))
num_deleted = len(delete_completed_public_stopped_torrents(TRANS_HOST, TRANS_PORT, TRANS_USER, TRANS_PASS))
print("[%s] Torrents changed: %d; stopped: %d; deleted: %d" % (dt.now().strftime('%Y-%m-%d %H:%M:%S'), num_changed, num_stopped, num_deleted))<|fim▁end|> | # Update torrents seed ratio limit and mode |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>"""Utility functions"""<|fim▁hole|>def get_diff(str1, str2):
"""Returns git-diff-like diff between two strings"""
expected = str1.splitlines(1)
actual = str2.splitlines(1)
diff = difflib.unified_diff(expected, actual, lineterm=-0, n=0)
return ''.join(diff)
def ensure_directory(path):
"""Creates the given directory, if not existing"""
os.makedirs(path, exist_ok=True)
def ensure_directory_of_file(file_path):
"""Creates the parent directory of a given file path, if not existing"""
ensure_directory(os.path.dirname(file_path))
def check_service_name(service_name):
"""Raises an exception if service_name is not valid"""
service_name_errors = get_service_name_errors(service_name)
if service_name_errors:
raise Exception('errors: %s' % str(service_name_errors))
def get_service_name_errors(service_name):
"""Checks if service_name is valid and returns errors if it is not.
Returns None if service_name is valid"""
errors = []
legal_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\\'
for index in range(len(service_name)):
if not service_name[index] in legal_characters:
errors.append('Illegal character in service name: %s at position %s'
% (service_name[index], index))
return errors<|fim▁end|> |
import os
import difflib
|
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>pub mod checksum;
use crate::checksum::Result;
use pretty_toa::ThousandsSep;
use std::io::Write;
use std::path::PathBuf;
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
pub fn print_res(samples: &[i64; 32]) {
let mut stdout = StandardStream::stdout(ColorChoice::Always);
let min = samples.iter().min().unwrap();
let max = samples.iter().max().unwrap();
let avg: i64 = samples.iter().sum::<i64>() / samples.len() as i64;
let stddev = (samples
.iter()
.map(|v| (v - avg) as f64)
.map(|v| v * v)
.sum::<f64>()
/ (samples.len() - 1) as f64)
.sqrt() as i64;<|fim▁hole|> .set_color(ColorSpec::new().set_fg(Some(Color::White)))
.unwrap();
write!(&mut stdout, "---- ").unwrap();
stdout
.set_color(ColorSpec::new().set_fg(Some(Color::Green)))
.unwrap();
write!(&mut stdout, "Min: {}", min.thousands_sep()).unwrap();
stdout
.set_color(ColorSpec::new().set_fg(Some(Color::White)))
.unwrap();
write!(&mut stdout, " | ").unwrap();
stdout
.set_color(ColorSpec::new().set_fg(Some(Color::Red)))
.unwrap();
write!(&mut stdout, "Max: {}", max.thousands_sep()).unwrap();
stdout
.set_color(ColorSpec::new().set_fg(Some(Color::White)))
.unwrap();
write!(&mut stdout, " | ").unwrap();
stdout
.set_color(ColorSpec::new().set_fg(Some(Color::Yellow)))
.unwrap();
writeln!(&mut stdout, "Avg: {}", avg.thousands_sep()).unwrap();
stdout
.set_color(ColorSpec::new().set_fg(Some(Color::White)))
.unwrap();
write!(&mut stdout, "---- ").unwrap();
stdout
.set_color(ColorSpec::new().set_fg(Some(Color::Magenta)))
.unwrap();
writeln!(&mut stdout, "Std. Deviation: {} ", stddev.thousands_sep()).unwrap();
}
pub fn bench_checksum(msg: String, songs: &Vec<PathBuf>, f: &dyn Fn(&PathBuf) -> Result) {
let mut stdout = StandardStream::stdout(ColorChoice::Always);
stdout
.set_color(ColorSpec::new().set_fg(Some(Color::White)))
.unwrap();
writeln!(&mut stdout, "{}", msg).unwrap();
for song in songs {
let mut sample_times = [0i64; 32];
let mut hashes: Vec<checksum::Checksum> = Vec::with_capacity(sample_times.len());
stdout
.set_color(ColorSpec::new().set_fg(Some(Color::White)))
.unwrap();
writeln!(&mut stdout, "-- File: {:?}", song).unwrap();
for sample_time in &mut sample_times {
let start = time::PreciseTime::now();
let check = match f(song) {
Err(why) => panic!("{}", why),
Ok(check) => check,
};
let end = time::PreciseTime::now();
*sample_time = start.to(end).num_nanoseconds().unwrap();
hashes.push(check);
}
hashes.dedup();
if hashes.len() != 1 {
panic!("Bug! Inconsistent hash calculation.\n Hashes: {:?}", hashes)
}
stdout
.set_color(ColorSpec::new().set_fg(Some(Color::White)))
.unwrap();
write!(&mut stdout, "---- ").unwrap();
stdout
.set_color(ColorSpec::new().set_fg(Some(Color::Blue)))
.unwrap();
writeln!(&mut stdout, "Hash: {}", hashes[0]).unwrap();
print_res(&sample_times);
}
}<|fim▁end|> | stdout |
<|file_name|>main-for-windows.py<|end_file_name|><|fim▁begin|># This script is actually for Cyber Security on Windows 7. Should mostly work
# for Windows 8 and 10 too. I just absolutely hate using Windows 8 and refuse
# to test it on any Windows 8 machine.
from __future__ import print_function
from subprocess import call
from subprocess import check_output
import os
############################# User Management #############################
# Get username
username = os.getenv('username')
# Make alphanumeric variable
alpha = 'abcdefghijklmnopqrstuvwxyz'
numbers = '1234567890'
alpha_numeric = alpha + alpha.upper() + numbers
registry_commands = open("commands.txt", "r")
# Initialize important variables
users = []
incoming_user = ''
times_through = 1
temp_users = str(check_output('net user'))
for not_allowed_characters in '"/\[]:;|=,+*?<>':
temp_users.replace(not_allowed_characters, '')
temp_users.replace("\r\n","")
temp_users.replace("\r","")
temp_users.replace("\n","")
# " / \ [ ] : ; | = , + * ? < > are the characters not allowed in usernames
# Get a list of all users on the system
for character in temp_users:
if character in alpha_numeric or character in "-#\'.!@$%^&()}{":
incoming_user += character
elif len(incoming_user) > 0:
if times_through > 5:
users.append(incoming_user)
incoming_user = ''
times_through += 1
# Remove unnecessary stuff at end
users = users[0:len(users)-4]
# Print all users
print('All the users currently on this computer are ' + str(users))<|fim▁hole|> should_be_admin = raw_input(user + " is an administrator. Should they be? y/n. ")
if should_be_admin == 'y':
return True
if should_be_admin == 'n':
return False
def should_be_user(user):
# Should the user be a user
should_be_user = raw_input(user + " is a user. Should they be? y/n. ")
if should_be_user == 'y':
return True
if should_be_user == 'n':
return False
for user in users:
# Iterate through user list
if user in check_output('net localgroup Administrators'):
# If user is in the Administrators localgroup
if not should_be_admin(user):
print('Removing ' + user + ' from the Administrators group')
os.system('net localgroup Administrators ' + user + ' /delete')
else:
print('OK. We are keeping ' + user + ' in the Administrators group.')
else:
should_be_user_answer = should_be_user(user)
if not should_be_user_answer:
print('Removing ' + user)
os.system('net user ' + user + ' /delete')
if should_be_admin(user):
if user not in check_output('net localgroup Administrators'):
if should_be_admin(user):
print('Adding ' + user + 'to the Administrators group')
os.system('net localgroup Administrators ' + user + ' /add')
# Ask if we should do user management stuff.
do_user_management = raw_input("Shall we manage users? y/n. ")
if do_user_management == 'y':
user_management(users)
############################# Registry keys and such #############################
if raw_input("Shall we change some registry stuff? y/n. ") == 'y':
# Password policy automagic
print('Chaning password policies and such...')
os.system('net accounts /FORCELOGOFF:30 /MINPWLEN:8 /MAXPWAGE:30 /MINPWAGE:10 /UNIQUEPW:5')
# Clean DNS cache, cause why not
print('Bro, I cleaned your DNS cache. Deal with it.')
os.system('ipconfig /flushdns')
# Disable built-in accounts
print('I really hope you weren\'t the default Administrator account')
os.system('net user Guest /active:NO')
os.system('net user Administrator /active:NO')
# Make auditing great again.
print('Auditing now on! Yay!!!!')
os.system('auditpol /set /category:* /success:enable')
os.system('auditpol /set /category:* /failure:enable')
# Enable firewall
print('The firewall torch has been passed on to you')
os.system('netsh advfirewall set allprofiles state on')
os.system('echo You\'re going to have to type exit')
#I have no idea what I was doing here....
os.system('secedit /import /db secedit.sdb /cfg cyber.inf /overwrite /log MyLog.txt')
reg_dir = '"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\\ '
for command in (('FilterAdministratorToken"','1'),('ConsentPromptBehaviorAdmin"','1'),('ConsentPromptBehaviorUser"','1'),('EnableInstallerDetection"','1'),('ValidateAdminCodeSignatures"','1'),('EnableLUA"','1'),('PromptOnSecureDesktop"','1'),('EnableVirtualization"','1'),):
os.system('reg add ' + reg_dir + ' /v ' + command[0] + ' /t REG_DWORD /d ' + command[1] + ' /f')
reg_dir = '"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\\'
for command in (('AUOptions"', '4'),('ElevateNonAdmins"', '1'),('IncludeRecommendedUpdates"', '1'),('ScheduledInstallTime"', '22')):
os.system('reg add ' + reg_dir + ' /v ' + command[0] + ' /t REG_DWORD /d ' + command[1] + ' /f')
reg_dir = '"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\\'
for command in (('fDenyTSConnections"', '1'),('AllowRemoteRPC"', '0')):
os.system('reg add ' + reg_dir + ' /v ' + command[0] + ' /t REG_DWORD /d ' + command[1] + ' /f')
reg_dir = '"HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Remote Assistance\\'
for command in (('fAllowFullControl"','0'),('fAllowToGetHelp"','0')):
os.system('reg add ' + reg_dir + ' /v ' + command[0] + ' /t REG_DWORD /d ' + command[1] + ' /f')
reg_dir = '"HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp\\'
command = ('UserAuthentication"','1')
os.system('reg add ' + reg_dir + ' /v ' + command[0] + ' /t REG_DWORD /d ' + command[1] + ' /f')
reg_dir = '"HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Remote Assistance\\'
command = ('CreateEncryptedOnlyTickets"','1')
os.system('reg add ' + reg_dir + ' /v ' + command[0] + ' /t REG_DWORD /d ' + command[1] + ' /f')
reg_dir = '"HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp\\'
command = ('fDisableEncryption"','0')
os.system('reg add ' + reg_dir + ' /v ' + command[0] + ' /t REG_DWORD /d ' + command[1] + ' /f')
# I have found additional commands. This one 'might' fix the host file.
os.system('attrib -r -s C:\WINDOWS\system32\drivers\etc\hosts')
os.system('echo > C:\Windows\System32\drivers\etc\hosts')
# This isn't really appropriate for this option, but...
os.system('net start > started_services.txt')
# Remote registry
os.system('net stop RemoteRegistry')
os.system('sc config RemoteRegistry start=disabled')
for service in ('RemoteAccess', 'Telephony', 'tlntsvr', 'p2pimsvc', 'simptcp', 'fax', 'msftpsvc'):
os.system('net stop ' + service)
os.system('sc config ' + service + ' start = disabled')
for command in registry_commands.readlines():
os.system(command)
############################# Search for media files #############################
if raw_input("Shall we search for media files? y/n. ") == 'y':
file_list = []
# Ask for directory to be scanned.
directory_to_scan = input('What directory would you like to scan for media files? Remember to enclose your directory in \'s or "s, and use two \s if your directory ends in a \. ')
# Inefficient but I spent too much time looking how to do this to delete it.
'''for root, dirs, files in os.walk(directory_to_scan):
for f_name in files:
file_path = os.path.join(root, f_name)
# If the file ends with common media extension, add file path to text_file
for extension in ('.mp3','.wav','.png','wmv','.jpg','.jpeg','.mp4','.avi','.mov','.aif','.iff','.php','.m3u','.m4a','.wma','.m4v','.mpg','.bmp','.gif','.bat','.exe','.zip','.7z'):
if root in file_list:
pass
else:
file_list.append(root)'''
os.system('dir /s /b ' + directory_to_scan + ' > allfiles.txt')
input_file = open('allfiles.txt', 'r')
text_file = open('media_files.txt','w')
for line in input_file:
for extension in ('.mp3','.wav','.png','wmv','.jpg','.jpeg','.mp4','.avi','.mov','.aif','.iff','.m3u','.m4a','.wma','.m4v','.mpg','.bmp','.gif','.bat','.txt','.exe','.zip','.7z','.php','.html'):
if line.endswith(extension + '\n'):
text_file.write(line)
for line in input_file.readlines():
for bad_stuff in ['cain','able','nmap','keylogger','armitage','metasploit','shellter','clean']:
if bad_stuff in line:
text_file.write(line)
text_file.close()
print('Available commands are addUser, passwords, and exit.')
command = raw_input('What would you like to do? ')
if command == 'addUser':
username = raw_input('What is the desired username? ')
os.system('net user ' + username + ' P@55w0rd /ADD')
if command == 'passwords':
users_string = str(users).replace('[','')
users_string = str(users).replace(']','')
username = raw_input('The current users on the machine are ' + users_string + '. Who\'s password would you like to change? ')
new_password = raw_input('What shall the password be? ')
os.system('net user ' + username + ' P@55w0rd')
if command == 'exit':
os.system('pause')<|fim▁end|> | def user_management(users):
def should_be_admin(user):
# Should the user be an admin |
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models
from olc_webportalv2.users.models import User
from django.contrib.postgres.fields.jsonb import JSONField
import os
from django.core.exceptions import ValidationError
# Create your models here.
def validate_fastq(fieldfile):
filename = os.path.basename(fieldfile.name)
if filename.endswith('.fastq.gz') or filename.endswith('.fastq'):
print('File extension for {} confirmed valid'.format(filename))
else:
raise ValidationError(
_('%(file)s does not end with .fastq or .fastq.gz'),
params={'filename': filename},
)
class ProjectMulti(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
project_title = models.CharField(max_length=256)
description = models.CharField(max_length=200, blank=True)
date = models.DateTimeField(auto_now_add=True)
forward_id = models.CharField(max_length=256, default='_R1')
reverse_id = models.CharField(max_length=256, default='_R2')
def __str__(self):
return self.project_title
class Sample(models.Model):
project = models.ForeignKey(ProjectMulti, on_delete=models.CASCADE, related_name='samples')
file_R1 = models.FileField(upload_to='%Y%m%d%s', blank=True)
file_R2 = models.FileField(upload_to='%Y%m%d%s', blank=True)
file_fasta = models.FileField(upload_to='%Y%m%d%s', blank=True)
title = models.CharField(max_length=200, blank=True)
genesippr_status = models.CharField(max_length=128,
default="Unprocessed")
sendsketch_status = models.CharField(max_length=128,
default="Unprocessed")
confindr_status = models.CharField(max_length=128,
default="Unprocessed")
genomeqaml_status = models.CharField(max_length=128,
default="Unprocessed")
amr_status = models.CharField(max_length=128,
default="Unprocessed")
def __str__(self):
return self.title
<|fim▁hole|> sample = models.ForeignKey(Sample, on_delete=models.CASCADE, related_name='genomeqaml_result')
predicted_class = models.CharField(max_length=128, default='N/A')
percent_fail = models.CharField(max_length=128, default='N/A')
percent_pass = models.CharField(max_length=128, default='N/A')
percent_reference = models.CharField(max_length=118, default='N/A')
def __str__(self):
return '{}'.format(self.sample)
class SendsketchResult(models.Model):
class Meta:
verbose_name_plural = "Sendsketch Results"
def __str__(self):
return 'pk {}: Rank {}: Sample {}'.format(self.pk, self.rank, self.sample.pk)
sample = models.ForeignKey(Sample, on_delete=models.CASCADE)
rank = models.CharField(max_length=8, default='N/A')
wkid = models.CharField(max_length=256, default='N/A')
kid = models.CharField(max_length=256, default='N/A')
ani = models.CharField(max_length=256, default='N/A')
complt = models.CharField(max_length=256, default='N/A')
contam = models.CharField(max_length=256, default='N/A')
matches = models.CharField(max_length=256, default='N/A')
unique = models.CharField(max_length=256, default='N/A')
nohit = models.CharField(max_length=256, default='N/A')
taxid = models.CharField(max_length=256, default='N/A')
gsize = models.CharField(max_length=256, default='N/A')
gseqs = models.CharField(max_length=256, default='N/A')
taxname = models.CharField(max_length=256, default='N/A')
class GenesipprResults(models.Model):
# For admin panel
def __str__(self):
return '{}'.format(self.sample)
# TODO: Accomodate seqID
sample = models.ForeignKey(Sample, on_delete=models.CASCADE, related_name='genesippr_results')
# genesippr.csv
strain = models.CharField(max_length=256, default="N/A")
genus = models.CharField(max_length=256, default="N/A")
# STEC
serotype = models.CharField(max_length=256, default="N/A")
o26 = models.CharField(max_length=256, default="N/A")
o45 = models.CharField(max_length=256, default="N/A")
o103 = models.CharField(max_length=256, default="N/A")
o111 = models.CharField(max_length=256, default="N/A")
o121 = models.CharField(max_length=256, default="N/A")
o145 = models.CharField(max_length=256, default="N/A")
o157 = models.CharField(max_length=256, default="N/A")
uida = models.CharField(max_length=256, default="N/A")
eae = models.CharField(max_length=256, default="N/A")
eae_1 = models.CharField(max_length=256, default="N/A")
vt1 = models.CharField(max_length=256, default="N/A")
vt2 = models.CharField(max_length=256, default="N/A")
vt2f = models.CharField(max_length=256, default="N/A")
# listeria
igs = models.CharField(max_length=256, default="N/A")
hlya = models.CharField(max_length=256, default="N/A")
inlj = models.CharField(max_length=256, default="N/A")
# salmonella
inva = models.CharField(max_length=256, default="N/A")
stn = models.CharField(max_length=256, default="N/A")
def inva_number(self):
return float(self.inva.split('%')[0])
def uida_number(self):
return float(self.uida.split('%')[0])
def vt1_number(self):
return float(self.vt1.split('%')[0])
def vt2_number(self):
return float(self.vt2.split('%')[0])
def vt2f_number(self):
return float(self.vt2f.split('%')[0])
def eae_number(self):
return float(self.eae.split('%')[0])
def eae_1_number(self):
return float(self.eae_1.split('%')[0])
def hlya_number(self):
return float(self.hlya.split('%')[0])
def igs_number(self):
return float(self.igs.split('%')[0])
def inlj_number(self):
return float(self.inlj.split('%')[0])
class Meta:
verbose_name_plural = "Genesippr Results"
class GenesipprResultsSixteens(models.Model):
class Meta:
verbose_name_plural = "SixteenS Results"
def __str__(self):
return '{}'.format(self.sample)
sample = models.ForeignKey(Sample, on_delete=models.CASCADE, related_name='sixteens_results')
# sixteens_full.csv
strain = models.CharField(max_length=256, default="N/A")
gene = models.CharField(max_length=256, default="N/A")
percentidentity = models.CharField(max_length=256, default="N/A")
genus = models.CharField(max_length=256, default="N/A")
foldcoverage = models.CharField(max_length=256, default="N/A")
@property
def gi_accession(self):
# Split by | delimiter, pull second element which should be the GI#
gi_accession = self.gene.split('|')[1]
return gi_accession
class GenesipprResultsGDCS(models.Model):
class Meta:
verbose_name_plural = "GDCS Results"
def __str__(self):
return '{}'.format(self.sample)
sample = models.ForeignKey(Sample, on_delete=models.CASCADE, related_name='gdcs_results')
# GDCS.csv
strain = models.CharField(max_length=256, default="N/A")
genus = models.CharField(max_length=256, default="N/A")
matches = models.CharField(max_length=256, default="N/A")
meancoverage = models.CharField(max_length=128, default="N/A")
passfail = models.CharField(max_length=16, default="N/A")
allele_dict = JSONField(blank=True, null=True, default=dict)
class ConFindrResults(models.Model):
class Meta:
verbose_name_plural = 'Confindr Results'
def __str__(self):
return '{}'.format(self.sample)
sample = models.ForeignKey(Sample, on_delete=models.CASCADE, related_name='confindr_results')
strain = models.CharField(max_length=256, default="N/A")
genera_present = models.CharField(max_length=256, default="N/A")
contam_snvs = models.CharField(max_length=256, default="N/A")
contaminated = models.CharField(max_length=256, default="N/A")
class GenesipprResultsSerosippr(models.Model):
class Meta:
verbose_name_plural = "Serosippr Results"
def __str__(self):
return '{}'.format(self.sample)
sample = models.ForeignKey(Sample, on_delete=models.CASCADE)
class AMRResult(models.Model):
class Meta:
verbose_name_plural = 'AMR Results'
def __str__(self):
return '{}'.format(self.sample)
sample = models.ForeignKey(Sample, on_delete=models.CASCADE, related_name='amr_results')
results_dict = JSONField(blank=True, null=True, default=dict)
species = models.CharField(max_length=88, default='N/A')<|fim▁end|> |
class GenomeQamlResult(models.Model):
class Meta:
verbose_name_plural = "GenomeQAML Results" |
<|file_name|>tmbuilder.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from tm import TuringMachine
class TuringMachineBuilder:
"""
Creates a turing machine step by step by retrieving all the necessary
information.
By default (can be specified) sets the halt state to 'HALT and the
blank symbol to '#'
"""
def __init__(self):
"""
Initialize a new TuringMachineBuilder with the specified haltstate and
blank symbol.
haltstate takes as default value 'HALT'
blnak takes as default value '#' and must be one char length
"""
self._states = set()
self._in_alphabet = set()
self._trans_function = {}
self._istate = None
self._fstates = set()
self._blank = None
self._haltstate = None
#
#
def clean(self):
"""
Clear all the previous stored data
"""
self._states = set()
self._in_alphabet = set()
self._trans_function = {}
self._istate = None
self._fstates = set()
self._blank = None
self._haltstate = None
#
#
def addTransition(self, state, symbol, new_state, new_symbol, movement):
"""
addTransition(state, symbol, new_state, new_symbol, movement)
Adds the transition:
From state,symbol To new_state writing new_symbol at the current
possition and moving the head in movement direction
- state: something that represents a state, must be hashable
- symbol: something that represents a symbol, must be hashable
- new_state: something that represents a state, must be hashable
- new_symbol: something that represents a symbol, must be hashable
- movement: TuringMachine.MOVE_LEFT or TuringMachine.MOVE_RIGHT or
TuringMachine.NON_MOVEMENT
Raise Exception if symbols have more than one char length
"""
if movement not in TuringMachine.HEAD_MOVEMENTS:
raise Exception('Invalid movement')
if (hasattr(symbol, 'len') and len(symbol) > 1) or \
(hasattr(new_symbol, 'len') and len(new_symbol) > 1):
raise Exception('Symbol length > 1')
if state not in self._states:
self._states.add(state)
if symbol != self._blank and symbol not in self._in_alphabet:
self._in_alphabet.add(symbol)
if new_state not in self._states:
self._states.add(new_state)
if new_symbol != self._blank and new_symbol not in self._in_alphabet:
self._in_alphabet.add(new_symbol)
self._trans_function[(state,symbol)] = (new_state, new_symbol,
movement)
#
#
def addFinalState(self, state):
"""
Adds the specified state to the set of final states
"""
if state not in self._states:
self._states.add(state)
if state not in self._fstates:
self._fstates.add(state)
#
#
def setInitialState(self, state):
"""
Set the specified state as the initial. Mandatory operation
"""
if state not in self._states:
self._states.add(state)
self._istate = state
#
#
def hasInitialState(self):
"""
Returns True if the initial state was specified on a previous call
to setInitialState
"""
return self._istate != None
#
#
def hasHaltState(self):
"""
Returns True if the halt state was specified on a preivous call to
setHaltState
"""
return self._haltstate != None
#
#
def hasBlankSymbol(self):
"""
Returns True if the halt state was specified on a preivous call to
setBlankSymbol
"""
return self._blank != None
#
#
def setBlankSymbol(self, blank_sym):
"""
Specifies a new blank symbol
- The blank symbol must be one char length
Raise Exception if blank_sym has more than one char length
"""
if not blank_sym or len(blank_sym) > 1:
raise Exception('Symbol must be one char length')
self._blank = blank_sym
#
#
def setHaltState(self, haltstate):
"""
Specifies a new halt state
"""
# If there are a previous halt state. Check if it appears in some
# transition otherwise delete it from the list of states
if self.hasHaltState():
old_remains = False
for k, v in self._trans_function.iteritems():
if k[0] == self._haltstate or v[0] == self._haltstate:
old_remains = True
break
if not old_remains:
self._states.remove(self._haltstate)
self._haltstate = haltstate
self._states.add(self._haltstate)
#
#
def create(self):
"""
Creates a turing machine instance with the collected information.
Raises an Exception if:
The initial state remains unset
The halt state remains unset
The blank symbol remains unset
At this point the tape_alphabet is set to be: in_alphabet U {blank}
"""
if not self.hasInitialState():
raise Exception('It is necessary to specify an initial state')
if not self.hasBlankSymbol():
raise Exception('It is necessary to specify the blank symbol')
if not self.hasHaltState():
raise Exception('It is necessary to specify the halt state')
tape_alphabet = set(self._in_alphabet)
tape_alphabet.add(self._blank)
return TuringMachine(self._states, self._in_alphabet, tape_alphabet,
self._trans_function, self._istate,
self._fstates, self._haltstate, self._blank)
<|fim▁hole|> def getHaltState(self):
"""
Returns the halt state specified or assigned by default on the
initialization of this Builder
"""
return self._haltstate
if __name__ == '__main__':
tmb = TuringMachineBuilder()
tmb.setBlankSymbol('#')
tmb.setHaltState('HALT')
tmb.addTransition(1, 0, 2, 1, TuringMachine.MOVE_RIGHT)
tmb.addTransition(1, 1, 2, 0, TuringMachine.MOVE_RIGHT)
tmb.addTransition(2, 0, 1, 0, TuringMachine.NON_MOVEMENT)
tmb.addTransition(2, 1, 3, 1, TuringMachine.MOVE_RIGHT)
tmb.addTransition(3, 0, 'HALT', 0, TuringMachine.NON_MOVEMENT)
tmb.addTransition(3, 1, 'HALT', 1, TuringMachine.NON_MOVEMENT)
tmb.addTransition(3, '#', 'HALT', '#', TuringMachine.NON_MOVEMENT)
tmb.setInitialState(1)
tmb.addFinalState(2)
print tmb.create()<|fim▁end|> | #
# |
<|file_name|>socket.js<|end_file_name|><|fim▁begin|>//*************************************************************
// Filename: socket.js
//
// Author: Jake Higgins <[email protected]>
//*************************************************************
var Socket;
function addSocketListeners() {
Socket = new io();
Socket.on('sync objects', function(objects, room, caller) {
console.log(objects);
if(CallerID == caller) {
console.log(objects);
$.each(objects, function(key, object) {
createStroke(object);
});
CanvasManager.render();
}
});
Socket.on('add object', function(object, room, caller) {
if(CallerID != caller && RoomID == room) {
createStroke(object);
CanvasManager.clearCanvas();
}
});
Socket.on('move object', function(object, room, caller) {
console.log('move object');
if(CallerID != caller && RoomID == room) {
var targetObj = ObjectManager.findObject(object.objectID);
console.log(targetObj);
if(targetObj != null) {
targetObj.max = object.max;
targetObj.min = object.min;
$(targetObj.container).css({
top: targetObj.min.y,
left: targetObj.min.x
});
}
}
});
Socket.on('delete object', function(object, room, caller) {
if(CallerID != caller && RoomID == room)
{
ObjectManager.deleteObject(object.objectID);
}
});
Socket.on('clear objects', function(room, caller) {
console.log('clear');
if(CallerID != caller && RoomID == room) {
CanvasManager.clear(true);
}
});
Socket.on('draw', function(drawData, room, caller) {
if(CallerID != caller && RoomID == room) {
Drawing.draw(drawData, true);
}
});
// ======== Chat =============/
// Comes in the format message/roomID/caller
// if(roomID == this.roomID) // pseudocode for now
// add chat to chat thingy
Socket.on('receiveMessage', function(message, room, caller)
{
if ( RoomID == room )
{
// Proceed
Chat.write(message, caller);
}
});
}
function createStroke(stroke) {
console.log(stroke);
var obj = new object("stroke");
obj.initialize();
obj.imageData = stroke.imageData;
obj.layer = stroke.layer;
obj.max = stroke.max;
obj.min = stroke.min;
obj.objectID = stroke.objectID;
obj.type = "stroke";
obj.objectData = {
imageData: obj.imageData,
layer: obj.layer,
max: obj.max,<|fim▁hole|> };
obj.createImage();
ObjectManager.addObject(obj);
}<|fim▁end|> | min: obj.min,
objectID: obj.objectID,
objectType: obj.type, |
<|file_name|>sample.py<|end_file_name|><|fim▁begin|>from sklearn.utils import resample
from darts.api.dataset import Subset
def dummy_indices(dataset):
""" Get indexes for the dataset """
return [x for x in range(len(dataset))]
def sample(dataset, num_samples, replace=True):
""" Sample the dataset """
data_idx = dummy_indices(dataset)
sample_idx = resample(data_idx, n_samples=num_samples, replace=replace)<|fim▁hole|><|fim▁end|> | return Subset(dataset, sample_idx) |
<|file_name|>portal.rs<|end_file_name|><|fim▁begin|>use crate::compat::Mutex;
use crate::screen::{Screen, ScreenBuffer};
use alloc::sync::Arc;
use core::mem;
use graphics_base::frame_buffer::{AsSurfaceMut, FrameBuffer};
use graphics_base::system::{DeletedIndex, System};
use graphics_base::types::Rect;
use graphics_base::Result;
use hecs::World;
#[cfg(target_os = "rust_os")]
mod rust_os {
use alloc::sync::Arc;
use graphics_base::ipc;
use graphics_base::types::{Event, EventInput};
use graphics_base::Result;
use os::{File, Mutex};
#[derive(Clone)]
pub struct PortalRef {
pub server2client: Arc<Mutex<File>>,
pub portal_id: usize,
}
impl PartialEq for PortalRef {
fn eq(&self, other: &Self) -> bool {
self.portal_id == other.portal_id && Arc::ptr_eq(&self.server2client, &other.server2client)
}
}
impl PortalRef {
pub fn send_input(&self, input: EventInput) -> Result<()> {
let mut server2client = self.server2client.lock();
ipc::send_message(
&mut *server2client,
&Event::Input {
portal_id: self.portal_id,
input,
},<|fim▁hole|> )
}
}
}
#[cfg(not(target_os = "rust_os"))]
mod posix {
use graphics_base::types::{Event, EventInput};
use graphics_base::Result;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
#[derive(Clone)]
pub struct PortalRef {
pub portal_id: usize,
pub events: Rc<RefCell<VecDeque<Event>>>,
}
impl PartialEq for PortalRef {
fn eq(&self, other: &Self) -> bool {
self.portal_id == other.portal_id && Rc::ptr_eq(&self.events, &other.events)
}
}
impl PortalRef {
pub fn send_input(&self, input: EventInput) -> Result<()> {
let event = Event::Input {
portal_id: self.portal_id,
input,
};
self.events.borrow_mut().push_back(event);
Ok(())
}
}
}
#[cfg(target_os = "rust_os")]
pub use rust_os::PortalRef;
#[cfg(not(target_os = "rust_os"))]
pub use posix::PortalRef;
pub struct ServerPortal {
portal_ref: PortalRef,
pos: Rect,
prev_pos: Rect,
z_index: usize,
frame_buffer_id: usize,
frame_buffer_size: (u16, u16),
frame_buffer: Arc<FrameBuffer>,
needs_paint: bool,
}
impl ServerPortal {
pub fn new(
world: &World,
portal_ref: PortalRef,
pos: Rect,
frame_buffer_id: usize,
frame_buffer_size: (u16, u16),
frame_buffer: FrameBuffer,
) -> Self {
let z_index = world
.query::<&Self>()
.iter()
.map(|(_, portal)| &portal.z_index)
.max()
.cloned()
.unwrap_or(0);
Self {
portal_ref,
pos,
prev_pos: pos,
z_index,
frame_buffer_id,
frame_buffer_size,
frame_buffer: Arc::new(frame_buffer),
needs_paint: true,
}
}
}
impl ServerPortal {
pub fn move_to(&mut self, pos: Rect) {
self.pos = pos;
}
pub fn draw(&mut self, frame_buffer_id: usize, frame_buffer_size: (u16, u16), frame_buffer: FrameBuffer) -> usize {
self.frame_buffer_size = frame_buffer_size;
self.frame_buffer = Arc::new(frame_buffer);
self.needs_paint = true;
mem::replace(&mut self.frame_buffer_id, frame_buffer_id)
}
}
impl ServerPortal {
fn as_screen_buffer(&self) -> ScreenBuffer {
ScreenBuffer {
pos: self.pos,
frame_buffer_size: self.frame_buffer_size,
frame_buffer: Arc::downgrade(&self.frame_buffer),
portal_ref: self.portal_ref.clone(),
}
}
}
pub struct ServerPortalSystem<S> {
screen: Arc<Mutex<Screen<S>>>,
input_state: Arc<Mutex<Option<PortalRef>>>,
deleted_index: DeletedIndex<()>,
}
impl<S> ServerPortalSystem<S> {
pub fn new(screen: Arc<Mutex<Screen<S>>>, input_state: Arc<Mutex<Option<PortalRef>>>) -> Self {
ServerPortalSystem {
screen,
input_state,
deleted_index: DeletedIndex::new(),
}
}
}
impl<S> System for ServerPortalSystem<S>
where
S: AsSurfaceMut,
{
fn run(&mut self, world: &mut World) -> Result<()> {
let mut portals_borrow = world.query::<&mut ServerPortal>();
let mut portals = portals_borrow.iter().map(|(_, portal)| portal).collect::<Vec<_>>();
portals.sort_by(|a, b| a.z_index.cmp(&b.z_index));
for portal in portals.iter_mut() {
if portal.prev_pos != portal.pos {
portal.prev_pos = portal.pos;
portal.needs_paint = true;
}
}
*self.input_state.lock() = portals.last().map(|p| p.portal_ref.clone());
let deleted_entities = self
.deleted_index
.update(world.query::<()>().with::<ServerPortal>().iter());
if !deleted_entities.is_empty() || portals.iter().any(|p| p.needs_paint) {
self.screen
.lock()
.update_buffers(portals.iter_mut().rev().map(|portal| {
portal.needs_paint = false;
portal.as_screen_buffer()
}));
}
Ok(())
}
}<|fim▁end|> | |
<|file_name|>Webluker_cdn.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# encoding: utf-8
<|fim▁hole|>def run(whatweb, pluginname):
whatweb.recog_from_header(pluginname, "Webluker")<|fim▁end|> | |
<|file_name|>NByteArray.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2012 PRODYNA AG
*
* Licensed under the Eclipse Public License (EPL), Version 1.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.opensource.org/licenses/eclipse-1.0.php or
* http://www.nabucco.org/License.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nabucco.framework.base.facade.datatype;
import java.util.Arrays;
/**
* NByteArray
*
* @author Nicolas Moser, PRODYNA AG
*/
public abstract class NByteArray extends BasetypeSupport implements Basetype, Comparable<NByteArray> {
private static final long serialVersionUID = 1L;
private byte[] value;
/**
* Default constructor
*/
public NByteArray() {
this(null);
}
/**
* Constructor initializing the value.<|fim▁hole|> public NByteArray(byte[] value) {
super(BasetypeType.BYTE_ARRAY);
this.value = value;
}
@Override
public byte[] getValue() {
return value;
}
@Override
public String getValueAsString() {
if (this.value == null) {
return null;
}
return new String(this.value);
}
@Override
public void setValue(Object value) throws IllegalArgumentException {
if (value != null && !(value instanceof byte[])) {
throw new IllegalArgumentException("Cannot set value '" + value + "' to NByteArray.");
}
this.setValue((byte[]) value);
}
/**
* Setter for the byte[] value.
*
* @param value
* the byte[] value to set.
*/
public void setValue(byte[] value) {
this.value = value;
}
/**
* Returns a <code>String</code> object representing this <code>NByteArray</code>'s value.
*
* @return a string representation of the value of this object in base 10.
*/
@Override
public String toString() {
if (this.value == null) {
return null;
}
return new String(this.value);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(this.value);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof NByteArray))
return false;
NByteArray other = (NByteArray) obj;
if (!Arrays.equals(this.value, other.value))
return false;
return true;
}
@Override
public int compareTo(NByteArray other) {
if (other == null) {
return -1;
}
if (getValue() == null) {
if (other.getValue() == null) {
return 0;
}
return 1;
}
if (other.getValue() == null) {
return -1;
}
if (this.value.length != other.value.length) {
if (this.value.length > other.value.length) {
return 1;
}
if (this.value.length < other.value.length) {
return -1;
}
}
for (int i = 0; i < this.value.length; i++) {
if (this.value[i] != other.value[i]) {
if (this.value[i] > other.value[i]) {
return 1;
}
if (this.value[i] < other.value[i]) {
return -1;
}
}
}
return 0;
}
@Override
public abstract NByteArray cloneObject();
/**
* Clones the properties of this basetype into the given basetype.
*
* @param clone
* the cloned basetype
*/
protected void cloneObject(NByteArray clone) {
if (this.value != null) {
clone.value = Arrays.copyOf(this.value, this.value.length);
}
}
}<|fim▁end|> | *
* @param value
* the value to initialize
*/ |
<|file_name|>cs_scene.cpp<|end_file_name|><|fim▁begin|>/*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "Chat.h"
#include "DB2Stores.h"
#include "Language.h"
#include "ObjectMgr.h"
#include "Player.h"
#include "RBAC.h"
#include "WorldSession.h"
class scene_commandscript : public CommandScript
{
public:
scene_commandscript() : CommandScript("scene_commandscript") { }
std::vector<ChatCommand> GetCommands() const override
{
static std::vector<ChatCommand> sceneCommandTable =
{
{ "debug", rbac::RBAC_PERM_COMMAND_SCENE_DEBUG, false, &HandleDebugSceneCommand, "" },
{ "play", rbac::RBAC_PERM_COMMAND_SCENE_PLAY, false, &HandlePlaySceneCommand, "" },
{ "playpackage", rbac::RBAC_PERM_COMMAND_SCENE_PLAY_PACKAGE, false, &HandlePlayScenePackageCommand, "" },
{ "cancel", rbac::RBAC_PERM_COMMAND_SCENE_CANCEL, false, &HandleCancelSceneCommand, "" }
};
static std::vector<ChatCommand> commandTable =<|fim▁hole|> return commandTable;
}
static bool HandleDebugSceneCommand(ChatHandler* handler, char const* /*args*/)
{
if (Player* player = handler->GetSession()->GetPlayer())
{
player->GetSceneMgr().ToggleDebugSceneMode();
handler->PSendSysMessage(player->GetSceneMgr().IsInDebugSceneMode() ? LANG_COMMAND_SCENE_DEBUG_ON : LANG_COMMAND_SCENE_DEBUG_OFF);
}
return true;
}
static bool HandlePlaySceneCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
char const* sceneIdStr = strtok((char*)args, " ");
if (!sceneIdStr)
return false;
uint32 sceneId = atoi(sceneIdStr);
Player* target = handler->getSelectedPlayerOrSelf();
if (!target)
{
handler->SendSysMessage(LANG_PLAYER_NOT_FOUND);
handler->SetSentErrorMessage(true);
return false;
}
if (!sObjectMgr->GetSceneTemplate(sceneId))
return false;
target->GetSceneMgr().PlayScene(sceneId);
return true;
}
static bool HandlePlayScenePackageCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
char const* scenePackageIdStr = strtok((char*)args, " ");
char const* flagsStr = strtok(NULL, "");
if (!scenePackageIdStr)
return false;
uint32 scenePackageId = atoi(scenePackageIdStr);
uint32 flags = flagsStr ? atoi(flagsStr) : SCENEFLAG_UNK16;
Player* target = handler->getSelectedPlayerOrSelf();
if (!target)
{
handler->SendSysMessage(LANG_PLAYER_NOT_FOUND);
handler->SetSentErrorMessage(true);
return false;
}
if (!sSceneScriptPackageStore.HasRecord(scenePackageId))
return false;
target->GetSceneMgr().PlaySceneByPackageId(scenePackageId, flags);
return true;
}
static bool HandleCancelSceneCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
Player* target = handler->getSelectedPlayerOrSelf();
if (!target)
{
handler->SendSysMessage(LANG_PLAYER_NOT_FOUND);
handler->SetSentErrorMessage(true);
return false;
}
uint32 id = atoi((char*)args);
if (!sSceneScriptPackageStore.HasRecord(id))
return false;
target->GetSceneMgr().CancelSceneByPackageId(id);
return true;
}
};
void AddSC_scene_commandscript()
{
new scene_commandscript();
}<|fim▁end|> | {
{ "scene", rbac::RBAC_PERM_COMMAND_SCENE, true, NULL, "", sceneCommandTable }
}; |
<|file_name|>document_rule.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 https://mozilla.org/MPL/2.0/. */
//! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document)
//! initially in CSS Conditional Rules Module Level 3, @document has been postponed to the level 4.
//! We implement the prefixed `@-moz-document`.
use crate::media_queries::Device;
use crate::parser::{Parse, ParserContext};
use crate::shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked};
use crate::shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
use crate::str::CssStringWriter;
use crate::stylesheets::CssRules;
use crate::values::CssUrl;
use cssparser::{Parser, SourceLocation};
#[cfg(feature = "gecko")]
use malloc_size_of::{MallocSizeOfOps, MallocUnconditionalShallowSizeOf};
use servo_arc::Arc;
use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
#[derive(Debug, ToShmem)]
/// A @-moz-document rule
pub struct DocumentRule {
/// The parsed condition
pub condition: DocumentCondition,
/// Child rules
pub rules: Arc<Locked<CssRules>>,
/// The line and column of the rule's source code.
pub source_location: SourceLocation,
}
impl DocumentRule {
/// Measure heap usage.
#[cfg(feature = "gecko")]
pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize {
// Measurement of other fields may be added later.
self.rules.unconditional_shallow_size_of(ops) +
self.rules.read_with(guard).size_of(guard, ops)
}
}
impl ToCssWithGuard for DocumentRule {
fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
dest.write_str("@-moz-document ")?;
self.condition.to_css(&mut CssWriter::new(dest))?;
dest.write_str(" {")?;
for rule in self.rules.read_with(guard).0.iter() {
dest.write_str(" ")?;
rule.to_css(guard, dest)?;
}
dest.write_str(" }")
}
}
impl DeepCloneWithLock for DocumentRule {
/// Deep clones this DocumentRule.
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard,
params: &DeepCloneParams,
) -> Self {
let rules = self.rules.read_with(guard);
DocumentRule {
condition: self.condition.clone(),
rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard, params))),
source_location: self.source_location.clone(),
}
}
}
/// The kind of media document that the rule will match.
#[derive(Clone, Copy, Debug, Parse, PartialEq, ToCss, ToShmem)]
#[allow(missing_docs)]
pub enum MediaDocumentKind {
All,
Plugin,
Image,
Video,
}
/// A matching function for a `@document` rule's condition.
#[derive(Clone, Debug, ToCss, ToShmem)]
pub enum DocumentMatchingFunction {
/// Exact URL matching function. It evaluates to true whenever the
/// URL of the document being styled is exactly the URL given.
Url(CssUrl),
/// URL prefix matching function. It evaluates to true whenever the
/// URL of the document being styled has the argument to the
/// function as an initial substring (which is true when the two
/// strings are equal). When the argument is the empty string,
/// it evaluates to true for all documents.
#[css(function)]
UrlPrefix(String),
/// Domain matching function. It evaluates to true whenever the URL
/// of the document being styled has a host subcomponent and that
/// host subcomponent is exactly the argument to the ‘domain()’
/// function or a final substring of the host component is a
/// period (U+002E) immediately followed by the argument to the
/// ‘domain()’ function.
#[css(function)]
Domain(String),
/// Regular expression matching function. It evaluates to true
/// whenever the regular expression matches the entirety of the URL
/// of the document being styled.
#[css(function)]
Regexp(String),
/// Matching function for a media document.
#[css(function)]
MediaDocument(MediaDocumentKind),
}
macro_rules! parse_quoted_or_unquoted_string {
($input:ident, $url_matching_function:expr) => {
$input.parse_nested_block(|input| {
let start = input.position();
input
.parse_entirely(|input| {
let string = input.expect_string()?;
Ok($url_matching_function(string.as_ref().to_owned()))
})
.or_else(|_: ParseError| {
while let Ok(_) = input.next() {}
Ok($url_matching_function(input.slice_from(start).to_string()))
})
})
};
}
impl DocumentMatchingFunction {
/// Parse a URL matching function for a`@document` rule's condition.
pub fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
if let Ok(url) = input.try(|input| CssUrl::parse(context, input)) {
return Ok(DocumentMatchingFunction::Url(url));
}
let location = input.current_source_location();
let function = input.expect_function()?.clone();
match_ignore_ascii_case! { &function,
"url-prefix" => {
parse_quoted_or_unquoted_string!(input, DocumentMatchingFunction::UrlPrefix)
},
"domain" => {
parse_quoted_or_unquoted_string!(input, DocumentMatchingFunction::Domain)
},
"regexp" => {
input.parse_nested_block(|input| {
Ok(DocumentMatchingFunction::Regexp(
input.expect_string()?.as_ref().to_owned(),
))
})
},
"media-document" => {
input.parse_nested_block(|input| {
let kind = MediaDocumentKind::parse(input)?;
Ok(DocumentMatchingFunction::MediaDocument(kind))
})
},
_ => {
Err(location.new_custom_error(
StyleParseErrorKind::UnexpectedFunction(function.clone())
))
},
}
}
#[cfg(feature = "gecko")]
/// Evaluate a URL matching function.
pub fn evaluate(&self, device: &Device) -> bool {
use crate::gecko_bindings::bindings::Gecko_DocumentRule_UseForPresentation;
use crate::gecko_bindings::structs::DocumentMatchingFunction as GeckoDocumentMatchingFunction;
use nsstring::nsCStr;
let func = match *self {
DocumentMatchingFunction::Url(_) => GeckoDocumentMatchingFunction::URL,
DocumentMatchingFunction::UrlPrefix(_) => GeckoDocumentMatchingFunction::URLPrefix,
DocumentMatchingFunction::Domain(_) => GeckoDocumentMatchingFunction::Domain,
DocumentMatchingFunction::Regexp(_) => GeckoDocumentMatchingFunction::RegExp,
DocumentMatchingFunction::MediaDocument(_) => {
GeckoDocumentMatchingFunction::MediaDocument
},
};
let pattern = nsCStr::from(match *self {
DocumentMatchingFunction::Url(ref url) => url.as_str(),
DocumentMatchingFunction::UrlPrefix(ref pat) |
DocumentMatchingFunction::Domain(ref pat) |
DocumentMatchingFunction::Regexp(ref pat) => pat,
DocumentMatchingFunction::MediaDocument(kind) => match kind {
MediaDocumentKind::All => "all",
MediaDocumentKind::Image => "image",
MediaDocumentKind::Plugin => "plugin",
MediaDocumentKind::Video => "video",
},
});
unsafe { Gecko_DocumentRule_UseForPresentation(device.document(), &*pattern, func) }
}
#[cfg(not(feature = "gecko"))]
/// Evaluate a URL matching function.
pub fn evaluate(&self, _: &Device) -> bool {
false
}
}
/// A `@document` rule's condition.
///
/// <https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document>
///<|fim▁hole|>/// The `@document` rule's condition is written as a comma-separated list of
/// URL matching functions, and the condition evaluates to true whenever any
/// one of those functions evaluates to true.
#[css(comma)]
#[derive(Clone, Debug, ToCss, ToShmem)]
pub struct DocumentCondition(#[css(iterable)] Vec<DocumentMatchingFunction>);
impl DocumentCondition {
/// Parse a document condition.
pub fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let conditions =
input.parse_comma_separated(|input| DocumentMatchingFunction::parse(context, input))?;
let condition = DocumentCondition(conditions);
if !condition.allowed_in(context) {
return Err(
input.new_custom_error(StyleParseErrorKind::UnsupportedAtRule(
"-moz-document".into(),
)),
);
}
Ok(condition)
}
/// Evaluate a document condition.
pub fn evaluate(&self, device: &Device) -> bool {
self.0
.iter()
.any(|url_matching_function| url_matching_function.evaluate(device))
}
#[cfg(feature = "servo")]
fn allowed_in(&self, _: &ParserContext) -> bool {
false
}
#[cfg(feature = "gecko")]
fn allowed_in(&self, context: &ParserContext) -> bool {
use crate::stylesheets::Origin;
use static_prefs::pref;
if context.stylesheet_origin != Origin::Author {
return true;
}
if pref!("layout.css.moz-document.content.enabled") {
return true;
}
// Allow a single url-prefix() for compatibility.
//
// See bug 1446470 and dependencies.
if self.0.len() != 1 {
return false;
}
// NOTE(emilio): This technically allows url-prefix("") too, but...
match self.0[0] {
DocumentMatchingFunction::UrlPrefix(ref prefix) => prefix.is_empty(),
_ => false,
}
}
}<|fim▁end|> | |
<|file_name|>styles.js<|end_file_name|><|fim▁begin|>/*!
* Copyright (c) 2014 Milo van der Linden ([email protected])
*
* This file is part of opendispatcher/safetymapsDBK
*
* opendispatcher 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.
*
* opendispatcher 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 opendispatcher. If not, see <http://www.gnu.org/licenses/>.
*
*/
/* global OpenLayers, imagesBase64 */
var dbkjs = dbkjs || {};
window.dbkjs = dbkjs;
dbkjs.config = dbkjs.config || {};
OpenLayers.Renderer.symbol.arrow = [0, 2, 1, 0, 2, 2, 1, 0, 0, 2];
/**
* Factor to scale styling elements with
*
* @returns {Number}
*/
dbkjs.getStyleScaleFactor = function () {
if (!dbkjs.options.styleScaleAdjust) {
return 1;
} else {
dbkjs.options.originalScale = dbkjs.options.originalScale ? dbkjs.options.originalScale : 595.2744;
return dbkjs.options.originalScale / dbkjs.map.getScale();
}
};
/**
* Redraw all layers for which scaling of style applies
*
*/
dbkjs.redrawScaledLayers = function () {
dbkjs.protocol.jsonDBK.layerBrandcompartiment.redraw();
dbkjs.protocol.jsonDBK.layerHulplijn2.redraw();
dbkjs.protocol.jsonDBK.layerHulplijn1.redraw();
dbkjs.protocol.jsonDBK.layerHulplijn.redraw();
dbkjs.protocol.jsonDBK.layerToegangterrein.redraw();
dbkjs.protocol.jsonDBK.layerBrandweervoorziening.redraw();
dbkjs.protocol.jsonDBK.layerGevaarlijkestof.redraw();
dbkjs.protocol.jsonDBK.layerTekstobject.redraw();
};
/**
*
* Return a styling value with user size adjustment and scaled according to map
* map scale (if style scaling is enabled). If featureAttributeValue is not
* undefined use that instead of the first argument. If attributeScaleFactor
* is not undefined scale the featureAttributeValue by that factor.
*
* @param {type} value
* @param {type} featureAttributeValue
* @param {type} attributeScaleFactor
* @returns {Number|dbkjs.options.originalScaledbkjs.options.originalScale|
*/
dbkjs.scaleStyleValue = function (value, featureAttributeValue, attributeScaleFactor) {
if (featureAttributeValue) {
attributeScaleFactor = attributeScaleFactor ? attributeScaleFactor : 1;
value = featureAttributeValue * attributeScaleFactor;
}
value = value + (dbkjs.options.styleSizeAdjust ? dbkjs.options.styleSizeAdjust : 0);
return value * dbkjs.getStyleScaleFactor();
};
dbkjs.config.styles = {
dbkfeature: new OpenLayers.StyleMap({
"default": new OpenLayers.Style({
cursor: "pointer",
display: "${mydisplay}",
graphicWidth: "${mygraphicwidth}",
graphicHeight: "${mygraphicheight}",
fontColor: "${myfontcolor}",
fontSize: "${myfontsize}",
fontWeight: "${myfontweight}",
externalGraphic: "${myicon}",
label: "${labeltext}",
labelSelect: true,
labelAlign: "${mylabelalign}",
labelXOffset: "${mylabelxoffset}",
labelYOffset: "${mylabelyoffset}",
labelOutlineWidth: 5,
labelOutlineColor: '#000000'
}, {
context: {
mydisplay: function (feature) {
if (dbkjs.map.getResolution() > 1) {
// pandgeometrie not visible above resolution 1, always show feature icon
return "true";
} else {
if (dbkjs.options.alwaysShowDbkFeature) {
// Always show feature except the active feature
if (dbkjs.options.dbk && feature.attributes.identificatie === dbkjs.options.dbk) {
return "none";
} else {
// Controleer of actieve DBK meerdere verdiepingen heeft
// en feature om display van te bepalen niet het hoofdobject
// is van de actieve DBK. Zo ja, dan niet tonen
// Gebied heeft geen verdiepingen
if (dbkjs.options.feature && dbkjs.options.feature.verdiepingen && dbkjs.options.feature.verdiepingen.length > 1) {
// Het ID van de dbk waarvan we de display property
// bepalen
var verdiepingCheckDbkId = feature.attributes.identificatie;
// Loop over alle verdiepingen van actieve feature en check
// of verdieping id overeenkomt met dbkId
for (var i = 0; i < dbkjs.options.feature.verdiepingen.length; i++) {
var verdieping = dbkjs.options.feature.verdiepingen[i];
if (verdieping.identificatie === verdiepingCheckDbkId) {
return "none";
}
}
}
return "true";
}
} else {
// User should switch layer "Naburige DBK's" on (if configured)
return "none";
}
}
},
mygraphicheight: function (feature) {
if (feature.cluster) {
return 65;
} else {
if (feature.attributes.typeFeature === 'Object') {
return 38;
} else {
return 65;
}
}
},
mygraphicwidth: function (feature) {
if (feature.cluster) {
return 85;
} else {
if (feature.attributes.typeFeature === 'Object') {
return 24;
} else {
return 85;
}
}
},
myfontweight: function (feature) {
if (feature.cluster) {
return "bold";
} else {
return "normal";
}
},
myfontsize: function (feature) {
return "10.5px";
},
mylabelalign: function (feature) {
if (feature.cluster) {
return "cc";
} else {
return "rb";
}
},
mylabelxoffset: function (feature) {
if (feature.cluster) {
return 0;
} else {
return -16;
}
},
mylabelyoffset: function (feature) {
if (feature.cluster) {
return -4;
} else {
return -9;
}
},
myfontcolor: function (feature) {
if (feature.cluster) {
return "#ffffff";
} else {
return "#000000";
}
},
myicon: function (feature) {
if (feature.cluster) {
return typeof imagesBase64 === 'undefined' ? dbkjs.basePath + "images/jcartier_city_3.png" : imagesBase64["images/jcartier_city_3.png"];
} else {
if (feature.attributes.typeFeature === 'Object') {
var img;
if (feature.attributes.verdiepingen || feature.attributes.verdiepingen !== 0) {
img = "images/jcartier_building_1.png";
} else {
img = "images/jcartier_building_2.png";
}
return typeof imagesBase64 === 'undefined' ? dbkjs.basePath + img : imagesBase64[img];
} else {
return typeof imagesBase64 === 'undefined' ? dbkjs.basePath + "images/jcartier_event_1.png" : imagesBase64["images/jcartier_event_1.png"];
}
}
},
labeltext: function (feature) {
if (dbkjs.modules.feature.showlabels) {
if (feature.cluster) {
var lbl_txt, c;
if (feature.cluster.length > 1) {
lbl_txt = feature.cluster.length + "";
} else {
lbl_txt = "";
}
return lbl_txt;
} else {
return "";
}
} else {
return "";
}
}
}
}),
"select": new OpenLayers.Style({
fontColor: "${myfontcolor}"
}, {
context: {
myfontcolor: function (feature) {
if (feature.cluster) {
return "#fff722";
} else {
return "#000000";
}
}
}
})
}),
dbkpand: new OpenLayers.StyleMap({
'default': new OpenLayers.Style({
fillColor: "${mycolor}",
fillOpacity: 0.2,
strokeColor: "${mycolor}",
strokeWidth: 1
}, {
context: {
mycolor: function (feature) {
if (feature.attributes.type) {
if (feature.attributes.type === "gebied") {
return "#B45F04";
} else {
return "#66ff66";
}
} else {
return "#66ff66";
}
}
}
}),
'select': new OpenLayers.Style({
strokeWidth: 4,
fillOpacity: 0.7
}),
'temporary': new OpenLayers.Style({
strokeWidth: 3,
fillOpacity: 0.4
})
}),
dbkcompartiment: new OpenLayers.StyleMap({
'default': new OpenLayers.Style({
strokeColor: "${mycolor}",
strokeWidth: "${mystrokewidth}",
strokeLinecap: "butt",
strokeDashstyle: "${mystrokedashstyle}",
fontColor: "${mycolor}",
pointRadius: 5,
fontSize: "12px",
fontWeight: "bold",
labelSelect: true,
labelOutlineColor: "#ffffff",
labelOutlineWidth: 1,
label: "${mylabel}"
}, {
context: {
mycolor: function (feature) {
switch (feature.attributes.type) {
case "30 minuten brandwerende scheiding":
return "#c1001f";
case "60 minuten brandwerende scheiding":
return "#5da03b";
case "> 60 minuten brandwerende scheiding":
case "> 120 minuten brandwerende scheiding":
return "#ff0000";
case "Rookwerende scheiding":
return "#009cdd";
default:
return "#000000";
}
},
mystrokewidth: function (feature) {
switch (feature.attributes.type) {
case "60 minuten brandwerende scheiding":
case "> 60 minuten brandwerende scheiding":
case "> 120 minuten brandwerende scheiding":
return dbkjs.scaleStyleValue(4);
default:
return dbkjs.scaleStyleValue(2);
}
},
mystrokedashstyle: function (feature) {
switch (feature.attributes.type) {
case "30 minuten brandwerende scheiding":
return dbkjs.scaleStyleValue(8) + " " + dbkjs.scaleStyleValue(4);
case "60 minuten brandwerende scheiding":
return dbkjs.scaleStyleValue(4) + " " + dbkjs.scaleStyleValue(4);
case "> 60 minuten brandwerende scheiding":
case "> 120 minuten brandwerende scheiding":
return "solid";
case "Rookwerende scheiding":
return dbkjs.scaleStyleValue(8) + " " + dbkjs.scaleStyleValue(4) + dbkjs.scaleStyleValue(2) + " " + dbkjs.scaleStyleValue(4);
default:
return dbkjs.scaleStyleValue(10) + " " + dbkjs.scaleStyleValue(10);
}
},
mylabel: function (feature) {
if (feature.attributes.label) {
return feature.attributes.label;
} else {
return "";
}
}
}
}),
"temporary": new OpenLayers.Style({strokeColor: "#009FC3"}),
"select": new OpenLayers.Style({strokeColor: "#8F00C3"})
}),
hulplijn: new OpenLayers.StyleMap({
'default': new OpenLayers.Style({
strokeColor: "${mycolor}",
strokeLinecap: "butt",
strokeDashstyle: "${mydash}",
fillColor: "${mycolor}",
fillOpacity: "${myopacity}",
strokeWidth: "${mywidth}",
pointRadius: 5,
rotation: "${myrotation}",
graphicName: "${mygraphic}",
label: "${information}"
}, {
context: {
myopacity: function (feature) {
switch (feature.attributes.type) {
case "Arrow":
return 0.8;
default:
return 1;
}
},
myrotation: function (feature) {
if (feature.attributes.rotation) {
return -feature.attributes.rotation;
} else {
return 0;
}
},
mywidth: function (feature) {
switch (feature.attributes.type) {
case "Conduit":
case "Gate":
case "Fence":
case "Fence_O":
return dbkjs.scaleStyleValue(8);
case "HEAT":
return dbkjs.scaleStyleValue(3);
case "Broken":
return dbkjs.scaleStyleValue(1);
case "Arrow":
return dbkjs.scaleStyleValue(2);
default:
return dbkjs.scaleStyleValue(2);
}
},
mydash: function (feature) {
switch (feature.attributes.type) {
case "Cable":
case "Bbarrier":
return dbkjs.scaleStyleValue(10) + " " + dbkjs.scaleStyleValue(10);
case "Conduit":
case "Gate":
case "Fence":
case "Fence_O":
return dbkjs.scaleStyleValue(1) + " " + dbkjs.scaleStyleValue(20);
case "Broken":
return dbkjs.scaleStyleValue(3) + " " + dbkjs.scaleStyleValue(2);
default:
return "solid";
}
},
mycolor: function (feature) {
switch (feature.attributes.type) {
//Bbarrier
//Gate
case "Bbarrier":
return "#ffffff";
case "Arrow":
return "#040404";
case "Gate":
case "Fence":
return "#000000";
case "Fence_O":
return "#ff7f00";
case "Cable":
return "#ffff00";
case "Conduit":
return "#ff00ff";
case "HEAT":
return "#ff0000";
default:
return "#000000";
}
},
mygraphic: function (feature) {
switch (feature.attributes.type) {
case "Arrow":
return "triangle";
default:
return "";
}
}
}
}),
"temporary": new OpenLayers.Style({strokeColor: "#009FC3"}),
"select": new OpenLayers.Style({strokeColor: "#8F00C3"})}),
hulplijn1: new OpenLayers.StyleMap({
'default': new OpenLayers.Style({
strokeColor: "${mycolor}",
strokeDashstyle: "${mydash}",
strokeWidth: "${mywidth}"
}, {
context: {
mywidth: function (feature) {
switch (feature.attributes.type) {
case "Cable":
case "Bbarrier":
return dbkjs.scaleStyleValue(4);
case "Conduit":
case "Gate":
case "Fence":
case "Fence_O":
return dbkjs.scaleStyleValue(2);
default:
return dbkjs.scaleStyleValue(2);
}
},
mydash: function (feature) {
switch (feature.attributes.type) {
default:
return "none";
}
},
mycolor: function (feature) {
switch (feature.attributes.type) {
case "Conduit":
return "#ff00ff";
case "Bbarrier":
return "#ff0000";
case "Gate":
return "#ffffff";
case "Fence_O":
return "#ff7f00";
default:
return "#000000";
}
}
}
}),
"temporary": new OpenLayers.Style({strokeColor: "#009FC3"}),
"select": new OpenLayers.Style({strokeColor: "#8F00C3"})}),
hulplijn2: new OpenLayers.StyleMap({
'default': new OpenLayers.Style({
strokeColor: "${mycolor}",
strokeDashstyle: "${mydash}",
strokeWidth: "${mywidth}"
}, {
context: {
mywidth: function (feature) {
switch (feature.attributes.type) {
case "Gate":
return dbkjs.scaleStyleValue(5);
default:
return dbkjs.scaleStyleValue(2);
}
},
mydash: function (feature) {
switch (feature.attributes.type) {
case "Gate":
return "none";
default:
return "none";
}
},
mycolor: function (feature) {
switch (feature.attributes.type) {
case "Gate":
return "#000000";
default:
return "#000000";
}
}
}
}),
"temporary": new OpenLayers.Style({strokeColor: "#009FC3"}),
"select": new OpenLayers.Style({strokeColor: "#8F00C3"})}),
toegangterrein: new OpenLayers.StyleMap({
'default': new OpenLayers.Style({
strokeColor: "${mycolor}",
fillColor: "${mycolor}",
fillOpacity: 0.9,
strokeWidth: "${mywidth}",
pointRadius: 5,
rotation: "${myrotation}",
graphicName: "${mygraphic}"
}, {
context: {
myrotation: function(feature) {
if (feature.attributes.rotation) {
return -feature.attributes.rotation;
} else {
return 0;
}
},
mycolor: function (feature) {
switch (feature.attributes.primary) {
case true:
return "#ff0000";
default:
return "#00ff00";
}
},
mygraphic: function (feature) {
return "triangle";
},
mywidth: function (feature) {
return dbkjs.scaleStyleValue(1);
}
}
}),
'select': new OpenLayers.Style({}),
'temporary': new OpenLayers.Style({})}),
pandstylemap: new OpenLayers.StyleMap({
fillColor: "yellow",
fillOpacity: 0.4,
strokeColor: "red",
strokeWidth: 2,
pointRadius: 5
}),
vbostylemap: new OpenLayers.StyleMap({
fillColor: "black",
fillOpacity: 0.4,
strokeColor: "black",
strokeWidth: 1,
pointRadius: 3
}),
brandweervoorziening: new OpenLayers.StyleMap({
"default": new OpenLayers.Style({
pointRadius: "${myradius}",
externalGraphic: "${myicon}",
rotation: "${myrotation}",
display: "${mydisplay}"
}, {
context: {
myicon: function (feature) {<|fim▁hole|> },
myrotation: function (feature) {
if (feature.attributes.rotation) {
return -feature.attributes.rotation;
} else {
return 0;
}
},
myradius: function (feature) {
return dbkjs.scaleStyleValue(12, feature.attributes.radius);
},
mydisplay: function (feature) {
// This function is overridden by layertoggle module
// Any string except "none" means display feature
return "true";
/*
if (dbkjs.options.visibleCategories &&
feature.attributes.category &&
dbkjs.options.visibleCategories[feature.attributes.category] === false) {
return "none";
} else {
// any string except "none" works here
return "true";
}
*/
}
}
}), 'select': new OpenLayers.Style({
pointRadius: "${myradius}"
}, {
context: {
myradius: function (feature) {
return dbkjs.scaleStyleValue(20, feature.attributes.radius, 1.66);
}
}
}), 'temporary': new OpenLayers.Style({
pointRadius: "${myradius}"
}, {
context: {
myradius: function (feature) {
return dbkjs.scaleStyleValue(24, feature.attributes.radius, 2);
}
}
})
}),
gevaarlijkestof: new OpenLayers.StyleMap({
"default": new OpenLayers.Style({
pointRadius: "${myradius}",
externalGraphic: "${myicon}"
}, {
context: {
myradius: function (feature) {
return dbkjs.scaleStyleValue(12);
},
myicon: function (feature) {
var img = "images/" + feature.attributes.namespace.toLowerCase() + "/" + feature.attributes.type + ".png";
return typeof imagesBase64 === 'undefined' ? dbkjs.basePath + img : imagesBase64[img];
}
}
}), 'select': new OpenLayers.Style({
pointRadius: "${myradius}"
}, {
context: {
myradius: function (feature) {
return dbkjs.scaleStyleValue(20);
}
}
}), 'temporary': new OpenLayers.Style({
pointRadius: "${myradius}"
}, {
context: {
myradius: function (feature) {
return dbkjs.scaleStyleValue(25);
}
}
})
}),
comm: new OpenLayers.StyleMap({
"default": new OpenLayers.Style({
pointRadius: "${myradius}",
externalGraphic: "${myicon}"
}, {
context: {
myradius: function (feature) {
return dbkjs.scaleStyleValue(12);
},
myicon: function (feature) {
var img = "images/" + feature.attributes.namespace_hidden + "/" + feature.attributes.type_hidden + ".png";
return typeof imagesBase64 === 'undefined' ? dbkjs.basePath + img : imagesBase64[img];
}
}
}), 'select': new OpenLayers.Style({
pointRadius: "${myradius}"
}, {
context: {
myradius: function (feature) {
return dbkjs.scaleStyleValue(20);
}
}
}), 'temporary': new OpenLayers.Style({
pointRadius: "${myradius}"
}, {
context: {
myradius: function (feature) {
return dbkjs.scaleStyleValue(25);
}
}
})
}),
tekstobject: new OpenLayers.StyleMap({
"default": new OpenLayers.Style({
pointRadius: 0,
fontSize: "${mysize}",
label: "${title}",
rotation: "${myRotation}",
labelSelect: true,
labelOutlineColor: "#ffffff",
labelOutlineWidth: 1
}, {
context: {
mysize: function (feature) {
return dbkjs.scaleStyleValue(12, feature.attributes.scale);
},
myRotation: function (feature) {
if (parseFloat(feature.attributes.rotation) !== 0.0) {
var ori = parseFloat(feature.attributes.rotation);
return -ori;
} else {
return parseFloat(0);
}
}
}
}),
'select': new OpenLayers.Style({}),
'temporary': new OpenLayers.Style({})
})
};<|fim▁end|> | var img = "images/" + feature.attributes.namespace.toLowerCase() + "/" + feature.attributes.type + ".png";
return typeof imagesBase64 === 'undefined' ? dbkjs.basePath + img : imagesBase64[img]; |
<|file_name|>ants.js<|end_file_name|><|fim▁begin|>import * as util from '../src/utils.js'
import World from '../src/World.js'
import Color from '../src/Color.js'
import ColorMap from '../src/ColorMap.js'
import ThreeView from '../src/ThreeView.js'
const params = util.RESTapi({
seed: false,
population: 100,
maxX: 30,
maxY: 30,
steps: 500,
shapeSize: 2,
})
if (params.seed) util.randomSeed()
params.world = World.defaultOptions(params.maxX, params.maxY)
const nestColor = Color.typedColor('yellow')
const foodColor = Color.typedColor('blue')
const nestColorMap = ColorMap.gradientColorMap(20, ['black', nestColor.css])
const foodColorMap = ColorMap.gradientColorMap(20, ['black', foodColor.css])
const worker = new Worker('./antsWorker.js', { type: 'module' })
worker.postMessage({ cmd: 'init', params: params })
const view = new ThreeView(params.world)
const nestSprite = view.getSprite('bug', nestColor.css)
const foodSprite = view.getSprite('bug', foodColor.css)
util.toWindow({ view, worker, params, util })
const perf = util.fps() // Just for testing, not needed for production.
worker.onmessage = e => {
if (e.data === 'done') {
console.log(`Done, steps: ${perf.steps}, fps: ${perf.fps}`)
view.idle()
} else {
view.drawPatches(e.data.patches, p => {
if (p.isNest) return nestColor.pixel
if (p.isFood) return foodColor.pixel
const color =
p.foodPheromone > p.nestPheromone
? foodColorMap.scaleColor(p.foodPheromone, 0, 1)
: nestColorMap.scaleColor(p.nestPheromone, 0, 1)
return color.pixel
})
view.drawTurtles(e.data.turtles, t => ({<|fim▁hole|> size: params.shapeSize,
}))
view.render()
worker.postMessage({ cmd: 'step' })
perf()
}
}
// util.timeoutLoop(() => {
// model.step()
// view.drawPatches(model.patches, p => {
// if (p.isNest) return nestColor.pixel
// if (p.isFood) return foodColor.pixel
// const color =
// p.foodPheromone > p.nestPheromone
// ? foodColorMap.scaleColor(p.foodPheromone, 0, 1)
// : nestColorMap.scaleColor(p.nestPheromone, 0, 1)
// return color.pixel
// })
// view.drawTurtles(model.turtles, t => ({
// sprite: t.carryingFood ? nestSprite : foodSprite,
// size: params.shapeSize,
// }))
// view.render()
// perf()
// }, 500).then(() => {
// console.log(`Done, steps: ${perf.steps}, fps: ${perf.fps}`)
// view.idle()
// })<|fim▁end|> | sprite: t.carryingFood ? nestSprite : foodSprite, |
<|file_name|>signals.py<|end_file_name|><|fim▁begin|>"""
Grades related signals.
"""
from django.dispatch import Signal
# Signal that indicates that a user's score for a problem has been updated.
# This signal is generated when a scoring event occurs either within the core
# platform or in the Submissions module. Note that this signal will be triggered
# regardless of the new and previous values of the score (i.e. it may be the
# case that this signal is generated when a user re-attempts a problem but
# receives the same score).
PROBLEM_SCORE_CHANGED = Signal(
providing_args=[
'user_id', # Integer User ID
'course_id', # Unicode string representing the course<|fim▁hole|> 'points_possible', # Maximum score available for the exercise
'only_if_higher', # Boolean indicating whether updates should be
# made only if the new score is higher than previous.
]
)
# Signal that indicates that a user's score for a problem has been published
# for possible persistence and update. Typically, most clients should listen
# to the PROBLEM_SCORE_CHANGED signal instead, since that is signalled only after the
# problem's score is changed.
SCORE_PUBLISHED = Signal(
providing_args=[
'block', # Course block object
'user', # User object
'raw_earned', # Score obtained by the user
'raw_possible', # Maximum score available for the exercise
'only_if_higher', # Boolean indicating whether updates should be
# made only if the new score is higher than previous.
]
)
# Signal that indicates that a user's score for a subsection has been updated.
# This is a downstream signal of PROBLEM_SCORE_CHANGED sent for each affected containing
# subsection.
SUBSECTION_SCORE_CHANGED = Signal(
providing_args=[
'course', # Course object
'user', # User object
'subsection_grade', # SubsectionGrade object
]
)<|fim▁end|> | 'usage_id', # Unicode string indicating the courseware instance
'points_earned', # Score obtained by the user |
<|file_name|>replace.ts<|end_file_name|><|fim▁begin|>/* eslint-disable unicorn/consistent-function-scoping */
import { ensure, isDefined, isString } from 'tiny-types';
import { AnswersQuestions } from '../../../actor';
import { Answerable } from '../../../Answerable';
import { AnswerMappingFunction } from '../AnswerMappingFunction';
/**
* @desc
* Returns a new string with some or all matches of a pattern replaced by a replacement.
* The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
* If pattern is a string, only the first occurrence will be replaced.
*
* @param {Answerable<string | RegExp>} pattern
*
* @param {Answerable<string|function>} replacement
*
* @returns {MappingFunction<string, string>}
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
*/
export function replace(pattern: Answerable<RegExp | string>, replacement: Answerable<string | ((substring: string, ...args: any[]) => string)>): AnswerMappingFunction<string, string> {<|fim▁hole|> return (actor: AnswersQuestions) =>
(value: string) => {
ensure('The value to be mapped', value, isDefined(), isString())
return Promise.all([
actor.answer(pattern),
actor.answer(replacement),
]).then(([p, r]) =>
value.replace(p, r as any),
);
}
}<|fim▁end|> | |
<|file_name|>shard_test.go<|end_file_name|><|fim▁begin|>package shard
import (
"fmt"
"math"
"sort"
"testing"
"time"
"github.com/coreos/go-etcd/etcd"
"github.com/csigo/ephemeral"
"github.com/csigo/portforward"
"github.com/csigo/test"
"github.com/golang/groupcache/consistenthash"
"github.com/satori/go.uuid"
"github.com/spaolacci/murmur3"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
const (
svr1 = "127.0.0.1:8080"
svr2 = "192.168.0.1:81"
svr3 = "10.0.0.1:4000"
testEmRoot = "/htc.com/csi/groupcache"
)
var (
etcdCli *etcd.Client<|fim▁hole|> suite.Suite
etcdOriPort int
etcdPort int
stopForward chan struct{}
forwarder func() (chan struct{}, error)
}
func portForwarder(from, to string) func() (chan struct{}, error) {
return func() (chan struct{}, error) {
return portforward.PortForward(
from, to,
)
}
}
func TestConnHashTestSuite(t *testing.T) {
if testing.Short() {
t.Skip("Skipping zk shard test in short mode.")
}
//launch zk
sl := test.NewServiceLauncher()
etcdOriPort, stopEtcd, err := sl.Start(test.Etcd)
assert.NoError(t, err)
s := new(ConnHashTestSuite)
s.etcdOriPort = etcdOriPort
s.etcdPort = 3333 // used for port forward
s.forwarder = portForwarder(
fmt.Sprintf(":%d", s.etcdPort), fmt.Sprintf(":%d", s.etcdOriPort))
s.stopForward, err = s.forwarder()
assert.NoError(t, err, "no error")
// non-forward etcdCli
etcdCli = etcd.NewClient([]string{fmt.Sprintf("http://localhost:%d", etcdOriPort)})
// forwardable etcdCli
etcdForwdCli = etcd.NewClient([]string{fmt.Sprintf("http://localhost:%d", s.etcdPort)})
suite.Run(t, s)
// clean up the forwarding
s.stopForward <- struct{}{}
etcdCli.Close()
etcdForwdCli.Close()
assert.NoError(s.T(), stopEtcd())
}
func (c *ConnHashTestSuite) TestNewConnHashTimeout() {
// overwrite log.Exiter as do noting, otherwise,
// we will go to fatal since conn is closed and we attemp to create a znode on a closed conn
em, err := ephemeral.NewEtcdEphemeral(etcdCli)
assert.NoError(c.T(), err, "should get the connection")
conn, err := NewConsistentHashResServer(em, testEmRoot, svr3,
ConsistentHashMapReplicaNum, time.Nanosecond, dummy{})
fmt.Printf("result of NewConsistentHashResServer %v, %v\n", conn, err)
assert.Error(c.T(), err, "should hit timeout error")
assert.Equal(c.T(), err, ErrConnTimedOut)
assert.Nil(c.T(), conn, "should be nil")
em.Close()
fmt.Println("done")
}
func (c *ConnHashTestSuite) TestConsistentHashRes() {
//creates two servers 127.0.0.1:8080 and 192.168.0.1:81
//testing key uid[1-10]. Compare the result against
//direct hash calculation from consistenthash.Map
//first connect server 1 and server 2
//consistent server 1
t := c.T()
em1, err := ephemeral.NewEtcdEphemeral(etcdForwdCli)
if err != nil {
t.Fatalf("Connect to zk error for server1: %s", err)
}
conn1, err := NewConsistentHashResServer(em1, testEmRoot, svr1,
ConsistentHashMapReplicaNum, time.Second, dummy{})
if err != nil {
t.Fatalf("consistent server 1 %s create failed:%s", svr1, err)
}
assert.Equal(t, conn1.HostPort(), svr1)
// wait zk change to stablize
time.Sleep(1 * time.Second)
assert.True(t, conn1.IsMyKey("any keys"), "should always be true since only one server only")
//consistent server 2
em2, err := ephemeral.NewEtcdEphemeral(etcdForwdCli)
if err != nil {
t.Fatalf("Connect to zk error for server2: %s", err)
}
conn2, err := NewConsistentHashResServer(em2, testEmRoot, svr2,
ConsistentHashMapReplicaNum, time.Second, dummy{})
if err != nil {
t.Fatalf("consistent server 2 %s create failed:%s", svr2, err)
}
assert.Equal(t, conn2.HostPort(), svr2)
//client
emClient, err := ephemeral.NewEtcdEphemeral(etcdForwdCli)
assert.NoError(t, err)
client, err := NewConsistentHashResClient(emClient, testEmRoot,
ConsistentHashMapReplicaNum, time.Second, dummy{})
if err != nil {
t.Fatalf("consistent client create failed:%s", err)
}
assert.Equal(t, client.HostPort(), "")
//add server 1 and 2
cmap := consistenthash.New(ConsistentHashMapReplicaNum, murmur3.Sum32)
cmap.Add(svr1, svr2)
//verify hashes are the same across all instances
verifyAnswer(t, cmap, conn1, conn2, client)
//verify peers
verifyPeers(t, client.GetResources(), []string{svr1, svr2})
// verify shard assignment distribution
verifyShardDist(t, client, 2, 1000)
//add another server
em3, err := ephemeral.NewEtcdEphemeral(etcdForwdCli)
if err != nil {
t.Fatalf("Connect to zk error for server3: %s", err)
}
conn3, err := NewConsistentHashResServer(em3, testEmRoot, svr3,
ConsistentHashMapReplicaNum, time.Second, dummy{})
if err != nil {
t.Fatalf("consistent server 3 %s create failed:%s", svr3, err)
}
assert.Equal(t, conn3.HostPort(), svr3)
cmap.Add(svr3)
//verify hashes are the same across all instances
verifyAnswer(t, cmap, conn1, conn3, client, conn1)
//verify peers
verifyPeers(t, client.GetResources(), []string{svr1, svr2, svr3})
// verify shard assignment distribution
verifyShardDist(t, client, 3, 1000)
// when zk are unreachable for like 20 seconds
// all znodes are expired due to clent session is expired by zk
// when the zkconn is back again, we still can do sharding
c.stopForward <- struct{}{}
time.Sleep(10 * time.Second)
// make conn alive
c.stopForward, _ = c.forwarder()
time.Sleep(time.Second) // wait one second for ready
//verify peers
verifyPeers(t, client.GetResources(), []string{svr1, svr2, svr3})
// verify shard assignment distribution
verifyShardDist(t, client, 3, 1000)
conn1.Close()
conn2.Close()
conn3.Close()
client.Close()
emClient.Close()
em1.Close()
em2.Close()
em3.Close()
}
func verifyPeers(t *testing.T, recv []string, expect []string) {
if len(recv) != len(expect) {
t.Errorf("peers are different. Expecting %v, received %v", expect, recv)
}
sort.Strings(recv)
sort.Strings(expect)
for i := 0; i < len(recv); i++ {
if recv[i] != expect[i] {
t.Errorf("peers are different. Expecting %v, received %v", expect, recv)
break
}
}
}
func verifyAnswer(t *testing.T, cmap *consistenthash.Map, servers ...*ConsistentHashRes) {
//give zk sometime to stabalize
time.Sleep(time.Second)
for i := 0; i < 10; i++ {
key := fmt.Sprintf("uid%d", i)
answer := cmap.Get(key)
for _, s := range servers {
shash, _ := s.Get(key)
if answer != shash {
t.Errorf("for %s expected %s, %s responded %s",
key, answer, s.HostPort(), shash)
}
}
}
}
func (c *ConnHashTestSuite) TestShardDistribution() {
checkShardDispatch(c.T(), 5, 1000)
checkShardDispatch(c.T(), 10, 10000)
checkShardDispatch(c.T(), 80, 100000)
}
func checkShardDispatch(t *testing.T, nServer int, iteration int) {
replica := ConsistentHashMapReplicaNum
em, err := ephemeral.NewEtcdEphemeral(etcdForwdCli)
if err != nil {
t.Fatalf("Connect to zk error for server1: %s", err)
}
defer em.Close()
fmt.Println("start creating shard host")
for i := 0; i < nServer; i++ {
name := fmt.Sprintf("192.168.0.1:%d", i)
conn, err := NewConsistentHashResServer(em, testEmRoot, name,
replica, 5*time.Second, dummy{})
if err != nil {
t.Fatalf("consistent server %s create failed:%s", name, err)
}
fmt.Printf("%d\t", i)
defer conn.Close()
assert.Equal(t, conn.HostPort(), name)
}
fmt.Println("finish creating shard host")
// take a snap to get ready
time.Sleep(time.Second)
emClient, err := ephemeral.NewEtcdEphemeral(etcdForwdCli)
assert.NoError(t, err)
defer emClient.Close()
client, err := NewConsistentHashResClient(emClient, testEmRoot,
replica, 5*time.Second, dummy{})
if err != nil {
t.Fatalf("consistent client create failed:%s", err)
}
defer client.Close()
assert.Equal(t, client.HostPort(), "")
verifyShardDist(t, client, nServer, iteration)
}
func verifyShardDist(t *testing.T, client *ConsistentHashRes, nShard int, n int) {
sdMax := float64(6)
result := make(map[string]int)
fmt.Println("========================")
for i := 0; i < n; i++ {
id := murmur3.Sum64(uuid.NewV4().Bytes())
info, ok := client.Get(fmt.Sprintf("%d", id))
assert.True(t, ok, "should get shard info")
if _, b := result[info]; b == true {
result[info]++
} else {
result[info] = 1
}
}
avg := float64(100.0) / float64(nShard)
var sum float64
for key, val := range result {
fmt.Printf("%s, count = %d\n", key, val)
sum += math.Pow(((100.0 * float64(val) / float64(n)) - avg), 2)
}
sd := math.Sqrt(sum / float64(nShard))
fmt.Printf("average: %.3f%% standard deviation: %.3f%%\n", avg, sd)
if sd > sdMax {
assert.Fail(t, fmt.Sprintf("standard deviation is too high %v", sd))
}
}
func TestExtractIPort(t *testing.T) {
ipport := "192.180.1.1:1234"
v, err := ExtractIPPort(ipport + seperator + "xxxxx")
assert.NoError(t, err)
assert.Equal(t, ipport, v)
v, err = ExtractIPPort(ipport + seperator)
assert.NoError(t, err)
assert.Equal(t, ipport, v)
v, err = ExtractIPPort(ipport)
assert.NoError(t, err)
assert.Equal(t, ipport, v)
v, err = ExtractIPPort("xxxxxyyyyyy")
assert.NoError(t, err)
assert.Equal(t, "xxxxxyyyyyy", v)
v, err = ExtractIPPort("")
assert.NoError(t, err)
assert.Equal(t, "", v)
}
type dummy struct{}
func (d dummy) BumpAvg(key string, val float64) {}
func (d dummy) BumpSum(key string, val float64) {}
func (d dummy) BumpHistogram(key string, val float64) {}
func (d dummy) End() {}
func (d dummy) BumpTime(key string) interface {
End()
} {
return dummy{}
}<|fim▁end|> | etcdForwdCli *etcd.Client
)
type ConnHashTestSuite struct { |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.apps import apps
from django.contrib import admin
AccessToken = apps.get_model('oauth2', 'AccessToken')
Client = apps.get_model('oauth2', 'Client')
Grant = apps.get_model('oauth2', 'Grant')
RefreshToken = apps.get_model('oauth2', 'RefreshToken')
class AccessTokenAdmin(admin.ModelAdmin):<|fim▁hole|>
class GrantAdmin(admin.ModelAdmin):
list_display = ('user', 'client', 'code', 'expires')
raw_id_fields = ('user',)
class ClientAdmin(admin.ModelAdmin):
list_display = ('url', 'user', 'redirect_uri', 'client_id', 'client_type')
raw_id_fields = ('user',)
admin.site.register(AccessToken, AccessTokenAdmin)
admin.site.register(Grant, GrantAdmin)
admin.site.register(Client, ClientAdmin)
admin.site.register(RefreshToken)<|fim▁end|> | list_display = ('user', 'client', 'token', 'expires', 'scope')
raw_id_fields = ('user',) |
<|file_name|>resources.py<|end_file_name|><|fim▁begin|># coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.base.payload import Payload
from pants.base.target import Target
class Resources(Target):
"""A set of files accessible as resources from the JVM classpath.
Looking for loose files in your application bundle? Those are
`bundle <#bundle>`_\s.
Resources are Java-style resources accessible via the ``Class.getResource``
and friends API. In the ``jar`` goal, the resource files are placed in the resulting `.jar`.
"""
def __init__(self, address=None, payload=None, sources=None, **kwargs):
"""
:param sources: Files to "include". Paths are relative to the<|fim▁hole|> payload = payload or Payload()
payload.add_fields({
'sources': self.create_sources_field(sources,
sources_rel_path=address.spec_path, key_arg='sources'),
})
super(Resources, self).__init__(address=address, payload=payload, **kwargs)
def has_sources(self, extension=None):
"""``Resources`` never own sources of any particular native type, like for example
``JavaLibrary``.
"""
# TODO(John Sirois): track down the reason for this hack and kill or explain better.
return extension is None<|fim▁end|> | BUILD file's directory.
:type sources: ``Fileset`` or list of strings
""" |
<|file_name|>tests.rs<|end_file_name|><|fim▁begin|>use scanner::tokenize;
use scanner::tokens::Token;
use scanner::tokens::Token::*;
#[test]
fn scan_terminals() {
let expected = vec![Lparen, Rparen, Dot];
let actual = tokenize("().");
assert_eq!(expected, actual);
}
#[test]
fn scan_base_command() {
let expected: Vec<Token> = vec![
Base,
Ident("name".to_string()),
Lparen,
Ident("A50".to_string()),
Rparen,
Dot];
let actual = tokenize("base name (A50).");
assert_eq!(expected, actual);
}
#[test]
fn scan_end_command() {
let expected = vec![End, Dot];
let actual = tokenize("end.");
assert_eq!(expected, actual);
}
#[test]
fn scan_unicode_ident() {<|fim▁hole|>
assert_eq!(expected, actual);
}
#[test]
fn scan_keywords() {
let expected = vec![Database, Base, Type, End];
let actual = tokenize("database base type end");
assert_eq!(expected, actual);
}<|fim▁end|> | // todo: add some unicode characters to the test
let expected = vec![Lparen, Ident("abc1231".to_string()), Rparen];
let actual = tokenize("(abc1231)"); |
<|file_name|>galaxy.cpp<|end_file_name|><|fim▁begin|>// license:BSD-3-Clause
// copyright-holders:Krzysztof Strzecha, Miodrag Milanovic
/***************************************************************************
Galaksija driver by Krzysztof Strzecha and Miodrag Milanovic
22/05/2008 Tape support added (Miodrag Milanovic)
21/05/2008 Galaksija plus initial support (Miodrag Milanovic)
20/05/2008 Added real video implementation (Miodrag Milanovic)
18/04/2005 Possibilty to disable ROM 2. 2k, 22k, 38k and 54k memory
configurations added.
13/03/2005 Memory mapping improved. Palette corrected. Supprort for newer
version of snapshots added. Lot of cleanups. Keyboard mapping
corrected.
19/09/2002 malloc() replaced by image_malloc().
15/09/2002 Snapshot loading fixed. Code cleanup.
31/01/2001 Snapshot loading corrected.
09/01/2001 Fast mode implemented (many thanks to Kevin Thacker).
07/01/2001 Keyboard corrected (still some keys unknown).
Horizontal screen positioning in video subsystem added.
05/01/2001 Keyboard implemented (some keys unknown).
03/01/2001 Snapshot loading added.
01/01/2001 Preliminary driver.
***************************************************************************/
#include "emu.h"
#include "cpu/z80/z80.h"
#include "sound/wave.h"
#include "includes/galaxy.h"
#include "imagedev/snapquik.h"
#include "imagedev/cassette.h"
#include "sound/ay8910.h"
#include "formats/gtp_cas.h"
#include "machine/ram.h"
#include "softlist.h"
static ADDRESS_MAP_START (galaxyp_io, AS_IO, 8, galaxy_state )
ADDRESS_MAP_GLOBAL_MASK(0x01)
ADDRESS_MAP_UNMAP_HIGH
AM_RANGE(0xbe, 0xbe) AM_DEVWRITE("ay8910", ay8910_device, address_w)
AM_RANGE(0xbf, 0xbf) AM_DEVWRITE("ay8910", ay8910_device, data_w)
ADDRESS_MAP_END
static ADDRESS_MAP_START (galaxy_mem, AS_PROGRAM, 8, galaxy_state )
AM_RANGE(0x0000, 0x0fff) AM_ROM
AM_RANGE(0x2000, 0x2037) AM_MIRROR(0x07c0) AM_READ(galaxy_keyboard_r )
AM_RANGE(0x2038, 0x203f) AM_MIRROR(0x07c0) AM_WRITE(galaxy_latch_w )
ADDRESS_MAP_END
static ADDRESS_MAP_START (galaxyp_mem, AS_PROGRAM, 8, galaxy_state )
AM_RANGE(0x0000, 0x0fff) AM_ROM // ROM A
AM_RANGE(0x1000, 0x1fff) AM_ROM // ROM B
AM_RANGE(0x2000, 0x2037) AM_MIRROR(0x07c0) AM_READ(galaxy_keyboard_r )
AM_RANGE(0x2038, 0x203f) AM_MIRROR(0x07c0) AM_WRITE(galaxy_latch_w )
AM_RANGE(0xe000, 0xefff) AM_ROM // ROM C
AM_RANGE(0xf000, 0xffff) AM_ROM // ROM D
ADDRESS_MAP_END
/* 2008-05 FP:
Small note about natural keyboard support. Currently:
- "List" is mapped to 'ESC'
- "Break" is mapped to 'F1'
- "Repeat" is mapped to 'F2' */
static INPUT_PORTS_START (galaxy_common)
PORT_START("LINE0")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_UNUSED)
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_A) PORT_CHAR('A')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_B) PORT_CHAR('B')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_C) PORT_CHAR('C')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_D) PORT_CHAR('D')
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_E) PORT_CHAR('E')
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_F) PORT_CHAR('F')
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_G) PORT_CHAR('G')
PORT_START("LINE1")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_H) PORT_CHAR('H')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_I) PORT_CHAR('I')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_J) PORT_CHAR('J')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_K) PORT_CHAR('K')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_L) PORT_CHAR('L')
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_M) PORT_CHAR('M')
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_N) PORT_CHAR('N')
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_O) PORT_CHAR('O')
PORT_START("LINE2")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_P) PORT_CHAR('P')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_Q) PORT_CHAR('Q')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_R) PORT_CHAR('R')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_S) PORT_CHAR('S')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_T) PORT_CHAR('T')
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_U) PORT_CHAR('U')
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_V) PORT_CHAR('V')
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_W) PORT_CHAR('W')
PORT_START("LINE3")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_X) PORT_CHAR('X')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_Y) PORT_CHAR('Y')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_Z) PORT_CHAR('Z')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_UP) PORT_CHAR(UCHAR_MAMEKEY(UP))
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_DOWN) PORT_CHAR(UCHAR_MAMEKEY(DOWN))
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_LEFT) PORT_CHAR(UCHAR_MAMEKEY(LEFT))
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_RIGHT) PORT_CHAR(UCHAR_MAMEKEY(RIGHT))
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ')
PORT_START("LINE4")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_0) PORT_CHAR('0') PORT_CHAR('_')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_1) PORT_CHAR('1') PORT_CHAR('!')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_2) PORT_CHAR('2') PORT_CHAR('"')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_3) PORT_CHAR('3') PORT_CHAR('#')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_4) PORT_CHAR('4') PORT_CHAR('$')
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_5) PORT_CHAR('5') PORT_CHAR('%')
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_6) PORT_CHAR('6') PORT_CHAR('&')
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_7) PORT_CHAR('7') PORT_CHAR('\'')
PORT_START("LINE5")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_8) PORT_CHAR('8') PORT_CHAR('(')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_9) PORT_CHAR('9') PORT_CHAR(')')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_COLON) PORT_CHAR(';') PORT_CHAR('+')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_QUOTE) PORT_CHAR(':') PORT_CHAR('*')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_COMMA) PORT_CHAR(',') PORT_CHAR('<')
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_EQUALS) PORT_CHAR('=') PORT_CHAR('-')
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_STOP) PORT_CHAR('.') PORT_CHAR('>')
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_SLASH) PORT_CHAR('/') PORT_CHAR('?')
PORT_START("LINE6")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_ENTER) PORT_CHAR(13)
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("Break") PORT_CODE(KEYCODE_PAUSE) PORT_CHAR(UCHAR_MAMEKEY(F1))
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("Repeat") PORT_CODE(KEYCODE_LALT) PORT_CHAR(UCHAR_MAMEKEY(F2))
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("Delete") PORT_CODE(KEYCODE_BACKSPACE) PORT_CHAR(8)
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("List") PORT_CODE(KEYCODE_ESC) PORT_CHAR(UCHAR_MAMEKEY(ESC))
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_LSHIFT) PORT_CODE(KEYCODE_RSHIFT) PORT_CHAR(UCHAR_SHIFT_1)
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_UNUSED)
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_UNUSED)
INPUT_PORTS_END
static INPUT_PORTS_START( galaxy )
PORT_INCLUDE( galaxy_common )
PORT_START("ROM2")
PORT_CONFNAME(0x01, 0x01, "ROM 2")
PORT_CONFSETTING(0x01, "Installed")
PORT_CONFSETTING(0x00, "Not installed")
INPUT_PORTS_END
static INPUT_PORTS_START( galaxyp )
PORT_INCLUDE( galaxy_common )
INPUT_PORTS_END
#define XTAL 6144000
/* F4 Character Displayer */
static const gfx_layout galaxy_charlayout =
{
8, 16, /* 8 x 16 characters */
128, /* 128 characters */
1, /* 1 bits per pixel */
{ 0 }, /* no bitplanes */
/* x offsets */
{ 7, 6, 5, 4, 3, 2, 1, 0 },
/* y offsets */
{ 0, 1*128*8, 2*128*8, 3*128*8, 4*128*8, 5*128*8, 6*128*8, 7*128*8, 8*128*8, 9*128*8, 10*128*8, 11*128*8, 12*128*8, 13*128*8, 14*128*8, 15*128*8 },
8 /* every char takes 1 x 16 bytes */<|fim▁hole|>};
static GFXDECODE_START( galaxy )
GFXDECODE_ENTRY( "gfx1", 0x0000, galaxy_charlayout, 0, 1 )
GFXDECODE_END
static MACHINE_CONFIG_START( galaxy, galaxy_state )
/* basic machine hardware */
MCFG_CPU_ADD("maincpu", Z80, XTAL / 2)
MCFG_CPU_PROGRAM_MAP(galaxy_mem)
MCFG_CPU_VBLANK_INT_DRIVER("screen", galaxy_state, galaxy_interrupt)
MCFG_CPU_IRQ_ACKNOWLEDGE_DRIVER(galaxy_state,galaxy_irq_callback)
MCFG_SCREEN_ADD("screen", RASTER)
MCFG_SCREEN_REFRESH_RATE(50)
MCFG_SCREEN_PALETTE("palette")
MCFG_MACHINE_RESET_OVERRIDE(galaxy_state, galaxy )
/* video hardware */
MCFG_SCREEN_SIZE(384, 212)
MCFG_SCREEN_VISIBLE_AREA(0, 384-1, 0, 208-1)
MCFG_SCREEN_UPDATE_DRIVER(galaxy_state, screen_update_galaxy)
MCFG_GFXDECODE_ADD("gfxdecode", "palette", galaxy)
MCFG_PALETTE_ADD_MONOCHROME("palette")
/* snapshot */
MCFG_SNAPSHOT_ADD("snapshot", galaxy_state, galaxy, "gal", 0)
MCFG_SPEAKER_STANDARD_MONO("mono")
MCFG_SOUND_WAVE_ADD(WAVE_TAG, "cassette")
MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.25)
MCFG_CASSETTE_ADD( "cassette" )
MCFG_CASSETTE_FORMATS(gtp_cassette_formats)
MCFG_CASSETTE_DEFAULT_STATE(CASSETTE_STOPPED | CASSETTE_SPEAKER_ENABLED | CASSETTE_MOTOR_ENABLED)
MCFG_CASSETTE_INTERFACE("galaxy_cass")
MCFG_SOFTWARE_LIST_ADD("cass_list","galaxy")
/* internal ram */
MCFG_RAM_ADD(RAM_TAG)
MCFG_RAM_DEFAULT_SIZE("6K")
MCFG_RAM_EXTRA_OPTIONS("2K,22K,38K,54K")
MACHINE_CONFIG_END
static MACHINE_CONFIG_START( galaxyp, galaxy_state )
/* basic machine hardware */
MCFG_CPU_ADD("maincpu", Z80, XTAL / 2)
MCFG_CPU_PROGRAM_MAP(galaxyp_mem)
MCFG_CPU_IO_MAP(galaxyp_io)
MCFG_CPU_VBLANK_INT_DRIVER("screen", galaxy_state, galaxy_interrupt)
MCFG_CPU_IRQ_ACKNOWLEDGE_DRIVER(galaxy_state,galaxy_irq_callback)
MCFG_SCREEN_ADD("screen", RASTER)
MCFG_SCREEN_REFRESH_RATE(50)
MCFG_SCREEN_PALETTE("palette")
MCFG_MACHINE_RESET_OVERRIDE(galaxy_state, galaxyp )
/* video hardware */
MCFG_SCREEN_SIZE(384, 208)
MCFG_SCREEN_VISIBLE_AREA(0, 384-1, 0, 208-1)
MCFG_SCREEN_UPDATE_DRIVER(galaxy_state, screen_update_galaxy)
MCFG_PALETTE_ADD_MONOCHROME("palette")
/* snapshot */
MCFG_SNAPSHOT_ADD("snapshot", galaxy_state, galaxy, "gal", 0)
/* sound hardware */
MCFG_SPEAKER_STANDARD_MONO("mono")
MCFG_SOUND_ADD("ay8910", AY8910, XTAL/4)
MCFG_SOUND_WAVE_ADD(WAVE_TAG, "cassette")
MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.25)
MCFG_CASSETTE_ADD( "cassette" )
MCFG_CASSETTE_FORMATS(gtp_cassette_formats)
MCFG_CASSETTE_DEFAULT_STATE(CASSETTE_STOPPED | CASSETTE_SPEAKER_ENABLED | CASSETTE_MOTOR_ENABLED)
MCFG_CASSETTE_INTERFACE("galaxy_cass")
MCFG_SOFTWARE_LIST_ADD("cass_list","galaxy")
/* internal ram */
MCFG_RAM_ADD(RAM_TAG)
MCFG_RAM_DEFAULT_SIZE("38K")
MACHINE_CONFIG_END
ROM_START (galaxy)
ROM_REGION (0x10000, "maincpu", ROMREGION_ERASEFF)
ROM_LOAD ("galrom1.bin", 0x0000, 0x1000, CRC(dc970a32) SHA1(dfc92163654a756b70f5a446daf49d7534f4c739))
ROM_LOAD_OPTIONAL ("galrom2.bin", 0x1000, 0x1000, CRC(5dc5a100) SHA1(5d5ab4313a2d0effe7572bb129193b64cab002c1))
ROM_REGION(0x0800, "gfx1",0)
ROM_LOAD ("galchr.bin", 0x0000, 0x0800, CRC(5c3b5bb5) SHA1(19429a61dc5e55ddec3242a8f695e06dd7961f88))
ROM_END
ROM_START (galaxyp)
ROM_REGION (0x10000, "maincpu", ROMREGION_ERASEFF)
ROM_LOAD ("galrom1.bin", 0x0000, 0x1000, CRC(dc970a32) SHA1(dfc92163654a756b70f5a446daf49d7534f4c739))
ROM_LOAD ("galrom2.bin", 0x1000, 0x1000, CRC(5dc5a100) SHA1(5d5ab4313a2d0effe7572bb129193b64cab002c1))
ROM_LOAD ("galplus.bin", 0xe000, 0x1000, CRC(d4cfab14) SHA1(b507b9026844eeb757547679907394aa42055eee))
ROM_REGION(0x0800, "gfx1",0)
ROM_LOAD ("galchr.bin", 0x0000, 0x0800, CRC(5c3b5bb5) SHA1(19429a61dc5e55ddec3242a8f695e06dd7961f88))
ROM_END
/* YEAR NAME PARENT COMPAT MACHINE INPUT INIT COMPANY FULLNAME */
COMP(1983, galaxy, 0, 0, galaxy, galaxy, galaxy_state, galaxy, "Voja Antonic / Elektronika inzenjering", "Galaksija", 0)
COMP(1985, galaxyp, galaxy, 0, galaxyp,galaxyp, galaxy_state,galaxyp,"Nenad Dunjic", "Galaksija plus", 0)<|fim▁end|> | |
<|file_name|>nested-object.js<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | let x = { a: (b ? 1 : 2)}; |
<|file_name|>Action-test.js<|end_file_name|><|fim▁begin|>'use strict';
import Application from '../../core/Application.js';
import Action from '../../core/Action.js';
describe('Action', () => {
var app;
var action;
class ChildAction extends Action {
get name() {
return 'ChildAction';
}
}
beforeEach(() => {
app = new Application();
action = new ChildAction(app);
});
it('has to be defined, be a function and can be instantiated', () => {
expect(ChildAction).toBeDefined();
expect(ChildAction).toEqual(jasmine.any(Function));
expect(action instanceof ChildAction).toBe(true);
});
it('holds an app instance', () => {
var myApp = action.app;
expect(myApp).toEqual(jasmine.any(Application));
expect(myApp).toBe(app);
});
it('has an execute function that throws an error if it is not implemented', () => {<|fim▁hole|> });
});<|fim▁end|> | expect(action.execute).toEqual(jasmine.any(Function));
expect(() => action.execute(payload)).toThrow(); |
<|file_name|>FileReaderModel.java<|end_file_name|><|fim▁begin|>package edu.casetools.icase.mreasoner.gui.model.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderModel {
FileReader fileReader = null;
BufferedReader br = null;
<|fim▁hole|> public void open(String fileName){
try {
fileReader = new FileReader(fileName);
br = new BufferedReader(fileReader);
} catch (IOException e) {
e.printStackTrace();
}
}
public String read(String fileName) throws IOException{
this.open(fileName);
String result= "",sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
result = result + sCurrentLine+"\n";
}
this.close();
return result;
}
public void close(){
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}<|fim▁end|> | |
<|file_name|>associated-types-no-suitable-bound.rs<|end_file_name|><|fim▁begin|>trait Get {
type Value;
fn get(&self) -> <Self as Get>::Value;
}
struct Struct {<|fim▁hole|>}
impl Struct {
fn uhoh<T>(foo: <T as Get>::Value) {}
//~^ ERROR the trait bound `T: Get` is not satisfied
}
fn main() {
}<|fim▁end|> | x: isize, |
<|file_name|>columns.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
This module contains the :class:`Column` class, which defines a "vertical"
array of tabular data. Whereas :class:`.Row` instances are independent of their
parent :class:`.Table`, columns depend on knowledge of both their position in
the parent (column name, data type) as well as the rows that contain their data.
"""
import six
from agate.mapped_sequence import MappedSequence
from agate.utils import NullOrder, memoize
if six.PY3: # pragma: no cover
# pylint: disable=W0622
xrange = range
def null_handler(k):
"""
Key method for sorting nulls correctly.
"""
if k is None:
return NullOrder()
return k
class Column(MappedSequence):
"""
Proxy access to column data. Instances of :class:`Column` should
not be constructed directly. They are created by :class:`.Table`
instances and are unique to them.
Columns are implemented as subclass of :class:`.MappedSequence`. They
deviate from the underlying implementation in that loading of their data
is deferred until it is needed.
:param name:
The name of this column.
:param data_type:
An instance of :class:`.DataType`.
:param rows:
A :class:`.MappedSequence` that contains the :class:`.Row` instances
containing the data for this column.
:param row_names:
An optional list of row names (keys) for this column.<|fim▁hole|> """
__slots__ = ['_index', '_name', '_data_type', '_rows', '_row_names']
def __init__(self, index, name, data_type, rows, row_names=None):
self._index = index
self._name = name
self._data_type = data_type
self._rows = rows
self._keys = row_names
def __getstate__(self):
"""
Return state values to be pickled.
This is necessary on Python2.7 when using :code:`__slots__`.
"""
return {
'_index': self._index,
'_name': self._name,
'_data_type': self._data_type,
'_rows': self._rows,
'_keys': self._keys
}
def __setstate__(self, data):
"""
Restore pickled state.
This is necessary on Python2.7 when using :code:`__slots__`.
"""
self._index = data['_index']
self._name = data['_name']
self._data_type = data['_data_type']
self._rows = data['_rows']
self._keys = data['_keys']
@property
def index(self):
"""
This column's index.
"""
return self._index
@property
def name(self):
"""
This column's name.
"""
return self._name
@property
def data_type(self):
"""
This column's data type.
"""
return self._data_type
@memoize
def values(self):
"""
Get the values in this column, as a tuple.
"""
return tuple(row[self._index] for row in self._rows)
@memoize
def values_distinct(self):
"""
Get the distinct values in this column, as a tuple.
"""
return tuple(set(self.values()))
@memoize
def values_without_nulls(self):
"""
Get the values in this column with any null values removed.
"""
return tuple(d for d in self.values() if d is not None)
@memoize
def values_sorted(self):
"""
Get the values in this column sorted.
"""
return sorted(self.values(), key=null_handler)
@memoize
def values_without_nulls_sorted(self):
"""
Get the values in this column with any null values removed and sorted.
"""
return sorted(self.values_without_nulls(), key=null_handler)<|fim▁end|> | |
<|file_name|>Main.java<|end_file_name|><|fim▁begin|>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sv.edu.uesocc.ingenieria.disenio2_2015.pymesell.presentacion.pymesellv1desktopclient;
/**
*
* @author David
*/
public class Main {<|fim▁hole|> /**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Hola a todos!!!");
}
}<|fim▁end|> | |
<|file_name|>SoftIndexFileStoreConfigurationBuilder.java<|end_file_name|><|fim▁begin|>/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.clustering.infinispan.spi.persistence.sifs;
import static org.infinispan.configuration.cache.AbstractStoreConfiguration.SEGMENTED;
import static org.infinispan.persistence.sifs.configuration.SoftIndexFileStoreConfiguration.COMPACTION_THRESHOLD;
import static org.infinispan.persistence.sifs.configuration.SoftIndexFileStoreConfiguration.OPEN_FILES_LIMIT;
import org.infinispan.commons.configuration.attributes.Attribute;
import org.infinispan.configuration.cache.AbstractStoreConfigurationBuilder;
import org.infinispan.configuration.cache.AsyncStoreConfiguration;
import org.infinispan.configuration.cache.PersistenceConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.configuration.global.GlobalStateConfiguration;
import org.infinispan.persistence.PersistenceUtil;
import org.infinispan.persistence.sifs.Log;
import org.infinispan.persistence.sifs.NonBlockingSoftIndexFileStore;<|fim▁hole|>import org.infinispan.persistence.sifs.configuration.DataConfigurationBuilder;
import org.infinispan.persistence.sifs.configuration.IndexConfiguration;
import org.infinispan.persistence.sifs.configuration.IndexConfigurationBuilder;
import org.infinispan.util.logging.LogFactory;
/**
* Workaround for ISPN-13605.
* @author Paul Ferraro
*/
public class SoftIndexFileStoreConfigurationBuilder extends AbstractStoreConfigurationBuilder<SoftIndexFileStoreConfiguration, SoftIndexFileStoreConfigurationBuilder> {
private static final Log LOG = LogFactory.getLog(SoftIndexFileStoreConfigurationBuilder.class, Log.class);
protected final IndexConfigurationBuilder index = new IndexConfigurationBuilder();
protected final DataConfigurationBuilder data = new DataConfigurationBuilder();
public SoftIndexFileStoreConfigurationBuilder(PersistenceConfigurationBuilder builder) {
super(builder, org.infinispan.persistence.sifs.configuration.SoftIndexFileStoreConfiguration.attributeDefinitionSet(), AsyncStoreConfiguration.attributeDefinitionSet());
}
/**
* The path where the Soft-Index store will keep its data files. Under this location the store will create
* a directory named after the cache name, under which a <code>data</code> directory will be created.
*
* The default behaviour is to use the {@link GlobalStateConfiguration#persistentLocation()}.
*/
public SoftIndexFileStoreConfigurationBuilder dataLocation(String dataLocation) {
this.data.dataLocation(dataLocation);
return this;
}
/**
* The path where the Soft-Index store will keep its index files. Under this location the store will create
* a directory named after the cache name, under which a <code>index</code> directory will be created.
*
* The default behaviour is to use the {@link GlobalStateConfiguration#persistentLocation()}.
*/
public SoftIndexFileStoreConfigurationBuilder indexLocation(String indexLocation) {
this.index.indexLocation(indexLocation);
return this;
}
/**
* Number of index segment files. Increasing this value improves throughput but requires more threads to be spawned.
* <p>
* Defaults to <code>16</code>.
*/
public SoftIndexFileStoreConfigurationBuilder indexSegments(int indexSegments) {
this.index.indexSegments(indexSegments);
return this;
}
/**
* Sets the maximum size of single data file with entries, in bytes.
*
* Defaults to <code>16777216</code> (16MB).
*/
public SoftIndexFileStoreConfigurationBuilder maxFileSize(int maxFileSize) {
this.data.maxFileSize(maxFileSize);
return this;
}
/**
* If the size of the node (continuous block on filesystem used in index implementation) drops below this threshold,
* the node will try to balance its size with some neighbour node, possibly causing join of multiple nodes.
*
* Defaults to <code>0</code>.
*/
public SoftIndexFileStoreConfigurationBuilder minNodeSize(int minNodeSize) {
this.index.minNodeSize(minNodeSize);
return this;
}
/**
* Max size of node (continuous block on filesystem used in index implementation), in bytes.
*
* Defaults to <code>4096</code>.
*/
public SoftIndexFileStoreConfigurationBuilder maxNodeSize(int maxNodeSize) {
this.index.maxNodeSize(maxNodeSize);
return this;
}
/**
* Sets the maximum number of entry writes that are waiting to be written to the index, per index segment.
*
* Defaults to <code>1000</code>.
*/
public SoftIndexFileStoreConfigurationBuilder indexQueueLength(int indexQueueLength) {
this.index.indexQueueLength(indexQueueLength);
return this;
}
/**
* Sets whether writes shoud wait to be fsynced to disk.
*
* Defaults to <code>false</code>.
*/
public SoftIndexFileStoreConfigurationBuilder syncWrites(boolean syncWrites) {
this.data.syncWrites(syncWrites);
return this;
}
/**
* Sets the maximum number of open files.
*
* Defaults to <code>1000</code>.
*/
public SoftIndexFileStoreConfigurationBuilder openFilesLimit(int openFilesLimit) {
this.attributes.attribute(OPEN_FILES_LIMIT).set(openFilesLimit);
return this;
}
/**
* If the amount of unused space in some data file gets above this threshold, the file is compacted - entries from that file are copied to a new file and the old file is deleted.
*
* Defaults to <code>0.5</code> (50%).
*/
public SoftIndexFileStoreConfigurationBuilder compactionThreshold(double compactionThreshold) {
this.attributes.attribute(COMPACTION_THRESHOLD).set(compactionThreshold);
return this;
}
@Override
public SoftIndexFileStoreConfiguration create() {
return new SoftIndexFileStoreConfiguration(this.attributes.protect(), this.async.create(), this.index.create(), this.data.create());
}
@Override
public SoftIndexFileStoreConfigurationBuilder read(SoftIndexFileStoreConfiguration template) {
super.read(template);
this.index.read(template.index());
this.data.read(template.data());
return this;
}
@Override
public SoftIndexFileStoreConfigurationBuilder self() {
return this;
}
@Override
protected void validate (boolean skipClassChecks) {
Attribute<Boolean> segmentedAttribute = this.attributes.attribute(SEGMENTED);
if (segmentedAttribute.isModified() && !segmentedAttribute.get()) {
throw org.infinispan.util.logging.Log.CONFIG.storeRequiresBeingSegmented(NonBlockingSoftIndexFileStore.class.getSimpleName());
}
super.validate(skipClassChecks);
this.index.validate();
double compactionThreshold = this.attributes.attribute(COMPACTION_THRESHOLD).get();
if (compactionThreshold <= 0 || compactionThreshold > 1) {
throw LOG.invalidCompactionThreshold(compactionThreshold);
}
}
@Override
public void validate(GlobalConfiguration globalConfig) {
PersistenceUtil.validateGlobalStateStoreLocation(globalConfig, NonBlockingSoftIndexFileStore.class.getSimpleName(),
this.data.attributes().attribute(DataConfiguration.DATA_LOCATION),
this.index.attributes().attribute(IndexConfiguration.INDEX_LOCATION));
super.validate(globalConfig);
}
@Override
public String toString () {
return String.format("SoftIndexFileStoreConfigurationBuilder{index=%s, data=%s, attributes=%s, async=%s}", this.index, this.data, this.attributes, this.async);
}
}<|fim▁end|> | import org.infinispan.persistence.sifs.configuration.DataConfiguration; |
<|file_name|>configure.py<|end_file_name|><|fim▁begin|>import os, sys
import commands
import optparse
import shutil
INSTALL_DIR = ""
BASE_DIR = os.path.dirname(__file__)
SIP_FILE = "poppler-qt4.sip"
BUILD_DIR = "build"
SBF_FILE = "QtPoppler.sbf"
def _cleanup_path(path):
"""
Cleans the path:
- Removes traling / or \
"""
path = path.rstrip('/')
path = path.rstrip('\\')
return path
def pkgconfig(package):
'''
Calls pkg-config for the given package
Returns: - None if the package is not found.
- {'inc_dirs': [List of -L Paths]
'lib_dirs' : [List of -I Paths]
'libs ' : [List of -l libs]
}
'''
code, msg = commands.getstatusoutput("pkg-config --exists %s" % package)
if code != 0:
return None
tokens = commands.getoutput("pkg-config --libs --cflags %s" % package).split()
return {
'inc_dirs': [ token[2:] for token in tokens if token[:2] == '-I'],
'lib_dirs': [ token[2:] for token in tokens if token[:2] == '-L'],
'libs': [ token[2:] for token in tokens if token[:2] == '-l'],
}
def create_optparser(sipcfg):
'''Comandline parser'''
def store_abspath(option, opt_str, value, parser):
setattr(parser.values, option.dest, os.path.abspath(value))
def get_default_moddir():
default = sipcfg.default_mod_dir
default = os.path.join(default, INSTALL_DIR)
return default
p = optparse.OptionParser(usage="%prog [options]")
default_moddir = get_default_moddir()
p.add_option("-d", "--destdir", action="callback",
default=default_moddir, type="string",
metavar="DIR",
dest="moddir", callback=store_abspath,
help="Where to install PyPoppler-Qt4 python modules."
"[default: %default]")
p.add_option("-s", "--sipdir", action="callback",
default=os.path.join(sipcfg.default_sip_dir, INSTALL_DIR),
metavar="DIR", dest="sipdir", callback=store_abspath,
type="string", help="Where the .sip files will be installed "
"[default: %default]")
p.add_option("", "--popplerqt-includes-dir", action="callback",
default=None,
metavar="DIR", dest="popplerqt_inc_dirs", callback=store_abspath,
type="string", help="PopplerQt include paths"
"[default: Auto-detected with pkg-config]")
p.add_option("", "--popplerqt-libs-dir", action="callback",
default=None,
metavar="DIR", dest="popplerqt_lib_dirs", callback=store_abspath,
type="string", help="PopplerQt libraries paths"
"[default: Auto-detected with pkg-config]")
return p
def get_pyqt4_config():
try:
import PyQt4.pyqtconfig
return PyQt4.pyqtconfig.Configuration()
except ImportError, e:
print >> sys.stderr, "ERROR: PyQt4 not found."
sys.exit(1)
def get_sip_config():
try:
import sipconfig
return sipconfig.Configuration()
except ImportError, e:
print >> sys.stderr, "ERROR: SIP (sipconfig) not found."
sys.exit(1)
def get_popplerqt_config(opts):
config = pkgconfig('poppler-qt4')
if config is not None:
found_pkgconfig = True
else:
found_pkgconfig = False
config = {'libs': ['poppler-qt4', 'poppler'],
'inc_dirs': None,
'lib_dirs': None}
if opts.popplerqt_inc_dirs is not None:
config['inc_dirs'] = opts.popplerqt_inc_dirs.split(" ")
if opts.popplerqt_lib_dirs is not None:
config['lib_dirs'] = opts.popplerqt_lib_dirs.split(" ")
if config['lib_dirs'] is None or config['inc_dirs'] is None:
print >> sys.stderr, "ERROR: poppler-qt4 not found."
print "Try to define PKG_CONFIG_PATH "
print "or use --popplerqt-libs-dir and --popplerqt-includes-dir options"
sys.exit(1)
config['inc_dirs'] = map(_cleanup_path, config['inc_dirs'])
config['lib_dirs'] = map(_cleanup_path, config['lib_dirs'])
config['sip_dir'] = _cleanup_path(opts.sipdir)
config['mod_dir'] = _cleanup_path(opts.moddir)
print "Using PopplerQt include paths: %s" % config['inc_dirs']
print "Using PopplerQt libraries paths: %s" % config['lib_dirs']
print "Configured to install SIP in %s" % config['sip_dir']
print "Configured to install binaries in %s" % config['mod_dir']
return config
def create_build_dir():
dir = os.path.join(BASE_DIR, BUILD_DIR)
if os.path.exists(dir):
return
try:
os.mkdir(dir)
except:
print >> sys.stderr, "ERROR: Unable to create the build directory (%s)" % dir
sys.exit(1)
def run_sip(pyqtcfg):
create_build_dir()
cmd = [pyqtcfg.sip_bin,
"-c", os.path.join(BASE_DIR, BUILD_DIR),
"-b", os.path.join(BUILD_DIR, SBF_FILE),
"-I", pyqtcfg.pyqt_sip_dir,
pyqtcfg.pyqt_sip_flags,
os.path.join(BASE_DIR, SIP_FILE)]
os.system( " ".join(cmd) )
def generate_makefiles(pyqtcfg, popplerqtcfg, opts):
from PyQt4 import pyqtconfig
import sipconfig
pypopplerqt4config_file = os.path.join(BASE_DIR, "pypopplerqt4config.py")
# Creeates the Makefiles objects for the build directory
makefile_build = pyqtconfig.sipconfig.ModuleMakefile(
configuration=pyqtcfg,
build_file=SBF_FILE,
dir=BUILD_DIR,
install_dir=popplerqtcfg['mod_dir'],
warnings=1,
qt=['QtCore', 'QtGui', 'QtXml']
)
# Add extras dependencies for the compiler and the linker
# Libraries names don't include any platform specific prefixes
# or extensions (e.g. the "lib" prefix on UNIX, or the ".dll" extension on Windows)
makefile_build.extra_lib_dirs = popplerqtcfg['lib_dirs']
makefile_build.extra_libs = popplerqtcfg['libs']
makefile_build.extra_include_dirs = popplerqtcfg['inc_dirs']
# Generates build Makefile
makefile_build.generate()
# Generates root Makefile
installs_root = []
installs_root.append( (os.path.join(BASE_DIR, SIP_FILE), popplerqtcfg['sip_dir']) )
installs_root.append( (pypopplerqt4config_file, popplerqtcfg['mod_dir']) )
sipconfig.ParentMakefile(
configuration=pyqtcfg,
subdirs=[_cleanup_path(BUILD_DIR)],
installs=installs_root
).generate()
def generate_configuration_module(pyqtcfg, popplerqtcfg, opts):
import sipconfig
content = {
"pypopplerqt4_sip_dir": popplerqtcfg['sip_dir'],
"pypopplerqt4_sip_flags": pyqtcfg.pyqt_sip_flags,
"pypopplerqt4_mod_dir": popplerqtcfg['mod_dir'],
"pypopplerqt4_modules": 'PopplerQt',
"popplerqt4_inc_dirs": popplerqtcfg['inc_dirs'],
"popplerqt4_lib_dirs": popplerqtcfg['lib_dirs'],
}
# This creates the pypopplerqt4config.py module from the pypopplerqt4config.py.in<|fim▁hole|> os.path.join(BASE_DIR, "pypopplerqt4config.py.in"),
content)
def main():
sipcfg = get_sip_config()
pyqtcfg = get_pyqt4_config()
parser = create_optparser(sipcfg)
opts, args = parser.parse_args()
popplerqtcfg = get_popplerqt_config(opts)
run_sip(pyqtcfg)
generate_makefiles(pyqtcfg, popplerqtcfg, opts)
generate_configuration_module(pyqtcfg, popplerqtcfg, opts)
if __name__ == "__main__":
main()<|fim▁end|> | # template and the dictionary.
sipconfig.create_config_module(
os.path.join(BASE_DIR, "pypopplerqt4config.py"), |
<|file_name|>SlidingWindowReservoirTest.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2010-2013 Coda Hale and Yammer, Inc., 2014-2017 Dropwizard 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.
*/
package io.dropwizard.metrics;
import org.junit.Test;
import io.dropwizard.metrics.SlidingWindowReservoir;
import static org.assertj.core.api.Assertions.assertThat;
public class SlidingWindowReservoirTest {
private final SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3);
@Test
public void handlesSmallDataStreams() throws Exception {
reservoir.update(1);
reservoir.update(2);
assertThat(reservoir.getSnapshot().getValues())
.containsOnly(1, 2);
}
@Test
public void onlyKeepsTheMostRecentFromBigDataStreams() throws Exception {
reservoir.update(1);
reservoir.update(2);
reservoir.update(3);
reservoir.update(4);
assertThat(reservoir.getSnapshot().getValues())<|fim▁hole|>}<|fim▁end|> | .containsOnly(2, 3, 4);
} |
<|file_name|>p62.rs<|end_file_name|><|fim▁begin|>enum BinaryTree<T> {
Node(T, ~BinaryTree<T>, ~BinaryTree<T>),
Empty
}
fn internals<T>(tree: BinaryTree<T>) -> ~[T] {
match tree {
Empty => ~[],
Node(_, ~Empty, ~Empty) => ~[],
Node(x, ~left, ~right) => (~[x]).move_iter()
.chain(internals(left).move_iter())
.chain(internals(right).move_iter())
.to_owned_vec()
}
}
fn main() {<|fim▁hole|>}<|fim▁end|> | let t1: BinaryTree<uint> = Empty;
let t2 = Node('x', ~Node('y', ~Empty, ~Empty), ~Node('z', ~Node('t', ~Empty, ~Empty), ~Empty));
assert_eq!(internals(t1), ~[]);
assert_eq!(internals(t2), ~['x', 'z']); |
<|file_name|>stack.rs<|end_file_name|><|fim▁begin|>pub type Stack<T> = Vec<T>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_stack() {
let mut stack: Stack<i32> = Stack::new();
assert_eq!(true, stack.is_empty());
assert_eq!(None, stack.pop());
stack.push(15);
assert_eq!(false, stack.is_empty());
stack.push(6);<|fim▁hole|> stack.push(9);
assert_eq!(9, stack.pop().unwrap());
assert_eq!(15, stack.pop().unwrap());
}
}<|fim▁end|> | stack.push(2);
assert_eq!(2, stack.pop().unwrap());
assert_eq!(6, stack.pop().unwrap()); |
<|file_name|>jquery-galleria.d.ts<|end_file_name|><|fim▁begin|>// Type definitions for galleria.js v1.4.2
// Project: https://github.com/aino/galleria
// Definitions by: Robert Imig <https://github.com/rimig>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module GalleriaJS {
interface GalleriaOptions {
dataSource: GalleriaEntry[];
autoplay?: boolean;
lightbox?: boolean;
}
<|fim▁hole|> description?: string;
}
interface GalleriaFactory {
run(): GalleriaFactory;
run(selector: String): GalleriaFactory;
run(selector: String, options: GalleriaOptions): GalleriaFactory;
loadTheme(url : String): GalleriaFactory;
configure(options: GalleriaOptions): GalleriaFactory;
ready( method: () => any): void;
refreshImage(): GalleriaFactory;
resize(): GalleriaFactory;
load( data: GalleriaEntry[]): GalleriaFactory;
setOptions( options: GalleriaOptions): GalleriaFactory;
}
}
declare var Galleria: GalleriaJS.GalleriaFactory;<|fim▁end|> | interface GalleriaEntry {
image?: string;
thumbnail?: string;
title?: string; |
<|file_name|>BaseDecimaterT.hh<|end_file_name|><|fim▁begin|>/* ========================================================================= *
* *
* OpenMesh *
* Copyright (c) 2001-2015, RWTH-Aachen University *
* Department of Computer Graphics and Multimedia *
* All rights reserved. *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
*---------------------------------------------------------------------------*
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* 3. Neither the name of the copyright holder 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. *
* *
* ========================================================================= */
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
/** \file BaseDecimaterT.hh
*/
//=============================================================================
//
// CLASS McDecimaterT
//
//=============================================================================
#ifndef OPENMESH_BASE_DECIMATER_DECIMATERT_HH
#define OPENMESH_BASE_DECIMATER_DECIMATERT_HH
//== INCLUDES =================================================================
#include <memory>
#include <OpenMesh/Core/Utils/Property.hh>
#include <OpenMesh/Tools/Decimater/ModBaseT.hh>
#include <OpenMesh/Core/Utils/Noncopyable.hh>
#include <OpenMesh/Tools/Decimater/Observer.hh>
//== NAMESPACE ================================================================
namespace OpenMesh {
namespace Decimater {
//== CLASS DEFINITION =========================================================
/** base class decimater framework
\see BaseDecimaterT, \ref decimater_docu
*/
class BaseDecimaterModule
{
};
template < typename MeshT >
class BaseDecimaterT : private Utils::Noncopyable
{
public: //-------------------------------------------------------- public types
typedef BaseDecimaterT< MeshT > Self;
typedef MeshT Mesh;
typedef CollapseInfoT<MeshT> CollapseInfo;
typedef ModBaseT<MeshT> Module;
typedef std::vector< Module* > ModuleList;
typedef typename ModuleList::iterator ModuleListIterator;
public: //------------------------------------------------------ public methods
BaseDecimaterT(Mesh& _mesh);
virtual ~BaseDecimaterT();
/** Initialize decimater and decimating modules.
Return values:
true ok
false No ore more than one non-binary module exist. In that case
the decimater is uninitialized!
*/
bool initialize();
/// Returns whether decimater has been successfully initialized.
bool is_initialized() const { return initialized_; }
/// Print information about modules to _os
void info( std::ostream& _os );
public: //--------------------------------------------------- module management
/** \brief Add observer
*
* You can set an observer which is used as a callback to check the decimators progress and to
* abort it if necessary.
*
* @param _o Observer to be used
*/
void set_observer(Observer* _o)
{
observer_ = _o;
}
/// Get current observer of a decimater
Observer* observer()
{
return observer_;
}
/// access mesh. used in modules.
Mesh& mesh() { return mesh_; }
/// add module to decimater
template < typename _Module >
bool add( ModHandleT<_Module>& _mh )
{
if (_mh.is_valid())
return false;
_mh.init( new _Module(mesh()) );
all_modules_.push_back( _mh.module() );
set_uninitialized();
return true;
}
/// remove module
template < typename _Module >
bool remove( ModHandleT<_Module>& _mh )
{
if (!_mh.is_valid())
return false;
typename ModuleList::iterator it = std::find(all_modules_.begin(),
all_modules_.end(),
_mh.module() );
if ( it == all_modules_.end() ) // module not found
return false;
delete *it;
all_modules_.erase( it ); // finally remove from list
_mh.clear();
set_uninitialized();
return true;
}
/// get module referenced by handle _mh
template < typename Module >
Module& module( ModHandleT<Module>& _mh )
{
assert( _mh.is_valid() );
return *_mh.module();
}
protected:
/// returns false, if abort requested by observer
bool notify_observer(size_t _n_collapses)
{
if (observer() && _n_collapses % observer()->get_interval() == 0)
{
observer()->notify(_n_collapses);
return !observer()->abort();
}
return true;
}
/// Reset the initialized flag, and clear the bmodules_ and cmodule_
void set_uninitialized() {
initialized_ = false;
cmodule_ = 0;
bmodules_.clear();
}
void update_modules(CollapseInfo& _ci)
{
typename ModuleList::iterator m_it, m_end = bmodules_.end();
for (m_it = bmodules_.begin(); m_it != m_end; ++m_it)
(*m_it)->postprocess_collapse(_ci);
cmodule_->postprocess_collapse(_ci);
}
protected: //---------------------------------------------------- private methods
/// Is an edge collapse legal? Performs topological test only.
/// The method evaluates the status bit Locked, Deleted, and Feature.
/// \attention The method temporarily sets the bit Tagged. After usage
/// the bit will be disabled!
bool is_collapse_legal(const CollapseInfo& _ci);
/// Calculate priority of an halfedge collapse (using the modules)
float collapse_priority(const CollapseInfo& _ci);
/// Pre-process a collapse
void preprocess_collapse(CollapseInfo& _ci);
/// Post-process a collapse
void postprocess_collapse(CollapseInfo& _ci);
/**
* This provides a function that allows the setting of a percentage
* of the original constraint of the modules<|fim▁hole|> * Note that some modules might re-initialize in their
* set_error_tolerance_factor function as necessary
* @param _factor has to be in the closed interval between 0.0 and 1.0
*/
void set_error_tolerance_factor(double _factor);
/** Reset the status of this class
*
* You have to call initialize again!!
*/
void reset(){ initialized_ = false; };
private: //------------------------------------------------------- private data
/// reference to mesh
Mesh& mesh_;
/// list of binary modules
ModuleList bmodules_;
/// the current priority module
Module* cmodule_;
/// list of all allocated modules (including cmodule_ and all of bmodules_)
ModuleList all_modules_;
/// Flag if all modules were initialized
bool initialized_;
/// observer
Observer* observer_;
};
//=============================================================================
} // END_NS_DECIMATER
} // END_NS_OPENMESH
//=============================================================================
#if defined(OM_INCLUDE_TEMPLATES) && !defined(OPENMESH_BASE_DECIMATER_DECIMATERT_CC)
#define OPENMESH_BASE_DECIMATER_TEMPLATES
#include "BaseDecimaterT.cc"
#endif
//=============================================================================
#endif // OPENMESH_BASE_DECIMATER_DECIMATERT_HH defined
//=============================================================================<|fim▁end|> | * |
<|file_name|>l10n.js<|end_file_name|><|fim▁begin|>/**
* Copyright 2019 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.
*/
const ISO6391 = require('iso-639-1');
module.exports = eleventy => {
// Transforms given date string into local date string
// Requires full-icu and NODE_ICU_DATA=node_modules/full-icu to function
eleventy.addFilter('date', (date, locale = 'en-US', format = {}) => new Date(date).toLocaleDateString(locale, format));
// Transforms given URL into a URL for the given locale
eleventy.addFilter('localeURL', (url, locale) => {
const changed = url.split('/');
if (changed[changed.length - 1] === '') {
changed.splice(-1, 1);
}
changed.splice(1, 1, locale);
return changed.join('/');
});
// Returns the native name for the language code
eleventy.addFilter('langName', code => ISO6391.getNativeName(code));<|fim▁hole|><|fim▁end|> | }; |
<|file_name|>ranker_root.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.<|fim▁hole|>#
# 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.
"""This module contains the RankerRoot model
"""
__authors__ = [
'"Lennard de Rijk" <[email protected]>',
]
from google.appengine.ext import db
import soc.models.linkable
class RankerRoot(soc.models.linkable.Linkable):
"""Links the Root of a RankList tree to an owner and also
gives it an unique ID.
"""
#: A required reference property to the root of the RankList tree
root = db.ReferenceProperty(required=True,
collection_name='roots')<|fim▁end|> | |
<|file_name|>mymodule_demo3.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
from mymodule import *
sayhi()<|fim▁hole|># print('Version: ', __version__)<|fim▁end|> |
# __version__ 不会导入 |
<|file_name|>test_install_suse.py<|end_file_name|><|fim▁begin|>"""
Tests for install.py for SUSE based Linux distributions
"""
import os
import shutil
from unittest import mock
<|fim▁hole|>pytestmark = pytest.mark.skipif(
not pytest.helpers.helper_is_suse(),
reason="Tests for openSUSE/SUSE"
)
def test_rpm_download_raise_not_found_error(sys_rpm):
with mock.patch.object(Cmd, 'sh_e') as mock_sh_e:
ce = CmdError('test.')
ce.stderr = 'Package \'dummy\' not found.\n'
mock_sh_e.side_effect = ce
with pytest.raises(RemoteFileNotFoundError) as exc:
sys_rpm.download('dummy')
assert mock_sh_e.called
assert str(exc.value) == 'Package dummy not found on remote'
def test_rpm_extract_is_ok(sys_rpm, rpm_files, monkeypatch):
# mocking arch object for multi arch test cases.
sys_rpm.arch = 'x86_64'
with pytest.helpers.work_dir():
for rpm_file in rpm_files:
shutil.copy(rpm_file, '.')
sys_rpm.extract('rpm-build-libs')
files = os.listdir('./usr/lib64')
files.sort()
assert files == [
'librpmbuild.so.7',
'librpmbuild.so.7.0.1',
'librpmsign.so.7',
'librpmsign.so.7.0.1',
]
@pytest.mark.network
def test_app_verify_system_status_is_ok_on_sys_rpm_and_missing_pkgs(app):
app.linux.rpm.is_system_rpm = mock.MagicMock(return_value=True)
app.linux.verify_system_status()<|fim▁end|> | import pytest
from install import Cmd, CmdError, RemoteFileNotFoundError
|
<|file_name|>forms.py<|end_file_name|><|fim▁begin|>from madrona.features.forms import FeatureForm
from django import forms
from visualize.models import *<|fim▁hole|>class BookmarkForm(FeatureForm):
class Meta(FeatureForm.Meta):
model = Bookmark<|fim▁end|> | |
<|file_name|>test_sahara_job_binary.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
#<|fim▁hole|># 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 mock
import six
from heat.common import exception
from heat.common import template_format
from heat.engine.clients.os import sahara
from heat.engine.resources.openstack.sahara import job_binary
from heat.engine import scheduler
from heat.tests import common
from heat.tests import utils
job_binary_template = """
heat_template_version: 2015-10-15
resources:
job-binary:
type: OS::Sahara::JobBinary
properties:
name: my-jb
url: swift://container/jar-example.jar
credentials: {'user': 'admin','password': 'swordfish'}
"""
class SaharaJobBinaryTest(common.HeatTestCase):
def setUp(self):
super(SaharaJobBinaryTest, self).setUp()
t = template_format.parse(job_binary_template)
self.stack = utils.parse_stack(t)
resource_defns = self.stack.t.resource_definitions(self.stack)
self.rsrc_defn = resource_defns['job-binary']
self.client = mock.Mock()
self.patchobject(job_binary.JobBinary, 'client',
return_value=self.client)
def _create_resource(self, name, snippet, stack):
jb = job_binary.JobBinary(name, snippet, stack)
value = mock.MagicMock(id='12345')
self.client.job_binaries.create.return_value = value
scheduler.TaskRunner(jb.create)()
return jb
def test_create(self):
jb = self._create_resource('job-binary', self.rsrc_defn, self.stack)
args = self.client.job_binaries.create.call_args[1]
expected_args = {
'name': 'my-jb',
'description': '',
'url': 'swift://container/jar-example.jar',
'extra': {
'user': 'admin',
'password': 'swordfish'
}
}
self.assertEqual(expected_args, args)
self.assertEqual('12345', jb.resource_id)
expected_state = (jb.CREATE, jb.COMPLETE)
self.assertEqual(expected_state, jb.state)
def test_resource_mapping(self):
mapping = job_binary.resource_mapping()
self.assertEqual(1, len(mapping))
self.assertEqual(job_binary.JobBinary,
mapping['OS::Sahara::JobBinary'])
def test_update(self):
jb = self._create_resource('job-binary', self.rsrc_defn,
self.stack)
self.rsrc_defn['Properties']['url'] = (
'internal-db://94b8821d-1ce7-4131-8364-a6c6d85ad57b')
scheduler.TaskRunner(jb.update, self.rsrc_defn)()
data = {
'name': 'my-jb',
'description': '',
'url': 'internal-db://94b8821d-1ce7-4131-8364-a6c6d85ad57b',
'extra': {
'user': 'admin',
'password': 'swordfish'
}
}
self.client.job_binaries.update.assert_called_once_with(
'12345', data)
self.assertEqual((jb.UPDATE, jb.COMPLETE), jb.state)
def test_delete(self):
jb = self._create_resource('job-binary', self.rsrc_defn, self.stack)
scheduler.TaskRunner(jb.delete)()
self.assertEqual((jb.DELETE, jb.COMPLETE), jb.state)
self.client.job_binaries.delete.assert_called_once_with(
jb.resource_id)
def test_delete_not_found(self):
jb = self._create_resource('job-binary', self.rsrc_defn, self.stack)
self.client.job_binaries.delete.side_effect = (
sahara.sahara_base.APIException(error_code=404))
scheduler.TaskRunner(jb.delete)()
self.assertEqual((jb.DELETE, jb.COMPLETE), jb.state)
self.client.job_binaries.delete.assert_called_once_with(
jb.resource_id)
def test_show_attribute(self):
jb = self._create_resource('job-binary', self.rsrc_defn, self.stack)
value = mock.MagicMock()
value.to_dict.return_value = {'jb': 'info'}
self.client.job_binaries.get.return_value = value
self.assertEqual({'jb': 'info'}, jb.FnGetAtt('show'))
def test_validate_invalid_url(self):
self.rsrc_defn['Properties']['url'] = 'internal-db://38273f82'
jb = job_binary.JobBinary('job-binary', self.rsrc_defn, self.stack)
ex = self.assertRaises(exception.StackValidationFailed, jb.validate)
error_msg = ('resources.job-binary.properties: internal-db://38273f82 '
'is not a valid job location.')
self.assertEqual(error_msg, six.text_type(ex))
def test_validate_password_without_user(self):
self.rsrc_defn['Properties']['credentials'].pop('user')
jb = job_binary.JobBinary('job-binary', self.rsrc_defn, self.stack)
ex = self.assertRaises(exception.StackValidationFailed, jb.validate)
error_msg = ('Property error: resources.job-binary.properties.'
'credentials: Property user not assigned')
self.assertEqual(error_msg, six.text_type(ex))<|fim▁end|> | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, |
<|file_name|>lib.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.
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
#![crate_name = "rustc_llvm"]
#![experimental]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![allow(unknown_features)]
#![feature(link_args)]
#![feature(box_syntax)]
extern crate libc;
pub use self::OtherAttribute::*;
pub use self::SpecialAttribute::*;
pub use self::AttributeSet::*;
pub use self::IntPredicate::*;
pub use self::RealPredicate::*;
pub use self::TypeKind::*;
pub use self::AtomicBinOp::*;
pub use self::AtomicOrdering::*;
pub use self::FileType::*;
pub use self::MetadataType::*;
pub use self::AsmDialect::*;
pub use self::CodeGenOptLevel::*;
pub use self::RelocMode::*;
pub use self::CodeGenModel::*;
pub use self::DiagnosticKind::*;
pub use self::CallConv::*;
pub use self::Visibility::*;
pub use self::DiagnosticSeverity::*;
pub use self::Linkage::*;
use std::ffi::CString;
use std::cell::RefCell;
use std::{raw, mem};
use libc::{c_uint, c_ushort, uint64_t, c_int, size_t, c_char};
use libc::{c_longlong, c_ulonglong, c_void};
use debuginfo::{DIBuilderRef, DIDescriptor,
DIFile, DILexicalBlock, DISubprogram, DIType,
DIBasicType, DIDerivedType, DICompositeType,
DIVariable, DIGlobalVariable, DIArray, DISubrange};
pub mod archive_ro;
pub mod diagnostic;
pub type Opcode = u32;
pub type Bool = c_uint;
pub const True: Bool = 1 as Bool;
pub const False: Bool = 0 as Bool;
// Consts for the LLVM CallConv type, pre-cast to uint.
#[derive(Copy, PartialEq)]
pub enum CallConv {
CCallConv = 0,
FastCallConv = 8,
ColdCallConv = 9,
X86StdcallCallConv = 64,
X86FastcallCallConv = 65,
X86_64_Win64 = 79,
}
#[derive(Copy)]
pub enum Visibility {
LLVMDefaultVisibility = 0,
HiddenVisibility = 1,
ProtectedVisibility = 2,
}
// This enum omits the obsolete (and no-op) linkage types DLLImportLinkage,
// DLLExportLinkage, GhostLinkage and LinkOnceODRAutoHideLinkage.
// LinkerPrivateLinkage and LinkerPrivateWeakLinkage are not included either;
// they've been removed in upstream LLVM commit r203866.
#[derive(Copy)]
pub enum Linkage {
ExternalLinkage = 0,
AvailableExternallyLinkage = 1,
LinkOnceAnyLinkage = 2,
LinkOnceODRLinkage = 3,
WeakAnyLinkage = 5,
WeakODRLinkage = 6,
AppendingLinkage = 7,
InternalLinkage = 8,<|fim▁hole|>}
#[repr(C)]
#[derive(Copy, Show)]
pub enum DiagnosticSeverity {
Error,
Warning,
Remark,
Note,
}
bitflags! {
flags Attribute : u32 {
const ZExtAttribute = 1 << 0,
const SExtAttribute = 1 << 1,
const NoReturnAttribute = 1 << 2,
const InRegAttribute = 1 << 3,
const StructRetAttribute = 1 << 4,
const NoUnwindAttribute = 1 << 5,
const NoAliasAttribute = 1 << 6,
const ByValAttribute = 1 << 7,
const NestAttribute = 1 << 8,
const ReadNoneAttribute = 1 << 9,
const ReadOnlyAttribute = 1 << 10,
const NoInlineAttribute = 1 << 11,
const AlwaysInlineAttribute = 1 << 12,
const OptimizeForSizeAttribute = 1 << 13,
const StackProtectAttribute = 1 << 14,
const StackProtectReqAttribute = 1 << 15,
const AlignmentAttribute = 31 << 16,
const NoCaptureAttribute = 1 << 21,
const NoRedZoneAttribute = 1 << 22,
const NoImplicitFloatAttribute = 1 << 23,
const NakedAttribute = 1 << 24,
const InlineHintAttribute = 1 << 25,
const StackAttribute = 7 << 26,
const ReturnsTwiceAttribute = 1 << 29,
const UWTableAttribute = 1 << 30,
const NonLazyBindAttribute = 1 << 31,
}
}
#[repr(u64)]
#[derive(Copy)]
pub enum OtherAttribute {
// The following are not really exposed in
// the LLVM c api so instead to add these
// we call a wrapper function in RustWrapper
// that uses the C++ api.
SanitizeAddressAttribute = 1 << 32,
MinSizeAttribute = 1 << 33,
NoDuplicateAttribute = 1 << 34,
StackProtectStrongAttribute = 1 << 35,
SanitizeThreadAttribute = 1 << 36,
SanitizeMemoryAttribute = 1 << 37,
NoBuiltinAttribute = 1 << 38,
ReturnedAttribute = 1 << 39,
ColdAttribute = 1 << 40,
BuiltinAttribute = 1 << 41,
OptimizeNoneAttribute = 1 << 42,
InAllocaAttribute = 1 << 43,
NonNullAttribute = 1 << 44,
}
#[derive(Copy)]
pub enum SpecialAttribute {
DereferenceableAttribute(u64)
}
#[repr(C)]
#[derive(Copy)]
pub enum AttributeSet {
ReturnIndex = 0,
FunctionIndex = !0
}
pub trait AttrHelper {
fn apply_llfn(&self, idx: c_uint, llfn: ValueRef);
fn apply_callsite(&self, idx: c_uint, callsite: ValueRef);
}
impl AttrHelper for Attribute {
fn apply_llfn(&self, idx: c_uint, llfn: ValueRef) {
unsafe {
LLVMAddFunctionAttribute(llfn, idx, self.bits() as uint64_t);
}
}
fn apply_callsite(&self, idx: c_uint, callsite: ValueRef) {
unsafe {
LLVMAddCallSiteAttribute(callsite, idx, self.bits() as uint64_t);
}
}
}
impl AttrHelper for OtherAttribute {
fn apply_llfn(&self, idx: c_uint, llfn: ValueRef) {
unsafe {
LLVMAddFunctionAttribute(llfn, idx, *self as uint64_t);
}
}
fn apply_callsite(&self, idx: c_uint, callsite: ValueRef) {
unsafe {
LLVMAddCallSiteAttribute(callsite, idx, *self as uint64_t);
}
}
}
impl AttrHelper for SpecialAttribute {
fn apply_llfn(&self, idx: c_uint, llfn: ValueRef) {
match *self {
DereferenceableAttribute(bytes) => unsafe {
LLVMAddDereferenceableAttr(llfn, idx, bytes as uint64_t);
}
}
}
fn apply_callsite(&self, idx: c_uint, callsite: ValueRef) {
match *self {
DereferenceableAttribute(bytes) => unsafe {
LLVMAddDereferenceableCallSiteAttr(callsite, idx, bytes as uint64_t);
}
}
}
}
pub struct AttrBuilder {
attrs: Vec<(uint, Box<AttrHelper+'static>)>
}
impl AttrBuilder {
pub fn new() -> AttrBuilder {
AttrBuilder {
attrs: Vec::new()
}
}
pub fn arg<'a, T: AttrHelper + 'static>(&'a mut self, idx: uint, a: T) -> &'a mut AttrBuilder {
self.attrs.push((idx, box a as Box<AttrHelper+'static>));
self
}
pub fn ret<'a, T: AttrHelper + 'static>(&'a mut self, a: T) -> &'a mut AttrBuilder {
self.attrs.push((ReturnIndex as uint, box a as Box<AttrHelper+'static>));
self
}
pub fn apply_llfn(&self, llfn: ValueRef) {
for &(idx, ref attr) in self.attrs.iter() {
attr.apply_llfn(idx as c_uint, llfn);
}
}
pub fn apply_callsite(&self, callsite: ValueRef) {
for &(idx, ref attr) in self.attrs.iter() {
attr.apply_callsite(idx as c_uint, callsite);
}
}
}
// enum for the LLVM IntPredicate type
#[derive(Copy)]
pub enum IntPredicate {
IntEQ = 32,
IntNE = 33,
IntUGT = 34,
IntUGE = 35,
IntULT = 36,
IntULE = 37,
IntSGT = 38,
IntSGE = 39,
IntSLT = 40,
IntSLE = 41,
}
// enum for the LLVM RealPredicate type
#[derive(Copy)]
pub enum RealPredicate {
RealPredicateFalse = 0,
RealOEQ = 1,
RealOGT = 2,
RealOGE = 3,
RealOLT = 4,
RealOLE = 5,
RealONE = 6,
RealORD = 7,
RealUNO = 8,
RealUEQ = 9,
RealUGT = 10,
RealUGE = 11,
RealULT = 12,
RealULE = 13,
RealUNE = 14,
RealPredicateTrue = 15,
}
// The LLVM TypeKind type - must stay in sync with the def of
// LLVMTypeKind in llvm/include/llvm-c/Core.h
#[derive(Copy, PartialEq)]
#[repr(C)]
pub enum TypeKind {
Void = 0,
Half = 1,
Float = 2,
Double = 3,
X86_FP80 = 4,
FP128 = 5,
PPC_FP128 = 6,
Label = 7,
Integer = 8,
Function = 9,
Struct = 10,
Array = 11,
Pointer = 12,
Vector = 13,
Metadata = 14,
X86_MMX = 15,
}
#[repr(C)]
#[derive(Copy)]
pub enum AtomicBinOp {
AtomicXchg = 0,
AtomicAdd = 1,
AtomicSub = 2,
AtomicAnd = 3,
AtomicNand = 4,
AtomicOr = 5,
AtomicXor = 6,
AtomicMax = 7,
AtomicMin = 8,
AtomicUMax = 9,
AtomicUMin = 10,
}
#[repr(C)]
#[derive(Copy)]
pub enum AtomicOrdering {
NotAtomic = 0,
Unordered = 1,
Monotonic = 2,
// Consume = 3, // Not specified yet.
Acquire = 4,
Release = 5,
AcquireRelease = 6,
SequentiallyConsistent = 7
}
// Consts for the LLVMCodeGenFileType type (in include/llvm/c/TargetMachine.h)
#[repr(C)]
#[derive(Copy)]
pub enum FileType {
AssemblyFileType = 0,
ObjectFileType = 1
}
#[derive(Copy)]
pub enum MetadataType {
MD_dbg = 0,
MD_tbaa = 1,
MD_prof = 2,
MD_fpmath = 3,
MD_range = 4,
MD_tbaa_struct = 5
}
// Inline Asm Dialect
#[derive(Copy)]
pub enum AsmDialect {
AD_ATT = 0,
AD_Intel = 1
}
#[derive(Copy, PartialEq, Clone)]
#[repr(C)]
pub enum CodeGenOptLevel {
CodeGenLevelNone = 0,
CodeGenLevelLess = 1,
CodeGenLevelDefault = 2,
CodeGenLevelAggressive = 3,
}
#[derive(Copy, PartialEq)]
#[repr(C)]
pub enum RelocMode {
RelocDefault = 0,
RelocStatic = 1,
RelocPIC = 2,
RelocDynamicNoPic = 3,
}
#[repr(C)]
#[derive(Copy)]
pub enum CodeGenModel {
CodeModelDefault = 0,
CodeModelJITDefault = 1,
CodeModelSmall = 2,
CodeModelKernel = 3,
CodeModelMedium = 4,
CodeModelLarge = 5,
}
#[repr(C)]
#[derive(Copy)]
pub enum DiagnosticKind {
DK_InlineAsm = 0,
DK_StackSize,
DK_DebugMetadataVersion,
DK_SampleProfile,
DK_OptimizationRemark,
DK_OptimizationRemarkMissed,
DK_OptimizationRemarkAnalysis,
DK_OptimizationFailure,
}
// Opaque pointer types
#[allow(missing_copy_implementations)]
pub enum Module_opaque {}
pub type ModuleRef = *mut Module_opaque;
#[allow(missing_copy_implementations)]
pub enum Context_opaque {}
pub type ContextRef = *mut Context_opaque;
#[allow(missing_copy_implementations)]
pub enum Type_opaque {}
pub type TypeRef = *mut Type_opaque;
#[allow(missing_copy_implementations)]
pub enum Value_opaque {}
pub type ValueRef = *mut Value_opaque;
#[allow(missing_copy_implementations)]
pub enum BasicBlock_opaque {}
pub type BasicBlockRef = *mut BasicBlock_opaque;
#[allow(missing_copy_implementations)]
pub enum Builder_opaque {}
pub type BuilderRef = *mut Builder_opaque;
#[allow(missing_copy_implementations)]
pub enum ExecutionEngine_opaque {}
pub type ExecutionEngineRef = *mut ExecutionEngine_opaque;
#[allow(missing_copy_implementations)]
pub enum RustJITMemoryManager_opaque {}
pub type RustJITMemoryManagerRef = *mut RustJITMemoryManager_opaque;
#[allow(missing_copy_implementations)]
pub enum MemoryBuffer_opaque {}
pub type MemoryBufferRef = *mut MemoryBuffer_opaque;
#[allow(missing_copy_implementations)]
pub enum PassManager_opaque {}
pub type PassManagerRef = *mut PassManager_opaque;
#[allow(missing_copy_implementations)]
pub enum PassManagerBuilder_opaque {}
pub type PassManagerBuilderRef = *mut PassManagerBuilder_opaque;
#[allow(missing_copy_implementations)]
pub enum Use_opaque {}
pub type UseRef = *mut Use_opaque;
#[allow(missing_copy_implementations)]
pub enum TargetData_opaque {}
pub type TargetDataRef = *mut TargetData_opaque;
#[allow(missing_copy_implementations)]
pub enum ObjectFile_opaque {}
pub type ObjectFileRef = *mut ObjectFile_opaque;
#[allow(missing_copy_implementations)]
pub enum SectionIterator_opaque {}
pub type SectionIteratorRef = *mut SectionIterator_opaque;
#[allow(missing_copy_implementations)]
pub enum Pass_opaque {}
pub type PassRef = *mut Pass_opaque;
#[allow(missing_copy_implementations)]
pub enum TargetMachine_opaque {}
pub type TargetMachineRef = *mut TargetMachine_opaque;
#[allow(missing_copy_implementations)]
pub enum Archive_opaque {}
pub type ArchiveRef = *mut Archive_opaque;
#[allow(missing_copy_implementations)]
pub enum Twine_opaque {}
pub type TwineRef = *mut Twine_opaque;
#[allow(missing_copy_implementations)]
pub enum DiagnosticInfo_opaque {}
pub type DiagnosticInfoRef = *mut DiagnosticInfo_opaque;
#[allow(missing_copy_implementations)]
pub enum DebugLoc_opaque {}
pub type DebugLocRef = *mut DebugLoc_opaque;
#[allow(missing_copy_implementations)]
pub enum SMDiagnostic_opaque {}
pub type SMDiagnosticRef = *mut SMDiagnostic_opaque;
pub type DiagnosticHandler = unsafe extern "C" fn(DiagnosticInfoRef, *mut c_void);
pub type InlineAsmDiagHandler = unsafe extern "C" fn(SMDiagnosticRef, *const c_void, c_uint);
pub mod debuginfo {
pub use self::DIDescriptorFlags::*;
use super::{ValueRef};
#[allow(missing_copy_implementations)]
pub enum DIBuilder_opaque {}
pub type DIBuilderRef = *mut DIBuilder_opaque;
pub type DIDescriptor = ValueRef;
pub type DIScope = DIDescriptor;
pub type DILocation = DIDescriptor;
pub type DIFile = DIScope;
pub type DILexicalBlock = DIScope;
pub type DISubprogram = DIScope;
pub type DIType = DIDescriptor;
pub type DIBasicType = DIType;
pub type DIDerivedType = DIType;
pub type DICompositeType = DIDerivedType;
pub type DIVariable = DIDescriptor;
pub type DIGlobalVariable = DIDescriptor;
pub type DIArray = DIDescriptor;
pub type DISubrange = DIDescriptor;
#[derive(Copy)]
pub enum DIDescriptorFlags {
FlagPrivate = 1 << 0,
FlagProtected = 1 << 1,
FlagFwdDecl = 1 << 2,
FlagAppleBlock = 1 << 3,
FlagBlockByrefStruct = 1 << 4,
FlagVirtual = 1 << 5,
FlagArtificial = 1 << 6,
FlagExplicit = 1 << 7,
FlagPrototyped = 1 << 8,
FlagObjcClassComplete = 1 << 9,
FlagObjectPointer = 1 << 10,
FlagVector = 1 << 11,
FlagStaticMember = 1 << 12,
FlagIndirectVariable = 1 << 13,
FlagLValueReference = 1 << 14,
FlagRValueReference = 1 << 15
}
}
// Link to our native llvm bindings (things that we need to use the C++ api
// for) and because llvm is written in C++ we need to link against libstdc++
//
// You'll probably notice that there is an omission of all LLVM libraries
// from this location. This is because the set of LLVM libraries that we
// link to is mostly defined by LLVM, and the `llvm-config` tool is used to
// figure out the exact set of libraries. To do this, the build system
// generates an llvmdeps.rs file next to this one which will be
// automatically updated whenever LLVM is updated to include an up-to-date
// set of the libraries we need to link to LLVM for.
#[link(name = "rustllvm", kind = "static")]
extern {
/* Create and destroy contexts. */
pub fn LLVMContextCreate() -> ContextRef;
pub fn LLVMContextDispose(C: ContextRef);
pub fn LLVMGetMDKindIDInContext(C: ContextRef,
Name: *const c_char,
SLen: c_uint)
-> c_uint;
/* Create and destroy modules. */
pub fn LLVMModuleCreateWithNameInContext(ModuleID: *const c_char,
C: ContextRef)
-> ModuleRef;
pub fn LLVMGetModuleContext(M: ModuleRef) -> ContextRef;
pub fn LLVMDisposeModule(M: ModuleRef);
/// Data layout. See Module::getDataLayout.
pub fn LLVMGetDataLayout(M: ModuleRef) -> *const c_char;
pub fn LLVMSetDataLayout(M: ModuleRef, Triple: *const c_char);
/// Target triple. See Module::getTargetTriple.
pub fn LLVMGetTarget(M: ModuleRef) -> *const c_char;
pub fn LLVMSetTarget(M: ModuleRef, Triple: *const c_char);
/// See Module::dump.
pub fn LLVMDumpModule(M: ModuleRef);
/// See Module::setModuleInlineAsm.
pub fn LLVMSetModuleInlineAsm(M: ModuleRef, Asm: *const c_char);
/// See llvm::LLVMTypeKind::getTypeID.
pub fn LLVMGetTypeKind(Ty: TypeRef) -> TypeKind;
/// See llvm::LLVMType::getContext.
pub fn LLVMGetTypeContext(Ty: TypeRef) -> ContextRef;
/* Operations on integer types */
pub fn LLVMInt1TypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMInt8TypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMInt16TypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMInt32TypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMInt64TypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMIntTypeInContext(C: ContextRef, NumBits: c_uint)
-> TypeRef;
pub fn LLVMGetIntTypeWidth(IntegerTy: TypeRef) -> c_uint;
/* Operations on real types */
pub fn LLVMFloatTypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMDoubleTypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMX86FP80TypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMFP128TypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMPPCFP128TypeInContext(C: ContextRef) -> TypeRef;
/* Operations on function types */
pub fn LLVMFunctionType(ReturnType: TypeRef,
ParamTypes: *const TypeRef,
ParamCount: c_uint,
IsVarArg: Bool)
-> TypeRef;
pub fn LLVMIsFunctionVarArg(FunctionTy: TypeRef) -> Bool;
pub fn LLVMGetReturnType(FunctionTy: TypeRef) -> TypeRef;
pub fn LLVMCountParamTypes(FunctionTy: TypeRef) -> c_uint;
pub fn LLVMGetParamTypes(FunctionTy: TypeRef, Dest: *mut TypeRef);
/* Operations on struct types */
pub fn LLVMStructTypeInContext(C: ContextRef,
ElementTypes: *const TypeRef,
ElementCount: c_uint,
Packed: Bool)
-> TypeRef;
pub fn LLVMCountStructElementTypes(StructTy: TypeRef) -> c_uint;
pub fn LLVMGetStructElementTypes(StructTy: TypeRef,
Dest: *mut TypeRef);
pub fn LLVMIsPackedStruct(StructTy: TypeRef) -> Bool;
/* Operations on array, pointer, and vector types (sequence types) */
pub fn LLVMRustArrayType(ElementType: TypeRef, ElementCount: u64) -> TypeRef;
pub fn LLVMPointerType(ElementType: TypeRef, AddressSpace: c_uint)
-> TypeRef;
pub fn LLVMVectorType(ElementType: TypeRef, ElementCount: c_uint)
-> TypeRef;
pub fn LLVMGetElementType(Ty: TypeRef) -> TypeRef;
pub fn LLVMGetArrayLength(ArrayTy: TypeRef) -> c_uint;
pub fn LLVMGetPointerAddressSpace(PointerTy: TypeRef) -> c_uint;
pub fn LLVMGetPointerToGlobal(EE: ExecutionEngineRef, V: ValueRef)
-> *const ();
pub fn LLVMGetVectorSize(VectorTy: TypeRef) -> c_uint;
/* Operations on other types */
pub fn LLVMVoidTypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMLabelTypeInContext(C: ContextRef) -> TypeRef;
pub fn LLVMMetadataTypeInContext(C: ContextRef) -> TypeRef;
/* Operations on all values */
pub fn LLVMTypeOf(Val: ValueRef) -> TypeRef;
pub fn LLVMGetValueName(Val: ValueRef) -> *const c_char;
pub fn LLVMSetValueName(Val: ValueRef, Name: *const c_char);
pub fn LLVMDumpValue(Val: ValueRef);
pub fn LLVMReplaceAllUsesWith(OldVal: ValueRef, NewVal: ValueRef);
pub fn LLVMHasMetadata(Val: ValueRef) -> c_int;
pub fn LLVMGetMetadata(Val: ValueRef, KindID: c_uint) -> ValueRef;
pub fn LLVMSetMetadata(Val: ValueRef, KindID: c_uint, Node: ValueRef);
/* Operations on Uses */
pub fn LLVMGetFirstUse(Val: ValueRef) -> UseRef;
pub fn LLVMGetNextUse(U: UseRef) -> UseRef;
pub fn LLVMGetUser(U: UseRef) -> ValueRef;
pub fn LLVMGetUsedValue(U: UseRef) -> ValueRef;
/* Operations on Users */
pub fn LLVMGetNumOperands(Val: ValueRef) -> c_int;
pub fn LLVMGetOperand(Val: ValueRef, Index: c_uint) -> ValueRef;
pub fn LLVMSetOperand(Val: ValueRef, Index: c_uint, Op: ValueRef);
/* Operations on constants of any type */
pub fn LLVMConstNull(Ty: TypeRef) -> ValueRef;
/* all zeroes */
pub fn LLVMConstAllOnes(Ty: TypeRef) -> ValueRef;
pub fn LLVMConstICmp(Pred: c_ushort, V1: ValueRef, V2: ValueRef)
-> ValueRef;
pub fn LLVMConstFCmp(Pred: c_ushort, V1: ValueRef, V2: ValueRef)
-> ValueRef;
/* only for int/vector */
pub fn LLVMGetUndef(Ty: TypeRef) -> ValueRef;
pub fn LLVMIsConstant(Val: ValueRef) -> Bool;
pub fn LLVMIsNull(Val: ValueRef) -> Bool;
pub fn LLVMIsUndef(Val: ValueRef) -> Bool;
pub fn LLVMConstPointerNull(Ty: TypeRef) -> ValueRef;
/* Operations on metadata */
pub fn LLVMMDStringInContext(C: ContextRef,
Str: *const c_char,
SLen: c_uint)
-> ValueRef;
pub fn LLVMMDNodeInContext(C: ContextRef,
Vals: *const ValueRef,
Count: c_uint)
-> ValueRef;
pub fn LLVMAddNamedMetadataOperand(M: ModuleRef,
Str: *const c_char,
Val: ValueRef);
/* Operations on scalar constants */
pub fn LLVMConstInt(IntTy: TypeRef, N: c_ulonglong, SignExtend: Bool)
-> ValueRef;
pub fn LLVMConstIntOfString(IntTy: TypeRef, Text: *const c_char, Radix: u8)
-> ValueRef;
pub fn LLVMConstIntOfStringAndSize(IntTy: TypeRef,
Text: *const c_char,
SLen: c_uint,
Radix: u8)
-> ValueRef;
pub fn LLVMConstReal(RealTy: TypeRef, N: f64) -> ValueRef;
pub fn LLVMConstRealOfString(RealTy: TypeRef, Text: *const c_char)
-> ValueRef;
pub fn LLVMConstRealOfStringAndSize(RealTy: TypeRef,
Text: *const c_char,
SLen: c_uint)
-> ValueRef;
pub fn LLVMConstIntGetZExtValue(ConstantVal: ValueRef) -> c_ulonglong;
pub fn LLVMConstIntGetSExtValue(ConstantVal: ValueRef) -> c_longlong;
/* Operations on composite constants */
pub fn LLVMConstStringInContext(C: ContextRef,
Str: *const c_char,
Length: c_uint,
DontNullTerminate: Bool)
-> ValueRef;
pub fn LLVMConstStructInContext(C: ContextRef,
ConstantVals: *const ValueRef,
Count: c_uint,
Packed: Bool)
-> ValueRef;
pub fn LLVMConstArray(ElementTy: TypeRef,
ConstantVals: *const ValueRef,
Length: c_uint)
-> ValueRef;
pub fn LLVMConstVector(ScalarConstantVals: *const ValueRef, Size: c_uint)
-> ValueRef;
/* Constant expressions */
pub fn LLVMAlignOf(Ty: TypeRef) -> ValueRef;
pub fn LLVMSizeOf(Ty: TypeRef) -> ValueRef;
pub fn LLVMConstNeg(ConstantVal: ValueRef) -> ValueRef;
pub fn LLVMConstNSWNeg(ConstantVal: ValueRef) -> ValueRef;
pub fn LLVMConstNUWNeg(ConstantVal: ValueRef) -> ValueRef;
pub fn LLVMConstFNeg(ConstantVal: ValueRef) -> ValueRef;
pub fn LLVMConstNot(ConstantVal: ValueRef) -> ValueRef;
pub fn LLVMConstAdd(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstNSWAdd(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstNUWAdd(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstFAdd(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstSub(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstNSWSub(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstNUWSub(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstFSub(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstMul(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstNSWMul(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstNUWMul(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstFMul(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstUDiv(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstSDiv(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstExactSDiv(LHSConstant: ValueRef,
RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstFDiv(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstURem(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstSRem(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstFRem(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstAnd(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstOr(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstXor(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstShl(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstLShr(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstAShr(LHSConstant: ValueRef, RHSConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstGEP(ConstantVal: ValueRef,
ConstantIndices: *const ValueRef,
NumIndices: c_uint)
-> ValueRef;
pub fn LLVMConstInBoundsGEP(ConstantVal: ValueRef,
ConstantIndices: *const ValueRef,
NumIndices: c_uint)
-> ValueRef;
pub fn LLVMConstTrunc(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstSExt(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstZExt(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstFPTrunc(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstFPExt(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstUIToFP(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstSIToFP(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstFPToUI(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstFPToSI(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstPtrToInt(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstIntToPtr(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstBitCast(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstZExtOrBitCast(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstSExtOrBitCast(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstTruncOrBitCast(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstPointerCast(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstIntCast(ConstantVal: ValueRef,
ToType: TypeRef,
isSigned: Bool)
-> ValueRef;
pub fn LLVMConstFPCast(ConstantVal: ValueRef, ToType: TypeRef)
-> ValueRef;
pub fn LLVMConstSelect(ConstantCondition: ValueRef,
ConstantIfTrue: ValueRef,
ConstantIfFalse: ValueRef)
-> ValueRef;
pub fn LLVMConstExtractElement(VectorConstant: ValueRef,
IndexConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstInsertElement(VectorConstant: ValueRef,
ElementValueConstant: ValueRef,
IndexConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstShuffleVector(VectorAConstant: ValueRef,
VectorBConstant: ValueRef,
MaskConstant: ValueRef)
-> ValueRef;
pub fn LLVMConstExtractValue(AggConstant: ValueRef,
IdxList: *const c_uint,
NumIdx: c_uint)
-> ValueRef;
pub fn LLVMConstInsertValue(AggConstant: ValueRef,
ElementValueConstant: ValueRef,
IdxList: *const c_uint,
NumIdx: c_uint)
-> ValueRef;
pub fn LLVMConstInlineAsm(Ty: TypeRef,
AsmString: *const c_char,
Constraints: *const c_char,
HasSideEffects: Bool,
IsAlignStack: Bool)
-> ValueRef;
pub fn LLVMBlockAddress(F: ValueRef, BB: BasicBlockRef) -> ValueRef;
/* Operations on global variables, functions, and aliases (globals) */
pub fn LLVMGetGlobalParent(Global: ValueRef) -> ModuleRef;
pub fn LLVMIsDeclaration(Global: ValueRef) -> Bool;
pub fn LLVMGetLinkage(Global: ValueRef) -> c_uint;
pub fn LLVMSetLinkage(Global: ValueRef, Link: c_uint);
pub fn LLVMGetSection(Global: ValueRef) -> *const c_char;
pub fn LLVMSetSection(Global: ValueRef, Section: *const c_char);
pub fn LLVMGetVisibility(Global: ValueRef) -> c_uint;
pub fn LLVMSetVisibility(Global: ValueRef, Viz: c_uint);
pub fn LLVMGetAlignment(Global: ValueRef) -> c_uint;
pub fn LLVMSetAlignment(Global: ValueRef, Bytes: c_uint);
/* Operations on global variables */
pub fn LLVMAddGlobal(M: ModuleRef, Ty: TypeRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMAddGlobalInAddressSpace(M: ModuleRef,
Ty: TypeRef,
Name: *const c_char,
AddressSpace: c_uint)
-> ValueRef;
pub fn LLVMGetNamedGlobal(M: ModuleRef, Name: *const c_char) -> ValueRef;
pub fn LLVMGetFirstGlobal(M: ModuleRef) -> ValueRef;
pub fn LLVMGetLastGlobal(M: ModuleRef) -> ValueRef;
pub fn LLVMGetNextGlobal(GlobalVar: ValueRef) -> ValueRef;
pub fn LLVMGetPreviousGlobal(GlobalVar: ValueRef) -> ValueRef;
pub fn LLVMDeleteGlobal(GlobalVar: ValueRef);
pub fn LLVMGetInitializer(GlobalVar: ValueRef) -> ValueRef;
pub fn LLVMSetInitializer(GlobalVar: ValueRef,
ConstantVal: ValueRef);
pub fn LLVMIsThreadLocal(GlobalVar: ValueRef) -> Bool;
pub fn LLVMSetThreadLocal(GlobalVar: ValueRef, IsThreadLocal: Bool);
pub fn LLVMIsGlobalConstant(GlobalVar: ValueRef) -> Bool;
pub fn LLVMSetGlobalConstant(GlobalVar: ValueRef, IsConstant: Bool);
/* Operations on aliases */
pub fn LLVMAddAlias(M: ModuleRef,
Ty: TypeRef,
Aliasee: ValueRef,
Name: *const c_char)
-> ValueRef;
/* Operations on functions */
pub fn LLVMAddFunction(M: ModuleRef,
Name: *const c_char,
FunctionTy: TypeRef)
-> ValueRef;
pub fn LLVMGetNamedFunction(M: ModuleRef, Name: *const c_char) -> ValueRef;
pub fn LLVMGetFirstFunction(M: ModuleRef) -> ValueRef;
pub fn LLVMGetLastFunction(M: ModuleRef) -> ValueRef;
pub fn LLVMGetNextFunction(Fn: ValueRef) -> ValueRef;
pub fn LLVMGetPreviousFunction(Fn: ValueRef) -> ValueRef;
pub fn LLVMDeleteFunction(Fn: ValueRef);
pub fn LLVMGetOrInsertFunction(M: ModuleRef,
Name: *const c_char,
FunctionTy: TypeRef)
-> ValueRef;
pub fn LLVMGetIntrinsicID(Fn: ValueRef) -> c_uint;
pub fn LLVMGetFunctionCallConv(Fn: ValueRef) -> c_uint;
pub fn LLVMSetFunctionCallConv(Fn: ValueRef, CC: c_uint);
pub fn LLVMGetGC(Fn: ValueRef) -> *const c_char;
pub fn LLVMSetGC(Fn: ValueRef, Name: *const c_char);
pub fn LLVMAddDereferenceableAttr(Fn: ValueRef, index: c_uint, bytes: uint64_t);
pub fn LLVMAddFunctionAttribute(Fn: ValueRef, index: c_uint, PA: uint64_t);
pub fn LLVMAddFunctionAttrString(Fn: ValueRef, index: c_uint, Name: *const c_char);
pub fn LLVMRemoveFunctionAttrString(Fn: ValueRef, index: c_uint, Name: *const c_char);
pub fn LLVMGetFunctionAttr(Fn: ValueRef) -> c_ulonglong;
/* Operations on parameters */
pub fn LLVMCountParams(Fn: ValueRef) -> c_uint;
pub fn LLVMGetParams(Fn: ValueRef, Params: *const ValueRef);
pub fn LLVMGetParam(Fn: ValueRef, Index: c_uint) -> ValueRef;
pub fn LLVMGetParamParent(Inst: ValueRef) -> ValueRef;
pub fn LLVMGetFirstParam(Fn: ValueRef) -> ValueRef;
pub fn LLVMGetLastParam(Fn: ValueRef) -> ValueRef;
pub fn LLVMGetNextParam(Arg: ValueRef) -> ValueRef;
pub fn LLVMGetPreviousParam(Arg: ValueRef) -> ValueRef;
pub fn LLVMAddAttribute(Arg: ValueRef, PA: c_uint);
pub fn LLVMRemoveAttribute(Arg: ValueRef, PA: c_uint);
pub fn LLVMGetAttribute(Arg: ValueRef) -> c_uint;
pub fn LLVMSetParamAlignment(Arg: ValueRef, align: c_uint);
/* Operations on basic blocks */
pub fn LLVMBasicBlockAsValue(BB: BasicBlockRef) -> ValueRef;
pub fn LLVMValueIsBasicBlock(Val: ValueRef) -> Bool;
pub fn LLVMValueAsBasicBlock(Val: ValueRef) -> BasicBlockRef;
pub fn LLVMGetBasicBlockParent(BB: BasicBlockRef) -> ValueRef;
pub fn LLVMCountBasicBlocks(Fn: ValueRef) -> c_uint;
pub fn LLVMGetBasicBlocks(Fn: ValueRef, BasicBlocks: *const ValueRef);
pub fn LLVMGetFirstBasicBlock(Fn: ValueRef) -> BasicBlockRef;
pub fn LLVMGetLastBasicBlock(Fn: ValueRef) -> BasicBlockRef;
pub fn LLVMGetNextBasicBlock(BB: BasicBlockRef) -> BasicBlockRef;
pub fn LLVMGetPreviousBasicBlock(BB: BasicBlockRef) -> BasicBlockRef;
pub fn LLVMGetEntryBasicBlock(Fn: ValueRef) -> BasicBlockRef;
pub fn LLVMAppendBasicBlockInContext(C: ContextRef,
Fn: ValueRef,
Name: *const c_char)
-> BasicBlockRef;
pub fn LLVMInsertBasicBlockInContext(C: ContextRef,
BB: BasicBlockRef,
Name: *const c_char)
-> BasicBlockRef;
pub fn LLVMDeleteBasicBlock(BB: BasicBlockRef);
pub fn LLVMMoveBasicBlockAfter(BB: BasicBlockRef,
MoveAfter: BasicBlockRef);
pub fn LLVMMoveBasicBlockBefore(BB: BasicBlockRef,
MoveBefore: BasicBlockRef);
/* Operations on instructions */
pub fn LLVMGetInstructionParent(Inst: ValueRef) -> BasicBlockRef;
pub fn LLVMGetFirstInstruction(BB: BasicBlockRef) -> ValueRef;
pub fn LLVMGetLastInstruction(BB: BasicBlockRef) -> ValueRef;
pub fn LLVMGetNextInstruction(Inst: ValueRef) -> ValueRef;
pub fn LLVMGetPreviousInstruction(Inst: ValueRef) -> ValueRef;
pub fn LLVMInstructionEraseFromParent(Inst: ValueRef);
/* Operations on call sites */
pub fn LLVMSetInstructionCallConv(Instr: ValueRef, CC: c_uint);
pub fn LLVMGetInstructionCallConv(Instr: ValueRef) -> c_uint;
pub fn LLVMAddInstrAttribute(Instr: ValueRef,
index: c_uint,
IA: c_uint);
pub fn LLVMRemoveInstrAttribute(Instr: ValueRef,
index: c_uint,
IA: c_uint);
pub fn LLVMSetInstrParamAlignment(Instr: ValueRef,
index: c_uint,
align: c_uint);
pub fn LLVMAddCallSiteAttribute(Instr: ValueRef,
index: c_uint,
Val: uint64_t);
pub fn LLVMAddDereferenceableCallSiteAttr(Instr: ValueRef,
index: c_uint,
bytes: uint64_t);
/* Operations on call instructions (only) */
pub fn LLVMIsTailCall(CallInst: ValueRef) -> Bool;
pub fn LLVMSetTailCall(CallInst: ValueRef, IsTailCall: Bool);
/* Operations on load/store instructions (only) */
pub fn LLVMGetVolatile(MemoryAccessInst: ValueRef) -> Bool;
pub fn LLVMSetVolatile(MemoryAccessInst: ValueRef, volatile: Bool);
/* Operations on phi nodes */
pub fn LLVMAddIncoming(PhiNode: ValueRef,
IncomingValues: *const ValueRef,
IncomingBlocks: *const BasicBlockRef,
Count: c_uint);
pub fn LLVMCountIncoming(PhiNode: ValueRef) -> c_uint;
pub fn LLVMGetIncomingValue(PhiNode: ValueRef, Index: c_uint)
-> ValueRef;
pub fn LLVMGetIncomingBlock(PhiNode: ValueRef, Index: c_uint)
-> BasicBlockRef;
/* Instruction builders */
pub fn LLVMCreateBuilderInContext(C: ContextRef) -> BuilderRef;
pub fn LLVMPositionBuilder(Builder: BuilderRef,
Block: BasicBlockRef,
Instr: ValueRef);
pub fn LLVMPositionBuilderBefore(Builder: BuilderRef,
Instr: ValueRef);
pub fn LLVMPositionBuilderAtEnd(Builder: BuilderRef,
Block: BasicBlockRef);
pub fn LLVMGetInsertBlock(Builder: BuilderRef) -> BasicBlockRef;
pub fn LLVMClearInsertionPosition(Builder: BuilderRef);
pub fn LLVMInsertIntoBuilder(Builder: BuilderRef, Instr: ValueRef);
pub fn LLVMInsertIntoBuilderWithName(Builder: BuilderRef,
Instr: ValueRef,
Name: *const c_char);
pub fn LLVMDisposeBuilder(Builder: BuilderRef);
/* Execution engine */
pub fn LLVMRustCreateJITMemoryManager(morestack: *const ())
-> RustJITMemoryManagerRef;
pub fn LLVMBuildExecutionEngine(Mod: ModuleRef,
MM: RustJITMemoryManagerRef) -> ExecutionEngineRef;
pub fn LLVMDisposeExecutionEngine(EE: ExecutionEngineRef);
pub fn LLVMExecutionEngineFinalizeObject(EE: ExecutionEngineRef);
pub fn LLVMRustLoadDynamicLibrary(path: *const c_char) -> Bool;
pub fn LLVMExecutionEngineAddModule(EE: ExecutionEngineRef, M: ModuleRef);
pub fn LLVMExecutionEngineRemoveModule(EE: ExecutionEngineRef, M: ModuleRef)
-> Bool;
/* Metadata */
pub fn LLVMSetCurrentDebugLocation(Builder: BuilderRef, L: ValueRef);
pub fn LLVMGetCurrentDebugLocation(Builder: BuilderRef) -> ValueRef;
pub fn LLVMSetInstDebugLocation(Builder: BuilderRef, Inst: ValueRef);
/* Terminators */
pub fn LLVMBuildRetVoid(B: BuilderRef) -> ValueRef;
pub fn LLVMBuildRet(B: BuilderRef, V: ValueRef) -> ValueRef;
pub fn LLVMBuildAggregateRet(B: BuilderRef,
RetVals: *const ValueRef,
N: c_uint)
-> ValueRef;
pub fn LLVMBuildBr(B: BuilderRef, Dest: BasicBlockRef) -> ValueRef;
pub fn LLVMBuildCondBr(B: BuilderRef,
If: ValueRef,
Then: BasicBlockRef,
Else: BasicBlockRef)
-> ValueRef;
pub fn LLVMBuildSwitch(B: BuilderRef,
V: ValueRef,
Else: BasicBlockRef,
NumCases: c_uint)
-> ValueRef;
pub fn LLVMBuildIndirectBr(B: BuilderRef,
Addr: ValueRef,
NumDests: c_uint)
-> ValueRef;
pub fn LLVMBuildInvoke(B: BuilderRef,
Fn: ValueRef,
Args: *const ValueRef,
NumArgs: c_uint,
Then: BasicBlockRef,
Catch: BasicBlockRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildLandingPad(B: BuilderRef,
Ty: TypeRef,
PersFn: ValueRef,
NumClauses: c_uint,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildResume(B: BuilderRef, Exn: ValueRef) -> ValueRef;
pub fn LLVMBuildUnreachable(B: BuilderRef) -> ValueRef;
/* Add a case to the switch instruction */
pub fn LLVMAddCase(Switch: ValueRef,
OnVal: ValueRef,
Dest: BasicBlockRef);
/* Add a destination to the indirectbr instruction */
pub fn LLVMAddDestination(IndirectBr: ValueRef, Dest: BasicBlockRef);
/* Add a clause to the landing pad instruction */
pub fn LLVMAddClause(LandingPad: ValueRef, ClauseVal: ValueRef);
/* Set the cleanup on a landing pad instruction */
pub fn LLVMSetCleanup(LandingPad: ValueRef, Val: Bool);
/* Arithmetic */
pub fn LLVMBuildAdd(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNSWAdd(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNUWAdd(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFAdd(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildSub(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNSWSub(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNUWSub(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFSub(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildMul(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNSWMul(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNUWMul(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFMul(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildUDiv(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildSDiv(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildExactSDiv(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFDiv(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildURem(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildSRem(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFRem(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildShl(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildLShr(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildAShr(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildAnd(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildOr(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildXor(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildBinOp(B: BuilderRef,
Op: Opcode,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNeg(B: BuilderRef, V: ValueRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNSWNeg(B: BuilderRef, V: ValueRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNUWNeg(B: BuilderRef, V: ValueRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFNeg(B: BuilderRef, V: ValueRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildNot(B: BuilderRef, V: ValueRef, Name: *const c_char)
-> ValueRef;
/* Memory */
pub fn LLVMBuildMalloc(B: BuilderRef, Ty: TypeRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildArrayMalloc(B: BuilderRef,
Ty: TypeRef,
Val: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildAlloca(B: BuilderRef, Ty: TypeRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildArrayAlloca(B: BuilderRef,
Ty: TypeRef,
Val: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFree(B: BuilderRef, PointerVal: ValueRef) -> ValueRef;
pub fn LLVMBuildLoad(B: BuilderRef,
PointerVal: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildStore(B: BuilderRef, Val: ValueRef, Ptr: ValueRef)
-> ValueRef;
pub fn LLVMBuildGEP(B: BuilderRef,
Pointer: ValueRef,
Indices: *const ValueRef,
NumIndices: c_uint,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildInBoundsGEP(B: BuilderRef,
Pointer: ValueRef,
Indices: *const ValueRef,
NumIndices: c_uint,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildStructGEP(B: BuilderRef,
Pointer: ValueRef,
Idx: c_uint,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildGlobalString(B: BuilderRef,
Str: *const c_char,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildGlobalStringPtr(B: BuilderRef,
Str: *const c_char,
Name: *const c_char)
-> ValueRef;
/* Casts */
pub fn LLVMBuildTrunc(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildZExt(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildSExt(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFPToUI(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFPToSI(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildUIToFP(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildSIToFP(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFPTrunc(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFPExt(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildPtrToInt(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildIntToPtr(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildBitCast(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildZExtOrBitCast(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildSExtOrBitCast(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildTruncOrBitCast(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildCast(B: BuilderRef,
Op: Opcode,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char) -> ValueRef;
pub fn LLVMBuildPointerCast(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildIntCast(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFPCast(B: BuilderRef,
Val: ValueRef,
DestTy: TypeRef,
Name: *const c_char)
-> ValueRef;
/* Comparisons */
pub fn LLVMBuildICmp(B: BuilderRef,
Op: c_uint,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildFCmp(B: BuilderRef,
Op: c_uint,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
/* Miscellaneous instructions */
pub fn LLVMBuildPhi(B: BuilderRef, Ty: TypeRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildCall(B: BuilderRef,
Fn: ValueRef,
Args: *const ValueRef,
NumArgs: c_uint,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildSelect(B: BuilderRef,
If: ValueRef,
Then: ValueRef,
Else: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildVAArg(B: BuilderRef,
list: ValueRef,
Ty: TypeRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildExtractElement(B: BuilderRef,
VecVal: ValueRef,
Index: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildInsertElement(B: BuilderRef,
VecVal: ValueRef,
EltVal: ValueRef,
Index: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildShuffleVector(B: BuilderRef,
V1: ValueRef,
V2: ValueRef,
Mask: ValueRef,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildExtractValue(B: BuilderRef,
AggVal: ValueRef,
Index: c_uint,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildInsertValue(B: BuilderRef,
AggVal: ValueRef,
EltVal: ValueRef,
Index: c_uint,
Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildIsNull(B: BuilderRef, Val: ValueRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildIsNotNull(B: BuilderRef, Val: ValueRef, Name: *const c_char)
-> ValueRef;
pub fn LLVMBuildPtrDiff(B: BuilderRef,
LHS: ValueRef,
RHS: ValueRef,
Name: *const c_char)
-> ValueRef;
/* Atomic Operations */
pub fn LLVMBuildAtomicLoad(B: BuilderRef,
PointerVal: ValueRef,
Name: *const c_char,
Order: AtomicOrdering,
Alignment: c_uint)
-> ValueRef;
pub fn LLVMBuildAtomicStore(B: BuilderRef,
Val: ValueRef,
Ptr: ValueRef,
Order: AtomicOrdering,
Alignment: c_uint)
-> ValueRef;
pub fn LLVMBuildAtomicCmpXchg(B: BuilderRef,
LHS: ValueRef,
CMP: ValueRef,
RHS: ValueRef,
Order: AtomicOrdering,
FailureOrder: AtomicOrdering)
-> ValueRef;
pub fn LLVMBuildAtomicRMW(B: BuilderRef,
Op: AtomicBinOp,
LHS: ValueRef,
RHS: ValueRef,
Order: AtomicOrdering,
SingleThreaded: Bool)
-> ValueRef;
pub fn LLVMBuildAtomicFence(B: BuilderRef, Order: AtomicOrdering);
/* Selected entries from the downcasts. */
pub fn LLVMIsATerminatorInst(Inst: ValueRef) -> ValueRef;
pub fn LLVMIsAStoreInst(Inst: ValueRef) -> ValueRef;
/// Writes a module to the specified path. Returns 0 on success.
pub fn LLVMWriteBitcodeToFile(M: ModuleRef, Path: *const c_char) -> c_int;
/// Creates target data from a target layout string.
pub fn LLVMCreateTargetData(StringRep: *const c_char) -> TargetDataRef;
/// Adds the target data to the given pass manager. The pass manager
/// references the target data only weakly.
pub fn LLVMAddTargetData(TD: TargetDataRef, PM: PassManagerRef);
/// Number of bytes clobbered when doing a Store to *T.
pub fn LLVMStoreSizeOfType(TD: TargetDataRef, Ty: TypeRef)
-> c_ulonglong;
/// Number of bytes clobbered when doing a Store to *T.
pub fn LLVMSizeOfTypeInBits(TD: TargetDataRef, Ty: TypeRef)
-> c_ulonglong;
/// Distance between successive elements in an array of T. Includes ABI padding.
pub fn LLVMABISizeOfType(TD: TargetDataRef, Ty: TypeRef) -> c_ulonglong;
/// Returns the preferred alignment of a type.
pub fn LLVMPreferredAlignmentOfType(TD: TargetDataRef, Ty: TypeRef)
-> c_uint;
/// Returns the minimum alignment of a type.
pub fn LLVMABIAlignmentOfType(TD: TargetDataRef, Ty: TypeRef)
-> c_uint;
/// Computes the byte offset of the indexed struct element for a
/// target.
pub fn LLVMOffsetOfElement(TD: TargetDataRef,
StructTy: TypeRef,
Element: c_uint)
-> c_ulonglong;
/// Returns the minimum alignment of a type when part of a call frame.
pub fn LLVMCallFrameAlignmentOfType(TD: TargetDataRef, Ty: TypeRef)
-> c_uint;
/// Disposes target data.
pub fn LLVMDisposeTargetData(TD: TargetDataRef);
/// Creates a pass manager.
pub fn LLVMCreatePassManager() -> PassManagerRef;
/// Creates a function-by-function pass manager
pub fn LLVMCreateFunctionPassManagerForModule(M: ModuleRef)
-> PassManagerRef;
/// Disposes a pass manager.
pub fn LLVMDisposePassManager(PM: PassManagerRef);
/// Runs a pass manager on a module.
pub fn LLVMRunPassManager(PM: PassManagerRef, M: ModuleRef) -> Bool;
/// Runs the function passes on the provided function.
pub fn LLVMRunFunctionPassManager(FPM: PassManagerRef, F: ValueRef)
-> Bool;
/// Initializes all the function passes scheduled in the manager
pub fn LLVMInitializeFunctionPassManager(FPM: PassManagerRef) -> Bool;
/// Finalizes all the function passes scheduled in the manager
pub fn LLVMFinalizeFunctionPassManager(FPM: PassManagerRef) -> Bool;
pub fn LLVMInitializePasses();
/// Adds a verification pass.
pub fn LLVMAddVerifierPass(PM: PassManagerRef);
pub fn LLVMAddGlobalOptimizerPass(PM: PassManagerRef);
pub fn LLVMAddIPSCCPPass(PM: PassManagerRef);
pub fn LLVMAddDeadArgEliminationPass(PM: PassManagerRef);
pub fn LLVMAddInstructionCombiningPass(PM: PassManagerRef);
pub fn LLVMAddCFGSimplificationPass(PM: PassManagerRef);
pub fn LLVMAddFunctionInliningPass(PM: PassManagerRef);
pub fn LLVMAddFunctionAttrsPass(PM: PassManagerRef);
pub fn LLVMAddScalarReplAggregatesPass(PM: PassManagerRef);
pub fn LLVMAddScalarReplAggregatesPassSSA(PM: PassManagerRef);
pub fn LLVMAddJumpThreadingPass(PM: PassManagerRef);
pub fn LLVMAddConstantPropagationPass(PM: PassManagerRef);
pub fn LLVMAddReassociatePass(PM: PassManagerRef);
pub fn LLVMAddLoopRotatePass(PM: PassManagerRef);
pub fn LLVMAddLICMPass(PM: PassManagerRef);
pub fn LLVMAddLoopUnswitchPass(PM: PassManagerRef);
pub fn LLVMAddLoopDeletionPass(PM: PassManagerRef);
pub fn LLVMAddLoopUnrollPass(PM: PassManagerRef);
pub fn LLVMAddGVNPass(PM: PassManagerRef);
pub fn LLVMAddMemCpyOptPass(PM: PassManagerRef);
pub fn LLVMAddSCCPPass(PM: PassManagerRef);
pub fn LLVMAddDeadStoreEliminationPass(PM: PassManagerRef);
pub fn LLVMAddStripDeadPrototypesPass(PM: PassManagerRef);
pub fn LLVMAddConstantMergePass(PM: PassManagerRef);
pub fn LLVMAddArgumentPromotionPass(PM: PassManagerRef);
pub fn LLVMAddTailCallEliminationPass(PM: PassManagerRef);
pub fn LLVMAddIndVarSimplifyPass(PM: PassManagerRef);
pub fn LLVMAddAggressiveDCEPass(PM: PassManagerRef);
pub fn LLVMAddGlobalDCEPass(PM: PassManagerRef);
pub fn LLVMAddCorrelatedValuePropagationPass(PM: PassManagerRef);
pub fn LLVMAddPruneEHPass(PM: PassManagerRef);
pub fn LLVMAddSimplifyLibCallsPass(PM: PassManagerRef);
pub fn LLVMAddLoopIdiomPass(PM: PassManagerRef);
pub fn LLVMAddEarlyCSEPass(PM: PassManagerRef);
pub fn LLVMAddTypeBasedAliasAnalysisPass(PM: PassManagerRef);
pub fn LLVMAddBasicAliasAnalysisPass(PM: PassManagerRef);
pub fn LLVMPassManagerBuilderCreate() -> PassManagerBuilderRef;
pub fn LLVMPassManagerBuilderDispose(PMB: PassManagerBuilderRef);
pub fn LLVMPassManagerBuilderSetOptLevel(PMB: PassManagerBuilderRef,
OptimizationLevel: c_uint);
pub fn LLVMPassManagerBuilderSetSizeLevel(PMB: PassManagerBuilderRef,
Value: Bool);
pub fn LLVMPassManagerBuilderSetDisableUnitAtATime(
PMB: PassManagerBuilderRef,
Value: Bool);
pub fn LLVMPassManagerBuilderSetDisableUnrollLoops(
PMB: PassManagerBuilderRef,
Value: Bool);
pub fn LLVMPassManagerBuilderSetDisableSimplifyLibCalls(
PMB: PassManagerBuilderRef,
Value: Bool);
pub fn LLVMPassManagerBuilderUseInlinerWithThreshold(
PMB: PassManagerBuilderRef,
threshold: c_uint);
pub fn LLVMPassManagerBuilderPopulateModulePassManager(
PMB: PassManagerBuilderRef,
PM: PassManagerRef);
pub fn LLVMPassManagerBuilderPopulateFunctionPassManager(
PMB: PassManagerBuilderRef,
PM: PassManagerRef);
pub fn LLVMPassManagerBuilderPopulateLTOPassManager(
PMB: PassManagerBuilderRef,
PM: PassManagerRef,
Internalize: Bool,
RunInliner: Bool);
/// Destroys a memory buffer.
pub fn LLVMDisposeMemoryBuffer(MemBuf: MemoryBufferRef);
/* Stuff that's in rustllvm/ because it's not upstream yet. */
/// Opens an object file.
pub fn LLVMCreateObjectFile(MemBuf: MemoryBufferRef) -> ObjectFileRef;
/// Closes an object file.
pub fn LLVMDisposeObjectFile(ObjFile: ObjectFileRef);
/// Enumerates the sections in an object file.
pub fn LLVMGetSections(ObjFile: ObjectFileRef) -> SectionIteratorRef;
/// Destroys a section iterator.
pub fn LLVMDisposeSectionIterator(SI: SectionIteratorRef);
/// Returns true if the section iterator is at the end of the section
/// list:
pub fn LLVMIsSectionIteratorAtEnd(ObjFile: ObjectFileRef,
SI: SectionIteratorRef)
-> Bool;
/// Moves the section iterator to point to the next section.
pub fn LLVMMoveToNextSection(SI: SectionIteratorRef);
/// Returns the current section size.
pub fn LLVMGetSectionSize(SI: SectionIteratorRef) -> c_ulonglong;
/// Returns the current section contents as a string buffer.
pub fn LLVMGetSectionContents(SI: SectionIteratorRef) -> *const c_char;
/// Reads the given file and returns it as a memory buffer. Use
/// LLVMDisposeMemoryBuffer() to get rid of it.
pub fn LLVMRustCreateMemoryBufferWithContentsOfFile(Path: *const c_char)
-> MemoryBufferRef;
/// Borrows the contents of the memory buffer (doesn't copy it)
pub fn LLVMCreateMemoryBufferWithMemoryRange(InputData: *const c_char,
InputDataLength: size_t,
BufferName: *const c_char,
RequiresNull: Bool)
-> MemoryBufferRef;
pub fn LLVMCreateMemoryBufferWithMemoryRangeCopy(InputData: *const c_char,
InputDataLength: size_t,
BufferName: *const c_char)
-> MemoryBufferRef;
pub fn LLVMIsMultithreaded() -> Bool;
pub fn LLVMStartMultithreaded() -> Bool;
/// Returns a string describing the last error caused by an LLVMRust* call.
pub fn LLVMRustGetLastError() -> *const c_char;
/// Print the pass timings since static dtors aren't picking them up.
pub fn LLVMRustPrintPassTimings();
pub fn LLVMStructCreateNamed(C: ContextRef, Name: *const c_char) -> TypeRef;
pub fn LLVMStructSetBody(StructTy: TypeRef,
ElementTypes: *const TypeRef,
ElementCount: c_uint,
Packed: Bool);
pub fn LLVMConstNamedStruct(S: TypeRef,
ConstantVals: *const ValueRef,
Count: c_uint)
-> ValueRef;
/// Enables LLVM debug output.
pub fn LLVMSetDebug(Enabled: c_int);
/// Prepares inline assembly.
pub fn LLVMInlineAsm(Ty: TypeRef,
AsmString: *const c_char,
Constraints: *const c_char,
SideEffects: Bool,
AlignStack: Bool,
Dialect: c_uint)
-> ValueRef;
pub static LLVMRustDebugMetadataVersion: u32;
pub fn LLVMRustAddModuleFlag(M: ModuleRef,
name: *const c_char,
value: u32);
pub fn LLVMDIBuilderCreate(M: ModuleRef) -> DIBuilderRef;
pub fn LLVMDIBuilderDispose(Builder: DIBuilderRef);
pub fn LLVMDIBuilderFinalize(Builder: DIBuilderRef);
pub fn LLVMDIBuilderCreateCompileUnit(Builder: DIBuilderRef,
Lang: c_uint,
File: *const c_char,
Dir: *const c_char,
Producer: *const c_char,
isOptimized: bool,
Flags: *const c_char,
RuntimeVer: c_uint,
SplitName: *const c_char)
-> DIDescriptor;
pub fn LLVMDIBuilderCreateFile(Builder: DIBuilderRef,
Filename: *const c_char,
Directory: *const c_char)
-> DIFile;
pub fn LLVMDIBuilderCreateSubroutineType(Builder: DIBuilderRef,
File: DIFile,
ParameterTypes: DIArray)
-> DICompositeType;
pub fn LLVMDIBuilderCreateFunction(Builder: DIBuilderRef,
Scope: DIDescriptor,
Name: *const c_char,
LinkageName: *const c_char,
File: DIFile,
LineNo: c_uint,
Ty: DIType,
isLocalToUnit: bool,
isDefinition: bool,
ScopeLine: c_uint,
Flags: c_uint,
isOptimized: bool,
Fn: ValueRef,
TParam: ValueRef,
Decl: ValueRef)
-> DISubprogram;
pub fn LLVMDIBuilderCreateBasicType(Builder: DIBuilderRef,
Name: *const c_char,
SizeInBits: c_ulonglong,
AlignInBits: c_ulonglong,
Encoding: c_uint)
-> DIBasicType;
pub fn LLVMDIBuilderCreatePointerType(Builder: DIBuilderRef,
PointeeTy: DIType,
SizeInBits: c_ulonglong,
AlignInBits: c_ulonglong,
Name: *const c_char)
-> DIDerivedType;
pub fn LLVMDIBuilderCreateStructType(Builder: DIBuilderRef,
Scope: DIDescriptor,
Name: *const c_char,
File: DIFile,
LineNumber: c_uint,
SizeInBits: c_ulonglong,
AlignInBits: c_ulonglong,
Flags: c_uint,
DerivedFrom: DIType,
Elements: DIArray,
RunTimeLang: c_uint,
VTableHolder: ValueRef,
UniqueId: *const c_char)
-> DICompositeType;
pub fn LLVMDIBuilderCreateMemberType(Builder: DIBuilderRef,
Scope: DIDescriptor,
Name: *const c_char,
File: DIFile,
LineNo: c_uint,
SizeInBits: c_ulonglong,
AlignInBits: c_ulonglong,
OffsetInBits: c_ulonglong,
Flags: c_uint,
Ty: DIType)
-> DIDerivedType;
pub fn LLVMDIBuilderCreateLexicalBlock(Builder: DIBuilderRef,
Scope: DIDescriptor,
File: DIFile,
Line: c_uint,
Col: c_uint)
-> DILexicalBlock;
pub fn LLVMDIBuilderCreateStaticVariable(Builder: DIBuilderRef,
Context: DIDescriptor,
Name: *const c_char,
LinkageName: *const c_char,
File: DIFile,
LineNo: c_uint,
Ty: DIType,
isLocalToUnit: bool,
Val: ValueRef,
Decl: ValueRef)
-> DIGlobalVariable;
pub fn LLVMDIBuilderCreateLocalVariable(Builder: DIBuilderRef,
Tag: c_uint,
Scope: DIDescriptor,
Name: *const c_char,
File: DIFile,
LineNo: c_uint,
Ty: DIType,
AlwaysPreserve: bool,
Flags: c_uint,
ArgNo: c_uint)
-> DIVariable;
pub fn LLVMDIBuilderCreateArrayType(Builder: DIBuilderRef,
Size: c_ulonglong,
AlignInBits: c_ulonglong,
Ty: DIType,
Subscripts: DIArray)
-> DIType;
pub fn LLVMDIBuilderCreateVectorType(Builder: DIBuilderRef,
Size: c_ulonglong,
AlignInBits: c_ulonglong,
Ty: DIType,
Subscripts: DIArray)
-> DIType;
pub fn LLVMDIBuilderGetOrCreateSubrange(Builder: DIBuilderRef,
Lo: c_longlong,
Count: c_longlong)
-> DISubrange;
pub fn LLVMDIBuilderGetOrCreateArray(Builder: DIBuilderRef,
Ptr: *const DIDescriptor,
Count: c_uint)
-> DIArray;
pub fn LLVMDIBuilderInsertDeclareAtEnd(Builder: DIBuilderRef,
Val: ValueRef,
VarInfo: DIVariable,
InsertAtEnd: BasicBlockRef)
-> ValueRef;
pub fn LLVMDIBuilderInsertDeclareBefore(Builder: DIBuilderRef,
Val: ValueRef,
VarInfo: DIVariable,
InsertBefore: ValueRef)
-> ValueRef;
pub fn LLVMDIBuilderCreateEnumerator(Builder: DIBuilderRef,
Name: *const c_char,
Val: c_ulonglong)
-> ValueRef;
pub fn LLVMDIBuilderCreateEnumerationType(Builder: DIBuilderRef,
Scope: ValueRef,
Name: *const c_char,
File: ValueRef,
LineNumber: c_uint,
SizeInBits: c_ulonglong,
AlignInBits: c_ulonglong,
Elements: ValueRef,
ClassType: ValueRef)
-> ValueRef;
pub fn LLVMDIBuilderCreateUnionType(Builder: DIBuilderRef,
Scope: ValueRef,
Name: *const c_char,
File: ValueRef,
LineNumber: c_uint,
SizeInBits: c_ulonglong,
AlignInBits: c_ulonglong,
Flags: c_uint,
Elements: ValueRef,
RunTimeLang: c_uint,
UniqueId: *const c_char)
-> ValueRef;
pub fn LLVMSetUnnamedAddr(GlobalVar: ValueRef, UnnamedAddr: Bool);
pub fn LLVMDIBuilderCreateTemplateTypeParameter(Builder: DIBuilderRef,
Scope: ValueRef,
Name: *const c_char,
Ty: ValueRef,
File: ValueRef,
LineNo: c_uint,
ColumnNo: c_uint)
-> ValueRef;
pub fn LLVMDIBuilderCreateOpDeref(IntType: TypeRef) -> ValueRef;
pub fn LLVMDIBuilderCreateOpPlus(IntType: TypeRef) -> ValueRef;
pub fn LLVMDIBuilderCreateComplexVariable(Builder: DIBuilderRef,
Tag: c_uint,
Scope: ValueRef,
Name: *const c_char,
File: ValueRef,
LineNo: c_uint,
Ty: ValueRef,
AddrOps: *const ValueRef,
AddrOpsCount: c_uint,
ArgNo: c_uint)
-> ValueRef;
pub fn LLVMDIBuilderCreateNameSpace(Builder: DIBuilderRef,
Scope: ValueRef,
Name: *const c_char,
File: ValueRef,
LineNo: c_uint)
-> ValueRef;
pub fn LLVMDICompositeTypeSetTypeArray(CompositeType: ValueRef, TypeArray: ValueRef);
pub fn LLVMWriteTypeToString(Type: TypeRef, s: RustStringRef);
pub fn LLVMWriteValueToString(value_ref: ValueRef, s: RustStringRef);
pub fn LLVMIsAArgument(value_ref: ValueRef) -> ValueRef;
pub fn LLVMIsAAllocaInst(value_ref: ValueRef) -> ValueRef;
pub fn LLVMInitializeX86TargetInfo();
pub fn LLVMInitializeX86Target();
pub fn LLVMInitializeX86TargetMC();
pub fn LLVMInitializeX86AsmPrinter();
pub fn LLVMInitializeX86AsmParser();
pub fn LLVMInitializeARMTargetInfo();
pub fn LLVMInitializeARMTarget();
pub fn LLVMInitializeARMTargetMC();
pub fn LLVMInitializeARMAsmPrinter();
pub fn LLVMInitializeARMAsmParser();
pub fn LLVMInitializeAArch64TargetInfo();
pub fn LLVMInitializeAArch64Target();
pub fn LLVMInitializeAArch64TargetMC();
pub fn LLVMInitializeAArch64AsmPrinter();
pub fn LLVMInitializeAArch64AsmParser();
pub fn LLVMInitializeMipsTargetInfo();
pub fn LLVMInitializeMipsTarget();
pub fn LLVMInitializeMipsTargetMC();
pub fn LLVMInitializeMipsAsmPrinter();
pub fn LLVMInitializeMipsAsmParser();
pub fn LLVMRustAddPass(PM: PassManagerRef, Pass: *const c_char) -> bool;
pub fn LLVMRustCreateTargetMachine(Triple: *const c_char,
CPU: *const c_char,
Features: *const c_char,
Model: CodeGenModel,
Reloc: RelocMode,
Level: CodeGenOptLevel,
EnableSegstk: bool,
UseSoftFP: bool,
NoFramePointerElim: bool,
PositionIndependentExecutable: bool,
FunctionSections: bool,
DataSections: bool) -> TargetMachineRef;
pub fn LLVMRustDisposeTargetMachine(T: TargetMachineRef);
pub fn LLVMRustAddAnalysisPasses(T: TargetMachineRef,
PM: PassManagerRef,
M: ModuleRef);
pub fn LLVMRustAddBuilderLibraryInfo(PMB: PassManagerBuilderRef,
M: ModuleRef,
DisableSimplifyLibCalls: bool);
pub fn LLVMRustAddLibraryInfo(PM: PassManagerRef, M: ModuleRef,
DisableSimplifyLibCalls: bool);
pub fn LLVMRustRunFunctionPassManager(PM: PassManagerRef, M: ModuleRef);
pub fn LLVMRustWriteOutputFile(T: TargetMachineRef,
PM: PassManagerRef,
M: ModuleRef,
Output: *const c_char,
FileType: FileType) -> bool;
pub fn LLVMRustPrintModule(PM: PassManagerRef,
M: ModuleRef,
Output: *const c_char);
pub fn LLVMRustSetLLVMOptions(Argc: c_int, Argv: *const *const c_char);
pub fn LLVMRustPrintPasses();
pub fn LLVMRustSetNormalizedTarget(M: ModuleRef, triple: *const c_char);
pub fn LLVMRustAddAlwaysInlinePass(P: PassManagerBuilderRef,
AddLifetimes: bool);
pub fn LLVMRustLinkInExternalBitcode(M: ModuleRef,
bc: *const c_char,
len: size_t) -> bool;
pub fn LLVMRustRunRestrictionPass(M: ModuleRef,
syms: *const *const c_char,
len: size_t);
pub fn LLVMRustMarkAllFunctionsNounwind(M: ModuleRef);
pub fn LLVMRustOpenArchive(path: *const c_char) -> ArchiveRef;
pub fn LLVMRustArchiveReadSection(AR: ArchiveRef, name: *const c_char,
out_len: *mut size_t) -> *const c_char;
pub fn LLVMRustDestroyArchive(AR: ArchiveRef);
pub fn LLVMRustSetDLLExportStorageClass(V: ValueRef);
pub fn LLVMVersionMajor() -> c_int;
pub fn LLVMVersionMinor() -> c_int;
pub fn LLVMRustGetSectionName(SI: SectionIteratorRef,
data: *mut *const c_char) -> c_int;
pub fn LLVMWriteTwineToString(T: TwineRef, s: RustStringRef);
pub fn LLVMContextSetDiagnosticHandler(C: ContextRef,
Handler: DiagnosticHandler,
DiagnosticContext: *mut c_void);
pub fn LLVMUnpackOptimizationDiagnostic(DI: DiagnosticInfoRef,
pass_name_out: *mut *const c_char,
function_out: *mut ValueRef,
debugloc_out: *mut DebugLocRef,
message_out: *mut TwineRef);
pub fn LLVMWriteDiagnosticInfoToString(DI: DiagnosticInfoRef, s: RustStringRef);
pub fn LLVMGetDiagInfoSeverity(DI: DiagnosticInfoRef) -> DiagnosticSeverity;
pub fn LLVMGetDiagInfoKind(DI: DiagnosticInfoRef) -> DiagnosticKind;
pub fn LLVMWriteDebugLocToString(C: ContextRef, DL: DebugLocRef, s: RustStringRef);
pub fn LLVMSetInlineAsmDiagnosticHandler(C: ContextRef,
H: InlineAsmDiagHandler,
CX: *mut c_void);
pub fn LLVMWriteSMDiagnosticToString(d: SMDiagnosticRef, s: RustStringRef);
}
pub fn SetInstructionCallConv(instr: ValueRef, cc: CallConv) {
unsafe {
LLVMSetInstructionCallConv(instr, cc as c_uint);
}
}
pub fn SetFunctionCallConv(fn_: ValueRef, cc: CallConv) {
unsafe {
LLVMSetFunctionCallConv(fn_, cc as c_uint);
}
}
pub fn SetLinkage(global: ValueRef, link: Linkage) {
unsafe {
LLVMSetLinkage(global, link as c_uint);
}
}
pub fn SetUnnamedAddr(global: ValueRef, unnamed: bool) {
unsafe {
LLVMSetUnnamedAddr(global, unnamed as Bool);
}
}
pub fn set_thread_local(global: ValueRef, is_thread_local: bool) {
unsafe {
LLVMSetThreadLocal(global, is_thread_local as Bool);
}
}
pub fn ConstICmp(pred: IntPredicate, v1: ValueRef, v2: ValueRef) -> ValueRef {
unsafe {
LLVMConstICmp(pred as c_ushort, v1, v2)
}
}
pub fn ConstFCmp(pred: RealPredicate, v1: ValueRef, v2: ValueRef) -> ValueRef {
unsafe {
LLVMConstFCmp(pred as c_ushort, v1, v2)
}
}
pub fn SetFunctionAttribute(fn_: ValueRef, attr: Attribute) {
unsafe {
LLVMAddFunctionAttribute(fn_, FunctionIndex as c_uint, attr.bits() as uint64_t)
}
}
/* Memory-managed interface to target data. */
pub struct TargetData {
pub lltd: TargetDataRef
}
impl Drop for TargetData {
fn drop(&mut self) {
unsafe {
LLVMDisposeTargetData(self.lltd);
}
}
}
pub fn mk_target_data(string_rep: &str) -> TargetData {
let string_rep = CString::from_slice(string_rep.as_bytes());
TargetData {
lltd: unsafe { LLVMCreateTargetData(string_rep.as_ptr()) }
}
}
/* Memory-managed interface to object files. */
pub struct ObjectFile {
pub llof: ObjectFileRef,
}
impl ObjectFile {
// This will take ownership of llmb
pub fn new(llmb: MemoryBufferRef) -> Option<ObjectFile> {
unsafe {
let llof = LLVMCreateObjectFile(llmb);
if llof as int == 0 {
// LLVMCreateObjectFile took ownership of llmb
return None
}
Some(ObjectFile {
llof: llof,
})
}
}
}
impl Drop for ObjectFile {
fn drop(&mut self) {
unsafe {
LLVMDisposeObjectFile(self.llof);
}
}
}
/* Memory-managed interface to section iterators. */
pub struct SectionIter {
pub llsi: SectionIteratorRef
}
impl Drop for SectionIter {
fn drop(&mut self) {
unsafe {
LLVMDisposeSectionIterator(self.llsi);
}
}
}
pub fn mk_section_iter(llof: ObjectFileRef) -> SectionIter {
unsafe {
SectionIter {
llsi: LLVMGetSections(llof)
}
}
}
/// Safe wrapper around `LLVMGetParam`, because segfaults are no fun.
pub fn get_param(llfn: ValueRef, index: c_uint) -> ValueRef {
unsafe {
assert!(index < LLVMCountParams(llfn));
LLVMGetParam(llfn, index)
}
}
#[allow(missing_copy_implementations)]
pub enum RustString_opaque {}
pub type RustStringRef = *mut RustString_opaque;
type RustStringRepr = *mut RefCell<Vec<u8>>;
/// Appending to a Rust string -- used by raw_rust_string_ostream.
#[no_mangle]
pub unsafe extern "C" fn rust_llvm_string_write_impl(sr: RustStringRef,
ptr: *const c_char,
size: size_t) {
let slice: &[u8] = mem::transmute(raw::Slice {
data: ptr as *const u8,
len: size as uint,
});
let sr: RustStringRepr = mem::transmute(sr);
(*sr).borrow_mut().push_all(slice);
}
pub fn build_string<F>(f: F) -> Option<String> where F: FnOnce(RustStringRef){
let mut buf = RefCell::new(Vec::new());
f(&mut buf as RustStringRepr as RustStringRef);
String::from_utf8(buf.into_inner()).ok()
}
pub unsafe fn twine_to_string(tr: TwineRef) -> String {
build_string(|s| LLVMWriteTwineToString(tr, s))
.expect("got a non-UTF8 Twine from LLVM")
}
pub unsafe fn debug_loc_to_string(c: ContextRef, tr: DebugLocRef) -> String {
build_string(|s| LLVMWriteDebugLocToString(c, tr, s))
.expect("got a non-UTF8 DebugLoc from LLVM")
}
// FIXME #15460 - create a public function that actually calls our
// static LLVM symbols. Otherwise the linker will just throw llvm
// away. We're just calling lots of stuff until we transitively get
// all of LLVM. This is worse than anything.
pub unsafe fn static_link_hack_this_sucks() {
LLVMInitializePasses();
LLVMInitializeX86TargetInfo();
LLVMInitializeX86Target();
LLVMInitializeX86TargetMC();
LLVMInitializeX86AsmPrinter();
LLVMInitializeX86AsmParser();
LLVMInitializeARMTargetInfo();
LLVMInitializeARMTarget();
LLVMInitializeARMTargetMC();
LLVMInitializeARMAsmPrinter();
LLVMInitializeARMAsmParser();
LLVMInitializeAArch64TargetInfo();
LLVMInitializeAArch64Target();
LLVMInitializeAArch64TargetMC();
LLVMInitializeAArch64AsmPrinter();
LLVMInitializeAArch64AsmParser();
LLVMInitializeMipsTargetInfo();
LLVMInitializeMipsTarget();
LLVMInitializeMipsTargetMC();
LLVMInitializeMipsAsmPrinter();
LLVMInitializeMipsAsmParser();
LLVMRustSetLLVMOptions(0 as c_int,
0 as *const _);
LLVMPassManagerBuilderPopulateModulePassManager(0 as *mut _, 0 as *mut _);
LLVMPassManagerBuilderPopulateLTOPassManager(0 as *mut _, 0 as *mut _, False, False);
LLVMPassManagerBuilderPopulateFunctionPassManager(0 as *mut _, 0 as *mut _);
LLVMPassManagerBuilderSetOptLevel(0 as *mut _, 0 as c_uint);
LLVMPassManagerBuilderUseInlinerWithThreshold(0 as *mut _, 0 as c_uint);
LLVMWriteBitcodeToFile(0 as *mut _, 0 as *const _);
LLVMPassManagerBuilderCreate();
LLVMPassManagerBuilderDispose(0 as *mut _);
LLVMRustLinkInExternalBitcode(0 as *mut _, 0 as *const _, 0 as size_t);
LLVMLinkInMCJIT();
LLVMLinkInInterpreter();
extern {
fn LLVMLinkInMCJIT();
fn LLVMLinkInInterpreter();
}
}
// The module containing the native LLVM dependencies, generated by the build system
// Note that this must come after the rustllvm extern declaration so that
// parts of LLVM that rustllvm depends on aren't thrown away by the linker.
// Works to the above fix for #15460 to ensure LLVM dependencies that
// are only used by rustllvm don't get stripped by the linker.
mod llvmdeps {
include! { env!("CFG_LLVM_LINKAGE_FILE") }
}<|fim▁end|> | PrivateLinkage = 9,
ExternalWeakLinkage = 12,
CommonLinkage = 14, |
<|file_name|>macro-crate-use.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
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
<|fim▁hole|>}
#[macro_export]
macro_rules! increment {
($x:expr) => ({
use $crate::increment;
increment($x)
})
}
fn main() {
assert_eq!(increment!(3), 4);
}<|fim▁end|> | pub fn increment(x: usize) -> usize {
x + 1 |
<|file_name|>ui.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/. */
//! Specified types for UI properties.
use cssparser::Parser;
use parser::{Parse, ParserContext};
use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use style_traits::cursor::CursorKind;
use values::{Auto, Either};
use values::generics::ui as generics;
use values::specified::Number;
use values::specified::color::Color;
use values::specified::url::SpecifiedImageUrl;
/// auto | <color>
pub type ColorOrAuto = Either<Color, Auto>;
/// A specified value for the `cursor` property.
pub type Cursor = generics::Cursor<CursorImage>;
/// A specified value for item of `image cursors`.
pub type CursorImage = generics::CursorImage<SpecifiedImageUrl, Number>;
impl Parse for Cursor {
/// cursor: [<url> [<number> <number>]?]# [auto | default | ...]
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let mut images = vec![];
loop {
match input.try(|input| CursorImage::parse(context, input)) {
Ok(image) => images.push(image),
Err(_) => break,
}
input.expect_comma()?;
}
Ok(Self {
images: images.into_boxed_slice(),
keyword: CursorKind::parse(context, input)?,
})
}
}
impl Parse for CursorKind {
fn parse<'i, 't>(
_context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let location = input.current_source_location();
let ident = input.expect_ident()?;
CursorKind::from_css_keyword(&ident)
.map_err(|_| location.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
}
impl Parse for CursorImage {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Ok(Self {
url: SpecifiedImageUrl::parse(context, input)?,
hotspot: match input.try(|input| Number::parse(context, input)) {<|fim▁hole|> }
}
/// Specified value of `-moz-force-broken-image-icon`
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
pub struct MozForceBrokenImageIcon(pub bool);
impl MozForceBrokenImageIcon {
/// Return initial value of -moz-force-broken-image-icon which is false.
#[inline]
pub fn false_value() -> MozForceBrokenImageIcon {
MozForceBrokenImageIcon(false)
}
}
impl Parse for MozForceBrokenImageIcon {
fn parse<'i, 't>(
_context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<MozForceBrokenImageIcon, ParseError<'i>> {
// We intentionally don't support calc values here.
match input.expect_integer()? {
0 => Ok(MozForceBrokenImageIcon(false)),
1 => Ok(MozForceBrokenImageIcon(true)),
_ => Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)),
}
}
}
impl ToCss for MozForceBrokenImageIcon {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
dest.write_str(if self.0 { "1" } else { "0" })
}
}
impl From<u8> for MozForceBrokenImageIcon {
fn from(bits: u8) -> MozForceBrokenImageIcon {
MozForceBrokenImageIcon(bits == 1)
}
}
impl From<MozForceBrokenImageIcon> for u8 {
fn from(v: MozForceBrokenImageIcon) -> u8 {
if v.0 {
1
} else {
0
}
}
}
/// A specified value for `scrollbar-color` property
pub type ScrollbarColor = generics::ScrollbarColor<Color>;
impl Parse for ScrollbarColor {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
if input.try(|i| i.expect_ident_matching("auto")).is_ok() {
return Ok(generics::ScrollbarColor::Auto);
}
Ok(generics::ScrollbarColor::Colors {
thumb: Color::parse(context, input)?,
track: Color::parse(context, input)?,
})
}
}<|fim▁end|> | Ok(number) => Some((number, Number::parse(context, input)?)),
Err(_) => None,
},
}) |
<|file_name|>strutil.rs<|end_file_name|><|fim▁begin|>// miscelaneous string utilities
// returns the string slice following the target, if any
pub fn after<'a>(s: &'a str, target: &str) -> Option<&'a str> {
if let Some(idx) = s.find(target) {
Some(&s[(idx+target.len())..])
} else {
None
}
}
// like after, but subsequently finds a word following...
pub fn word_after(txt: &str, target: &str) -> Option<String> {
if let Some(txt) = after(txt,target) {
// maybe skip some space, and end with whitespace or semicolon
let start = txt.find(|c:char| c.is_alphanumeric()).unwrap();
let end = txt.find(|c:char| c == ';' || c.is_whitespace()).unwrap();
Some((&txt[start..end]).to_string())
} else {
None
}
}
// next two items from an iterator, assuming that it has at least two items...
pub fn next_2<T, I: Iterator<Item=T>> (mut iter: I) -> (T,T) {
(iter.next().unwrap(), iter.next().unwrap())
}
// split into two at a delimiter
pub fn split(txt: &str, delim: char) -> (&str,&str) {<|fim▁hole|> (&txt[0..idx], &txt[idx+1..])
} else {
(txt,"")
}
}<|fim▁end|> | if let Some(idx) = txt.find(delim) { |
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" API v0 views. """
import logging
from django.http import Http404
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from lms.djangoapps.ccx.utils import prep_course_for_grading
from lms.djangoapps.courseware import courses
from lms.djangoapps.grades.api.serializers import GradingPolicySerializer
from lms.djangoapps.grades.new.course_grade import CourseGradeFactory
from openedx.core.lib.api.authentication import OAuth2AuthenticationAllowInactiveUser
from openedx.core.lib.api.view_utils import DeveloperErrorViewMixin
log = logging.getLogger(__name__)
class GradeViewMixin(DeveloperErrorViewMixin):
"""
Mixin class for Grades related views.
"""
authentication_classes = (
OAuth2AuthenticationAllowInactiveUser,
SessionAuthentication,
)
permission_classes = (IsAuthenticated,)
def _get_course(self, course_key_string, user, access_action):
"""
Returns the course for the given course_key_string after
verifying the requested access to the course by the given user.
"""
try:
course_key = CourseKey.from_string(course_key_string)
except InvalidKeyError:
return self.make_error_response(
status_code=status.HTTP_404_NOT_FOUND,
developer_message='The provided course key cannot be parsed.',
error_code='invalid_course_key'
)
try:
return courses.get_course_with_access(
user,
access_action,
course_key,
check_if_enrolled=True
)
except Http404:
log.info('Course with ID "%s" not found', course_key_string)
return self.make_error_response(
status_code=status.HTTP_404_NOT_FOUND,
developer_message='The user, the course or both do not exist.',
error_code='user_or_course_does_not_exist'
)
def perform_authentication(self, request):
"""
Ensures that the user is authenticated (e.g. not an AnonymousUser), unless DEBUG mode is enabled.
"""
super(GradeViewMixin, self).perform_authentication(request)
if request.user.is_anonymous():
raise AuthenticationFailed
class UserGradeView(GradeViewMixin, GenericAPIView):
"""
**Use Case**
* Get the current course grades for users in a course.
Currently, getting the grade for only an individual user is supported.
**Example Request**
GET /api/grades/v0/course_grade/{course_id}/users/?username={username}
**GET Parameters**
A GET request must include the following parameters.
* course_id: A string representation of a Course ID.
* username: A string representation of a user's username.
**GET Response Values**
If the request for information about the course grade
is successful, an HTTP 200 "OK" response is returned.
The HTTP 200 response has the following values.
* username: A string representation of a user's username passed in the request.
* course_id: A string representation of a Course ID.
* passed: Boolean representing whether the course has been
passed according the course's grading policy.
* percent: A float representing the overall grade for the course
* letter_grade: A letter grade as defined in grading_policy (e.g. 'A' 'B' 'C' for 6.002x) or None
**Example GET Response**
[{
"username": "bob",
"course_key": "edX/DemoX/Demo_Course",
"passed": false,
"percent": 0.03,
"letter_grade": None,
}]
"""
def get(self, request, course_id):
"""
Gets a course progress status.
Args:
request (Request): Django request object.
course_id (string): URI element specifying the course location.
Return:
A JSON serialized representation of the requesting user's current grade status.
"""
username = request.GET.get('username')
# only the student can access her own grade status info
if request.user.username != username:
log.info(
'User %s tried to access the grade for user %s.',
request.user.username,
username
)
return self.make_error_response(
status_code=status.HTTP_404_NOT_FOUND,<|fim▁hole|> developer_message='The user requested does not match the logged in user.',
error_code='user_mismatch'
)
course = self._get_course(course_id, request.user, 'load')
if isinstance(course, Response):
return course
prep_course_for_grading(course, request)
course_grade = CourseGradeFactory().create(request.user, course)
return Response([{
'username': username,
'course_key': course_id,
'passed': course_grade.passed,
'percent': course_grade.percent,
'letter_grade': course_grade.letter_grade,
}])
class CourseGradingPolicy(GradeViewMixin, ListAPIView):
"""
**Use Case**
Get the course grading policy.
**Example requests**:
GET /api/grades/v0/policy/{course_id}/
**Response Values**
* assignment_type: The type of the assignment, as configured by course
staff. For example, course staff might make the assignment types Homework,
Quiz, and Exam.
* count: The number of assignments of the type.
* dropped: Number of assignments of the type that are dropped.
* weight: The weight, or effect, of the assignment type on the learner's
final grade.
"""
allow_empty = False
def get(self, request, course_id, **kwargs):
course = self._get_course(course_id, request.user, 'staff')
if isinstance(course, Response):
return course
return Response(GradingPolicySerializer(course.raw_grader, many=True).data)<|fim▁end|> | |
<|file_name|>products.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import pgettext_lazy
from .base import Product
from .variants import (ProductVariant, PhysicalProduct, ColoredVariant,
StockedProduct)
class Bag(PhysicalProduct, Product, ColoredVariant):
class Meta:
app_label = 'product'
class Shirt(PhysicalProduct, Product, ColoredVariant):
class Meta:
app_label = 'product'
class BagVariant(ProductVariant, StockedProduct):
product = models.ForeignKey(Bag, related_name='variants')<|fim▁hole|> class Meta:
app_label = 'product'
@python_2_unicode_compatible
class ShirtVariant(ProductVariant, StockedProduct):
SIZE_CHOICES = (
('xs', pgettext_lazy('Variant size', 'XS')),
('s', pgettext_lazy('Variant size', 'S')),
('m', pgettext_lazy('Variant size', 'M')),
('l', pgettext_lazy('Variant size', 'L')),
('xl', pgettext_lazy('Variant size', 'XL')),
('xxl', pgettext_lazy('Variant size', 'XXL')))
product = models.ForeignKey(Shirt, related_name='variants')
size = models.CharField(
pgettext_lazy('Variant field', 'size'), choices=SIZE_CHOICES,
max_length=3)
class Meta:
app_label = 'product'
def __str__(self):
return '%s (%s)' % (self.product.name, self.size)<|fim▁end|> | |
<|file_name|>about_monkey_patching.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Related to AboutOpenClasses in the Ruby Koans
#
from runner.koan import *
class AboutMonkeyPatching(Koan):
class Dog:
def bark(self):
return "WOOF"
def test_as_defined_dogs_do_bark(self):
fido = self.Dog()
self.assertEqual('WOOF', fido.bark())
# ------------------------------------------------------------------
# Add a new method to an existing class.
def test_after_patching_dogs_can_both_wag_and_bark(self):
def wag(self): return "HAPPY"
self.Dog.wag = wag
fido = self.Dog()
self.assertEqual('HAPPY', fido.wag())
self.assertEqual('WOOF', fido.bark())
# ------------------------------------------------------------------
def test_most_built_in_classes_cannot_be_monkey_patched(self):
try:
int.is_even = lambda self: (self % 2) == 0
except Exception as ex:
err_msg = ex.args[0]
self.assertRegex(err_msg, "can't set attributes of built-in/extension type 'int'")
# ------------------------------------------------------------------
class MyInt(int): pass<|fim▁hole|>
self.assertEqual(False, self.MyInt(1).is_even())
self.assertEqual(True, self.MyInt(2).is_even())<|fim▁end|> |
def test_subclasses_of_built_in_classes_can_be_be_monkey_patched(self):
self.MyInt.is_even = lambda self: (self % 2) == 0 |
<|file_name|>StockResult.java<|end_file_name|><|fim▁begin|>package com.board.gd.domain.stock;
import lombok.Data;
import java.util.List;
import java.util.stream.Collectors;
/**<|fim▁hole|>public class StockResult {
private Long id;
private String name;
private String code;
public static StockResult getStockResult(Stock stock) {
StockResult stockResult = new StockResult();
stockResult.setId(stock.getId());
stockResult.setName(stock.getName());
stockResult.setCode(stock.getCode());
return stockResult;
}
public static List<StockResult> getStockResultList(List<Stock> stockList) {
return stockList.stream()
.map(stock -> getStockResult(stock))
.collect(Collectors.toList());
}
}<|fim▁end|> | * Created by gd.godong9 on 2017. 5. 19.
*/
@Data |
<|file_name|>utilities.py<|end_file_name|><|fim▁begin|># #
# Copyright 2012-2019 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (FWO) (http://www.fwo.be/en)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# https://github.com/easybuilders/easybuild
#
# EasyBuild 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 v2.
#
# EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>.
# #
"""
Module with various utility functions
:author: Kenneth Hoste (Ghent University)
"""
import datetime
import glob
import os
import re
import sys
from string import digits
from easybuild.base import fancylogger
from easybuild.tools.build_log import EasyBuildError, print_msg
from easybuild.tools.config import build_option
from easybuild.tools.py2vs3 import ascii_letters, string_type
_log = fancylogger.getLogger('tools.utilities')
INDENT_2SPACES = ' ' * 2
INDENT_4SPACES = ' ' * 4
def flatten(lst):
"""Flatten a list of lists."""
res = []
for x in lst:
res.extend(x)
return res
def quote_str(val, escape_newline=False, prefer_single_quotes=False, tcl=False):
"""
Obtain a new value to be used in string replacement context.
For non-string values, it just returns the exact same value.
For string values, it tries to escape the string in quotes, e.g.,
foo becomes 'foo', foo'bar becomes "foo'bar",
foo'bar"baz becomes \"\"\"foo'bar"baz\"\"\", etc.
:param escape_newline: wrap strings that include a newline in triple quotes
:param prefer_single_quotes: if possible use single quotes
:param tcl: Boolean for whether we are quoting for Tcl syntax
"""
if isinstance(val, string_type):
# forced triple double quotes
if ("'" in val and '"' in val) or (escape_newline and '\n' in val):
return '"""%s"""' % val
# escape double quote(s) used in strings
elif '"' in val:
if tcl:
return '"%s"' % val.replace('"', '\\"')
else:
return "'%s'" % val
# if single quotes are preferred, use single quotes;
# unless a space or a single quote are in the string
elif prefer_single_quotes and "'" not in val and ' ' not in val:
return "'%s'" % val
# fallback on double quotes (required in tcl syntax)
else:
return '"%s"' % val
else:
return val
def quote_py_str(val):
"""Version of quote_str specific for generating use in Python context (e.g., easyconfig parameters)."""<|fim▁hole|> return quote_str(val, escape_newline=True, prefer_single_quotes=True)
def shell_quote(token):
"""
Wrap provided token in single quotes (to escape space and characters with special meaning in a shell),
so it can be used in a shell command. This results in token that is not expanded/interpolated by the shell.
"""
# first, strip off double quotes that may wrap the entire value,
# we don't want to wrap single quotes around a double-quoted value
token = str(token).strip('"')
# escape any non-escaped single quotes, and wrap entire token in single quotes
return "'%s'" % re.sub(r"(?<!\\)'", r"\'", token)
def remove_unwanted_chars(inputstring):
"""Remove unwanted characters from the given string and return a copy
All non-letter and non-numeral characters are considered unwanted except for underscore ('_').
"""
return ''.join(c for c in inputstring if c in (ascii_letters + digits + '_'))
def import_available_modules(namespace):
"""
Import all available module in the specified namespace.
:param namespace: The namespace to import modules from.
"""
modules = []
for path in sys.path:
cand_modpath_glob = os.path.sep.join([path] + namespace.split('.') + ['*.py'])
# if sys.path entry being considered is the empty string
# (which corresponds to Python packages/modules in current working directory being considered),
# we need to strip off / from the start of the path
if path == '' and cand_modpath_glob.startswith(os.path.sep):
cand_modpath_glob = cand_modpath_glob.lstrip(os.path.sep)
for module in sorted(glob.glob(cand_modpath_glob)):
if not module.endswith('__init__.py'):
mod_name = module.split(os.path.sep)[-1].split('.')[0]
modpath = '.'.join([namespace, mod_name])
_log.debug("importing module %s", modpath)
try:
mod = __import__(modpath, globals(), locals(), [''])
except ImportError as err:
raise EasyBuildError("import_available_modules: Failed to import %s: %s", modpath, err)
if mod not in modules:
modules.append(mod)
return modules
def only_if_module_is_available(modnames, pkgname=None, url=None):
"""Decorator to guard functions/methods against missing required module with specified name."""
if pkgname and url is None:
url = 'https://pypi.python.org/pypi/%s' % pkgname
if isinstance(modnames, string_type):
modnames = (modnames,)
def wrap(orig):
"""Decorated function, raises ImportError if specified module is not available."""
try:
imported = None
for modname in modnames:
try:
__import__(modname)
imported = modname
break
except ImportError:
pass
if imported is None:
raise ImportError("None of the specified modules %s is available" % ', '.join(modnames))
else:
return orig
except ImportError as err:
# need to pass down 'err' via named argument to ensure it's in scope when using Python 3.x
def error(err=err, *args, **kwargs):
msg = "%s; required module '%s' is not available" % (err, modname)
if pkgname:
msg += " (provided by Python package %s, available from %s)" % (pkgname, url)
elif url:
msg += " (available from %s)" % url
raise EasyBuildError("ImportError: %s", msg)
return error
return wrap
def trace_msg(message, silent=False):
"""Print trace message."""
if build_option('trace'):
print_msg(' >> ' + message, prefix=False)
def nub(list_):
"""Returns the unique items of a list of hashables, while preserving order of
the original list, i.e. the first unique element encoutered is
retained.
Code is taken from
http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order
Supposedly, this is one of the fastest ways to determine the
unique elements of a list.
@type list_: a list :-)
:return: a new list with each element from `list` appearing only once (cfr. Michelle Dubois).
"""
seen = set()
seen_add = seen.add
return [x for x in list_ if x not in seen and not seen_add(x)]
def get_class_for(modulepath, class_name):
"""
Get class for a given Python class name and Python module path.
:param modulepath: Python module path (e.g., 'easybuild.base.generaloption')
:param class_name: Python class name (e.g., 'GeneralOption')
"""
# try to import specified module path, reraise ImportError if it occurs
try:
module = __import__(modulepath, globals(), locals(), [''])
except ImportError as err:
raise ImportError(err)
# try to import specified class name from specified module path, throw ImportError if this fails
try:
klass = getattr(module, class_name)
except AttributeError as err:
raise ImportError("Failed to import %s from %s: %s" % (class_name, modulepath, err))
return klass
def get_subclasses_dict(klass, include_base_class=False):
"""Get dict with subclasses per classes, recursively from the specified base class."""
res = {}
subclasses = klass.__subclasses__()
if include_base_class:
res.update({klass: subclasses})
for subclass in subclasses:
# always include base class for recursive call
res.update(get_subclasses_dict(subclass, include_base_class=True))
return res
def get_subclasses(klass, include_base_class=False):
"""Get list of all subclasses, recursively from the specified base class."""
return get_subclasses_dict(klass, include_base_class=include_base_class).keys()
def mk_rst_table(titles, columns):
"""
Returns an rst table with given titles and columns (a nested list of string columns for each column)
"""
title_cnt, col_cnt = len(titles), len(columns)
if title_cnt != col_cnt:
msg = "Number of titles/columns should be equal, found %d titles and %d columns" % (title_cnt, col_cnt)
raise ValueError(msg)
table = []
tmpl = []
line = []
# figure out column widths
for i, title in enumerate(titles):
width = max(map(len, columns[i] + [title]))
# make line template
tmpl.append('{%s:{c}<%s}' % (i, width))
line = [''] * col_cnt
line_tmpl = INDENT_4SPACES.join(tmpl)
table_line = line_tmpl.format(*line, c='=')
table.append(table_line)
table.append(line_tmpl.format(*titles, c=' '))
table.append(table_line)
for row in map(list, zip(*columns)):
table.append(line_tmpl.format(*row, c=' '))
table.extend([table_line, ''])
return table
def time2str(delta):
"""Return string representing provided datetime.timedelta value in human-readable form."""
res = None
if not isinstance(delta, datetime.timedelta):
raise EasyBuildError("Incorrect value type provided to time2str, should be datetime.timedelta: %s", type(delta))
delta_secs = delta.days * 3600 * 24 + delta.seconds + delta.microseconds / 10**6
if delta_secs < 60:
res = '%d sec' % int(delta_secs)
elif delta_secs < 3600:
mins = int(delta_secs / 60)
secs = int(delta_secs - (mins * 60))
res = '%d min %d sec' % (mins, secs)
else:
hours = int(delta_secs / 3600)
mins = int((delta_secs - hours * 3600) / 60)
secs = int(delta_secs - (hours * 3600) - (mins * 60))
hours_str = 'hours' if hours > 1 else 'hour'
res = '%d %s %d min %d sec' % (hours, hours_str, mins, secs)
return res<|fim▁end|> | |
<|file_name|>tail.rs<|end_file_name|><|fim▁begin|>/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use anyhow::{Context, Error};
use bookmarks::{BookmarkUpdateLog, BookmarkUpdateLogEntry, Freshness};
use cloned::cloned;
use context::CoreContext;
use futures::{
future::{self, FutureExt},
stream::{self, StreamExt},
TryStreamExt,
};
use mononoke_types::RepositoryId;
use scuba_ext::MononokeScubaSampleBuilder;
use slog::debug;
use std::sync::Arc;
use std::time::Duration;
use crate::reporting::log_noop_iteration_to_scuba;
const SLEEP_SECS: u64 = 10;
const SIGNLE_DB_QUERY_ENTRIES_LIMIT: u64 = 10;
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct QueueSize(pub usize);
/// Adds remaining number of changesets to sync to each entry
/// The idea is to indicate the number of changesets, left to sync
/// *after* a given changeset has been synced, therefore `n-i-1`
/// For example, `[c1, c2, c3]` will turn into `[(c1, 2), (c2, 1), (c3, 0)]`
fn add_queue_sizes<T>(
items: Vec<T>,
initial_queue_size: usize,
) -> impl Iterator<Item = (T, QueueSize)> {
items
.into_iter()
.enumerate()
.map(move |(i, item)| (item, QueueSize(initial_queue_size - i - 1)))
}
/// Run a queue size query, consume the produced `Result` and turn it
/// into an `Option`, suitable for `unfold`
async fn query_queue_size(
ctx: CoreContext,
bookmark_update_log: Arc<dyn BookmarkUpdateLog>,
current_id: u64,
) -> Result<u64, Error> {
bookmark_update_log
.count_further_bookmark_log_entries(ctx.clone(), current_id, None)
.await
.map(|queue_size| {
debug!(ctx.logger(), "queue size query returned: {}", queue_size);
queue_size
})
}
/// Produce an infinite stream of `Result` from a fallible item factory
/// Two differences with the normal `unfold`:
/// - this one does not expect the item factory (`f`) to return an `Option`,
/// so there's no way to terminate a stream from within `f`
/// - this one expects `f` to return a `Result`, which is threaded downstream
/// and allows the consumer of the stream to terminate it on `Err`
/// The main motivation for this is to be able to use `?` in the item factory
fn unfold_forever<T, F, Fut, Item>(
init: T,
mut f: F,
) -> impl stream::Stream<Item = Result<Item, Error>>
where
T: Copy,
F: FnMut(T) -> Fut,
Fut: future::Future<Output = Result<(Item, T), Error>>,
{
stream::unfold(init, move |iteration_value| {
f(iteration_value).then(move |result| {
match result {
Ok((item, next_it_val)) => future::ready(Some((Ok(item), next_it_val))),
Err(e) => future::ready(Some((Err(e), iteration_value))),
}
})
})
}
pub(crate) fn tail_entries(
ctx: CoreContext,
start_id: u64,
repo_id: RepositoryId,
bookmark_update_log: Arc<dyn BookmarkUpdateLog>,
scuba_sample: MononokeScubaSampleBuilder,
) -> impl stream::Stream<Item = Result<(BookmarkUpdateLogEntry, QueueSize), Error>> {
unfold_forever((0, start_id), move |(iteration, current_id)| {
cloned!(ctx, bookmark_update_log, scuba_sample);
async move {
let entries: Vec<Result<_, Error>> = bookmark_update_log
.read_next_bookmark_log_entries(
ctx.clone(),
current_id,
SIGNLE_DB_QUERY_ENTRIES_LIMIT,
Freshness::MaybeStale,
)
.collect()<|fim▁hole|> let entries: Result<Vec<_>, Error> = entries.into_iter().collect();
let entries: Vec<_> = entries.context("While querying bookmarks_update_log")?;
let queue_size =
query_queue_size(ctx.clone(), bookmark_update_log.clone(), current_id).await?;
match entries.last().map(|last_item_ref| last_item_ref.id) {
Some(last_entry_id) => {
debug!(
ctx.logger(),
"tail_entries generating, iteration {}", iteration
);
let entries_with_queue_size: std::iter::Map<_, _> =
add_queue_sizes(entries, queue_size as usize).map(Ok);
Ok((
stream::iter(entries_with_queue_size).boxed(),
(iteration + 1, last_entry_id as u64),
))
}
None => {
debug!(
ctx.logger(),
"tail_entries: no more entries during iteration {}. Sleeping.", iteration
);
log_noop_iteration_to_scuba(scuba_sample, repo_id);
tokio::time::sleep(Duration::new(SLEEP_SECS, 0)).await;
Ok((stream::empty().boxed(), (iteration + 1, current_id)))
}
}
}
})
.try_flatten()
}<|fim▁end|> | .await;
|
<|file_name|>app.js<|end_file_name|><|fim▁begin|>/*
This file is generated and updated by Sencha Cmd. You can edit this file as
needed for your application, but these edits will have to be merged by
Sencha Cmd when it performs code generation tasks such as generating new
models, controllers or views and when running "sencha app upgrade".
Ideally changes to this file would be limited and most work would be done
in other places (such as Controllers). If Sencha Cmd cannot merge your
changes and its generated code, it will produce a "merge conflict" that you
will need to resolve manually.
*/
Ext.application({
name: 'SenchaBDD',
requires: [
'Ext.MessageBox'
],<|fim▁hole|> controllers: [
'Login',
'Main'
],
views: [
'ColorsList',
'Login',
'Main',
],
stores: [
'Colors'
],
icon: {
'57': 'resources/icons/Icon.png',
'72': 'resources/icons/Icon~ipad.png',
'114': 'resources/icons/[email protected]',
'144': 'resources/icons/[email protected]'
},
isIconPrecomposed: true,
startupImage: {
'320x460': 'resources/startup/320x460.jpg',
'640x920': 'resources/startup/640x920.png',
'768x1004': 'resources/startup/768x1004.png',
'748x1024': 'resources/startup/748x1024.png',
'1536x2008': 'resources/startup/1536x2008.png',
'1496x2048': 'resources/startup/1496x2048.png'
},
launch: function() {
// Destroy the #appLoadingIndicator element
Ext.fly('appLoadingIndicator').destroy();
// Initialize the login view
Ext.Viewport.add(Ext.create('SenchaBDD.view.Login'));
},
onUpdated: function() {
Ext.Msg.confirm(
"Application Update",
"This application has just successfully been updated to the latest version. Reload now?",
function(buttonId) {
if (buttonId === 'yes') {
window.location.reload();
}
}
);
}
});<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .engine import BloggingEngine
from .processor import PostProcessor<|fim▁hole|>
"""
Flask-Blogging is a Flask extension to add blog support to your
web application. This extension uses Markdown to store and then
render the webpage.
Author: Gouthaman Balaraman
Date: June 1, 2015
"""
__author__ = 'Gouthaman Balaraman'
__version__ = '0.4.2'<|fim▁end|> | from .sqlastorage import SQLAStorage
from .storage import Storage
|
<|file_name|>params.py<|end_file_name|><|fim▁begin|># coding: utf-8
"""
DLRN API
DLRN API client
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
class Params(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, max_age=None, success=None, job_id=None,
sequential_mode=None, previous_job_id=None, component=None):
"""Params - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'max_age': 'int',
'success': 'bool',<|fim▁hole|> 'job_id': 'str',
'sequential_mode': 'bool',
'previous_job_id': 'str',
'component': 'str'
}
self.attribute_map = {
'max_age': 'max_age',
'success': 'success',
'job_id': 'job_id',
'sequential_mode': 'sequential_mode',
'previous_job_id': 'previous_job_id',
'component': 'component'
}
self._max_age = max_age
self._success = success
self._job_id = job_id
self._sequential_mode = sequential_mode
self._previous_job_id = previous_job_id
self._component = component
@property
def max_age(self):
"""Gets the max_age of this Params.
Maximum age (in hours) for the repo to be considered.
Any repo tested or being tested after \"now - max_age\" will be taken
into account. If set to 0, all repos will be considered.
:return: The max_age of this Params.
:rtype: int
"""
return self._max_age
@max_age.setter
def max_age(self, max_age):
"""Sets the max_age of this Params.
Maximum age (in hours) for the repo to be considered.
Any repo tested or being tested after \"now - max_age\" will be taken
into account. If set to 0, all repos will be considered.
:param max_age: The max_age of this Params.
:type: int
"""
if max_age is None:
raise ValueError("Invalid value for `max_age`, must not be `None`")
if max_age is not None and max_age < 0:
raise ValueError("Invalid value for `max_age`, must be a value"
" greater than or equal to `0`")
self._max_age = max_age
@property
def success(self):
"""Gets the success of this Params.
If set to a value, find repos with a successful/unsuccessful vote
(as specified). If not set, any tested repo will be considered.
:return: The success of this Params.
:rtype: bool
"""
return self._success
@success.setter
def success(self, success):
"""Sets the success of this Params.
If set to a value, find repos with a successful/unsuccessful vote
(as specified). If not set, any tested repo will be considered.
:param success: The success of this Params.
:type: bool
"""
self._success = success
@property
def job_id(self):
"""Gets the job_id of this Params.
Name of the CI that sent the vote. If not set, no filter will be set
on CI.
:return: The job_id of this Params.
:rtype: str
"""
return self._job_id
@job_id.setter
def job_id(self, job_id):
"""Sets the job_id of this Params.
Name of the CI that sent the vote. If not set, no filter will be set
on CI.
:param job_id: The job_id of this Params.
:type: str
"""
self._job_id = job_id
@property
def sequential_mode(self):
"""Gets the sequential_mode of this Params.
Use the sequential mode algorithm. In this case, return the last tested
repo within that timeframe for the CI job described by previous_job_id.
Defaults to false.
:return: The sequential_mode of this Params.
:rtype: bool
"""
return self._sequential_mode
@sequential_mode.setter
def sequential_mode(self, sequential_mode):
"""Sets the sequential_mode of this Params.
Use the sequential mode algorithm. In this case, return the last tested
repo within that timeframe for the CI job described by previous_job_id.
Defaults to false.
:param sequential_mode: The sequential_mode of this Params.
:type: bool
"""
self._sequential_mode = sequential_mode
@property
def previous_job_id(self):
"""Gets the previous_job_id of this Params.
If sequential_mode is set to true, look for jobs tested by the CI
identified by previous_job_id.
:return: The previous_job_id of this Params.
:rtype: str
"""
return self._previous_job_id
@previous_job_id.setter
def previous_job_id(self, previous_job_id):
"""Sets the previous_job_id of this Params.
If sequential_mode is set to true, look for jobs tested by the CI
identified by previous_job_id.
:param previous_job_id: The previous_job_id of this Params.
:type: str
"""
self._previous_job_id = previous_job_id
@property
def component(self):
"""Gets the component of this Params.
additional notes
:return: The component of this Params.
:rtype: str
"""
return self._component
@component.setter
def component(self, component):
"""Sets the component of this Params.
additional notes
:param component: The component of this Params.
:type: str
"""
self._component = component
def to_dict(self):
"""Returns the model properties as a dict """
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model """
return pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint` """
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal """
if not isinstance(other, Params):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal """
return not self == other<|fim▁end|> | |
<|file_name|>TEnum.java<|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.
*/<|fim▁hole|>
public interface TEnum {
public int getValue();
}<|fim▁end|> |
package libthrift091; |
<|file_name|>down_pic_thread.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-09-01 22:26:01
# @Author : Your Name ([email protected])
# @Link : http://example.org
# @Version : $Id$
import os
import threading
import requests
import lxml<|fim▁hole|>from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
pic_path = 'pic/' # 保存文件路径
URL = 'http://www.nanrenwo.net/z/tupian/hashiqitupian/'
URL1 = 'http://www.nanrenwo.net/'
class Worker(threading.Thread):
def __init__(self, url, img, filename):
super(Worker, self).__init__()
self.url = url
self.img = img
self.filename = filename
def run(self):
try:
u = self.url + self.img
r = requests.get(u, stream=True)
with open(self.filename, 'wb') as fd:
for chunk in r.iter_content(4096):
fd.write(chunk)
except Exception, e:
raise
def get_imgs(url):
t = 1
r = requests.get(url, stream=True)
soup = BeautifulSoup(r.text, 'lxml')
myimg = [img.get('src') for img in soup.find(id='brand-waterfall').find_all('img')] # 查询id下所有img元素
print 'myimg:', myimg
for img in myimg:
pic_name = pic_path + str(t) + '.jpg'
# img_src = img.get('src')
print 'img: ', img
# self.download_pic(URL1,img,pic_name) #request Url,img src,picture name
w = Worker(URL1, img, pic_name)
w.start()
t += 1
get_imgs(URL)<|fim▁end|> | from threading import Thread |
<|file_name|>ServicesPanel.spec.tsx<|end_file_name|><|fim▁begin|>/// <reference types='jest' />
import * as React from 'react';
import ServicesPanel from '../ServicesPanel';
import Cases from './ServicesPanel.cases';
import { shallow, mount, render } from 'enzyme';
describe('ServicesPanel', () => {
let servicesPanel:any;
beforeEach(()=>{
servicesPanel = mount(<ServicesPanel {...Cases['Default']}/>)
});
it('should render correctly', () => {
expect(servicesPanel.find('Dropdown').length).toEqual(1);
expect(servicesPanel.find('ServicesList').length).toEqual(1);
expect(servicesPanel.find('Input').length).toEqual(1);
});
it('should render the roles dropdown with the services prop roles as items', () => {
// let roles: string[] = [];
// servicesPanel.props().services.forEach((service:any) => {
// if (roles.indexOf(service.roleId) === -1) {
// roles.push(service.roleId);
// }
// });
// let dropDownItemsTexts = servicesPanel.find('DropdownItem .role').map((node:any) => { return node.text()});
// expect(JSON.stringify(roles.sort())).toEqual(JSON.stringify(dropDownItemsTexts.sort()));
});
it('should render only services with the selected role', () => {
// let activeRole = 'Mollis.';
// servicesPanel.setState({
// activeRole: activeRole
// });
// let allHaveActiveRole = servicesPanel.find('ServiceCard').map((node:any) => {
// return node.props().service.roles.indexOf(activeRole) > -1;
// }).every((value:boolean) => {
// return value === true;
// });
// expect(allHaveActiveRole).toEqual(true);
});
it('should render only services with the selected role when a search value is entered by user', () => {
// let activeRole = 'Mollis.';
// servicesPanel.setState({
// activeRole: activeRole,
// searhValue: 'test'
// });
// let allHaveActiveRole = servicesPanel.find('ServiceCard').map((node:any) => {
// return node.props().service.roles.indexOf(activeRole) > -1;
// }).every((value:boolean) => {
// return value === true;
// });
// expect(allHaveActiveRole).toEqual(true);
});
it('should render the Not found services message when search is performed an it returns no services', () => {
// servicesPanel.setState({
// searchValue:'mycrazytestsearchcriteria',
// activeRole:'Mollis.'
// });
// expect(servicesPanel.find('h3').first().text()).toEqual('No services found');
});
it('should render the right search indicator in search bar depending on searching state', () => {
// servicesPanel.setState({loadingSearch:false, searchValue:''});
// expect(servicesPanel.find('.rowHead').first().find('i').length).toEqual(0);<|fim▁hole|>
// servicesPanel.setState({loadingSearch:true, searchValue:'mysearchcriteria'});
// expect(servicesPanel.find('.rowHead').first().find('i').length).toEqual(1);
// expect(servicesPanel.find('.rowHead').first().find('i').html()).toContain('fa fa-pulse fa-spinner');
});
it(`should set the right searching state after a second
depending on the searchOnChangeMethod actioned by user input`, (done) => {
done();
// servicesPanel.instance().searchOnChange({target:{value:'mysearchcriteria'}, persist: () => {}});
// expect(servicesPanel.state().searchValue).toEqual('mysearchcriteria');
// expect(servicesPanel.state().loadingSearch).toEqual(true);
// try {
// setTimeout(()=>{
// expect(servicesPanel.state().loadingSearch).toEqual(false);
// done();
// }, 2000);
// }catch (e){
// done.fail(e);
// }
});
});<|fim▁end|> |
// servicesPanel.setState({loadingSearch:false, searchValue:'mysearchcriteria'});
// expect(servicesPanel.find('.rowHead').first().find('i').length).toEqual(1);
// expect(servicesPanel.find('.rowHead').first().find('i').html()).toContain('fa fa-times fa-lg'); |
<|file_name|>index.ts<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | export * from './tabs-demo.component'; |
<|file_name|>simple_tomo_test.py<|end_file_name|><|fim▁begin|># Copyright 2014 Diamond Light Source Ltd.
#
# 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.
"""
.. module:: tomo_recon
:platform: Unix
:synopsis: runner for tests using the MPI framework
.. moduleauthor:: Mark Basham <[email protected]>
"""<|fim▁hole|>import tempfile
from savu.test import test_utils as tu
from savu.test.plugin_runner_test import run_protected_plugin_runner
class SimpleTomoTest(unittest.TestCase):
def test_process(self):
options = {
"transport": "hdf5",
"process_names": "CPU0",
"data_file": tu.get_test_data_path('24737.nxs'),
"process_file": tu.get_test_data_path('simple_recon_test_process.nxs'),
"out_path": tempfile.mkdtemp()
}
run_protected_plugin_runner(options)
if __name__ == "__main__":
unittest.main()<|fim▁end|> | import unittest |
<|file_name|>encoder.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.
use cstore;
use index::Index;
use schema::*;
use rustc::middle::cstore::{InlinedItemRef, LinkMeta};
use rustc::middle::cstore::{LinkagePreference, NativeLibraryKind};
use rustc::hir::def;
use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId};
use rustc::middle::dependency_format::Linkage;
use rustc::middle::lang_items;
use rustc::mir;
use rustc::traits::specialization_graph;
use rustc::ty::{self, Ty, TyCtxt};
use rustc::mir::mir_map::MirMap;
use rustc::session::config::{self, CrateTypeProcMacro};
use rustc::util::nodemap::{FnvHashMap, NodeSet};
use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
use std::hash::Hash;
use std::intrinsics;
use std::io::prelude::*;
use std::io::Cursor;
use std::rc::Rc;
use std::u32;
use syntax::ast::{self, CRATE_NODE_ID};
use syntax::attr;
use syntax;
use syntax_pos;
use rustc::hir::{self, PatKind};
use rustc::hir::intravisit::Visitor;
use rustc::hir::intravisit;
use super::index_builder::{FromId, IndexBuilder, Untracked};
pub struct EncodeContext<'a, 'tcx: 'a> {
opaque: opaque::Encoder<'a>,
pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
reexports: &'a def::ExportMap,
link_meta: &'a LinkMeta,
cstore: &'a cstore::CStore,
reachable: &'a NodeSet,
mir_map: &'a MirMap<'tcx>,
lazy_state: LazyState,
type_shorthands: FnvHashMap<Ty<'tcx>, usize>,
predicate_shorthands: FnvHashMap<ty::Predicate<'tcx>, usize>,
}
macro_rules! encoder_methods {
($($name:ident($ty:ty);)*) => {
$(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
self.opaque.$name(value)
})*
}
}
impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
type Error = <opaque::Encoder<'a> as Encoder>::Error;
fn emit_nil(&mut self) -> Result<(), Self::Error> {
Ok(())
}
encoder_methods! {
emit_usize(usize);
emit_u64(u64);
emit_u32(u32);
emit_u16(u16);
emit_u8(u8);
emit_isize(isize);
emit_i64(i64);
emit_i32(i32);
emit_i16(i16);
emit_i8(i8);
emit_bool(bool);
emit_f64(f64);
emit_f32(f32);
emit_char(char);
emit_str(&str);
}
}
impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'a, 'tcx> {
fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
}
}
impl<'a, 'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'a, 'tcx> {
fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
self.emit_usize(seq.len)?;
if seq.len == 0 {
return Ok(());
}
self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
}
}
impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
self.encode_with_shorthand(ty, &ty.sty, |ecx| &mut ecx.type_shorthands)
}
}
impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
fn specialized_encode(&mut self, predicates: &ty::GenericPredicates<'tcx>)
-> Result<(), Self::Error> {
predicates.parent.encode(self)?;
predicates.predicates.len().encode(self)?;
for predicate in &predicates.predicates {
self.encode_with_shorthand(predicate, predicate, |ecx| &mut ecx.predicate_shorthands)?
}
Ok(())
}
}
impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
pub fn position(&self) -> usize {
self.opaque.position()
}
fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
assert_eq!(self.lazy_state, LazyState::NoNode);
let pos = self.position();
self.lazy_state = LazyState::NodeStart(pos);
let r = f(self, pos);
self.lazy_state = LazyState::NoNode;
r
}
fn emit_lazy_distance(&mut self, position: usize, min_size: usize)
-> Result<(), <Self as Encoder>::Error> {
let min_end = position + min_size;
let distance = match self.lazy_state {
LazyState::NoNode => {
bug!("emit_lazy_distance: outside of a metadata node")
}
LazyState::NodeStart(start) => {
assert!(min_end <= start);
start - min_end
}
LazyState::Previous(last_min_end) => {
assert!(last_min_end <= position);
position - last_min_end
}
};
self.lazy_state = LazyState::Previous(min_end);
self.emit_usize(distance)
}
pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
self.emit_node(|ecx, pos| {
value.encode(ecx).unwrap();
assert!(pos + Lazy::<T>::min_size() <= ecx.position());
Lazy::with_position(pos)
})
}
fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
where I: IntoIterator<Item=T>, T: Encodable {
self.emit_node(|ecx, pos| {
let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
LazySeq::with_position_and_length(pos, len)
})
}
fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
where I: IntoIterator<Item=&'b T>, T: 'b + Encodable {
self.emit_node(|ecx, pos| {
let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
LazySeq::with_position_and_length(pos, len)
})
}
/// Encode the given value or a previously cached shorthand.
fn encode_with_shorthand<T, U, M>(&mut self, value: &T, variant: &U, map: M)
-> Result<(), <Self as Encoder>::Error>
where M: for<'b> Fn(&'b mut Self) -> &'b mut FnvHashMap<T, usize>,
T: Clone + Eq + Hash,
U: Encodable {
let existing_shorthand = map(self).get(value).cloned();
if let Some(shorthand) = existing_shorthand {
return self.emit_usize(shorthand);
}
let start = self.position();
variant.encode(self)?;
let len = self.position() - start;
// The shorthand encoding uses the same usize as the
// discriminant, with an offset so they can't conflict.
let discriminant = unsafe {
intrinsics::discriminant_value(variant)
};
assert!(discriminant < SHORTHAND_OFFSET as u64);
let shorthand = start + SHORTHAND_OFFSET;
// Get the number of bits that leb128 could fit
// in the same space as the fully encoded type.
let leb128_bits = len * 7;
// Check that the shorthand is a not longer than the
// full encoding itself, i.e. it's an obvious win.
if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
map(self).insert(value.clone(), shorthand);
}
Ok(())
}
/// For every DefId that we create a metadata item for, we include a
/// serialized copy of its DefKey, which allows us to recreate a path.
fn encode_def_key(&mut self, def_id: DefId) -> Lazy<hir::map::DefKey> {
let tcx = self.tcx;
self.lazy(&tcx.map.def_key(def_id))
}
fn encode_item_variances(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
let tcx = self.tcx;
self.lazy_seq(tcx.item_variances(def_id).iter().cloned())
}
fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
let tcx = self.tcx;
self.lazy(&tcx.lookup_item_type(def_id).ty)
}
/// Encode data for the given variant of the given ADT. The
/// index of the variant is untracked: this is ok because we
/// will have to lookup the adt-def by its id, and that gives us
/// the right to access any information in the adt-def (including,
/// e.g., the length of the various vectors).
fn encode_enum_variant_info(&mut self,
(enum_did, Untracked(index)):
(DefId, Untracked<usize>)) -> Entry<'tcx> {
let tcx = self.tcx;
let def = tcx.lookup_adt_def(enum_did);
let variant = &def.variants[index];
let def_id = variant.did;
let data = VariantData {
ctor_kind: variant.ctor_kind,
disr: variant.disr_val.to_u64_unchecked(),
struct_ctor: None
};
let enum_id = tcx.map.as_local_node_id(enum_did).unwrap();
let enum_vis = &tcx.map.expect_item(enum_id).vis;
Entry {
kind: EntryKind::Variant(self.lazy(&data)),
visibility: enum_vis.simplify(),
def_key: self.encode_def_key(def_id),
attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
children: self.lazy_seq(variant.fields.iter().map(|f| {
assert!(f.did.is_local());
f.did.index
})),
stability: self.encode_stability(def_id),
deprecation: self.encode_deprecation(def_id),
ty: Some(self.encode_item_type(def_id)),
inherent_impls: LazySeq::empty(),
variances: LazySeq::empty(),
generics: Some(self.encode_generics(def_id)),
predicates: Some(self.encode_predicates(def_id)),
ast: None,
mir: None
}
}
fn encode_info_for_mod(&mut self,
FromId(id, (md, attrs, vis)):
FromId<(&hir::Mod, &[ast::Attribute], &hir::Visibility)>)
-> Entry<'tcx> {
let tcx = self.tcx;
let def_id = tcx.map.local_def_id(id);
let data = ModData {
reexports: match self.reexports.get(&id) {
Some(exports) if *vis == hir::Public => {
self.lazy_seq_ref(exports)
}
_ => LazySeq::empty()
}
};
Entry {
kind: EntryKind::Mod(self.lazy(&data)),
visibility: vis.simplify(),
def_key: self.encode_def_key(def_id),
attributes: self.encode_attributes(attrs),
children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
tcx.map.local_def_id(item_id.id).index
})),
stability: self.encode_stability(def_id),
deprecation: self.encode_deprecation(def_id),
ty: None,
inherent_impls: LazySeq::empty(),
variances: LazySeq::empty(),
generics: None,
predicates: None,
ast: None,
mir: None
}
}
}
trait Visibility {
fn simplify(&self) -> ty::Visibility;
}
impl Visibility for hir::Visibility {
fn simplify(&self) -> ty::Visibility {
if *self == hir::Public {
ty::Visibility::Public
} else {
ty::Visibility::PrivateExternal
}
}
}
impl Visibility for ty::Visibility {
fn simplify(&self) -> ty::Visibility {
if *self == ty::Visibility::Public {
ty::Visibility::Public
} else {
ty::Visibility::PrivateExternal
}
}
}
impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
fn encode_fields(&mut self,
adt_def_id: DefId) {
let def = self.tcx.lookup_adt_def(adt_def_id);
for (variant_index, variant) in def.variants.iter().enumerate() {
for (field_index, field) in variant.fields.iter().enumerate() {
self.record(field.did,
EncodeContext::encode_field,
(adt_def_id, Untracked((variant_index, field_index))));
}
}
}
}
impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
/// Encode data for the given field of the given variant of the
/// given ADT. The indices of the variant/field are untracked:
/// this is ok because we will have to lookup the adt-def by its
/// id, and that gives us the right to access any information in
/// the adt-def (including, e.g., the length of the various
/// vectors).
fn encode_field(&mut self,
(adt_def_id, Untracked((variant_index, field_index))):
(DefId, Untracked<(usize, usize)>)) -> Entry<'tcx> {
let tcx = self.tcx;
let variant = &tcx.lookup_adt_def(adt_def_id).variants[variant_index];
let field = &variant.fields[field_index];
let def_id = field.did;
let variant_id = tcx.map.as_local_node_id(variant.did).unwrap();
let variant_data = tcx.map.expect_variant_data(variant_id);
Entry {
kind: EntryKind::Field,
visibility: field.vis.simplify(),
def_key: self.encode_def_key(def_id),
attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
children: LazySeq::empty(),
stability: self.encode_stability(def_id),
deprecation: self.encode_deprecation(def_id),
ty: Some(self.encode_item_type(def_id)),
inherent_impls: LazySeq::empty(),
variances: LazySeq::empty(),
generics: Some(self.encode_generics(def_id)),
predicates: Some(self.encode_predicates(def_id)),
ast: None,
mir: None
}
}
fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId))
-> Entry<'tcx> {
let tcx = self.tcx;
let variant = tcx.lookup_adt_def(adt_def_id).struct_variant();
let data = VariantData {
ctor_kind: variant.ctor_kind,
disr: variant.disr_val.to_u64_unchecked(),
struct_ctor: Some(def_id.index)
};
let struct_id = tcx.map.as_local_node_id(adt_def_id).unwrap();
let struct_vis = &tcx.map.expect_item(struct_id).vis;
Entry {
kind: EntryKind::Struct(self.lazy(&data)),
visibility: struct_vis.simplify(),
def_key: self.encode_def_key(def_id),
attributes: LazySeq::empty(),
children: LazySeq::empty(),
stability: self.encode_stability(def_id),
deprecation: self.encode_deprecation(def_id),
ty: Some(self.encode_item_type(def_id)),
inherent_impls: LazySeq::empty(),
variances: LazySeq::empty(),
generics: Some(self.encode_generics(def_id)),
predicates: Some(self.encode_predicates(def_id)),
ast: None,
mir: None
}
}
fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics<'tcx>> {
let tcx = self.tcx;
self.lazy(tcx.lookup_generics(def_id))
}
fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
let tcx = self.tcx;
self.lazy(&tcx.lookup_predicates(def_id))
}
fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
let tcx = self.tcx;
let node_id = tcx.map.as_local_node_id(def_id).unwrap();
let ast_item = tcx.map.expect_trait_item(node_id);
let trait_item = tcx.impl_or_trait_item(def_id);
let container = |has_body| if has_body {
AssociatedContainer::TraitWithDefault
} else {
AssociatedContainer::TraitRequired
};
let kind = match trait_item {
ty::ConstTraitItem(ref associated_const) => {
EntryKind::AssociatedConst(container(associated_const.has_value))
}
ty::MethodTraitItem(ref method_ty) => {
let fn_data = if let hir::MethodTraitItem(ref sig, _) = ast_item.node {
FnData {
constness: hir::Constness::NotConst,
arg_names: self.encode_fn_arg_names(&sig.decl)
}
} else {
bug!()
};
let data = MethodData {
fn_data: fn_data,
container: container(method_ty.has_body),
explicit_self: self.lazy(&method_ty.explicit_self)
};
EntryKind::Method(self.lazy(&data))
}
ty::TypeTraitItem(_) => {
EntryKind::AssociatedType(container(false))
}
};
Entry {
kind: kind,
visibility: trait_item.vis().simplify(),
def_key: self.encode_def_key(def_id),
attributes: self.encode_attributes(&ast_item.attrs),
children: LazySeq::empty(),
stability: self.encode_stability(def_id),
deprecation: self.encode_deprecation(def_id),
ty: match trait_item {
ty::ConstTraitItem(_) |
ty::MethodTraitItem(_) => {
Some(self.encode_item_type(def_id))
}
ty::TypeTraitItem(ref associated_type) => {
associated_type.ty.map(|ty| self.lazy(&ty))
}
},
inherent_impls: LazySeq::empty(),
variances: LazySeq::empty(),
generics: Some(self.encode_generics(def_id)),
predicates: Some(self.encode_predicates(def_id)),
ast: if let ty::ConstTraitItem(_) = trait_item {
let trait_def_id = trait_item.container().id();
Some(self.encode_inlined_item(InlinedItemRef::TraitItem(trait_def_id, ast_item)))
} else {
None
},
mir: self.encode_mir(def_id)
}
}
fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
let node_id = self.tcx.map.as_local_node_id(def_id).unwrap();
let ast_item = self.tcx.map.expect_impl_item(node_id);
let impl_item = self.tcx.impl_or_trait_item(def_id);
let impl_def_id = impl_item.container().id();
let container = match ast_item.defaultness {
hir::Defaultness::Default => AssociatedContainer::ImplDefault,
hir::Defaultness::Final => AssociatedContainer::ImplFinal
};
let kind = match impl_item {
ty::ConstTraitItem(_) => {
EntryKind::AssociatedConst(container)
}
ty::MethodTraitItem(ref method_ty) => {
let fn_data = if let hir::ImplItemKind::Method(ref sig, _) = ast_item.node {
FnData {
constness: sig.constness,
arg_names: self.encode_fn_arg_names(&sig.decl)
}
} else {
bug!()
};
let data = MethodData {
fn_data: fn_data,
container: container,
explicit_self: self.lazy(&method_ty.explicit_self)
};
EntryKind::Method(self.lazy(&data))
}
ty::TypeTraitItem(_) => {
EntryKind::AssociatedType(container)
}
};
let (ast, mir) = if let ty::ConstTraitItem(_) = impl_item {
(true, true)
} else if let hir::ImplItemKind::Method(ref sig, _) = ast_item.node {
let generics = self.tcx.lookup_generics(def_id);
let types = generics.parent_types as usize + generics.types.len();
let needs_inline = types > 0 || attr::requests_inline(&ast_item.attrs);
let is_const_fn = sig.constness == hir::Constness::Const;
(is_const_fn, needs_inline || is_const_fn)
} else {
(false, false)
};
Entry {
kind: kind,
visibility: impl_item.vis().simplify(),
def_key: self.encode_def_key(def_id),
attributes: self.encode_attributes(&ast_item.attrs),
children: LazySeq::empty(),
stability: self.encode_stability(def_id),
deprecation: self.encode_deprecation(def_id),
ty: match impl_item {
ty::ConstTraitItem(_) |
ty::MethodTraitItem(_) => {
Some(self.encode_item_type(def_id))
}
ty::TypeTraitItem(ref associated_type) => {
associated_type.ty.map(|ty| self.lazy(&ty))
}
},
inherent_impls: LazySeq::empty(),
variances: LazySeq::empty(),
generics: Some(self.encode_generics(def_id)),
predicates: Some(self.encode_predicates(def_id)),
ast: if ast {
Some(self.encode_inlined_item(InlinedItemRef::ImplItem(impl_def_id, ast_item)))
} else {
None
},
mir: if mir {
self.encode_mir(def_id)
} else {
None
}
}
}
fn encode_fn_arg_names(&mut self, decl: &hir::FnDecl) -> LazySeq<ast::Name> {
self.lazy_seq(decl.inputs.iter().map(|arg| {
if let PatKind::Binding(_, ref path1, _) = arg.pat.node {
path1.node
} else {
syntax::parse::token::intern("")
}
}))
}
fn encode_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::repr::Mir<'tcx>>> {
self.mir_map.map.get(&def_id).map(|mir| self.lazy(mir))
}
// Encodes the inherent implementations of a structure, enumeration, or trait.
fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
match self.tcx.inherent_impls.borrow().get(&def_id) {
None => LazySeq::empty(),
Some(implementations) => {
self.lazy_seq(implementations.iter().map(|&def_id| {
assert!(def_id.is_local());
def_id.index
}))
}
}
}
fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
}
fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
}
fn encode_info_for_item(&mut self,
(def_id, item): (DefId, &hir::Item)) -> Entry<'tcx> {
let tcx = self.tcx;
debug!("encoding info for item at {}",
tcx.sess.codemap().span_to_string(item.span));
let kind = match item.node {
hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
hir::ItemConst(..) => EntryKind::Const,
hir::ItemFn(ref decl, _, constness, ..) => {
let data = FnData {
constness: constness,
arg_names: self.encode_fn_arg_names(&decl)
};
EntryKind::Fn(self.lazy(&data))
}
hir::ItemMod(ref m) => {
return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
}
hir::ItemForeignMod(_) => EntryKind::ForeignMod,
hir::ItemTy(..) => EntryKind::Type,
hir::ItemEnum(..) => EntryKind::Enum,
hir::ItemStruct(ref struct_def, _) => {
let variant = tcx.lookup_adt_def(def_id).struct_variant();
/* Encode def_ids for each field and method
for methods, write all the stuff get_trait_method
needs to know*/
let struct_ctor = if !struct_def.is_struct() {
Some(tcx.map.local_def_id(struct_def.id()).index)
} else {
None
};
EntryKind::Struct(self.lazy(&VariantData {
ctor_kind: variant.ctor_kind,
disr: variant.disr_val.to_u64_unchecked(),
struct_ctor: struct_ctor
}))
}
hir::ItemUnion(..) => {
let variant = tcx.lookup_adt_def(def_id).struct_variant();
EntryKind::Union(self.lazy(&VariantData {
ctor_kind: variant.ctor_kind,
disr: variant.disr_val.to_u64_unchecked(),
struct_ctor: None
}))
}
hir::ItemDefaultImpl(..) => {
let data = ImplData {
polarity: hir::ImplPolarity::Positive,
parent_impl: None,
coerce_unsized_kind: None,
trait_ref: tcx.impl_trait_ref(def_id).map(|trait_ref| self.lazy(&trait_ref))
};
EntryKind::DefaultImpl(self.lazy(&data))
}
hir::ItemImpl(_, polarity, ..) => {
let trait_ref = tcx.impl_trait_ref(def_id);
let parent = if let Some(trait_ref) = trait_ref {
let trait_def = tcx.lookup_trait_def(trait_ref.def_id);
trait_def.ancestors(def_id).skip(1).next().and_then(|node| {
match node {
specialization_graph::Node::Impl(parent) => Some(parent),
_ => None,
}
})
} else {
None
};
let data = ImplData {
polarity: polarity,
parent_impl: parent,
coerce_unsized_kind: tcx.custom_coerce_unsized_kinds.borrow()
.get(&def_id).cloned(),
trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref))
};
EntryKind::Impl(self.lazy(&data))
}
hir::ItemTrait(..) => {
let trait_def = tcx.lookup_trait_def(def_id);
let data = TraitData {
unsafety: trait_def.unsafety,
paren_sugar: trait_def.paren_sugar,
has_default_impl: tcx.trait_has_default_impl(def_id),
trait_ref: self.lazy(&trait_def.trait_ref),
super_predicates: self.lazy(&tcx.lookup_super_predicates(def_id))
};
EntryKind::Trait(self.lazy(&data))
}
hir::ItemExternCrate(_) | hir::ItemUse(_) => {
bug!("cannot encode info for item {:?}", item)
}
};
Entry {
kind: kind,
visibility: item.vis.simplify(),
def_key: self.encode_def_key(def_id),
attributes: self.encode_attributes(&item.attrs),
children: match item.node {
hir::ItemForeignMod(ref fm) => {
self.lazy_seq(fm.items.iter().map(|foreign_item| {
tcx.map.local_def_id(foreign_item.id).index
}))
}
hir::ItemEnum(..) => {
let def = self.tcx.lookup_adt_def(def_id);
self.lazy_seq(def.variants.iter().map(|v| {
assert!(v.did.is_local());
v.did.index
}))
}
hir::ItemStruct(..) |
hir::ItemUnion(..) => {
let def = self.tcx.lookup_adt_def(def_id);
self.lazy_seq(def.struct_variant().fields.iter().map(|f| {
assert!(f.did.is_local());
f.did.index
}))
}
hir::ItemImpl(..) |
hir::ItemTrait(..) => {
self.lazy_seq(tcx.impl_or_trait_items(def_id).iter().map(|&def_id| {
assert!(def_id.is_local());
def_id.index
}))
}
_ => LazySeq::empty()
},
stability: self.encode_stability(def_id),
deprecation: self.encode_deprecation(def_id),
ty: match item.node {
hir::ItemStatic(..) |
hir::ItemConst(..) |
hir::ItemFn(..) |
hir::ItemTy(..) |
hir::ItemEnum(..) |
hir::ItemStruct(..) |
hir::ItemUnion(..) |
hir::ItemImpl(..) => {
Some(self.encode_item_type(def_id))
}
_ => None
},
inherent_impls: self.encode_inherent_implementations(def_id),
variances: match item.node {
hir::ItemEnum(..) |
hir::ItemStruct(..) |
hir::ItemUnion(..) |
hir::ItemTrait(..) => {
self.encode_item_variances(def_id)
}
_ => LazySeq::empty()
},
generics: match item.node {
hir::ItemStatic(..) |
hir::ItemConst(..) |
hir::ItemFn(..) |
hir::ItemTy(..) |
hir::ItemEnum(..) |
hir::ItemStruct(..) |
hir::ItemUnion(..) |
hir::ItemImpl(..) |
hir::ItemTrait(..) => {
Some(self.encode_generics(def_id))
}
_ => None
},
predicates: match item.node {
hir::ItemStatic(..) |
hir::ItemConst(..) |
hir::ItemFn(..) |
hir::ItemTy(..) |
hir::ItemEnum(..) |
hir::ItemStruct(..) |
hir::ItemUnion(..) |
hir::ItemImpl(..) |
hir::ItemTrait(..) => {
Some(self.encode_predicates(def_id))
}
_ => None
},
ast: match item.node {
hir::ItemConst(..) |
hir::ItemFn(_, _, hir::Constness::Const, ..) => {
Some(self.encode_inlined_item(InlinedItemRef::Item(def_id, item)))
}
_ => None
},
mir: match item.node {
hir::ItemConst(..) => {
self.encode_mir(def_id)
}
hir::ItemFn(_, _, constness, _, ref generics, _) => {
let tps_len = generics.ty_params.len();
let needs_inline = tps_len > 0 || attr::requests_inline(&item.attrs);
if needs_inline || constness == hir::Constness::Const {
self.encode_mir(def_id)
} else {
None
}
}
_ => None
}
}
}
}
impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
/// In some cases, along with the item itself, we also
/// encode some sub-items. Usually we want some info from the item
/// so it's easier to do that here then to wait until we would encounter
/// normally in the visitor walk.
fn encode_addl_info_for_item(&mut self,
item: &hir::Item) {
let def_id = self.tcx.map.local_def_id(item.id);
match item.node {
hir::ItemStatic(..) |
hir::ItemConst(..) |
hir::ItemFn(..) |
hir::ItemMod(..) |
hir::ItemForeignMod(..) |
hir::ItemExternCrate(..) |
hir::ItemUse(..) |
hir::ItemDefaultImpl(..) |
hir::ItemTy(..) => {<|fim▁hole|> hir::ItemEnum(..) => {
self.encode_fields(def_id);
let def = self.tcx.lookup_adt_def(def_id);
for (i, variant) in def.variants.iter().enumerate() {
self.record(variant.did,
EncodeContext::encode_enum_variant_info,
(def_id, Untracked(i)));
}
}
hir::ItemStruct(ref struct_def, _) => {
self.encode_fields(def_id);
// If the struct has a constructor, encode it.
if !struct_def.is_struct() {
let ctor_def_id = self.tcx.map.local_def_id(struct_def.id());
self.record(ctor_def_id,
EncodeContext::encode_struct_ctor,
(def_id, ctor_def_id));
}
}
hir::ItemUnion(..) => {
self.encode_fields(def_id);
}
hir::ItemImpl(..) => {
for &trait_item_def_id in &self.tcx.impl_or_trait_items(def_id)[..] {
self.record(trait_item_def_id,
EncodeContext::encode_info_for_impl_item,
trait_item_def_id);
}
}
hir::ItemTrait(..) => {
for &item_def_id in &self.tcx.impl_or_trait_items(def_id)[..] {
self.record(item_def_id,
EncodeContext::encode_info_for_trait_item,
item_def_id);
}
}
}
}
}
impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
fn encode_info_for_foreign_item(&mut self,
(def_id, nitem): (DefId, &hir::ForeignItem))
-> Entry<'tcx> {
let tcx = self.tcx;
debug!("writing foreign item {}", tcx.node_path_str(nitem.id));
let kind = match nitem.node {
hir::ForeignItemFn(ref fndecl, _) => {
let data = FnData {
constness: hir::Constness::NotConst,
arg_names: self.encode_fn_arg_names(&fndecl)
};
EntryKind::ForeignFn(self.lazy(&data))
}
hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic
};
Entry {
kind: kind,
visibility: nitem.vis.simplify(),
def_key: self.encode_def_key(def_id),
attributes: self.encode_attributes(&nitem.attrs),
children: LazySeq::empty(),
stability: self.encode_stability(def_id),
deprecation: self.encode_deprecation(def_id),
ty: Some(self.encode_item_type(def_id)),
inherent_impls: LazySeq::empty(),
variances: LazySeq::empty(),
generics: Some(self.encode_generics(def_id)),
predicates: Some(self.encode_predicates(def_id)),
ast: None,
mir: None
}
}
}
struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
index: IndexBuilder<'a, 'b, 'tcx>,
}
impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
intravisit::walk_expr(self, ex);
self.index.encode_info_for_expr(ex);
}
fn visit_item(&mut self, item: &'tcx hir::Item) {
intravisit::walk_item(self, item);
let def_id = self.index.tcx.map.local_def_id(item.id);
match item.node {
hir::ItemExternCrate(_) | hir::ItemUse(_) => (), // ignore these
_ => self.index.record(def_id,
EncodeContext::encode_info_for_item,
(def_id, item)),
}
self.index.encode_addl_info_for_item(item);
}
fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
intravisit::walk_foreign_item(self, ni);
let def_id = self.index.tcx.map.local_def_id(ni.id);
self.index.record(def_id,
EncodeContext::encode_info_for_foreign_item,
(def_id, ni));
}
fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
intravisit::walk_ty(self, ty);
self.index.encode_info_for_ty(ty);
}
}
impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
if let hir::TyImplTrait(_) = ty.node {
let def_id = self.tcx.map.local_def_id(ty.id);
self.record(def_id,
EncodeContext::encode_info_for_anon_ty,
def_id);
}
}
fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
match expr.node {
hir::ExprClosure(..) => {
let def_id = self.tcx.map.local_def_id(expr.id);
self.record(def_id,
EncodeContext::encode_info_for_closure,
def_id);
}
_ => { }
}
}
}
impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
Entry {
kind: EntryKind::Type,
visibility: ty::Visibility::Public,
def_key: self.encode_def_key(def_id),
attributes: LazySeq::empty(),
children: LazySeq::empty(),
stability: None,
deprecation: None,
ty: Some(self.encode_item_type(def_id)),
inherent_impls: LazySeq::empty(),
variances: LazySeq::empty(),
generics: Some(self.encode_generics(def_id)),
predicates: Some(self.encode_predicates(def_id)),
ast: None,
mir: None
}
}
fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
let tcx = self.tcx;
let data = ClosureData {
kind: tcx.closure_kind(def_id),
ty: self.lazy(&tcx.tables.borrow().closure_tys[&def_id])
};
Entry {
kind: EntryKind::Closure(self.lazy(&data)),
visibility: ty::Visibility::Public,
def_key: self.encode_def_key(def_id),
attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
children: LazySeq::empty(),
stability: None,
deprecation: None,
ty: None,
inherent_impls: LazySeq::empty(),
variances: LazySeq::empty(),
generics: None,
predicates: None,
ast: None,
mir: self.encode_mir(def_id)
}
}
fn encode_info_for_items(&mut self) -> Index {
let krate = self.tcx.map.krate();
let mut index = IndexBuilder::new(self);
index.record(DefId::local(CRATE_DEF_INDEX),
EncodeContext::encode_info_for_mod,
FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
let mut visitor = EncodeVisitor {
index: index,
};
krate.visit_all_items(&mut visitor);
visitor.index.into_items()
}
fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
self.lazy_seq_ref(attrs)
}
fn encode_crate_deps(&mut self) -> LazySeq<CrateDep> {
fn get_ordered_deps(cstore: &cstore::CStore)
-> Vec<(CrateNum, Rc<cstore::CrateMetadata>)> {
// Pull the cnums and name,vers,hash out of cstore
let mut deps = Vec::new();
cstore.iter_crate_data(|cnum, val| {
deps.push((cnum, val.clone()));
});
// Sort by cnum
deps.sort_by(|kv1, kv2| kv1.0.cmp(&kv2.0));
// Sanity-check the crate numbers
let mut expected_cnum = 1;
for &(n, _) in &deps {
assert_eq!(n, CrateNum::new(expected_cnum));
expected_cnum += 1;
}
deps
}
// We're just going to write a list of crate 'name-hash-version's, with
// the assumption that they are numbered 1 to n.
// FIXME (#2166): This is not nearly enough to support correct versioning
// but is enough to get transitive crate dependencies working.
let deps = get_ordered_deps(self.cstore);
self.lazy_seq(deps.iter().map(|&(_, ref dep)| {
CrateDep {
name: syntax::parse::token::intern(dep.name()),
hash: dep.hash(),
explicitly_linked: dep.explicitly_linked.get()
}
}))
}
fn encode_lang_items(&mut self)
-> (LazySeq<(DefIndex, usize)>, LazySeq<lang_items::LangItem>) {
let tcx = self.tcx;
let lang_items = tcx.lang_items.items().iter();
(self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
if let Some(def_id) = opt_def_id {
if def_id.is_local() {
return Some((def_id.index, i));
}
}
None
})), self.lazy_seq_ref(&tcx.lang_items.missing))
}
fn encode_native_libraries(&mut self) -> LazySeq<(NativeLibraryKind, String)> {
let used_libraries = self.tcx.sess.cstore.used_libraries();
self.lazy_seq(used_libraries.into_iter().filter_map(|(lib, kind)| {
match kind {
cstore::NativeStatic => None, // these libraries are not propagated
cstore::NativeFramework | cstore::NativeUnknown => {
Some((kind, lib))
}
}
}))
}
fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
let codemap = self.tcx.sess.codemap();
let all_filemaps = codemap.files.borrow();
self.lazy_seq_ref(all_filemaps.iter().filter(|filemap| {
// No need to export empty filemaps, as they can't contain spans
// that need translation.
// Also no need to re-export imported filemaps, as any downstream
// crate will import them from their original source.
!filemap.lines.borrow().is_empty() && !filemap.is_imported()
}).map(|filemap| &**filemap))
}
/// Serialize the text of the exported macros
fn encode_macro_defs(&mut self) -> LazySeq<MacroDef> {
let tcx = self.tcx;
self.lazy_seq(tcx.map.krate().exported_macros.iter().map(|def| {
MacroDef {
name: def.name,
attrs: def.attrs.to_vec(),
span: def.span,
body: ::syntax::print::pprust::tts_to_string(&def.body)
}
}))
}
}
struct ImplVisitor<'a, 'tcx:'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
impls: FnvHashMap<DefId, Vec<DefIndex>>
}
impl<'a, 'tcx, 'v> Visitor<'v> for ImplVisitor<'a, 'tcx> {
fn visit_item(&mut self, item: &hir::Item) {
if let hir::ItemImpl(..) = item.node {
let impl_id = self.tcx.map.local_def_id(item.id);
if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
self.impls.entry(trait_ref.def_id)
.or_insert(vec![])
.push(impl_id.index);
}
}
}
}
impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
/// Encodes an index, mapping each trait to its (local) implementations.
fn encode_impls(&mut self) -> LazySeq<TraitImpls> {
let mut visitor = ImplVisitor {
tcx: self.tcx,
impls: FnvHashMap()
};
self.tcx.map.krate().visit_all_items(&mut visitor);
let all_impls: Vec<_> = visitor.impls.into_iter().map(|(trait_def_id, impls)| {
TraitImpls {
trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
impls: self.lazy_seq(impls)
}
}).collect();
self.lazy_seq(all_impls)
}
// Encodes all reachable symbols in this crate into the metadata.
//
// This pass is seeded off the reachability list calculated in the
// middle::reachable module but filters out items that either don't have a
// symbol associated with them (they weren't translated) or if they're an FFI
// definition (as that's not defined in this crate).
fn encode_reachable(&mut self) -> LazySeq<DefIndex> {
let reachable = self.reachable;
let tcx = self.tcx;
self.lazy_seq(reachable.iter().map(|&id| tcx.map.local_def_id(id).index))
}
fn encode_dylib_dependency_formats(&mut self) -> LazySeq<Option<LinkagePreference>> {
match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
Some(arr) => {
self.lazy_seq(arr.iter().map(|slot| {
match *slot {
Linkage::NotLinked |
Linkage::IncludedFromDylib => None,
Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
Linkage::Static => Some(LinkagePreference::RequireStatic),
}
}))
}
None => LazySeq::empty()
}
}
fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
let mut i = self.position();
let crate_deps = self.encode_crate_deps();
let dylib_dependency_formats = self.encode_dylib_dependency_formats();
let dep_bytes = self.position() - i;
// Encode the language items.
i = self.position();
let (lang_items, lang_items_missing) = self.encode_lang_items();
let lang_item_bytes = self.position() - i;
// Encode the native libraries used
i = self.position();
let native_libraries = self.encode_native_libraries();
let native_lib_bytes = self.position() - i;
// Encode codemap
i = self.position();
let codemap = self.encode_codemap();
let codemap_bytes = self.position() - i;
// Encode macro definitions
i = self.position();
let macro_defs = self.encode_macro_defs();
let macro_defs_bytes = self.position() - i;
// Encode the def IDs of impls, for coherence checking.
i = self.position();
let impls = self.encode_impls();
let impl_bytes = self.position() - i;
// Encode reachability info.
i = self.position();
let reachable_ids = self.encode_reachable();
let reachable_bytes = self.position() - i;
// Encode and index the items.
i = self.position();
let items = self.encode_info_for_items();
let item_bytes = self.position() - i;
i = self.position();
let index = items.write_index(&mut self.opaque.cursor);
let index_bytes = self.position() - i;
let tcx = self.tcx;
let link_meta = self.link_meta;
let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
let root = self.lazy(&CrateRoot {
rustc_version: rustc_version(),
name: link_meta.crate_name.clone(),
triple: tcx.sess.opts.target_triple.clone(),
hash: link_meta.crate_hash,
disambiguator: tcx.sess.local_crate_disambiguator().to_string(),
panic_strategy: tcx.sess.panic_strategy(),
plugin_registrar_fn: tcx.sess.plugin_registrar_fn.get().map(|id| {
tcx.map.local_def_id(id).index
}),
macro_derive_registrar: if is_proc_macro {
let id = tcx.sess.derive_registrar_fn.get().unwrap();
Some(tcx.map.local_def_id(id).index)
} else {
None
},
crate_deps: crate_deps,
dylib_dependency_formats: dylib_dependency_formats,
lang_items: lang_items,
lang_items_missing: lang_items_missing,
native_libraries: native_libraries,
codemap: codemap,
macro_defs: macro_defs,
impls: impls,
reachable_ids: reachable_ids,
index: index,
});
let total_bytes = self.position();
if self.tcx.sess.meta_stats() {
let mut zero_bytes = 0;
for e in self.opaque.cursor.get_ref() {
if *e == 0 {
zero_bytes += 1;
}
}
println!("metadata stats:");
println!(" dep bytes: {}", dep_bytes);
println!(" lang item bytes: {}", lang_item_bytes);
println!(" native bytes: {}", native_lib_bytes);
println!(" codemap bytes: {}", codemap_bytes);
println!(" macro def bytes: {}", macro_defs_bytes);
println!(" impl bytes: {}", impl_bytes);
println!(" reachable bytes: {}", reachable_bytes);
println!(" item bytes: {}", item_bytes);
println!(" index bytes: {}", index_bytes);
println!(" zero bytes: {}", zero_bytes);
println!(" total bytes: {}", total_bytes);
}
root
}
}
// NOTE(eddyb) The following comment was preserved for posterity, even
// though it's no longer relevant as EBML (which uses nested & tagged
// "documents") was replaced with a scheme that can't go out of bounds.
//
// And here we run into yet another obscure archive bug: in which metadata
// loaded from archives may have trailing garbage bytes. Awhile back one of
// our tests was failing sporadically on the OSX 64-bit builders (both nopt
// and opt) by having ebml generate an out-of-bounds panic when looking at
// metadata.
//
// Upon investigation it turned out that the metadata file inside of an rlib
// (and ar archive) was being corrupted. Some compilations would generate a
// metadata file which would end in a few extra bytes, while other
// compilations would not have these extra bytes appended to the end. These
// extra bytes were interpreted by ebml as an extra tag, so they ended up
// being interpreted causing the out-of-bounds.
//
// The root cause of why these extra bytes were appearing was never
// discovered, and in the meantime the solution we're employing is to insert
// the length of the metadata to the start of the metadata. Later on this
// will allow us to slice the metadata to the precise length that we just
// generated regardless of trailing bytes that end up in it.
pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
cstore: &cstore::CStore,
reexports: &def::ExportMap,
link_meta: &LinkMeta,
reachable: &NodeSet,
mir_map: &MirMap<'tcx>) -> Vec<u8> {
let mut cursor = Cursor::new(vec![]);
cursor.write_all(METADATA_HEADER).unwrap();
// Will be filed with the root position after encoding everything.
cursor.write_all(&[0, 0, 0, 0]).unwrap();
let root = EncodeContext {
opaque: opaque::Encoder::new(&mut cursor),
tcx: tcx,
reexports: reexports,
link_meta: link_meta,
cstore: cstore,
reachable: reachable,
mir_map: mir_map,
lazy_state: LazyState::NoNode,
type_shorthands: Default::default(),
predicate_shorthands: Default::default()
}.encode_crate_root();
let mut result = cursor.into_inner();
// Encode the root position.
let header = METADATA_HEADER.len();
let pos = root.position;
result[header + 0] = (pos >> 24) as u8;
result[header + 1] = (pos >> 16) as u8;
result[header + 2] = (pos >> 8) as u8;
result[header + 3] = (pos >> 0) as u8;
result
}<|fim▁end|> | // no sub-item recording needed in these cases
} |
<|file_name|>transaction_sr.py<|end_file_name|><|fim▁begin|># Copyright (C) 2020 Red Hat, Inc.
#
# 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<|fim▁hole|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import libdnf
import hawkey
from dnf.i18n import _
import dnf.exceptions
import json
VERSION_MAJOR = 0
VERSION_MINOR = 0
VERSION = "%s.%s" % (VERSION_MAJOR, VERSION_MINOR)
"""
The version of the stored transaction.
MAJOR version denotes backwards incompatible changes (old dnf won't work with
new transaction JSON).
MINOR version denotes extending the format without breaking backwards
compatibility (old dnf can work with new transaction JSON). Forwards
compatibility needs to be handled by being able to process the old format as
well as the new one.
"""
class TransactionError(dnf.exceptions.Error):
def __init__(self, msg):
super(TransactionError, self).__init__(msg)
class TransactionReplayError(dnf.exceptions.Error):
def __init__(self, filename, errors):
"""
:param filename: The name of the transaction file being replayed
:param errors: a list of error classes or a string with an error description
"""
# store args in case someone wants to read them from a caught exception
self.filename = filename
if isinstance(errors, (list, tuple)):
self.errors = errors
else:
self.errors = [errors]
if filename:
msg = _('The following problems occurred while replaying the transaction from file "{filename}":').format(filename=filename)
else:
msg = _('The following problems occurred while running a transaction:')
for error in self.errors:
msg += "\n " + str(error)
super(TransactionReplayError, self).__init__(msg)
class IncompatibleTransactionVersionError(TransactionReplayError):
def __init__(self, filename, msg):
super(IncompatibleTransactionVersionError, self).__init__(filename, msg)
def _check_version(version, filename):
major, minor = version.split('.')
try:
major = int(major)
except ValueError as e:
raise TransactionReplayError(
filename,
_('Invalid major version "{major}", number expected.').format(major=major)
)
try:
int(minor) # minor is unused, just check it's a number
except ValueError as e:
raise TransactionReplayError(
filename,
_('Invalid minor version "{minor}", number expected.').format(minor=minor)
)
if major != VERSION_MAJOR:
raise IncompatibleTransactionVersionError(
filename,
_('Incompatible major version "{major}", supported major version is "{major_supp}".')
.format(major=major, major_supp=VERSION_MAJOR)
)
def serialize_transaction(transaction):
"""
Serializes a transaction to a data structure that is equivalent to the stored JSON format.
:param transaction: the transaction to serialize (an instance of dnf.db.history.TransactionWrapper)
"""
data = {
"version": VERSION,
}
rpms = []
groups = []
environments = []
if transaction is None:
return data
for tsi in transaction.packages():
if tsi.is_package():
rpms.append({
"action": tsi.action_name,
"nevra": tsi.nevra,
"reason": libdnf.transaction.TransactionItemReasonToString(tsi.reason),
"repo_id": tsi.from_repo
})
elif tsi.is_group():
group = tsi.get_group()
group_data = {
"action": tsi.action_name,
"id": group.getGroupId(),
"packages": [],
"package_types": libdnf.transaction.compsPackageTypeToString(group.getPackageTypes())
}
for pkg in group.getPackages():
group_data["packages"].append({
"name": pkg.getName(),
"installed": pkg.getInstalled(),
"package_type": libdnf.transaction.compsPackageTypeToString(pkg.getPackageType())
})
groups.append(group_data)
elif tsi.is_environment():
env = tsi.get_environment()
env_data = {
"action": tsi.action_name,
"id": env.getEnvironmentId(),
"groups": [],
"package_types": libdnf.transaction.compsPackageTypeToString(env.getPackageTypes())
}
for grp in env.getGroups():
env_data["groups"].append({
"id": grp.getGroupId(),
"installed": grp.getInstalled(),
"group_type": libdnf.transaction.compsPackageTypeToString(grp.getGroupType())
})
environments.append(env_data)
if rpms:
data["rpms"] = rpms
if groups:
data["groups"] = groups
if environments:
data["environments"] = environments
return data
class TransactionReplay(object):
"""
A class that encapsulates replaying a transaction. The transaction data are
loaded and stored when the class is initialized. The transaction is run by
calling the `run()` method, after the transaction is created (but before it is
performed), the `post_transaction()` method needs to be called to verify no
extra packages were pulled in and also to fix the reasons.
"""
def __init__(
self,
base,
filename="",
data=None,
ignore_extras=False,
ignore_installed=False,
skip_unavailable=False
):
"""
:param base: the dnf base
:param filename: the filename to load the transaction from (conflicts with the 'data' argument)
:param data: the dictionary to load the transaction from (conflicts with the 'filename' argument)
:param ignore_extras: whether to ignore extra package pulled into the transaction
:param ignore_installed: whether to ignore installed versions of packages
:param skip_unavailable: whether to skip transaction packages that aren't available
"""
self._base = base
self._filename = filename
self._ignore_installed = ignore_installed
self._ignore_extras = ignore_extras
self._skip_unavailable = skip_unavailable
if not self._base.conf.strict:
self._skip_unavailable = True
self._nevra_cache = set()
self._nevra_reason_cache = {}
self._warnings = []
if filename and data:
raise ValueError(_("Conflicting TransactionReplay arguments have been specified: filename, data"))
elif filename:
self._load_from_file(filename)
else:
self._load_from_data(data)
def _load_from_file(self, fn):
self._filename = fn
with open(fn, "r") as f:
try:
replay_data = json.load(f)
except json.decoder.JSONDecodeError as e:
raise TransactionReplayError(fn, str(e) + ".")
try:
self._load_from_data(replay_data)
except TransactionError as e:
raise TransactionReplayError(fn, e)
def _load_from_data(self, data):
self._replay_data = data
self._verify_toplevel_json(self._replay_data)
self._rpms = self._replay_data.get("rpms", [])
self._assert_type(self._rpms, list, "rpms", "array")
self._groups = self._replay_data.get("groups", [])
self._assert_type(self._groups, list, "groups", "array")
self._environments = self._replay_data.get("environments", [])
self._assert_type(self._environments, list, "environments", "array")
def _raise_or_warn(self, warn_only, msg):
if warn_only:
self._warnings.append(msg)
else:
raise TransactionError(msg)
def _assert_type(self, value, t, id, expected):
if not isinstance(value, t):
raise TransactionError(_('Unexpected type of "{id}", {exp} expected.').format(id=id, exp=expected))
def _verify_toplevel_json(self, replay_data):
fn = self._filename
if "version" not in replay_data:
raise TransactionReplayError(fn, _('Missing key "{key}".'.format(key="version")))
self._assert_type(replay_data["version"], str, "version", "string")
_check_version(replay_data["version"], fn)
def _replay_pkg_action(self, pkg_data):
try:
action = pkg_data["action"]
nevra = pkg_data["nevra"]
repo_id = pkg_data["repo_id"]
reason = libdnf.transaction.StringToTransactionItemReason(pkg_data["reason"])
except KeyError as e:
raise TransactionError(
_('Missing object key "{key}" in an rpm.').format(key=e.args[0])
)
except IndexError as e:
raise TransactionError(
_('Unexpected value of package reason "{reason}" for rpm nevra "{nevra}".')
.format(reason=pkg_data["reason"], nevra=nevra)
)
subj = hawkey.Subject(nevra)
parsed_nevras = subj.get_nevra_possibilities(forms=[hawkey.FORM_NEVRA])
if len(parsed_nevras) != 1:
raise TransactionError(_('Cannot parse NEVRA for package "{nevra}".').format(nevra=nevra))
parsed_nevra = parsed_nevras[0]
na = "%s.%s" % (parsed_nevra.name, parsed_nevra.arch)
query_na = self._base.sack.query().filter(name=parsed_nevra.name, arch=parsed_nevra.arch)
epoch = parsed_nevra.epoch if parsed_nevra.epoch is not None else 0
query = query_na.filter(epoch=epoch, version=parsed_nevra.version, release=parsed_nevra.release)
# In case the package is found in the same repo as in the original
# transaction, limit the query to that plus installed packages. IOW
# remove packages with the same NEVRA in case they are found in
# multiple repos and the repo the package came from originally is one
# of them.
# This can e.g. make a difference in the system-upgrade plugin, in case
# the same NEVRA is in two repos, this makes sure the same repo is used
# for both download and upgrade steps of the plugin.
if repo_id:
query_repo = query.filter(reponame=repo_id)
if query_repo:
query = query_repo.union(query.installed())
if not query:
self._raise_or_warn(self._skip_unavailable, _('Cannot find rpm nevra "{nevra}".').format(nevra=nevra))
return
# a cache to check no extra packages were pulled into the transaction
if action != "Reason Change":
self._nevra_cache.add(nevra)
# store reasons for forward actions and "Removed", the rest of the
# actions reasons should stay as they were determined by the transaction
if action in ("Install", "Upgrade", "Downgrade", "Reinstall", "Removed"):
self._nevra_reason_cache[nevra] = reason
if action in ("Install", "Upgrade", "Downgrade"):
if action == "Install" and query_na.installed() and not self._base._get_installonly_query(query_na):
self._raise_or_warn(self._ignore_installed,
_('Package "{na}" is already installed for action "{action}".').format(na=na, action=action))
sltr = dnf.selector.Selector(self._base.sack).set(pkg=query)
self._base.goal.install(select=sltr, optional=not self._base.conf.strict)
elif action == "Reinstall":
query = query.available()
if not query:
self._raise_or_warn(self._skip_unavailable,
_('Package nevra "{nevra}" not available in repositories for action "{action}".')
.format(nevra=nevra, action=action))
return
sltr = dnf.selector.Selector(self._base.sack).set(pkg=query)
self._base.goal.install(select=sltr, optional=not self._base.conf.strict)
elif action in ("Upgraded", "Downgraded", "Reinstalled", "Removed", "Obsoleted"):
query = query.installed()
if not query:
self._raise_or_warn(self._ignore_installed,
_('Package nevra "{nevra}" not installed for action "{action}".').format(nevra=nevra, action=action))
return
# erasing the original version (the reverse part of an action like
# e.g. upgrade) is more robust, but we can't do it if
# skip_unavailable is True, because if the forward part of the
# action is skipped, we would simply remove the package here
if not self._skip_unavailable or action == "Removed":
for pkg in query:
self._base.goal.erase(pkg, clean_deps=False)
elif action == "Reason Change":
self._base.history.set_reason(query[0], reason)
else:
raise TransactionError(
_('Unexpected value of package action "{action}" for rpm nevra "{nevra}".')
.format(action=action, nevra=nevra)
)
def _create_swdb_group(self, group_id, pkg_types, pkgs):
comps_group = self._base.comps._group_by_id(group_id)
if not comps_group:
self._raise_or_warn(self._skip_unavailable, _("Group id '%s' is not available.") % group_id)
return None
swdb_group = self._base.history.group.new(group_id, comps_group.name, comps_group.ui_name, pkg_types)
try:
for pkg in pkgs:
name = pkg["name"]
self._assert_type(name, str, "groups.packages.name", "string")
installed = pkg["installed"]
self._assert_type(installed, bool, "groups.packages.installed", "boolean")
package_type = pkg["package_type"]
self._assert_type(package_type, str, "groups.packages.package_type", "string")
try:
swdb_group.addPackage(name, installed, libdnf.transaction.stringToCompsPackageType(package_type))
except libdnf.error.Error as e:
raise TransactionError(str(e))
except KeyError as e:
raise TransactionError(
_('Missing object key "{key}" in groups.packages.').format(key=e.args[0])
)
return swdb_group
def _swdb_group_install(self, group_id, pkg_types, pkgs):
swdb_group = self._create_swdb_group(group_id, pkg_types, pkgs)
if swdb_group is not None:
self._base.history.group.install(swdb_group)
def _swdb_group_upgrade(self, group_id, pkg_types, pkgs):
if not self._base.history.group.get(group_id):
self._raise_or_warn( self._ignore_installed, _("Group id '%s' is not installed.") % group_id)
return
swdb_group = self._create_swdb_group(group_id, pkg_types, pkgs)
if swdb_group is not None:
self._base.history.group.upgrade(swdb_group)
def _swdb_group_remove(self, group_id, pkg_types, pkgs):
if not self._base.history.group.get(group_id):
self._raise_or_warn(self._ignore_installed, _("Group id '%s' is not installed.") % group_id)
return
swdb_group = self._create_swdb_group(group_id, pkg_types, pkgs)
if swdb_group is not None:
self._base.history.group.remove(swdb_group)
def _create_swdb_environment(self, env_id, pkg_types, groups):
comps_env = self._base.comps._environment_by_id(env_id)
if not comps_env:
self._raise_or_warn(self._skip_unavailable, _("Environment id '%s' is not available.") % env_id)
return None
swdb_env = self._base.history.env.new(env_id, comps_env.name, comps_env.ui_name, pkg_types)
try:
for grp in groups:
id = grp["id"]
self._assert_type(id, str, "environments.groups.id", "string")
installed = grp["installed"]
self._assert_type(installed, bool, "environments.groups.installed", "boolean")
group_type = grp["group_type"]
self._assert_type(group_type, str, "environments.groups.group_type", "string")
try:
group_type = libdnf.transaction.stringToCompsPackageType(group_type)
except libdnf.error.Error as e:
raise TransactionError(str(e))
if group_type not in (
libdnf.transaction.CompsPackageType_MANDATORY,
libdnf.transaction.CompsPackageType_OPTIONAL
):
raise TransactionError(
_('Invalid value "{group_type}" of environments.groups.group_type, '
'only "mandatory" or "optional" is supported.'
).format(group_type=grp["group_type"])
)
swdb_env.addGroup(id, installed, group_type)
except KeyError as e:
raise TransactionError(
_('Missing object key "{key}" in environments.groups.').format(key=e.args[0])
)
return swdb_env
def _swdb_environment_install(self, env_id, pkg_types, groups):
swdb_env = self._create_swdb_environment(env_id, pkg_types, groups)
if swdb_env is not None:
self._base.history.env.install(swdb_env)
def _swdb_environment_upgrade(self, env_id, pkg_types, groups):
if not self._base.history.env.get(env_id):
self._raise_or_warn(self._ignore_installed,_("Environment id '%s' is not installed.") % env_id)
return
swdb_env = self._create_swdb_environment(env_id, pkg_types, groups)
if swdb_env is not None:
self._base.history.env.upgrade(swdb_env)
def _swdb_environment_remove(self, env_id, pkg_types, groups):
if not self._base.history.env.get(env_id):
self._raise_or_warn(self._ignore_installed, _("Environment id '%s' is not installed.") % env_id)
return
swdb_env = self._create_swdb_environment(env_id, pkg_types, groups)
if swdb_env is not None:
self._base.history.env.remove(swdb_env)
def get_data(self):
"""
:returns: the loaded data of the transaction
"""
return self._replay_data
def get_warnings(self):
"""
:returns: an array of warnings gathered during the transaction replay
"""
return self._warnings
def run(self):
"""
Replays the transaction.
"""
fn = self._filename
errors = []
for pkg_data in self._rpms:
try:
self._replay_pkg_action(pkg_data)
except TransactionError as e:
errors.append(e)
for group_data in self._groups:
try:
action = group_data["action"]
group_id = group_data["id"]
try:
pkg_types = libdnf.transaction.stringToCompsPackageType(group_data["package_types"])
except libdnf.error.Error as e:
errors.append(TransactionError(str(e)))
continue
if action == "Install":
self._swdb_group_install(group_id, pkg_types, group_data["packages"])
elif action == "Upgrade":
self._swdb_group_upgrade(group_id, pkg_types, group_data["packages"])
elif action == "Removed":
self._swdb_group_remove(group_id, pkg_types, group_data["packages"])
else:
errors.append(TransactionError(
_('Unexpected value of group action "{action}" for group "{group}".')
.format(action=action, group=group_id)
))
except KeyError as e:
errors.append(TransactionError(
_('Missing object key "{key}" in a group.').format(key=e.args[0])
))
except TransactionError as e:
errors.append(e)
for env_data in self._environments:
try:
action = env_data["action"]
env_id = env_data["id"]
try:
pkg_types = libdnf.transaction.stringToCompsPackageType(env_data["package_types"])
except libdnf.error.Error as e:
errors.append(TransactionError(str(e)))
continue
if action == "Install":
self._swdb_environment_install(env_id, pkg_types, env_data["groups"])
elif action == "Upgrade":
self._swdb_environment_upgrade(env_id, pkg_types, env_data["groups"])
elif action == "Removed":
self._swdb_environment_remove(env_id, pkg_types, env_data["groups"])
else:
errors.append(TransactionError(
_('Unexpected value of environment action "{action}" for environment "{env}".')
.format(action=action, env=env_id)
))
except KeyError as e:
errors.append(TransactionError(
_('Missing object key "{key}" in an environment.').format(key=e.args[0])
))
except TransactionError as e:
errors.append(e)
if errors:
raise TransactionReplayError(fn, errors)
def post_transaction(self):
"""
Sets reasons in the transaction history to values from the stored transaction.
Also serves to check whether additional packages were pulled in by the
transaction, which results in an error (unless ignore_extras is True).
"""
if not self._base.transaction:
return
errors = []
for tsi in self._base.transaction:
try:
pkg = tsi.pkg
except KeyError as e:
# the transaction item has no package, happens for action == "Reason Change"
continue
nevra = str(pkg)
if nevra not in self._nevra_cache:
# if ignore_installed is True, we don't want to check for
# Upgraded/Downgraded/Reinstalled extras in the transaction,
# basically those may be installed and we are ignoring them
if not self._ignore_installed or not tsi.action in (
libdnf.transaction.TransactionItemAction_UPGRADED,
libdnf.transaction.TransactionItemAction_DOWNGRADED,
libdnf.transaction.TransactionItemAction_REINSTALLED
):
msg = _('Package nevra "{nevra}", which is not present in the transaction file, was pulled '
'into the transaction.'
).format(nevra=nevra)
if not self._ignore_extras:
errors.append(TransactionError(msg))
else:
self._warnings.append(msg)
try:
replay_reason = self._nevra_reason_cache[nevra]
if tsi.action in (
libdnf.transaction.TransactionItemAction_INSTALL,
libdnf.transaction.TransactionItemAction_REMOVE
) or libdnf.transaction.TransactionItemReasonCompare(replay_reason, tsi.reason) > 0:
tsi.reason = replay_reason
except KeyError as e:
# if the pkg nevra wasn't found, we don't want to change the reason
pass
if errors:
raise TransactionReplayError(self._filename, errors)<|fim▁end|> | # 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, |
<|file_name|>ElasticsearchRestComponentVerifierExtensionTest.java<|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.
*/
package org.apache.camel.component.elasticsearch;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.Component;
import org.apache.camel.component.extension.ComponentVerifierExtension;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Assert;
import org.junit.Test;
public class ElasticsearchRestComponentVerifierExtensionTest extends CamelTestSupport {
// *************************************************
// Tests (parameters)
// *************************************************
@Override
public boolean isUseRouteBuilder() {
return false;
}
@Test
public void testParameters() throws Exception {
Component component = context().getComponent("elasticsearch-rest");
ComponentVerifierExtension verifier = component.getExtension(ComponentVerifierExtension.class).orElseThrow(IllegalStateException::new);
Map<String, Object> parameters = new HashMap<>();
parameters.put("hostAddresses", "http://localhost:9000");
parameters.put("clusterName", "es-test");
ComponentVerifierExtension.Result result = verifier.verify(ComponentVerifierExtension.Scope.PARAMETERS, parameters);
Assert.assertEquals(ComponentVerifierExtension.Result.Status.OK, result.getStatus());
}
@Test
public void testConnectivity() throws Exception {
Component component = context().getComponent("elasticsearch-rest");
ComponentVerifierExtension verifier = component.getExtension(ComponentVerifierExtension.class).orElseThrow(IllegalStateException::new);
Map<String, Object> parameters = new HashMap<>();
parameters.put("hostAddresses", "http://localhost:9000");
ComponentVerifierExtension.Result result = verifier.verify(ComponentVerifierExtension.Scope.CONNECTIVITY, parameters);
Assert.assertEquals(ComponentVerifierExtension.Result.Status.ERROR, result.getStatus());
}<|fim▁hole|><|fim▁end|> |
} |
<|file_name|>driver.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.
"""IoT Docker RPC handler."""
from docker import errors
from oslo.config import cfg
from iot.common import docker_utils
from iot.openstack.common import log as logging
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
class Handler(object):
<|fim▁hole|>
def _encode_utf8(self, value):
return unicode(value).encode('utf-8')
# Device operations
def device_create(self, ctxt, name, device_uuid, device):
LOG.debug('Creating device name %s'
% (name))
def device_list(self, ctxt):
LOG.debug("device_list")
def device_delete(self, ctxt, device_uuid):
LOG.debug("device_delete %s" % device_uuid)
def device_show(self, ctxt, device_uuid):
LOG.debug("device_show %s" % device_uuid)<|fim▁end|> | def __init__(self):
super(Handler, self).__init__()
self._docker = None |
<|file_name|>genesis_builder.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from ethereum.utils import sha3, encode_hex, denoms
from raiden.utils import privatekey_to_address
from raiden.tests.utils.blockchain import GENESIS_STUB
<|fim▁hole|>
def generate_accounts(seeds):
"""Create private keys and addresses for all seeds.
"""
return {
seed: dict(
privatekey=encode_hex(sha3(seed)),
address=encode_hex(privatekey_to_address(sha3(seed)))
) for seed in seeds}
def mk_genesis(accounts, initial_alloc=denoms.ether * 100000000):
"""
Create a genesis-block dict with allocation for all `accounts`.
:param accounts: list of account addresses (hex)
:param initial_alloc: the amount to allocate for the `accounts`
:return: genesis dict
"""
genesis = GENESIS_STUB.copy()
genesis['extraData'] = CLUSTER_NAME
genesis['alloc'] = {
account: {
'balance': str(initial_alloc)
}
for account in accounts
}
# add the one-privatekey account ("1" * 64) for convenience
genesis['alloc']['19e7e376e7c213b7e7e7e46cc70a5dd086daff2a'] = dict(balance=str(initial_alloc))
return genesis<|fim▁end|> | CLUSTER_NAME = 'raiden' |
<|file_name|>test.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<|fim▁hole|>// 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.
pub fn foo() -> isize { 10 }<|fim▁end|> | |
<|file_name|>form.utils.spec.ts<|end_file_name|><|fim▁begin|>/*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import {FormArray, FormControl} from '@angular/forms';
import {moveFormArrayItem} from './form.utils';
describe('moveFormArrayItem', () => {
it('should move item down', () => {
const formArray = createFormArray(4);
moveFormArrayItem(formArray, 0, 1);
expect(formArray.value).toEqual([2, 1, 3, 4]);
});
it('should move item up', () => {
const formArray = createFormArray(4);
moveFormArrayItem(formArray, 2, 1);
expect(formArray.value).toEqual([1, 3, 2, 4]);<|fim▁hole|> });
});
function createFormArray(controls: number): FormArray {
return new FormArray(
new Array(controls)
.fill(0)
.map((value, index) => index + 1)
.map(index => new FormControl(index))
);
}<|fim▁end|> | |
<|file_name|>SocketSecurityException.java<|end_file_name|><|fim▁begin|>/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.rmi.server;<|fim▁hole|>
/**
* An obsolete subclass of {@link ExportException}.
*
* @author Ann Wollrath
* @since JDK1.1
* @deprecated This class is obsolete. Use {@link ExportException} instead.
*/
@Deprecated
public class SocketSecurityException extends ExportException {
/* indicate compatibility with JDK 1.1.x version of class */
private static final long serialVersionUID = -7622072999407781979L;
/**
* Constructs an <code>SocketSecurityException</code> with the specified
* detail message.
*
* @param s the detail message.
* @since JDK1.1
*/
public SocketSecurityException(String s) {
super(s);
}
/**
* Constructs an <code>SocketSecurityException</code> with the specified
* detail message and nested exception.
*
* @param s the detail message.
* @param ex the nested exception
* @since JDK1.1
*/
public SocketSecurityException(String s, Exception ex) {
super(s, ex);
}
}<|fim▁end|> | |
<|file_name|>payment_form.js<|end_file_name|><|fim▁begin|>odoo.define('payment_stripe.payment_form', function (require) {
"use strict";
var ajax = require('web.ajax');
var core = require('web.core');
var Dialog = require('web.Dialog');
var PaymentForm = require('payment.payment_form');
var qweb = core.qweb;
var _t = core._t;
ajax.loadXML('/payment_stripe/static/src/xml/stripe_templates.xml', qweb);
PaymentForm.include({
willStart: function () {
return this._super.apply(this, arguments).then(function () {
return ajax.loadJS("https://js.stripe.com/v3/");
})
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* called to create payment method object for credit card/debit card.
*
* @private
* @param {Object} stripe
* @param {Object} formData
* @param {Object} card
* @param {Boolean} addPmEvent
* @returns {Promise}
*/
_createPaymentMethod: function (stripe, formData, card, addPmEvent) {
if (addPmEvent) {
return this._rpc({
route: '/payment/stripe/s2s/create_setup_intent',
params: {'acquirer_id': formData.acquirer_id}
}).then(function(intent_secret) {
return stripe.handleCardSetup(intent_secret, card);
});
} else {
return stripe.createPaymentMethod({
type: 'card',
card: card,
});
}
},
/**
* called when clicking on pay now or add payment event to create token for credit card/debit card.
*
* @private
* @param {Event} ev
* @param {DOMElement} checkedRadio
* @param {Boolean} addPmEvent
*/
_createStripeToken: function (ev, $checkedRadio, addPmEvent) {
var self = this;
if (ev.type === 'submit') {
var button = $(ev.target).find('*[type="submit"]')[0]
} else {
var button = ev.target;
}
this.disableButton(button);
var acquirerID = this.getAcquirerIdFromRadio($checkedRadio);
var acquirerForm = this.$('#o_payment_add_token_acq_' + acquirerID);
var inputsForm = $('input', acquirerForm);
if (this.options.partnerId === undefined) {
console.warn('payment_form: unset partner_id when adding new token; things could go wrong');
}
var formData = self.getFormData(inputsForm);
var stripe = this.stripe;
var card = this.stripe_card_element;
if (card._invalid) {
return;
}
this._createPaymentMethod(stripe, formData, card, addPmEvent).then(function(result) {
if (result.error) {
return Promise.reject({"message": {"data": { "arguments": [result.error.message]}}});
} else {
const paymentMethod = addPmEvent ? result.setupIntent.payment_method : result.paymentMethod.id;
_.extend(formData, {"payment_method": paymentMethod});
return self._rpc({
route: formData.data_set,
params: formData,
});
}
}).then(function(result) {
if (addPmEvent) {
if (formData.return_url) {
window.location = formData.return_url;
} else {
window.location.reload();
}
} else {
$checkedRadio.val(result.id);
self.el.submit();
}
}).guardedCatch(function (error) {
// We don't want to open the Error dialog since
// we already have a container displaying the error
if (error.event) {
error.event.preventDefault();
}
// if the rpc fails, pretty obvious<|fim▁hole|> self._parseError(error)
);
});
},
/**
* called when clicking a Stripe radio if configured for s2s flow; instanciates the card and bind it to the widget.
*
* @private
* @param {DOMElement} checkedRadio
*/
_bindStripeCard: function ($checkedRadio) {
var acquirerID = this.getAcquirerIdFromRadio($checkedRadio);
var acquirerForm = this.$('#o_payment_add_token_acq_' + acquirerID);
var inputsForm = $('input', acquirerForm);
var formData = this.getFormData(inputsForm);
var stripe = Stripe(formData.stripe_publishable_key);
var element = stripe.elements();
var card = element.create('card', {hidePostalCode: true});
card.mount('#card-element');
card.on('ready', function(ev) {
card.focus();
});
card.addEventListener('change', function (event) {
var displayError = document.getElementById('card-errors');
displayError.textContent = '';
if (event.error) {
displayError.textContent = event.error.message;
}
});
this.stripe = stripe;
this.stripe_card_element = card;
},
/**
* destroys the card element and any stripe instance linked to the widget.
*
* @private
*/
_unbindStripeCard: function () {
if (this.stripe_card_element) {
this.stripe_card_element.destroy();
}
this.stripe = undefined;
this.stripe_card_element = undefined;
},
/**
* @override
*/
updateNewPaymentDisplayStatus: function () {
var $checkedRadio = this.$('input[type="radio"]:checked');
if ($checkedRadio.length !== 1) {
return;
}
var provider = $checkedRadio.data('provider')
if (provider === 'stripe') {
// always re-init stripe (in case of multiple acquirers for stripe, make sure the stripe instance is using the right key)
this._unbindStripeCard();
if (this.isNewPaymentRadio($checkedRadio)) {
this._bindStripeCard($checkedRadio);
}
}
return this._super.apply(this, arguments);
},
//--------------------------------------------------------------------------
// Handlers
//--------------------------------------------------------------------------
/**
* @override
*/
payEvent: function (ev) {
ev.preventDefault();
var $checkedRadio = this.$('input[type="radio"]:checked');
// first we check that the user has selected a stripe as s2s payment method
if ($checkedRadio.length === 1 && this.isNewPaymentRadio($checkedRadio) && $checkedRadio.data('provider') === 'stripe') {
return this._createStripeToken(ev, $checkedRadio);
} else {
return this._super.apply(this, arguments);
}
},
/**
* @override
*/
addPmEvent: function (ev) {
ev.stopPropagation();
ev.preventDefault();
var $checkedRadio = this.$('input[type="radio"]:checked');
// first we check that the user has selected a stripe as add payment method
if ($checkedRadio.length === 1 && this.isNewPaymentRadio($checkedRadio) && $checkedRadio.data('provider') === 'stripe') {
return this._createStripeToken(ev, $checkedRadio, true);
} else {
return this._super.apply(this, arguments);
}
},
});
});<|fim▁end|> | self.enableButton(button);
self.displayError(
_t('Unable to save card'),
_t("We are not able to add your payment method at the moment. ") + |
<|file_name|>cli_utils.py<|end_file_name|><|fim▁begin|># Copyright 2018 Red Hat, Inc. and others. 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.
import argparse
import logging
import os
<|fim▁hole|>def type_input_file(path):
if path == '-':
return path
if not os.path.isfile(path):
logger.error('File "%s" not found' % path)
raise argparse.ArgumentError
return path
def add_common_args(parser):
parser.add_argument("--path",
help="the directory that the parsed data is written into")
parser.add_argument("--transport", default="http",
choices=["http", "https"],
help="transport for connections")
parser.add_argument("-i", "--ip", default="localhost",
help="OpenDaylight ip address")
parser.add_argument("-t", "--port", default="8181",
help="OpenDaylight restconf port, default: 8181")
parser.add_argument("-u", "--user", default="admin",
help="OpenDaylight restconf username, default: admin")
parser.add_argument("-w", "--pw", default="admin",
help="OpenDaylight restconf password, default: admin")
parser.add_argument("-p", "--pretty_print", action="store_true",
help="json dump with pretty_print")<|fim▁end|> | logger = logging.getLogger("cli_utils")
|
<|file_name|>path119.py<|end_file_name|><|fim▁begin|>import zstackwoodpecker.test_state as ts_header
TestAction = ts_header.TestAction
def path():
return dict(initial_formation="template4",\
path_list=[[TestAction.delete_volume, "vm1-volume1"], \
[TestAction.reboot_vm, "vm1"], \
[TestAction.create_volume, "volume1", "=scsi"], \<|fim▁hole|> [TestAction.attach_volume, "vm1", "volume1"], \
[TestAction.create_volume_backup, "volume1", "backup1"], \
[TestAction.stop_vm, "vm1"], \
[TestAction.cleanup_ps_cache], \
[TestAction.start_vm, "vm1"], \
[TestAction.create_volume_snapshot, "volume1", 'snapshot1'], \
[TestAction.detach_volume, "volume1"], \
[TestAction.clone_vm, "vm1", "vm2", "=full"], \
[TestAction.attach_volume, "vm1", "volume1"], \
[TestAction.stop_vm, "vm1"], \
[TestAction.use_volume_backup, "backup1"], \
[TestAction.start_vm, "vm1"], \
[TestAction.reboot_vm, "vm1"]])<|fim▁end|> | |
<|file_name|>bitcoin_fa.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="fa" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Litecoin</source>
<translation>در مورد Litecoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Litecoin</b> version</source>
<translation>نسخه Litecoin</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>⏎ ⏎ این نسخه نرم افزار آزمایشی است⏎ ⏎ نرم افزار تحت لیسانس MIT/X11 منتشر شده است. به فایل coping یا آدرس http://www.opensource.org/licenses/mit-license.php. مراجعه شود⏎ ⏎ این محصول شامل نرم افزاری است که با OpenSSL برای استفاده از OpenSSL Toolkit (http://www.openssl.org/) و نرم افزار نوشته شده توسط اریک یانگ ([email protected] ) و UPnP توسط توماس برنارد طراحی شده است.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The Litecoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>فهرست آدرس</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>برای ویرایش آدرس یا بر چسب دو بار کلیک کنید</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>آدرس جدید ایجاد کنید</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>آدرس انتخاب شده در سیستم تخته رسم گیره دار کپی کنید</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>آدرس جدید</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Litecoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>این آدرسها، آدرسهای litecoin شما برای دریافت وجوه هستند. شما ممکن است آدرسهای متفاوت را به هر گیرنده اختصاص دهید که بتوانید مواردی که پرداخت می کنید را پیگیری نمایید</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>کپی آدرس</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>نمایش &کد QR</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Litecoin address</source>
<translation>پیام را برای اثبات آدرس Litecoin خود امضا کنید</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>امضا و پیام</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>آدرس انتخاب شده در سیستم تخته رسم گیره دا حذف</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>داده ها نوارِ جاری را به فایل انتقال دهید</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Litecoin address</source>
<translation>یک پیام را برای حصول اطمینان از ورود به سیستم با آدرس litecoin مشخص، شناسایی کنید</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>شناسایی پیام</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>حذف</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Litecoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>کپی و برچسب گذاری</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>ویرایش</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>آدرس انتخاب شده در سیستم تخته رسم گیره دار کپی کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>خطای صدور</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>تا فایل %1 نمی شود نوشت</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>بر چسب</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>آدرس</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>بدون برچسب</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>دیالوگ Passphrase </translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>وارد عبارت عبور</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>عبارت عبور نو</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>تکرار عبارت عبور نو</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>وارد کنید..&lt;br/&gt عبارت عبور نو در پنجره
10 یا بیشتر کاراکتورهای تصادفی استفاده کنید &lt;b&gt لطفا عبارت عبور</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>رمز بندی پنجره</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>این عملیت نیاز عبارت عبور پنجره شما دارد برای رمز گشایی آن</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>تکرار عبارت عبور نو</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>این عملیت نیاز عبارت عبور شما دارد برای رمز بندی آن</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>رمز بندی پنجره</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>تغییر عبارت عبور</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>عبارت عبور نو و قدیم در پنجره وارد کنید</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>تایید رمز گذاری</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</b>!</source>
<translation>هشدار: اگر wallet رمزگذاری شود و شما passphrase را گم کنید شما همه اطلاعات litecoin را از دست خواهید داد.</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>آیا اطمینان دارید که می خواهید wallet رمزگذاری شود؟</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>هشدار: Caps lock key روشن است</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>تغییر عبارت عبور</translation>
</message>
<message>
<location line="-56"/>
<source>Litecoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your litecoins from being stolen by malware infecting your computer.</source>
<translation>Biticon هم اکنون بسته میشود تا فرایند رمزگذاری را تمام کند. به خاطر داشته باشید که رمزگذاری کیف پولتان نمیتواند به طور کامل بیتیکونهای شما را در برابر دزدیده شدن توسط بدافزارهایی که رایانه شما را آلوده میکنند، محافظت نماید.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>عبارت عبور نو و قدیم در پنجره وارد کنید</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>تنا موفق رمز بندی پنجره ناشی از خطای داخل شد. پنجره شما مرز بندی نشده است</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>عبارت عبور عرضه تطابق نشد</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>نجره رمز گذار شد</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>اموفق رمز بندی پنجر</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>ناموفق رمز بندی پنجره</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>wallet passphrase با موفقیت تغییر یافت</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>امضا و پیام</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>همگام سازی با شبکه ...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>بررسی اجمالی</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>نمای کلی پنجره نشان بده</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&معاملات</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>نمایش تاریخ معاملات</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>ویرایش لیست آدرسها و بر چسب های ذخیره ای</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>نمایش لیست آدرس ها برای در یافت پر داخت ها</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>خروج</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>خروج از برنامه </translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Litecoin</source>
<translation>نمایش اطلاعات در مورد بیتکویین</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>درباره &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>نمایش اطلاعات درباره Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>تنظیمات...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>رمزگذاری wallet</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>پشتیبان گیری از wallet</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>تغییر Passphrase</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Litecoin address</source>
<translation>سکه ها را به آدرس bitocin ارسال کن</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Litecoin</source>
<translation>انتخابهای پیکربندی را برای litecoin اصلاح کن</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>نسخه پیشتیبان wallet را به محل دیگر انتقال دهید</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>عبارت عبور رمز گشایی پنجره تغییر کنید</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>اشکال زدایی از صفحه</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>کنسول اشکال زدایی و تشخیص را باز کنید</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>بازبینی پیام</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Litecoin</source>
<translation>یت کویین </translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>wallet</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Litecoin</source>
<translation>در مورد litecoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&نمایش/ عدم نمایش</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Litecoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Litecoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>فایل</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>تنظیمات</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>کمک</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>نوار ابزار زبانه ها</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>آزمایش شبکه</translation>
</message>
<message>
<location line="+47"/>
<source>Litecoin client</source>
<translation>مشتری Litecoin</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Litecoin network</source>
<translation><numerusform>در صد ارتباطات فعال بیتکویین با شبکه %n</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>تا تاریخ</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>ابتلا به بالا</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>هزینه تراکنش را تایید کنید</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>معامله ارسال شده</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>معامله در یافت شده</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>تاریخ %1
مبلغ%2
نوع %3
آدرس %4</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>مدیریت URI</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Litecoin address or malformed URI parameters.</source>
<translation>URI قابل تحلیل نیست. این خطا ممکن است به دلیل ادرس LITECOIN اشتباه یا پارامترهای اشتباه URI رخ داده باشد</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>زمایش شبکهه</translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>زمایش شبکه</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Litecoin can no longer continue safely and will quit.</source>
<translation>خطا روی داده است. Litecoin نمی تواند بدون مشکل ادامه دهد و باید بسته شود</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>پیام شبکه</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>اصلاح آدرس</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>بر چسب</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>بر چسب با دفتر آدرس ورود مرتبط است</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>آدرس</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>آدرس با دفتر آدرس ورودی مرتبط است. این فقط در مورد آدرسهای ارسال شده است</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>آدرس در یافت نو</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>آدرس ارسال نو</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>اصلاح آدرس در یافت</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>اصلاح آدرس ارسال</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>%1آدرس وارد شده دیگر در دفتر آدرس است</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Litecoin address.</source>
<translation>آدرس وارد شده %1 یک ادرس صحیح litecoin نیست</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>رمز گشایی پنجره امکان پذیر نیست</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>کلید نسل جدید ناموفق است</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Litecoin-Qt</source>
<translation>Litecoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>نسخه</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>ستفاده :</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>انتخابها برای خطوط دستور command line</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>انتخابهای UI </translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>زبان را تنظیم کنید برای مثال "de_DE" (پیش فرض: system locale)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>شروع حد اقل</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>نمایش صفحه splash در STARTUP (پیش فرض:1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>اصلی</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>اصلی</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>دستمزد&پر داخت معامله</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Litecoin after logging in to the system.</source>
<translation>در زمان ورود به سیستم به صورت خودکار litecoin را اجرا کن</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Litecoin on system login</source>
<translation>اجرای litecoin در زمان ورود به سیستم</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>شبکه</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Litecoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>اتوماتیک باز کردن بندر بیتکویین در روتر . این فقط در مواردی می باشد که روتر با کمک یو پ ن پ کار می کند</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>درگاه با استفاده از</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Litecoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>اتصال به شبکه LITECOIN از طریق پراکسی ساکس (برای مثال وقتی از طریق نرم افزار TOR متصل می شوید)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>اتصال با پراکسی SOCKS</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>پراکسی و آی.پی.</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>درس پروکسی</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>درگاه</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>درگاه پراکسی (مثال 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS و نسخه</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>نسخه SOCKS از پراکسی (مثال 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>صفحه</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>tray icon را تنها بعد از کوچک کردن صفحه نمایش بده</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>حد اقل رساندن در جای نوار ابزار ها</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>حد اقل رساندن در جای خروج بر نامه وقتیکه پنجره بسته است.وقتیکه این فعال است برنامه خاموش می شود بعد از انتخاب دستور خاموش در منیو</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>کوچک کردن صفحه در زمان بستن</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>نمایش</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>میانجی کاربر و زبان</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Litecoin.</source>
<translation>زبان میانجی کاربر می تواند در اینجا تنظیم شود. این تنظیمات بعد از شروع دوباره RESTART در LITECOIN اجرایی خواهند بود.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>واحد برای نمایش میزان وجوه در:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>بخش فرعی پیش فرض را برای نمایش میانجی و زمان ارسال سکه ها مشخص و انتخاب نمایید</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Litecoin addresses in the transaction list or not.</source>
<translation>تا آدرسهای bITCOIN در فهرست تراکنش نمایش داده شوند یا نشوند.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>نمایش آدرسها در فهرست تراکنش</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>تایید</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>رد</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>انجام</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>پیش فرض</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>هشدار</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Litecoin.</source>
<translation>این تنظیمات پس از اجرای دوباره Litecoin اعمال می شوند</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>آدرس پراکسی داده شده صحیح نیست</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>تراز</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Litecoin network after a connection is established, but this process has not completed yet.</source>
<translation>اطلاعات نمایش داده شده روزآمد نیستند.wallet شما به صورت خودکار با شبکه litecoin بعد از برقراری اتصال روزآمد می شود اما این فرایند هنوز کامل نشده است.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>راز:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>تایید نشده</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>wallet</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>نابالغ</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>بالانس/تتمه حساب استخراج شده، نابالغ است /تکمیل نشده است</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation>اخرین معاملات&lt</translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>تزار جاری شما</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>تعداد معاملات که تایید شده ولی هنوز در تزار جاری شما بر شمار نرفته است</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>روزآمد نشده</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start litecoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>دیالوگ QR CODE</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>درخواست پرداخت</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>مقدار:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>برچسب:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>پیام</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&ذخیره به عنوان...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>خطا در زمان رمزدار کردن URI در کد QR</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>میزان وجه وارد شده صحیح نیست، لطفا بررسی نمایید</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>URI ذکر شده بسیار طولانی است، متن برچسب/پیام را کوتاه کنید</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>ذخیره کد QR</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>تصاویر با فرمت PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>نام مشتری</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>-</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>نسخه مشتری</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>اطلاعات</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>استفاده از نسخه OPENSSL</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>زمان آغاز STARTUP</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>شبکه</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>تعداد اتصالات</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>در testnetکها</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>زنجیره بلاک</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>تعداد کنونی بلاکها</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>تعداد تخمینی بلاکها</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>زمان آخرین بلاک</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>باز کردن</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>گزینه های command-line</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Litecoin-Qt help message to get a list with possible Litecoin command-line options.</source>
<translation>پیام راهنمای Litecoin-Qt را برای گرفتن فهرست گزینه های command-line نشان بده</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>نمایش</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>کنسول</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>ساخت تاریخ</translation><|fim▁hole|> <source>Litecoin - Debug window</source>
<translation>صفحه اشکال زدایی Litecoin </translation>
</message>
<message>
<location line="+25"/>
<source>Litecoin Core</source>
<translation> هسته Litecoin </translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>فایلِ لاگِ اشکال زدایی</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Litecoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>فایلِ لاگِ اشکال زدایی Litecoin را از دایرکتوری جاری داده ها باز کنید. این عملیات ممکن است برای فایلهای لاگِ حجیم طولانی شود.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>پاکسازی کنسول</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Litecoin RPC console.</source>
<translation>به کنسول Litecoin RPC خوش آمدید</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>دکمه های بالا و پایین برای مرور تاریخچه و Ctrl-L برای پاکسازی صفحه</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>با تایپ عبارت HELP دستورهای در دسترس را مرور خواهید کرد</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>ارسال سکه ها</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>ارسال چندین در یافت ها فورا</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>اضافه کردن دریافت کننده</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>پاک کردن تمام ستونهای تراکنش</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>پاکسازی همه</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>تزار :</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 بتس</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>عملیت دوم تایید کنید</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&;ارسال</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation>(%3) تا <b>%1</b> درصد%2</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>ارسال سکه ها تایید کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation> %1شما متماینید که می خواهید 1% ارسال کنید ؟</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>و</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>آدرس گیرنده نادرست است، لطفا دوباره بررسی کنید.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>مبلغ پر داخت باید از 0 بیشتر باشد </translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>میزان وجه از بالانس/تتمه حساب شما بیشتر است</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>کل میزان وجه از بالانس/تتمه حساب شما بیشتر می شود وقتی %1 هزینه تراکنش نیز به ین میزان افزوده می شود</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>آدرس تکراری یافت شده است، در زمان انجام عملیات به هر آدرس تنها یکبار می توانید اطلاعات ارسال کنید</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>خطا: تراکنش تایید نشد. این پیام زمانی روی می دهد که مقداری از سکه های WALLET شما استفاده شده اند برای مثال اگر شما از WALLET.DAT استفاده کرده اید، ممکن است سکه ها استفاده شده باشند اما در اینجا نمایش داده نشوند</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>تراز</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>A&مبلغ :</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>به&پر داخت :</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>برای آدرس بر پسب وارد کنید که در دفتر آدرس اضافه شود</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&بر چسب </translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>اآدرسن ازدفتر آدرس انتخاب کنید</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>آدرس از تخته رسم گیره دار پست کنید </translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>بر داشتن این در یافت کننده</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Litecoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>آدرس بیتکویین وارد کنید (bijvoorbeeld: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>امضا - امضا کردن /شناسایی یک پیام</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&امضای پیام</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>شما می توانید پیامها را با آدرس خودتان امضا نمایید تا ثابت شود متعلق به شما هستند. مواظب باشید تا چیزی که بدان مطمئن نیستنید را امضا نکنید زیرا حملات فیشینگ در زمان ورود شما به سیستم فریبنده هستند. تنها مواردی را که حاوی اطلاعات دقیق و قابل قبول برای شما هستند را امضا کنید</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>آدرس برای امضا کردن پیام با (برای مثال Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>یک آدرس را از فهرست آدرسها انتخاب کنید</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>آدرس از تخته رسم گیره دار پست کنید </translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>پیامی را که میخواهید امضا کنید در اینجا وارد کنید</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>این امضا را در system clipboard کپی کن</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Litecoin address</source>
<translation>پیام را برای اثبات آدرس LITECOIN خود امضا کنید</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>تنظیم دوباره تمامی فیلدهای پیام</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>پاکسازی همه</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>تایید پیام</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>آدرس/پیام خود را وارد کنید (مطمئن شوید که فاصله بین خطوط، فاصله ها، تب ها و ... را دقیقا کپی می کنید) و سپس امضا کنید تا پیام تایید شود. مراقب باشید که پیام را بیشتر از مطالب درون امضا مطالعه نمایید تا فریب شخص سوم/دزدان اینترنتی را نخورید.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>آدرس برای امضا کردن پیام با (برای مثال Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Litecoin address</source>
<translation>پیام را برای اطمنان از ورود به سیستم با آدرس LITECOIN مشخص خود،تایید کنید</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>تنظیم دوباره تمامی فیلدهای پیام تایید شده</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Litecoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>آدرس بیتکویین وارد کنید (bijvoorbeeld: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>با کلیک بر "امضای پیام" شما یک امضای جدید درست می کنید</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Litecoin signature</source>
<translation>امضای BITOCOIN خود را وارد کنید</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>آدرس وارد شده صحیح نیست</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>اطفا آدرس را بررسی کرده و دوباره امتحان کنید</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>آدرس وارد شده با کلید وارد شده مرتبط نیست</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>قفل کردن wallet انجام نشد</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>کلید شخصی برای آدرس وارد شده در دسترس نیست</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>پیام امضا کردن انجام نشد</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>پیام امضا شد</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>امضا نمی تواند رمزگشایی شود</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>لطفا امضا را بررسی و دوباره تلاش نمایید</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>امضا با تحلیلِ پیام مطابقت ندارد</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>عملیات شناسایی پیام انجام نشد</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>پیام شناسایی شد</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Litecoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>آزمایش شبکه</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>باز کردن تا%1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1 آفلاین</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1 تایید نشده </translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>ایید %1 </translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>وضعیت</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>انتشار از طریق n% گره
انتشار از طریق %n گره</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>تاریخ </translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>منبع</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>تولید شده</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>فرستنده</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>گیرنده</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>آدرس شما</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>برچسب</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>بدهی </translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>بلوغ در n% از بیشتر بلاکها
بلوغ در %n از بیشتر بلاکها</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>غیرقابل قبول</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>اعتبار</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>هزینه تراکنش</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>هزینه خالص</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>پیام</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>نظر</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>شناسه کاربری برای تراکنش</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>سکه های ایجاد شده باید 120 بلاک را قبل از استفاده بالغ کنند. در هنگام ایجاد بلاک، آن بلاک در شبکه منتشر می شود تا به زنجیره بلاکها بپیوندد. اگر در زنجیره قرار نگیرد، پیام وضعیت به غیرقابل قبول تغییر می بپیابد و قابل استفاده نیست. این مورد معمولا زمانی پیش می آید که گره دیگری به طور همزمان بلاکی را با فاصل چند ثانیه ای از شما ایجاد کند.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>اشکال زدایی طلاعات</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>تراکنش</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>درونداد</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>مبلغ</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>صحیح</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>نادرست</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>هنوز با مو فقیت ارسال نشده</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>مشخص نیست </translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>جزییات معاملات</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>در این قاب شیشه توصیف دقیق معامله نشان می شود</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>نوع</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>ایل جدا </translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>مبلغ</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>از شده تا 1%1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>افلایین (%1)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>تایید نشده (%1/%2)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>تایید شده (%1)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>بالانس/تتمه حساب استخراج شده زمانی که %n از بیشتر بلاکها بالغ شدند در دسترس خواهد بود
بالانس/تتمه حساب استخراج شده زمانی که n% از بیشتر بلاکها بالغ شدند در دسترس خواهد بود</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>این بلوک از دیگر گره ها در یافت نشده بدین دلیل شاید قابل قابول نیست</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>تولید شده ولی قبول نشده</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>در یافت با :</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>دریافتی از</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>ارسال به :</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>پر داخت به خودتان</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>استخراج</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(کاربرد ندارد)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>وضعیت معالمه . عرصه که تعداد تایید نشان می دهد</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>تاریخ و ساعت در یافت معامله</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>نوع معاملات</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>آدرس مقصود معاملات </translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>مبلغ از تزار شما خارج یا وارد شده</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>همه</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>امروز</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>این هفته</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>این ماه</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>ماه گذشته</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>امسال</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>محدوده </translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>در یافت با</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>ارسال به</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>به خودتان </translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>استخراج</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>یگر </translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>برای جستوجو نشانی یا برچسب را وارد کنید</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>حد اقل مبلغ </translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>کپی آدرس </translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>کپی بر چسب</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>روگرفت مقدار</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>اصلاح بر چسب</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>جزئیات تراکنش را نمایش بده</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>صادرات تاریخ معامله</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma فایل جدا </translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>تایید شده</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>تاریخ </translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>نوع </translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>ر چسب</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>ایل جدا </translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>مبلغ</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>آی دی</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>خطای صادرت</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>تا فایل %1 نمی شود نوشت</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>>محدوده</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>به</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>ارسال سکه ها</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>داده ها نوارِ جاری را به فایل انتقال دهید</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Litecoin version</source>
<translation>سخه بیتکویین</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>ستفاده :</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or litecoind</source>
<translation>ارسال فرمان به سرور یا باتکویین</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>لیست فومان ها</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>کمک برای فرمان </translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>تنظیمات</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: litecoin.conf)</source>
<translation>(: litecoin.confپیش فرض: )فایل تنظیمی خاص </translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: litecoind.pid)</source>
<translation>(litecoind.pidپیش فرض : ) فایل پید خاص</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>دایرکتور اطلاعاتی خاص</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>سایز کَش بانک داده را بر حسب مگابایت تنظیم کنید (پیش فرض:25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 67890 or testnet: 67891)</source>
<translation>برای اتصالات به <port> (پیشفرض: 67890 یا تستنت: 67891) گوش کنید</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>حداکثر <n> اتصال با همکاران برقرار داشته باشید (پیشفرض: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>اتصال به گره برای دریافت آدرسهای قرینه و قطع اتصال</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>آدرس عمومی خود را ذکر کنید</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>آستانه برای قطع ارتباط با همکاران بدرفتار (پیشفرض: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>مدت زمان به ثانیه برای جلوگیری از همکاران بدرفتار برای اتصال دوباره (پیشفرض: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>در زمان تنظیم درگاه RPX %u در فهرست کردن %s اشکالی رخ داده است</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 12345 or testnet: 12341)</source>
<translation>( 12345پیش فرض :) &lt;poort&gt; JSON-RPC شنوایی برای ارتباطات</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>JSON-RPC قابل فرمانها و</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>اجرای در پس زمینه به عنوان شبح و قبول فرمان ها</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>استفاده شبکه آزمایش</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>پذیرش اتصالات از بیرون (پیش فرض:1 بدون پراکسی یا اتصال)</translation>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=litecoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Litecoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Litecoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>حجم حداکثر تراکنشهای با/کم اهمیت را به بایت تنظیم کنید (پیش فرض:27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>هشدار:paytxfee بسیار بالا تعریف شده است! این هزینه تراکنش است که باید در زمان ارسال تراکنش بپردازید</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>هشدار: تراکنش نمایش داده شده ممکن است صحیح نباشد! شما/یا یکی از گره ها به روزآمد سازی نیاز دارید </translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Litecoin will not work properly.</source>
<translation>هشدار: لطفا زمان و تاریخ رایانه خود را تصحیح نمایید! اگر ساعت رایانه شما اشتباه باشد litecoin ممکن است صحیح کار نکند</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>بستن گزینه ایجاد</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>تنها در گره (های) مشخص شده متصل شوید</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>آدرس آی.پی. خود را شناسایی کنید (پیش فرض:1 در زمان when listening وno -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>شنیدن هر گونه درگاه انجام پذیر نیست. ازlisten=0 برای اینکار استفاده کیند.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>قرینه ها را برای جستجوی DNS بیاب (پیش فرض: 1 مگر در زمان اتصال)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>آدرس نرم افزار تور غلط است %s</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>حداکثر بافر دریافت شده بر اساس اتصال <n>* 1000 بایت (پیش فرض:5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>حداکثر بافر دریافت شده بر اساس اتصال <n>* 1000 بایت (پیش فرض:1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>تنها =به گره ها در شبکه متصا شوید <net> (IPv4, IPv6 or Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>برونداد اطلاعات اشکال زدایی اضافی. گزینه های اشکال زدایی دیگر رفع شدند</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>برونداد اطلاعات اشکال زدایی اضافی برای شبکه</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>به خروجی اشکالزدایی برچسب زمان بزنید</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Litecoin Wiki for SSL setup instructions)</source>
<translation>گزینه ssl (به ویکیlitecoin برای راهنمای راه اندازی ssl مراجعه شود)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>نسخه ای از پراکسی ساکس را برای استفاده انتخاب کنید (4-5 پیش فرض:5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>اطلاعات ردگیری/اشکالزدایی را به جای فایل لاگ اشکالزدایی به کنسول بفرستید</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>اطلاعات ردگیری/اشکالزدایی را به اشکالزدا بفرستید</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>حداکثر سایز بلاک بر اساس بایت تنظیم شود (پیش فرض: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>حداقل سایز بلاک بر اساس بایت تنظیم شود (پیش فرض: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>فایل debug.log را در startup مشتری کوچک کن (پیش فرض:1 اگر اشکال زدایی روی نداد)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>(میلی ثانیه )فاصله ارتباط خاص</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>از UPnP برای شناسایی درگاه شنیداری استفاده کنید (پیش فرض:0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>از UPnP برای شناسایی درگاه شنیداری استفاده کنید (پیش فرض:1 در زمان شنیدن)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>برای دستیابی به سرویس مخفیانه نرم افزار تور از پراکسی استفاده کنید (پیش فرض:same as -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>JSON-RPC شناسه برای ارتباطات</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>هشدار: این نسخه قدیمی است، روزآمدسازی مورد نیاز است</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>JSON-RPC عبارت عبور برای ارتباطات</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>از آدرس آی پی خاص JSON-RPC قبول ارتباطات</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>(127.0.0.1پیش فرض: ) &lt;ip&gt; دادن فرمانها برای استفاده گره ها روی</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>زمانی که بهترین بلاک تغییر کرد، دستور را اجرا کن (%s در cmd با block hash جایگزین شده است)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>wallet را به جدیدترین فرمت روزآمد کنید</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation> (100پیش فرض:)&lt;n&gt; گذاشتن اندازه کلید روی </translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>اسکان مجدد زنجیر بلوکها برای گم والت معامله</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>JSON-RPCبرای ارتباطات استفاده کنید OpenSSL (https)</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation> (server.certپیش فرض: )گواهی نامه سرور</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>(server.pemپیش فرض: ) کلید خصوصی سرور</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>رمز های قابل قبول( TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>پیام کمکی</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>امکان اتصال به %s از این رایانه وجود ندارد ( bind returned error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>اتصال از طریق پراکسی ساکس</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>به DNS اجازه بده تا برای addnode ، seednode و اتصال جستجو کند</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>بار گیری آدرس ها</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>خطا در بارگیری wallet.dat: کیف پول خراب شده است</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Litecoin</source>
<translation>خطا در بارگیری wallet.dat: کیف پول به ویرایش جدیدتری از Biticon نیاز دارد</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Litecoin to complete</source>
<translation>سلام</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>خطا در بارگیری wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>آدرس پراکسی اشتباه %s</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>شبکه مشخص شده غیرقابل شناسایی در onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>نسخه پراکسی ساکس غیرقابل شناسایی درخواست شده است: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>آدرس قابل اتصال- شناسایی نیست %s</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>آدرس خارجی قابل اتصال- شناسایی نیست %s</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>میزان وجه اشتباه برای paytxfee=<میزان وجه>: %s</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>میزان وجه اشتباه</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>بود جه نا کافی </translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>بار گیری شاخص بلوک</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>به اتصال یک گره اضافه کنید و اتصال را باز نگاه دارید</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Litecoin is probably already running.</source>
<translation>اتصال به %s از این رایانه امکان پذیر نیست. Litecoin احتمالا در حال اجراست.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>پر داجت برای هر کیلو بیت برای اضافه به معامله ارسال</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>بار گیری والت</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>امکان تنزل نسخه در wallet وجود ندارد</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>آدرس پیش فرض قابل ذخیره نیست</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>اسکان مجدد</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>بار گیری انجام شده است</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>برای استفاده از %s از انتخابات</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>خطا</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>%s، شما باید یک rpcpassword را در فایل پیکربندی تنظیم کنید :⏎%s⏎ اگر فایل ایجاد نشد، یک فایل فقط متنی ایجاد کنید.
</translation>
</message>
</context>
</TS><|fim▁end|> | </message>
<message>
<location line="-104"/> |
<|file_name|>ir_fields_converter.py<|end_file_name|><|fim▁begin|># Copyright 2016-2017 Jairo Llopis <[email protected]>
# Copyright 2016 Tecnativa - Vicent Cubells
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from lxml import etree, html
from odoo import api, models
_logger = logging.getLogger(__name__)
class IrFieldsConverter(models.AbstractModel):
_inherit = "ir.fields.converter"
@api.model
def text_from_html(self, html_content, max_words=None, max_chars=None,
ellipsis=u"…", fail=False):
"""Extract text from an HTML field in a generator.
:param str html_content:
HTML contents from where to extract the text.
:param int max_words:
Maximum amount of words allowed in the resulting string.
:param int max_chars:
Maximum amount of characters allowed in the resulting string. If
you apply this limit, beware that the last word could get cut in an
unexpected place.
:param str ellipsis:
Character(s) to be appended to the end of the resulting string if
it gets truncated after applying limits set in :param:`max_words`
or :param:`max_chars`. If you want nothing applied, just set an
empty string.
:param bool fail:
If ``True``, exceptions will be raised. Otherwise, an empty string
will be returned on failure.
"""
# Parse HTML
try:
doc = html.fromstring(html_content)
except (TypeError, etree.XMLSyntaxError, etree.ParserError):
if fail:
raise
else:
_logger.exception("Failure parsing this HTML:\n%s",<|fim▁hole|> # Get words
words = u"".join(doc.xpath("//text()")).split()
# Truncate words
suffix = max_words and len(words) > max_words
if max_words:
words = words[:max_words]
# Get text
text = u" ".join(words)
# Truncate text
suffix = suffix or max_chars and len(text) > max_chars
if max_chars:
text = text[:max_chars - (len(ellipsis) if suffix else 0)].strip()
# Append ellipsis if needed
if suffix:
text += ellipsis
return text<|fim▁end|> | html_content)
return ""
|
<|file_name|>bounding_box.py<|end_file_name|><|fim▁begin|>from model import User
from geo.geomodel import geotypes
def get(handler, response):
lat1 = handler.request.get('lat1')<|fim▁hole|> lon1 = handler.request.get('lng1')
lat2 = handler.request.get('lat2')
lon2 = handler.request.get('lng2')
response.users = User.bounding_box_fetch(
User.all(),
geotypes.Box(float(lat1),float(lon2),float(lat2),float(lon1)),
)<|fim▁end|> | |
<|file_name|>testifacecache.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
from basetest import BaseTest
import sys, tempfile, os, time
import unittest
import data
sys.path.insert(0, '..')
from zeroinstall.injector import model, gpg, trust
from zeroinstall.injector.namespaces import config_site
from zeroinstall.injector.iface_cache import PendingFeed
from zeroinstall.support import basedir
class TestIfaceCache(BaseTest):
def testList(self):
iface_cache = self.config.iface_cache
self.assertEquals([], iface_cache.list_all_interfaces())
iface_dir = basedir.save_cache_path(config_site, 'interfaces')
file(os.path.join(iface_dir, 'http%3a%2f%2ffoo'), 'w').close()
self.assertEquals(['http://foo'],
iface_cache.list_all_interfaces())
# TODO: test overrides
def testCheckSigned(self):
iface_cache = self.config.iface_cache
trust.trust_db.trust_key(
'92429807C9853C0744A68B9AAE07828059A53CC1')
feed_url = 'http://foo'
src = tempfile.TemporaryFile()
# Unsigned
src.write("hello")
src.flush()
src.seek(0)
try:
PendingFeed(feed_url, src)
assert 0
except model.SafeException:
pass
stream = tempfile.TemporaryFile()
stream.write(data.thomas_key)
stream.seek(0)
gpg.import_key(stream)
# Signed
src.seek(0)
src.write(data.foo_signed_xml)
src.flush()
src.seek(0)
pending = PendingFeed(feed_url, src)
assert iface_cache.update_feed_if_trusted(feed_url, pending.sigs, pending.new_xml)
self.assertEquals(['http://foo'],
iface_cache.list_all_interfaces())
feed = iface_cache.get_feed(feed_url)
self.assertEquals(1154850229, feed.last_modified)
def testXMLupdate(self):<|fim▁hole|> stream = tempfile.TemporaryFile()
stream.write(data.thomas_key)
stream.seek(0)
gpg.import_key(stream)
iface = iface_cache.get_interface('http://foo')
src = tempfile.TemporaryFile()
src.write(data.foo_signed_xml)
src.seek(0)
pending = PendingFeed(iface.uri, src)
assert iface_cache.update_feed_if_trusted(iface.uri, pending.sigs, pending.new_xml)
iface_cache.__init__()
feed = iface_cache.get_feed('http://foo')
assert feed.last_modified == 1154850229
# mtimes are unreliable because copying often changes them -
# check that we extract the time from the signature when upgrading
upstream_dir = basedir.save_cache_path(config_site, 'interfaces')
cached = os.path.join(upstream_dir, model.escape(feed.url))
os.utime(cached, None)
iface_cache.__init__()
feed = iface_cache.get_feed('http://foo')
assert feed.last_modified > 1154850229
src = tempfile.TemporaryFile()
src.write(data.new_foo_signed_xml)
src.seek(0)
pending = PendingFeed(feed.url, src)
assert iface_cache.update_feed_if_trusted(feed.url, pending.sigs, pending.new_xml)
# Can't 'update' to an older copy
src = tempfile.TemporaryFile()
src.write(data.foo_signed_xml)
src.seek(0)
try:
pending = PendingFeed(feed.url, src)
assert iface_cache.update_feed_if_trusted(feed.url, pending.sigs, pending.new_xml)
assert 0
except model.SafeException:
pass
def testTimes(self):
iface_cache = self.config.iface_cache
stream = tempfile.TemporaryFile()
stream.write(data.thomas_key)
stream.seek(0)
gpg.import_key(stream)
upstream_dir = basedir.save_cache_path(config_site, 'interfaces')
cached = os.path.join(upstream_dir, model.escape('http://foo'))
stream = file(cached, 'w')
stream.write(data.foo_signed_xml)
stream.close()
signed = iface_cache._get_signature_date('http://foo')
assert signed == None
trust.trust_db.trust_key(
'92429807C9853C0744A68B9AAE07828059A53CC1')
signed = iface_cache._get_signature_date('http://foo')
assert signed == 1154850229
stream = file(cached, 'w+')
stream.seek(0)
stream.write('Hello')
stream.close()
# When the signature is invalid, we just return None.
# This is because versions < 0.22 used to corrupt the signatue
# by adding an attribute to the XML
signed = iface_cache._get_signature_date('http://foo')
assert signed == None
def testCheckAttempt(self):
iface_cache = self.config.iface_cache
self.assertEquals(None, iface_cache.get_last_check_attempt("http://foo/bar.xml"))
start_time = time.time() - 5 # Seems to be some odd rounding here
iface_cache.mark_as_checking("http://foo/bar.xml")
last_check = iface_cache.get_last_check_attempt("http://foo/bar.xml")
assert last_check is not None
assert last_check >= start_time, (last_check, start_time)
self.assertEquals(None, iface_cache.get_last_check_attempt("http://foo/bar2.xml"))
if __name__ == '__main__':
unittest.main()<|fim▁end|> | iface_cache = self.config.iface_cache
trust.trust_db.trust_key(
'92429807C9853C0744A68B9AAE07828059A53CC1') |
<|file_name|>login.service.ts<|end_file_name|><|fim▁begin|>import { Injectable } from '@angular/core';
import { JhiLanguageService } from 'ng-jhipster';
<|fim▁hole|>export class LoginService {
constructor(
private languageService: JhiLanguageService,
private principal: Principal,
private authServerProvider: AuthServerProvider
) {}
login(credentials, callback?) {
const cb = callback || function() {};
return new Promise((resolve, reject) => {
this.authServerProvider.login(credentials).subscribe((data) => {
this.principal.identity(true).then((account) => {
// After the login the language will be changed to
// the language selected by the user during his registration
if (account !== null) {
this.languageService.changeLanguage(account.langKey);
}
resolve(data);
});
return cb();
}, (err) => {
this.logout();
reject(err);
return cb(err);
});
});
}
logout() {
this.authServerProvider.logout().subscribe();
this.principal.authenticate(null);
}
}<|fim▁end|> | import { Principal } from '../auth/principal.service';
import { AuthServerProvider } from '../auth/auth-jwt.service';
@Injectable() |
<|file_name|>test_ansiblegate.py<|end_file_name|><|fim▁begin|>import pytest
pytestmark = [
pytest.mark.skip_on_windows(reason="Not supported on Windows"),
pytest.mark.skip_if_binaries_missing(
"ansible",
"ansible-doc",
"ansible-playbook",
check_all=True,
reason="ansible is not installed",
),
]
@pytest.fixture
def ansible_ping_func(modules):
if "ansible.system.ping" in modules:
# we need to go by getattr() because salt's loader will try to find "system" in the dictionary and fail
# The ansible hack injects, in this case, "system.ping" as an attribute to the loaded module
return getattr(modules.ansible, "system.ping")
if "ansible.ping" in modules:
# Ansible >= 2.10
return modules.ansible.ping
pytest.fail("Where is the ping function these days in Ansible?!")
def test_ansible_functions_loaded(ansible_ping_func):
"""
Test that the ansible functions are actually loaded
"""
ret = ansible_ping_func()
assert ret == {"ping": "pong"}
def test_passing_data_to_ansible_modules(ansible_ping_func):
"""<|fim▁hole|> expected = "foobar"
ret = ansible_ping_func(data=expected)
assert ret == {"ping": expected}<|fim▁end|> | Test that the ansible functions are actually loaded
""" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.