prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>footerDirective.js<|end_file_name|><|fim▁begin|>module.exports = function () {
return {
templateUrl : './shared/partials/footer/directives/footer.html',
controller: require('./footerCtrl'),
restrict: 'E',
scope: {}<|fim▁hole|>};<|fim▁end|>
|
};
|
<|file_name|>config.rs<|end_file_name|><|fim▁begin|>//! Configuration module.
//!
//! Handles and configures the initial settings and variables needed to run the program.
use std::{
cmp::{Ordering, PartialOrd},
collections::{btree_set::Iter, BTreeSet},
convert::From,
fs, i64,
path::{Path, PathBuf},
slice::Iter as VecIter,
str::FromStr,
usize,
};
use clap::ArgMatches;
use colored::Colorize;
use failure::{format_err, Error, ResultExt};
use num_cpus;
use serde::{de, Deserialize, Deserializer};
use toml::{self, value::Value};
use crate::{criticality::Criticality, print_warning, static_analysis::manifest};
/// Config structure.
///
/// Contains configuration related fields. It is used for storing the configuration parameters and
/// checking their values. Implements the `Default` trait.
#[derive(Debug, Deserialize)]
#[serde(default)]
pub struct Config {
/// Application packages to analyze.
app_packages: Vec<PathBuf>,
/// Boolean to represent `--verbose` mode.
verbose: bool,
/// Boolean to represent `--quiet` mode.
quiet: bool,
/// Boolean to represent overall `--force` mode.
overall_force: bool,
/// Boolean to represent current `--force` mode.
force: bool,
/// Boolean to represent `--bench` mode.
bench: bool,
/// Boolean to represent `--open` mode.
open: bool,
/// Boolean to represent `--json` mode.
json: bool,
/// Boolean to represent `--html` mode.
html: bool,
/// Minimum criticality to analyze
min_criticality: Criticality,
/// Number of threads.
#[serde(deserialize_with = "ConfigDeserializer::deserialize_threads")]
threads: usize,
/// Folder where the applications are stored.
downloads_folder: PathBuf,
/// Folder with files from analyzed applications.
dist_folder: PathBuf,
/// Folder to store the results of analysis.
results_folder: PathBuf,
/// Path to the _Dex2jar_ binaries.
dex2jar_folder: PathBuf,
/// Path to the _JD\_CMD_ binary.
jd_cmd_file: PathBuf,
/// Path to the `rules.json` file.
rules_json: PathBuf,
/// The folder where the templates are stored.
templates_folder: PathBuf,
/// The name of the template to use.
template: String,
/// Represents an unknown permission.
#[serde(deserialize_with = "ConfigDeserializer::deserialize_unknown_permission")]
unknown_permission: (Criticality, String),
/// List of permissions to analyze.
permissions: BTreeSet<Permission>,
/// Checker for the loaded files
loaded_files: Vec<PathBuf>,
}
/// Helper struct that handles some specific field deserialization for `Config` struct
struct ConfigDeserializer;
/// `Criticality` and `String` tuple, used to shorten some return types.
type CriticalityString = (Criticality, String);
impl ConfigDeserializer {
/// Deserialize `thread` field and checks that is on the proper bounds
pub fn deserialize_threads<'de, D>(de: D) -> Result<usize, D::Error>
where
D: Deserializer<'de>,
{
let deserialize_result: Value = Deserialize::deserialize(de)?;
#[allow(clippy::use_debug)]
match deserialize_result {
Value::Integer(threads) => {
if threads > 0 && threads <= {
// TODO: change it for compile-time check.
if (usize::max_value() as i64) < 0 {
// 64-bit machine
i64::max_value()
} else {
// Smaller than 64 bit words.
usize::max_value() as i64
}
} {
Ok(threads as usize)
} else {
Err(de::Error::custom("threads is not in the valid range"))
}
}
_ => Err(de::Error::custom(format!(
"unexpected value: {:?}",
deserialize_result
))),
}
}
/// Deserialize `unknown_permission` field
pub fn deserialize_unknown_permission<'de, D>(de: D) -> Result<CriticalityString, D::Error>
where
D: Deserializer<'de>,
{
let deserialize_result: Value = Deserialize::deserialize(de)?;
#[allow(clippy::use_debug)]
match deserialize_result {
Value::Table(ref table) => {
let criticality_str = table
.get("criticality")
.and_then(|v| v.as_str())
.ok_or_else(|| {
de::Error::custom("criticality field not found for unknown permission")
})?;
let string = table
.get("description")
.and_then(|v| v.as_str())
.ok_or_else(|| {
de::Error::custom("description field not found for unknown permission")
})?;
let criticality = Criticality::from_str(criticality_str).map_err(|_| {
de::Error::custom(format!(
"invalid `criticality` value found: {}",
criticality_str
))
})?;
Ok((criticality, string.to_string()))
}
_ => Err(de::Error::custom(format!(
"Unexpected value: {:?}",
deserialize_result
))),
}
}
}
impl Config {
/// Creates a new `Config` struct.
pub fn from_file<P: AsRef<Path>>(config_path: P) -> Result<Self, Error> {
let cfg_result: Result<Self, Error> = fs::read_to_string(config_path.as_ref())
.context("could not open configuration file")
.map_err(Error::from)
.and_then(|file_content| {
Ok(toml::from_str(&file_content).context(format_err!(
"could not decode config file: {}, using default",
config_path.as_ref().to_string_lossy()
))?)
})
.and_then(|mut new_config: Self| {
new_config
.loaded_files
.push(config_path.as_ref().to_path_buf());
Ok(new_config)
});
cfg_result
}
/// Decorates the loaded config with the given flags from CLI
pub fn decorate_with_cli(&mut self, cli: &ArgMatches<'static>) -> Result<(), Error> {
self.set_options(cli);
self.verbose = cli.is_present("verbose");
self.quiet = cli.is_present("quiet");
self.overall_force = cli.is_present("force");
self.force = self.overall_force;
self.bench = cli.is_present("bench");
self.open = cli.is_present("open");
self.json = cli.is_present("json");
self.html = cli.is_present("html");
if cli.is_present("test-all") {
self.read_apks()
.context("error loading all the downloaded APKs")?;
} else {
self.add_app_package(
cli.value_of("package")
.expect("expected a value for the package CLI attribute"),
);
}
Ok(())
}
/// Modifies the options from the CLI.
fn set_options(&mut self, cli: &ArgMatches<'static>) {
if let Some(min_criticality) = cli.value_of("min_criticality") {
if let Ok(m) = min_criticality.parse() {
self.min_criticality = m;
} else {
print_warning(format!(
"The min_criticality option must be one of {}, {}, {}, {} or {}.\nUsing \
default.",
"warning".italic(),
"low".italic(),
"medium".italic(),
"high".italic(),
"critical".italic()
));
}
}
if let Some(threads) = cli.value_of("threads") {
match threads.parse() {
Ok(t) if t > 0_usize => {
self.threads = t;
}
_ => {
print_warning(format!(
"The threads option must be an integer between 1 and {}",
usize::max_value()
));
}
}
}
if let Some(downloads_folder) = cli.value_of("downloads") {
self.downloads_folder = PathBuf::from(downloads_folder);
}
if let Some(dist_folder) = cli.value_of("dist") {
self.dist_folder = PathBuf::from(dist_folder);
}
if let Some(results_folder) = cli.value_of("results") {
self.results_folder = PathBuf::from(results_folder);
}
if let Some(dex2jar_folder) = cli.value_of("dex2jar") {
self.dex2jar_folder = PathBuf::from(dex2jar_folder);
}
if let Some(jd_cmd_file) = cli.value_of("jd-cmd") {
self.jd_cmd_file = PathBuf::from(jd_cmd_file);
}
if let Some(template_name) = cli.value_of("template") {
self.template = template_name.to_owned();
}
if let Some(rules_json) = cli.value_of("rules") {
self.rules_json = PathBuf::from(rules_json);
}
}
/// Reads all the apk files in the downloads folder and adds them to the configuration.
fn read_apks(&mut self) -> Result<(), Error> {
let iter = fs::read_dir(&self.downloads_folder)?;
for entry in iter {
match entry {
Ok(entry) => {
if let Some(ext) = entry.path().extension() {
if ext == "apk" {
self.add_app_package(
entry
.path()
.file_stem()
.expect("expected file stem for apk file")
.to_string_lossy()
.into_owned(),
)
}
}
}
Err(e) => {
print_warning(format!(
"there was an error when reading the downloads folder: {}",
e
));
}
}
}
Ok(())
}
/// Checks if all the needed folders and files exist.
pub fn check(&self) -> bool {
let check = self.downloads_folder.exists()
&& self.dex2jar_folder.exists()
&& self.jd_cmd_file.exists()
&& self.template_path().exists()
&& self.rules_json.exists();
if check {
for package in &self.app_packages {
if !package.exists() {
return false;
}
}
true
} else {
false
}
}
/// Returns the folders and files that do not exist.
pub fn errors(&self) -> Vec<String> {
let mut errors = Vec::new();
if !self.downloads_folder.exists() {
errors.push(format!(
"The downloads folder `{}` does not exist",
self.downloads_folder.display()
));
}
for package in &self.app_packages {
if !package.exists() {
errors.push(format!(
"The APK file `{}` does not exist",
package.display()
));
}
}
if !self.dex2jar_folder.exists() {
errors.push(format!(
"The Dex2Jar folder `{}` does not exist",
self.dex2jar_folder.display()
));
}
if !self.jd_cmd_file.exists() {
errors.push(format!(
"The jd-cmd file `{}` does not exist",
self.jd_cmd_file.display()
));
}
if !self.templates_folder.exists() {
errors.push(format!(
"the templates folder `{}` does not exist",
self.templates_folder.display()
));
}
if !self.template_path().exists() {
errors.push(format!(
"the template `{}` does not exist in `{}`",
self.template,
self.templates_folder.display()
));
}
if !self.rules_json.exists() {
errors.push(format!(
"The `{}` rule file does not exist",
self.rules_json.display()
));
}
errors
}
/// Returns the currently loaded config files.
pub fn loaded_config_files(&self) -> VecIter<PathBuf> {
self.loaded_files.iter()
}
/// Returns the app package.
pub fn app_packages(&self) -> Vec<PathBuf> {
self.app_packages.clone()
}
/// Adds a package to check.
pub(crate) fn add_app_package<P: AsRef<Path>>(&mut self, app_package: P) {
let mut package_path = self.downloads_folder.join(app_package);
if package_path.extension().is_none() {
let updated = package_path.set_extension("apk");
debug_assert!(
updated,
"did not update package path extension, no file name"
);
} else if package_path
.extension()
.expect("expected extension in package path")
!= "apk"
{
let mut file_name = package_path
.file_name()
.expect("expected file name in package path")
.to_string_lossy()
.into_owned();
file_name.push_str(".apk");
package_path.set_file_name(file_name);
}
self.app_packages.push(package_path);
}
/// Returns true if the application is running in `--verbose` mode, false otherwise.
pub fn is_verbose(&self) -> bool {
self.verbose
}
/// Returns true if the application is running in `--quiet` mode, false otherwise.
pub fn is_quiet(&self) -> bool {
self.quiet
}
/// Returns true if the application is running in `--force` mode, false otherwise.
pub fn is_force(&self) -> bool {
self.force
}
/// Sets the application to force recreate the analysis files and results temporarily.
pub fn set_force(&mut self) {
self.force = true;
}
/// Resets the `--force` option, so that it gets reset to the configured force option.
pub fn reset_force(&mut self) {
self.force = self.overall_force
}
/// Returns true if the application is running in `--bench` mode, false otherwise.
pub fn is_bench(&self) -> bool {
self.bench
}
/// Returns true if the application is running in `--open` mode, false otherwise.
pub fn is_open(&self) -> bool {
self.open
}
/// Returns true if the application has to generate result in JSON format.
pub fn has_to_generate_json(&self) -> bool {
self.json
}
/// Returns true if the application has to generate result in HTML format.
pub fn has_to_generate_html(&self) -> bool {
!self.json || self.html
}
/// Returns the `min_criticality` field.
pub fn min_criticality(&self) -> Criticality {
self.min_criticality
}
/// Returns the `threads` field.
pub fn threads(&self) -> usize {
self.threads
}
/// Returns the path to the `dist_folder`.
pub fn dist_folder(&self) -> &Path {
&self.dist_folder
}
/// Returns the path to the `results_folder`.
pub fn results_folder(&self) -> &Path {
&self.results_folder
}
/// Returns the path to the `dex2jar_folder`.
pub fn dex2jar_folder(&self) -> &Path {
&self.dex2jar_folder
}
/// Returns the path to the `jd_cmd_file`.
pub fn jd_cmd_file(&self) -> &Path {
&self.jd_cmd_file
}
/// Gets the path to the template.
pub fn template_path(&self) -> PathBuf {
self.templates_folder.join(&self.template)
}
/// Gets the path to the templates folder.
pub fn templates_folder(&self) -> &Path {
&self.templates_folder
}
/// Gets the name of the template.
pub fn template_name(&self) -> &str {
&self.template
}
/// Returns the path to the `rules_json`.
pub fn rules_json(&self) -> &Path {
&self.rules_json
}
/// Returns the criticality of the `unknown_permission` field.
pub fn unknown_permission_criticality(&self) -> Criticality {
self.unknown_permission.0
}
/// Returns the description of the `unknown_permission` field.
pub fn unknown_permission_description(&self) -> &str {
self.unknown_permission.1.as_str()
}
/// Returns the loaded `permissions`.
pub fn permissions(&self) -> Iter<Permission> {
self.permissions.iter()
}
/// Returns the default `Config` struct.
fn local_default() -> Self {
Self {
app_packages: Vec::new(),
verbose: false,
quiet: false,
overall_force: false,
force: false,
bench: false,
open: false,
json: false,
html: false,
threads: num_cpus::get(),
min_criticality: Criticality::Warning,
downloads_folder: PathBuf::from("."),
dist_folder: PathBuf::from("dist"),
results_folder: PathBuf::from("results"),
dex2jar_folder: Path::new("vendor").join("dex2jar-2.1-SNAPSHOT"),
jd_cmd_file: Path::new("vendor").join("jd-cmd.jar"),
templates_folder: PathBuf::from("templates"),
template: String::from("super"),
rules_json: PathBuf::from("rules.json"),
unknown_permission: (
Criticality::Low,
String::from(
"Even if the application can create its own \
permissions, it's discouraged, since it can \
lead to misunderstanding between developers.",
),
),
permissions: BTreeSet::new(),
loaded_files: Vec::new(),
}
}
}
impl Default for Config {
/// Creates the default `Config` struct in Unix systems.
#[cfg(target_family = "unix")]
fn default() -> Self {
let mut config = Self::local_default();
let etc_rules = PathBuf::from("/etc/super-analyzer/rules.json");
if etc_rules.exists() {
config.rules_json = etc_rules;
}
let share_path = Path::new(if cfg!(target_os = "macos") {
"/usr/local/super-analyzer"
} else {
"/usr/share/super-analyzer"
});
if share_path.exists() {
config.dex2jar_folder = share_path.join("vendor/dex2jar-2.1-SNAPSHOT");
config.jd_cmd_file = share_path.join("vendor/jd-cmd.jar");
config.templates_folder = share_path.join("templates");
}
config
}
/// Creates the default `Config` struct in Windows systems.
#[cfg(target_family = "windows")]
fn default() -> Self {
Config::local_default()
}
}
/// Vulnerable permission configuration information.
///
/// Represents a Permission with all its fields. Implements the `PartialEq` and `PartialOrd`
/// traits.
#[derive(Debug, Ord, Eq, Deserialize)]
pub struct Permission {
/// Permission name.
name: manifest::Permission,
/// Permission criticality.
criticality: Criticality,
/// Permission label.
label: String,
/// Permission description.
description: String,
}
impl PartialEq for Permission {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
}
}
impl PartialOrd for Permission {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.name.cmp(&other.name))
}
}
impl Permission {
/// Returns the enum that represents the `name`.
pub fn name(&self) -> manifest::Permission {
self.name
}
/// Returns the permission's `criticality`.
pub fn criticality(&self) -> Criticality {
self.criticality
}
/// Returns the permission's `label`.
pub fn label(&self) -> &str {
self.label.as_str()
}
/// Returns the permission's `description`.
pub fn description(&self) -> &str {
self.description.as_str()
}
}
/// Test module for the configuration.
#[cfg(test)]
mod tests {
use std::{
fs,
path::{Path, PathBuf},
};
use num_cpus;
use super::Config;
use crate::{criticality::Criticality, static_analysis::manifest};
/// Test for the default configuration function.
#[allow(clippy::cyclomatic_complexity)]
#[test]
fn it_config() {
// Create config object.
let mut config = Config::default();
// Check that the properties of the config object are correct.
assert!(config.app_packages().is_empty());
assert!(!config.is_verbose());
assert!(!config.is_quiet());
assert!(!config.is_force());
assert!(!config.is_bench());
assert!(!config.is_open());
assert_eq!(config.threads(), num_cpus::get());
assert_eq!(config.downloads_folder, Path::new("."));
assert_eq!(config.dist_folder(), Path::new("dist"));
assert_eq!(config.results_folder(), Path::new("results"));
assert_eq!(config.template_name(), "super");
let share_path = Path::new(if cfg!(target_os = "macos") {
"/usr/local/super-analyzer"
} else if cfg!(target_family = "windows") {
""
} else {
"/usr/share/super-analyzer"
});
let share_path = if share_path.exists() {
share_path
} else {
Path::new("")
};
assert_eq!(
config.dex2jar_folder(),
share_path.join("vendor").join("dex2jar-2.1-SNAPSHOT")
);
assert_eq!(
config.jd_cmd_file(),
share_path.join("vendor").join("jd-cmd.jar")
);
assert_eq!(config.templates_folder(), share_path.join("templates"));
assert_eq!(
config.template_path(),
share_path.join("templates").join("super")
);
if cfg!(target_family = "unix") && Path::new("/etc/super-analyzer/rules.json").exists() {
assert_eq!(
config.rules_json(),<|fim▁hole|> } else {
assert_eq!(config.rules_json(), Path::new("rules.json"));
}
assert_eq!(config.unknown_permission_criticality(), Criticality::Low);
assert_eq!(
config.unknown_permission_description(),
"Even if the application can create its own permissions, it's discouraged, \
since it can lead to misunderstanding between developers."
);
assert_eq!(config.permissions().next(), None);
if !config.downloads_folder.exists() {
fs::create_dir(&config.downloads_folder).unwrap();
}
if !config.dist_folder().exists() {
fs::create_dir(config.dist_folder()).unwrap();
}
if !config.results_folder().exists() {
fs::create_dir(config.results_folder()).unwrap();
}
// Change properties.
config.add_app_package("test_app");
config.verbose = true;
config.quiet = true;
config.force = true;
config.bench = true;
config.open = true;
// Check that the new properties are correct.
let packages = config.app_packages();
assert_eq!(&packages[0], &config.downloads_folder.join("test_app.apk"));
assert!(config.is_verbose());
assert!(config.is_quiet());
assert!(config.is_force());
assert!(config.is_bench());
assert!(config.is_open());
config.reset_force();
assert!(!config.is_force());
config.overall_force = true;
config.reset_force();
assert!(config.is_force());
if packages[0].exists() {
fs::remove_file(&packages[0]).unwrap();
}
assert!(!config.check());
let _ = fs::File::create(&packages[0]).unwrap();
assert!(config.check());
let config = Config::default();
assert!(config.check());
fs::remove_file(&packages[0]).unwrap();
}
/// Test for the `config.toml.sample` sample configuration file.
#[test]
fn it_config_sample() {
// Create config object.
let mut config = Config::from_file(&PathBuf::from("config.toml.sample")).unwrap();
config.add_app_package("test_app");
// Check that the properties of the config object are correct.
assert_eq!(config.threads(), 2);
assert_eq!(config.downloads_folder, Path::new("downloads"));
assert_eq!(config.dist_folder(), Path::new("dist"));
assert_eq!(config.results_folder(), Path::new("results"));
assert_eq!(
config.dex2jar_folder(),
Path::new("/usr/share/super-analyzer/vendor/dex2jar-2.1-SNAPSHOT")
);
assert_eq!(
config.jd_cmd_file(),
Path::new("/usr/share/super-analyzer/vendor/jd-cmd.jar")
);
assert_eq!(
config.templates_folder(),
Path::new("/usr/share/super-analyzer/templates")
);
assert_eq!(
config.template_path(),
Path::new("/usr/share/super-analyzer/templates/super")
);
assert_eq!(config.template_name(), "super");
assert_eq!(
config.rules_json(),
Path::new("/etc/super-analyzer/rules.json")
);
assert_eq!(config.unknown_permission_criticality(), Criticality::Low);
assert_eq!(
config.unknown_permission_description(),
"Even if the application can create its own permissions, it's discouraged, \
since it can lead to misunderstanding between developers."
);
let permission = config.permissions().next().unwrap();
assert_eq!(
permission.name(),
manifest::Permission::AndroidPermissionInternet
);
assert_eq!(permission.criticality(), Criticality::Warning);
assert_eq!(permission.label(), "Internet permission");
assert_eq!(
permission.description(),
"Allows the app to create network sockets and use custom network protocols. \
The browser and other applications provide means to send data to the \
internet, so this permission is not required to send data to the internet. \
Check if the permission is actually needed."
);
}
/// Test to check the default reports to be generated
#[test]
fn it_generates_html_but_not_json_by_default() {
let mut final_config = Config::default();
final_config.html = false;
final_config.json = false;
assert!(final_config.has_to_generate_html());
assert!(!final_config.has_to_generate_json());
}
}<|fim▁end|>
|
Path::new("/etc/super-analyzer/rules.json")
);
|
<|file_name|>speed.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, division
import random
import string
import timeit
import os
import zipfile
import datrie
def words100k():
zip_name = os.path.join(
os.path.abspath(os.path.dirname(__file__)),
'words100k.txt.zip'
)
zf = zipfile.ZipFile(zip_name)
txt = zf.open(zf.namelist()[0]).read().decode('utf8')
return txt.splitlines()
def random_words(num):
russian = 'абвгдеёжзиклмнопрстуфхцчъыьэюя'
alphabet = russian + string.ascii_letters
return [<|fim▁hole|> ]
def truncated_words(words):
return [word[:3] for word in words]
def prefixes1k(words, prefix_len):
words = [w for w in words if len(w) >= prefix_len]
every_nth = int(len(words)/1000)
_words = [w[:prefix_len] for w in words[::every_nth]]
return _words[:1000]
WORDS100k = words100k()
MIXED_WORDS100k = truncated_words(WORDS100k)
NON_WORDS100k = random_words(100000)
PREFIXES_3_1k = prefixes1k(WORDS100k, 3)
PREFIXES_5_1k = prefixes1k(WORDS100k, 5)
PREFIXES_8_1k = prefixes1k(WORDS100k, 8)
PREFIXES_15_1k = prefixes1k(WORDS100k, 15)
def _alphabet(words):
chars = set()
for word in words:
for ch in word:
chars.add(ch)
return "".join(sorted(list(chars)))
ALPHABET = _alphabet(WORDS100k)
def bench(name, timer, descr='M ops/sec', op_count=0.1, repeats=3, runs=5):
times = []
for x in range(runs):
times.append(timer.timeit(repeats))
def op_time(time):
return op_count*repeats / time
print("%55s: %0.3f%s" % (
name,
op_time(min(times)),
descr,
))
def create_trie():
words = words100k()
trie = datrie.Trie(ALPHABET)
for word in words:
trie[word] = 1
return trie
def benchmark():
print('\n====== Benchmarks (100k unique unicode words) =======\n')
tests = [
('__getitem__ (hits)', "for word in words: data[word]", 'M ops/sec', 0.1, 3),
('__contains__ (hits)', "for word in words: word in data", 'M ops/sec', 0.1, 3),
('__contains__ (misses)', "for word in NON_WORDS100k: word in data", 'M ops/sec', 0.1, 3),
('__len__', 'len(data)', ' ops/sec', 1, 1),
('__setitem__ (updates)', 'for word in words: data[word]=1', 'M ops/sec', 0.1, 3),
('__setitem__ (inserts, random)', 'for word in NON_WORDS_10k: data[word]=1', 'M ops/sec',0.01, 3),
('__setitem__ (inserts, sorted)', 'for word in words: empty_data[word]=1', 'M ops/sec', 0.1, 3),
('setdefault (updates)', 'for word in words: data.setdefault(word, 1)', 'M ops/sec', 0.1, 3),
('setdefault (inserts)', 'for word in NON_WORDS_10k: data.setdefault(word, 1)', 'M ops/sec', 0.01, 3),
('values()', 'list(data.values())', ' ops/sec', 1, 1),
('keys()', 'list(data.keys())', ' ops/sec', 1, 1),
('items()', 'list(data.items())', ' ops/sec', 1, 1),
]
common_setup = """
from __main__ import create_trie, WORDS100k, NON_WORDS100k, MIXED_WORDS100k, datrie
from __main__ import PREFIXES_3_1k, PREFIXES_5_1k, PREFIXES_8_1k, PREFIXES_15_1k
from __main__ import ALPHABET
words = WORDS100k
NON_WORDS_10k = NON_WORDS100k[:10000]
NON_WORDS_1k = ['ыва', 'xyz', 'соы', 'Axx', 'avы']*200
"""
dict_setup = common_setup + 'data = dict((word, 1) for word in words); empty_data=dict()'
trie_setup = common_setup + 'data = create_trie(); empty_data = datrie.Trie(ALPHABET)'
for test_name, test, descr, op_count, repeats in tests:
t_dict = timeit.Timer(test, dict_setup)
t_trie = timeit.Timer(test, trie_setup)
bench('dict '+test_name, t_dict, descr, op_count, repeats)
bench('trie '+test_name, t_trie, descr, op_count, repeats)
# trie-specific benchmarks
bench(
'trie.iter_prefix_values (hits)',
timeit.Timer(
"for word in words:\n"
" for it in data.iter_prefix_values(word):\n"
" pass",
trie_setup
),
)
bench(
'trie.prefix_values (hits)',
timeit.Timer(
"for word in words: data.prefix_values(word)",
trie_setup
)
)
bench(
'trie.prefix_values loop (hits)',
timeit.Timer(
"for word in words:\n"
" for it in data.prefix_values(word):pass",
trie_setup
)
)
bench(
'trie.iter_prefix_items (hits)',
timeit.Timer(
"for word in words:\n"
" for it in data.iter_prefix_items(word):\n"
" pass",
trie_setup
),
)
bench(
'trie.prefix_items (hits)',
timeit.Timer(
"for word in words: data.prefix_items(word)",
trie_setup
)
)
bench(
'trie.prefix_items loop (hits)',
timeit.Timer(
"for word in words:\n"
" for it in data.prefix_items(word):pass",
trie_setup
)
)
bench(
'trie.iter_prefixes (hits)',
timeit.Timer(
"for word in words:\n"
" for it in data.iter_prefixes(word): pass",
trie_setup
)
)
bench(
'trie.iter_prefixes (misses)',
timeit.Timer(
"for word in NON_WORDS100k:\n"
" for it in data.iter_prefixes(word): pass",
trie_setup
)
)
bench(
'trie.iter_prefixes (mixed)',
timeit.Timer(
"for word in MIXED_WORDS100k:\n"
" for it in data.iter_prefixes(word): pass",
trie_setup
)
)
bench(
'trie.has_keys_with_prefix (hits)',
timeit.Timer(
"for word in words: data.has_keys_with_prefix(word)",
trie_setup
)
)
bench(
'trie.has_keys_with_prefix (misses)',
timeit.Timer(
"for word in NON_WORDS100k: data.has_keys_with_prefix(word)",
trie_setup
)
)
for meth in ('longest_prefix', 'longest_prefix_item', 'longest_prefix_value'):
bench(
'trie.%s (hits)' % meth,
timeit.Timer(
"for word in words: data.%s(word)" % meth,
trie_setup
)
)
bench(
'trie.%s (misses)' % meth,
timeit.Timer(
"for word in NON_WORDS100k: data.%s(word, default=None)" % meth,
trie_setup
)
)
bench(
'trie.%s (mixed)' % meth,
timeit.Timer(
"for word in MIXED_WORDS100k: data.%s(word, default=None)" % meth,
trie_setup
)
)
prefix_data = [
('xxx', 'avg_len(res)==415', 'PREFIXES_3_1k'),
('xxxxx', 'avg_len(res)==17', 'PREFIXES_5_1k'),
('xxxxxxxx', 'avg_len(res)==3', 'PREFIXES_8_1k'),
('xxxxx..xx', 'avg_len(res)==1.4', 'PREFIXES_15_1k'),
('xxx', 'NON_EXISTING', 'NON_WORDS_1k'),
]
for xxx, avg, data in prefix_data:
for meth in ('items', 'keys', 'values'):
bench(
'trie.%s(prefix="%s"), %s' % (meth, xxx, avg),
timeit.Timer(
"for word in %s: data.%s(word)" % (data, meth),
trie_setup
),
'K ops/sec',
op_count=1,
)
def profiling():
print('\n====== Profiling =======\n')
def profile_yep():
import yep
trie = create_trie()
#WORDS = words100k()
yep.start(b'output.prof')
for x in range(100):
trie.keys()
# for x in range(1000):
# for word in WORDS:
# trie[word]
yep.stop()
def profile_cprofile():
import pstats
import cProfile
trie = create_trie()
WORDS = words100k()
def check_trie(trie, words):
value = 0
for word in words:
value += trie[word]
if value != len(words):
raise Exception()
# def check_prefixes(trie, words):
# for word in words:
# trie.keys(word)
# cProfile.runctx("check_prefixes(trie, NON_WORDS_1k)", globals(), locals(), "Profile.prof")
cProfile.runctx("check_trie(trie, WORDS)", globals(), locals(), "Profile.prof")
s = pstats.Stats("Profile.prof")
s.strip_dirs().sort_stats("time").print_stats(20)
#profile_cprofile()
profile_yep()
#def memory():
# gc.collect()
# _memory = lambda: _get_memory(os.getpid())
# initial_memory = _memory()
# trie = create_trie()
# gc.collect()
# trie_memory = _memory()
#
# del trie
# gc.collect()
# alphabet, words = words100k()
# words_dict = dict((word, 1) for word in words)
# del alphabet
# del words
# gc.collect()
#
# dict_memory = _memory()
# print('initial: %s, trie: +%s, dict: +%s' % (
# initial_memory,
# trie_memory-initial_memory,
# dict_memory-initial_memory,
# ))
if __name__ == '__main__':
benchmark()
#profiling()
#memory()
print('\n~~~~~~~~~~~~~~\n')<|fim▁end|>
|
"".join([random.choice(alphabet) for x in range(random.randint(1,15))])
for y in range(num)
|
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>//! Requires the 'framework' feature flag be enabled in your project's
//! `Cargo.toml`.
//!
//! This can be enabled by specifying the feature in the dependency section:
//!
//! ```toml
//! [dependencies.serenity]
//! git = "https://github.com/serenity-rs/serenity.git"
//! features = ["framework", "standard_framework"]
//! ```
mod commands;
use std::{collections::HashSet, env, sync::Arc};
use commands::{math::*, meta::*, owner::*};
use serenity::{
async_trait,
client::bridge::gateway::ShardManager,
framework::{standard::macros::group, StandardFramework},
http::Http,
model::{event::ResumedEvent, gateway::Ready},
prelude::*,
};
use tracing::{error, info};
use tracing_subscriber::{EnvFilter, FmtSubscriber};
pub struct ShardManagerContainer;
impl TypeMapKey for ShardManagerContainer {
type Value = Arc<Mutex<ShardManager>>;
}
struct Handler;<|fim▁hole|>
#[async_trait]
impl EventHandler for Handler {
async fn ready(&self, _: Context, ready: Ready) {
info!("Connected as {}", ready.user.name);
}
async fn resume(&self, _: Context, _: ResumedEvent) {
info!("Resumed");
}
}
#[group]
#[commands(multiply, ping, quit)]
struct General;
#[tokio::main]
async fn main() {
// This will load the environment variables located at `./.env`, relative to
// the CWD. See `./.env.example` for an example on how to structure this.
dotenv::dotenv().expect("Failed to load .env file");
// Initialize the logger to use environment variables.
//
// In this case, a good default is setting the environment variable
// `RUST_LOG` to debug`.
let subscriber =
FmtSubscriber::builder().with_env_filter(EnvFilter::from_default_env()).finish();
tracing::subscriber::set_global_default(subscriber).expect("Failed to start the logger");
let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment");
let http = Http::new_with_token(&token);
// We will fetch your bot's owners and id
let (owners, _bot_id) = match http.get_current_application_info().await {
Ok(info) => {
let mut owners = HashSet::new();
owners.insert(info.owner.id);
(owners, info.id)
},
Err(why) => panic!("Could not access application info: {:?}", why),
};
// Create the framework
let framework =
StandardFramework::new().configure(|c| c.owners(owners).prefix("~")).group(&GENERAL_GROUP);
let mut client = Client::builder(&token)
.framework(framework)
.event_handler(Handler)
.await
.expect("Err creating client");
{
let mut data = client.data.write().await;
data.insert::<ShardManagerContainer>(client.shard_manager.clone());
}
let shard_manager = client.shard_manager.clone();
tokio::spawn(async move {
tokio::signal::ctrl_c().await.expect("Could not register ctrl+c handler");
shard_manager.lock().await.shutdown_all().await;
});
if let Err(why) = client.start().await {
error!("Client error: {:?}", why);
}
}<|fim▁end|>
| |
<|file_name|>UnidadFlt.java<|end_file_name|><|fim▁begin|>package com.atux.bean.consulta;
<|fim▁hole|>
/**
* Created by MATRIX-JAVA on 27/11/2014.
*/
public class UnidadFlt extends FilterBaseLocal {
public static final String PICK = "PICK";
public UnidadFlt(String unidad) {
this.unidad = unidad;
}
public UnidadFlt() {
}
private String unidad;
private String coUnidad;
public String getUnidad() {
return unidad;
}
public void setUnidad(String unidad) {
this.unidad = unidad;
}
public String getCoUnidad() {
return coUnidad;
}
public void setCoUnidad(String coUnidad) {
this.coUnidad = coUnidad;
}
}<|fim▁end|>
|
import com.atux.comun.FilterBaseLocal;
|
<|file_name|>plugin_dnssec_test.go<|end_file_name|><|fim▁begin|>package test
import (
"io/ioutil"
"os"
"testing"
"github.com/coredns/coredns/plugin/test"
"github.com/miekg/dns"
)
func TestLookupBalanceRewriteCacheDnssec(t *testing.T) {
t.Parallel()
name, rm, err := test.TempFile(".", exampleOrg)<|fim▁hole|> rm1 := createKeyFile(t)
defer rm1()
corefile := `example.org:0 {
file ` + name + `
rewrite type ANY HINFO
dnssec {
key file ` + base + `
}
loadbalance
}`
ex, udp, _, err := CoreDNSServerAndPorts(corefile)
if err != nil {
t.Fatalf("Could not get CoreDNS serving instance: %s", err)
}
defer ex.Stop()
c := new(dns.Client)
m := new(dns.Msg)
m.SetQuestion("example.org.", dns.TypeA)
m.SetEdns0(4096, true)
res, _, err := c.Exchange(m, udp)
if err != nil {
t.Fatalf("Could not send query: %s", err)
}
sig := 0
for _, a := range res.Answer {
if a.Header().Rrtype == dns.TypeRRSIG {
sig++
}
}
if sig == 0 {
t.Errorf("Expected RRSIGs, got none")
t.Logf("%v\n", res)
}
}
func createKeyFile(t *testing.T) func() {
ioutil.WriteFile(base+".key",
[]byte(`example.org. IN DNSKEY 256 3 13 tDyI0uEIDO4SjhTJh1AVTFBLpKhY3He5BdAlKztewiZ7GecWj94DOodg ovpN73+oJs+UfZ+p9zOSN5usGAlHrw==`),
0644)
ioutil.WriteFile(base+".private",
[]byte(`Private-key-format: v1.3
Algorithm: 13 (ECDSAP256SHA256)
PrivateKey: HPmldSNfrkj/aDdUMFwuk/lgzaC5KIsVEG3uoYvF4pQ=
Created: 20160426083115
Publish: 20160426083115
Activate: 20160426083115`),
0644)
return func() {
os.Remove(base + ".key")
os.Remove(base + ".private")
}
}
const base = "Kexample.org.+013+44563"<|fim▁end|>
|
if err != nil {
t.Fatalf("Failed to create zone: %s", err)
}
defer rm()
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>use ::pthread_mutex_t;
pub type blkcnt_t = i64;
pub type blksize_t = i64;
pub type c_char = u8;
pub type c_long = i64;
pub type c_ulong = u64;
pub type fsblkcnt_t = u64;
pub type fsfilcnt_t = u64;
pub type ino_t = u64;
pub type nlink_t = u64;
pub type off_t = i64;
pub type rlim_t = u64;
pub type suseconds_t = i64;
pub type time_t = i64;
pub type wchar_t = i32;
pub type greg_t = u64;
pub type clock_t = i64;
pub type shmatt_t = ::c_ulong;
pub type msgqnum_t = ::c_ulong;
pub type msglen_t = ::c_ulong;
pub type __fsword_t = ::c_long;
pub type __priority_which_t = ::c_uint;
pub type __u64 = u64;
s! {
pub struct aiocb {
pub aio_fildes: ::c_int,
pub aio_lio_opcode: ::c_int,
pub aio_reqprio: ::c_int,
pub aio_buf: *mut ::c_void,
pub aio_nbytes: ::size_t,
pub aio_sigevent: ::sigevent,
__next_prio: *mut aiocb,
__abs_prio: ::c_int,
__policy: ::c_int,
__error_code: ::c_int,
__return_value: ::ssize_t,
pub aio_offset: off_t,
#[cfg(target_pointer_width = "32")]
__unused1: [::c_char; 4],
__glibc_reserved: [::c_char; 32]
}
pub struct stat {
pub st_dev: ::dev_t,
pub st_ino: ::ino_t,
pub st_nlink: ::nlink_t,
pub st_mode: ::mode_t,
pub st_uid: ::uid_t,
pub st_gid: ::gid_t,
st_pad0: ::c_int,
pub st_rdev: ::dev_t,
pub st_size: ::off_t,
pub st_atime: ::time_t,
pub st_atime_nsec: ::c_long,
pub st_mtime: ::time_t,
pub st_mtime_nsec: ::c_long,
pub st_ctime: ::time_t,
pub st_ctime_nsec: ::c_long,
pub st_blksize: ::blksize_t,
pub st_blocks: ::blkcnt_t,
__glibc_reserved: [::c_long; 3],
}
pub struct stat64 {
pub st_dev: ::dev_t,
pub st_ino: ::ino64_t,
pub st_nlink: ::nlink_t,
pub st_mode: ::mode_t,
pub st_uid: ::uid_t,
pub st_gid: ::gid_t,
st_pad0: ::c_int,
pub st_rdev: ::dev_t,
pub st_size: ::off_t,
pub st_atime: ::time_t,
pub st_atime_nsec: ::c_long,
pub st_mtime: ::time_t,
pub st_mtime_nsec: ::c_long,
pub st_ctime: ::time_t,
pub st_ctime_nsec: ::c_long,
pub st_blksize: ::blksize_t,
pub st_blocks: ::blkcnt64_t,
__glibc_reserved: [::c_long; 3],
}
pub struct pthread_attr_t {
__size: [::c_ulong; 7]
}
pub struct sigaction {
pub sa_sigaction: ::sighandler_t,
__glibc_reserved0: ::c_int,
pub sa_flags: ::c_int,
pub sa_restorer: ::Option<extern fn()>,
pub sa_mask: sigset_t,
}
pub struct stack_t {
pub ss_sp: *mut ::c_void,
pub ss_flags: ::c_int,
pub ss_size: ::size_t,
}
pub struct sigset_t {
__size: [::c_ulong; 16],
}
pub struct siginfo_t {
pub si_signo: ::c_int,
pub si_errno: ::c_int,
pub si_code: ::c_int,
_pad: ::c_int,
_pad2: [::c_long; 14],
}
pub struct ipc_perm {
pub __key: ::key_t,
pub uid: ::uid_t,
pub gid: ::gid_t,
pub cuid: ::uid_t,
pub cgid: ::gid_t,
pub mode: ::mode_t,
pub __seq: ::c_ushort,
__pad1: ::c_ushort,
__unused1: ::c_ulong,
__unused2: ::c_ulong
}
pub struct shmid_ds {
pub shm_perm: ::ipc_perm,
pub shm_segsz: ::size_t,
pub shm_atime: ::time_t,
pub shm_dtime: ::time_t,
pub shm_ctime: ::time_t,
pub shm_cpid: ::pid_t,
pub shm_lpid: ::pid_t,
pub shm_nattch: ::shmatt_t,
__unused4: ::c_ulong,
__unused5: ::c_ulong
}
pub struct statfs {
pub f_type: ::c_uint,
pub f_bsize: ::c_uint,
pub f_blocks: ::fsblkcnt_t,
pub f_bfree: ::fsblkcnt_t,
pub f_bavail: ::fsblkcnt_t,
pub f_files: ::fsfilcnt_t,
pub f_ffree: ::fsfilcnt_t,
pub f_fsid: ::fsid_t,
pub f_namelen: ::c_uint,
pub f_frsize: ::c_uint,
pub f_flags: ::c_uint,
f_spare: [::c_uint; 4],
}
pub struct statvfs {
pub f_bsize: ::c_ulong,
pub f_frsize: ::c_ulong,
pub f_blocks: ::fsblkcnt_t,
pub f_bfree: ::fsblkcnt_t,
pub f_bavail: ::fsblkcnt_t,
pub f_files: ::fsfilcnt_t,
pub f_ffree: ::fsfilcnt_t,
pub f_favail: ::fsfilcnt_t,
pub f_fsid: ::c_ulong,
pub f_flag: ::c_ulong,
pub f_namemax: ::c_ulong,
__f_spare: [::c_int; 6],
}
pub struct msghdr {
pub msg_name: *mut ::c_void,
pub msg_namelen: ::socklen_t,
pub msg_iov: *mut ::iovec,
pub msg_iovlen: ::size_t,
pub msg_control: *mut ::c_void,
pub msg_controllen: ::size_t,
pub msg_flags: ::c_int,
}
pub struct cmsghdr {
pub cmsg_len: ::size_t,
pub cmsg_level: ::c_int,
pub cmsg_type: ::c_int,
}
pub struct termios {
pub c_iflag: ::tcflag_t,
pub c_oflag: ::tcflag_t,
pub c_cflag: ::tcflag_t,
pub c_lflag: ::tcflag_t,
pub c_line: ::cc_t,
pub c_cc: [::cc_t; ::NCCS],
pub c_ispeed: ::speed_t,
pub c_ospeed: ::speed_t,
}
pub struct termios2 {
pub c_iflag: ::tcflag_t,
pub c_oflag: ::tcflag_t,
pub c_cflag: ::tcflag_t,
pub c_lflag: ::tcflag_t,
pub c_line: ::cc_t,
pub c_cc: [::cc_t; 19],
pub c_ispeed: ::speed_t,
pub c_ospeed: ::speed_t,
}
pub struct sysinfo {
pub uptime: ::c_long,
pub loads: [::c_ulong; 3],
pub totalram: ::c_ulong,
pub freeram: ::c_ulong,
pub sharedram: ::c_ulong,
pub bufferram: ::c_ulong,
pub totalswap: ::c_ulong,
pub freeswap: ::c_ulong,
pub procs: ::c_ushort,
pub pad: ::c_ushort,
pub totalhigh: ::c_ulong,
pub freehigh: ::c_ulong,
pub mem_unit: ::c_uint,
pub _f: [::c_char; 0],
}
pub struct glob64_t {
pub gl_pathc: ::size_t,
pub gl_pathv: *mut *mut ::c_char,
pub gl_offs: ::size_t,
pub gl_flags: ::c_int,
__unused1: *mut ::c_void,
__unused2: *mut ::c_void,
__unused3: *mut ::c_void,
__unused4: *mut ::c_void,
__unused5: *mut ::c_void,
}
pub struct flock {
pub l_type: ::c_short,
pub l_whence: ::c_short,
pub l_start: ::off_t,
pub l_len: ::off_t,
pub l_pid: ::pid_t,
}
pub struct __psw_t {
pub mask: u64,
pub addr: u64,
}
pub struct fpregset_t {
pub fpc: u32,
__pad: u32,
pub fprs: [fpreg_t; 16],
}
pub struct mcontext_t {
pub psw: __psw_t,
pub gregs: [u64; 16],
pub aregs: [u32; 16],
pub fpregs: fpregset_t,
}
pub struct ucontext_t {
pub uc_flags: ::c_ulong,
pub uc_link: *mut ucontext_t,
pub uc_stack: ::stack_t,
pub uc_mcontext: mcontext_t,
pub uc_sigmask: ::sigset_t,
}
pub struct msqid_ds {
pub msg_perm: ::ipc_perm,
pub msg_stime: ::time_t,
pub msg_rtime: ::time_t,
pub msg_ctime: ::time_t,
__msg_cbytes: ::c_ulong,
pub msg_qnum: ::msgqnum_t,
pub msg_qbytes: ::msglen_t,
pub msg_lspid: ::pid_t,
pub msg_lrpid: ::pid_t,
__glibc_reserved4: ::c_ulong,
__glibc_reserved5: ::c_ulong,
}
pub struct statfs64 {
pub f_type: ::c_uint,
pub f_bsize: ::c_uint,
pub f_blocks: u64,
pub f_bfree: u64,
pub f_bavail: u64,
pub f_files: u64,
pub f_ffree: u64,
pub f_fsid: ::fsid_t,
pub f_namelen: ::c_uint,
pub f_frsize: ::c_uint,
pub f_flags: ::c_uint,
pub f_spare: [::c_uint; 4],
}
pub struct statvfs64 {
pub f_bsize: ::c_ulong,
pub f_frsize: ::c_ulong,
pub f_blocks: u64,
pub f_bfree: u64,
pub f_bavail: u64,
pub f_files: u64,
pub f_ffree: u64,
pub f_favail: u64,
pub f_fsid: ::c_ulong,
pub f_flag: ::c_ulong,
pub f_namemax: ::c_ulong,
__f_spare: [::c_int; 6],
}
}
s_no_extra_traits!{
// FIXME: This is actually a union.
pub struct fpreg_t {
pub d: ::c_double,
// f: ::c_float,
}
}
cfg_if! {
if #[cfg(feature = "extra_traits")] {
impl PartialEq for fpreg_t {
fn eq(&self, other: &fpreg_t) -> bool {
self.d == other.d
}
}
impl Eq for fpreg_t {}
impl ::fmt::Debug for fpreg_t {
fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result {
f.debug_struct("fpreg_t")
.field("d", &self.d)
.finish()
}
}
impl ::hash::Hash for fpreg_t {
fn hash<H: ::hash::Hasher>(&self, state: &mut H) {
let d: u64 = unsafe { ::mem::transmute(self.d) };
d.hash(state);
}
}
}
}
pub const SFD_CLOEXEC: ::c_int = 0x080000;
pub const NCCS: usize = 32;
pub const O_TRUNC: ::c_int = 512;
pub const O_LARGEFILE: ::c_int = 0;
pub const O_NOATIME: ::c_int = 0o1000000;
pub const O_CLOEXEC: ::c_int = 0x80000;
pub const O_PATH: ::c_int = 0o10000000;
pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY;
pub const EBFONT: ::c_int = 59;
pub const ENOSTR: ::c_int = 60;
pub const ENODATA: ::c_int = 61;
pub const ETIME: ::c_int = 62;
pub const ENOSR: ::c_int = 63;
pub const ENONET: ::c_int = 64;
pub const ENOPKG: ::c_int = 65;
pub const EREMOTE: ::c_int = 66;
pub const ENOLINK: ::c_int = 67;
pub const EADV: ::c_int = 68;
pub const ESRMNT: ::c_int = 69;
pub const ECOMM: ::c_int = 70;
pub const EPROTO: ::c_int = 71;
pub const EDOTDOT: ::c_int = 73;
pub const SA_NODEFER: ::c_int = 0x40000000;
pub const SA_RESETHAND: ::c_int = 0x80000000;
pub const SA_RESTART: ::c_int = 0x10000000;
pub const SA_NOCLDSTOP: ::c_int = 0x00000001;
pub const EPOLL_CLOEXEC: ::c_int = 0x80000;
pub const EFD_CLOEXEC: ::c_int = 0x80000;
pub const POSIX_FADV_DONTNEED: ::c_int = 6;
pub const POSIX_FADV_NOREUSE: ::c_int = 7;
pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4;
pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4;
pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40;
pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56;
pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8;
align_const! {
pub const PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP: ::pthread_mutex_t =
pthread_mutex_t {
size: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
};
pub const PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP: ::pthread_mutex_t =
pthread_mutex_t {
size: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
};
pub const PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP: ::pthread_mutex_t =
pthread_mutex_t {
size: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
};
}
pub const EADDRINUSE: ::c_int = 98;
pub const EADDRNOTAVAIL: ::c_int = 99;
pub const ECONNABORTED: ::c_int = 103;
pub const ECONNREFUSED: ::c_int = 111;
pub const ECONNRESET: ::c_int = 104;
pub const EDEADLK: ::c_int = 35;
pub const ENOSYS: ::c_int = 38;
pub const ENOTCONN: ::c_int = 107;
pub const ETIMEDOUT: ::c_int = 110;
pub const FIOCLEX: ::c_ulong = 0x5451;
pub const FIONBIO: ::c_ulong = 0x5421;
pub const MAP_ANON: ::c_int = 0x20;
pub const O_ACCMODE: ::c_int = 3;
pub const O_APPEND: ::c_int = 1024;
pub const O_CREAT: ::c_int = 64;
pub const O_EXCL: ::c_int = 128;
pub const O_NONBLOCK: ::c_int = 2048;
pub const PTHREAD_STACK_MIN: ::size_t = 16384;
pub const PTHREAD_MUTEX_ADAPTIVE_NP: ::c_int = 3;
pub const RLIM_INFINITY: ::rlim_t = 0xffffffffffffffff;
pub const SA_NOCLDWAIT: ::c_int = 2;
pub const SA_ONSTACK: ::c_int = 0x08000000;
pub const SA_SIGINFO: ::c_int = 4;
pub const SIGBUS: ::c_int = 7;
pub const SIGSTKSZ: ::size_t = 0x2000;
pub const MINSIGSTKSZ: ::size_t = 2048;
pub const SIG_SETMASK: ::c_int = 2;
pub const SOCK_DGRAM: ::c_int = 2;
pub const SOCK_STREAM: ::c_int = 1;
pub const SOL_SOCKET: ::c_int = 1;
pub const SO_BROADCAST: ::c_int = 6;
pub const SO_ERROR: ::c_int = 4;
pub const SO_RCVTIMEO: ::c_int = 20;
pub const SO_REUSEADDR: ::c_int = 2;
pub const SO_SNDTIMEO: ::c_int = 21;
pub const SO_BINDTODEVICE: ::c_int = 25;
pub const SO_TIMESTAMP: ::c_int = 29;
pub const SO_MARK: ::c_int = 36;
pub const SO_PROTOCOL: ::c_int = 38;
pub const SO_DOMAIN: ::c_int = 39;
pub const SO_RXQ_OVFL: ::c_int = 40;
pub const SO_PEEK_OFF: ::c_int = 42;
pub const SO_BUSY_POLL: ::c_int = 46;
pub const RLIMIT_RSS: ::c_int = 5;
pub const RLIMIT_NOFILE: ::c_int = 7;
pub const RLIMIT_AS: ::c_int = 9;
pub const RLIMIT_NPROC: ::c_int = 6;
pub const RLIMIT_MEMLOCK: ::c_int = 8;
pub const RLIMIT_RTTIME: ::c_int = 15;
pub const RLIMIT_NLIMITS: ::c_int = 16;
pub const O_NOCTTY: ::c_int = 256;
pub const O_SYNC: ::c_int = 1052672;
pub const O_RSYNC: ::c_int = 1052672;
pub const O_DSYNC: ::c_int = 4096;
pub const O_FSYNC: ::c_int = 0x101000;
pub const O_DIRECT: ::c_int = 0x4000;
pub const O_DIRECTORY: ::c_int = 0x10000;
pub const O_NOFOLLOW: ::c_int = 0x20000;
pub const SOCK_NONBLOCK: ::c_int = O_NONBLOCK;
pub const LC_PAPER: ::c_int = 7;
pub const LC_NAME: ::c_int = 8;
pub const LC_ADDRESS: ::c_int = 9;
pub const LC_TELEPHONE: ::c_int = 10;
pub const LC_MEASUREMENT: ::c_int = 11;
pub const LC_IDENTIFICATION: ::c_int = 12;
pub const LC_PAPER_MASK: ::c_int = (1 << LC_PAPER);
pub const LC_NAME_MASK: ::c_int = (1 << LC_NAME);
pub const LC_ADDRESS_MASK: ::c_int = (1 << LC_ADDRESS);
pub const LC_TELEPHONE_MASK: ::c_int = (1 << LC_TELEPHONE);
pub const LC_MEASUREMENT_MASK: ::c_int = (1 << LC_MEASUREMENT);
pub const LC_IDENTIFICATION_MASK: ::c_int = (1 << LC_IDENTIFICATION);
pub const LC_ALL_MASK: ::c_int = ::LC_CTYPE_MASK
| ::LC_NUMERIC_MASK
| ::LC_TIME_MASK
| ::LC_COLLATE_MASK
| ::LC_MONETARY_MASK
| ::LC_MESSAGES_MASK
| LC_PAPER_MASK
| LC_NAME_MASK
| LC_ADDRESS_MASK
| LC_TELEPHONE_MASK
| LC_MEASUREMENT_MASK
| LC_IDENTIFICATION_MASK;
pub const MAP_ANONYMOUS: ::c_int = 0x0020;
pub const MAP_GROWSDOWN: ::c_int = 0x0100;
pub const MAP_DENYWRITE: ::c_int = 0x0800;
pub const MAP_EXECUTABLE: ::c_int = 0x01000;
pub const MAP_LOCKED: ::c_int = 0x02000;
pub const MAP_NORESERVE: ::c_int = 0x04000;
pub const MAP_POPULATE: ::c_int = 0x08000;
pub const MAP_NONBLOCK: ::c_int = 0x010000;
pub const MAP_STACK: ::c_int = 0x020000;
pub const EDEADLOCK: ::c_int = 35;
pub const ENAMETOOLONG: ::c_int = 36;
pub const ENOLCK: ::c_int = 37;
pub const ENOTEMPTY: ::c_int = 39;
pub const ELOOP: ::c_int = 40;
pub const ENOMSG: ::c_int = 42;
pub const EIDRM: ::c_int = 43;
pub const ECHRNG: ::c_int = 44;
pub const EL2NSYNC: ::c_int = 45;
pub const EL3HLT: ::c_int = 46;
pub const EL3RST: ::c_int = 47;
pub const ELNRNG: ::c_int = 48;
pub const EUNATCH: ::c_int = 49;
pub const ENOCSI: ::c_int = 50;
pub const EL2HLT: ::c_int = 51;
pub const EBADE: ::c_int = 52;
pub const EBADR: ::c_int = 53;
pub const EXFULL: ::c_int = 54;
pub const ENOANO: ::c_int = 55;
pub const EBADRQC: ::c_int = 56;
pub const EBADSLT: ::c_int = 57;
pub const EMULTIHOP: ::c_int = 72;
pub const EOVERFLOW: ::c_int = 75;
pub const ENOTUNIQ: ::c_int = 76;
pub const EBADFD: ::c_int = 77;
pub const EBADMSG: ::c_int = 74;
pub const EREMCHG: ::c_int = 78;
pub const ELIBACC: ::c_int = 79;
pub const ELIBBAD: ::c_int = 80;
pub const ELIBSCN: ::c_int = 81;
pub const ELIBMAX: ::c_int = 82;
pub const ELIBEXEC: ::c_int = 83;
pub const EILSEQ: ::c_int = 84;
pub const ERESTART: ::c_int = 85;
pub const ESTRPIPE: ::c_int = 86;
pub const EUSERS: ::c_int = 87;
pub const ENOTSOCK: ::c_int = 88;
pub const EDESTADDRREQ: ::c_int = 89;
pub const EMSGSIZE: ::c_int = 90;
pub const EPROTOTYPE: ::c_int = 91;
pub const ENOPROTOOPT: ::c_int = 92;
pub const EPROTONOSUPPORT: ::c_int = 93;
pub const ESOCKTNOSUPPORT: ::c_int = 94;
pub const EOPNOTSUPP: ::c_int = 95;
pub const ENOTSUP: ::c_int = EOPNOTSUPP;
pub const EPFNOSUPPORT: ::c_int = 96;
pub const EAFNOSUPPORT: ::c_int = 97;
pub const ENETDOWN: ::c_int = 100;
pub const ENETUNREACH: ::c_int = 101;
pub const ENETRESET: ::c_int = 102;
pub const ENOBUFS: ::c_int = 105;
pub const EISCONN: ::c_int = 106;
pub const ESHUTDOWN: ::c_int = 108;
pub const ETOOMANYREFS: ::c_int = 109;
pub const EHOSTDOWN: ::c_int = 112;
pub const EHOSTUNREACH: ::c_int = 113;
pub const EALREADY: ::c_int = 114;
pub const EINPROGRESS: ::c_int = 115;
pub const ESTALE: ::c_int = 116;
pub const EUCLEAN: ::c_int = 117;
pub const ENOTNAM: ::c_int = 118;
pub const ENAVAIL: ::c_int = 119;
pub const EISNAM: ::c_int = 120;
pub const EREMOTEIO: ::c_int = 121;
pub const EDQUOT: ::c_int = 122;
pub const ENOMEDIUM: ::c_int = 123;
pub const EMEDIUMTYPE: ::c_int = 124;
pub const ECANCELED: ::c_int = 125;
pub const ENOKEY: ::c_int = 126;
pub const EKEYEXPIRED: ::c_int = 127;
pub const EKEYREVOKED: ::c_int = 128;
pub const EKEYREJECTED: ::c_int = 129;
pub const EOWNERDEAD: ::c_int = 130;
pub const ENOTRECOVERABLE: ::c_int = 131;
pub const EHWPOISON: ::c_int = 133;
pub const ERFKILL: ::c_int = 132;
pub const SOCK_SEQPACKET: ::c_int = 5;
pub const SO_TYPE: ::c_int = 3;
pub const SO_DONTROUTE: ::c_int = 5;
pub const SO_SNDBUF: ::c_int = 7;
pub const SO_RCVBUF: ::c_int = 8;
pub const SO_KEEPALIVE: ::c_int = 9;
pub const SO_OOBINLINE: ::c_int = 10;
pub const SO_PRIORITY: ::c_int = 12;
pub const SO_LINGER: ::c_int = 13;
pub const SO_BSDCOMPAT: ::c_int = 14;
pub const SO_REUSEPORT: ::c_int = 15;
pub const SO_PASSCRED: ::c_int = 16;
pub const SO_PEERCRED: ::c_int = 17;
pub const SO_RCVLOWAT: ::c_int = 18;
pub const SO_SNDLOWAT: ::c_int = 19;
pub const SO_ACCEPTCONN: ::c_int = 30;
pub const SO_SNDBUFFORCE: ::c_int = 32;
pub const SO_RCVBUFFORCE: ::c_int = 33;
pub const TCP_COOKIE_TRANSACTIONS: ::c_int = 15;
pub const TCP_THIN_LINEAR_TIMEOUTS: ::c_int = 16;
pub const TCP_THIN_DUPACK: ::c_int = 17;
pub const TCP_USER_TIMEOUT: ::c_int = 18;
pub const TCP_REPAIR: ::c_int = 19;
pub const TCP_REPAIR_QUEUE: ::c_int = 20;
pub const TCP_QUEUE_SEQ: ::c_int = 21;
pub const TCP_REPAIR_OPTIONS: ::c_int = 22;
pub const TCP_FASTOPEN: ::c_int = 23;
pub const TCP_TIMESTAMP: ::c_int = 24;
pub const SIGCHLD: ::c_int = 17;
pub const SIGUSR1: ::c_int = 10;
pub const SIGUSR2: ::c_int = 12;
pub const SIGCONT: ::c_int = 18;
pub const SIGSTOP: ::c_int = 19;
pub const SIGTSTP: ::c_int = 20;
pub const SIGURG: ::c_int = 23;
pub const SIGIO: ::c_int = 29;
pub const SIGSYS: ::c_int = 31;
pub const SIGSTKFLT: ::c_int = 16;
pub const SIGUNUSED: ::c_int = 31;
pub const SIGTTIN: ::c_int = 21;
pub const SIGTTOU: ::c_int = 22;
pub const SIGXCPU: ::c_int = 24;
pub const SIGXFSZ: ::c_int = 25;
pub const SIGVTALRM: ::c_int = 26;
pub const SIGPROF: ::c_int = 27;
pub const SIGWINCH: ::c_int = 28;
pub const SIGPOLL: ::c_int = 29;
pub const SIGPWR: ::c_int = 30;
pub const SIG_BLOCK: ::c_int = 0x000000;
pub const SIG_UNBLOCK: ::c_int = 0x01;
pub const BUFSIZ: ::c_uint = 8192;
pub const TMP_MAX: ::c_uint = 238328;
pub const FOPEN_MAX: ::c_uint = 16;
pub const POSIX_MADV_DONTNEED: ::c_int = 4;
pub const _SC_EQUIV_CLASS_MAX: ::c_int = 41;
pub const _SC_CHARCLASS_NAME_MAX: ::c_int = 45;
pub const _SC_PII: ::c_int = 53;
pub const _SC_PII_XTI: ::c_int = 54;
pub const _SC_PII_SOCKET: ::c_int = 55;
pub const _SC_PII_INTERNET: ::c_int = 56;
pub const _SC_PII_OSI: ::c_int = 57;
pub const _SC_POLL: ::c_int = 58;
pub const _SC_SELECT: ::c_int = 59;
pub const _SC_PII_INTERNET_STREAM: ::c_int = 61;
pub const _SC_PII_INTERNET_DGRAM: ::c_int = 62;
pub const _SC_PII_OSI_COTS: ::c_int = 63;
pub const _SC_PII_OSI_CLTS: ::c_int = 64;
pub const _SC_PII_OSI_M: ::c_int = 65;
pub const _SC_T_IOV_MAX: ::c_int = 66;
pub const _SC_2_C_VERSION: ::c_int = 96;
pub const _SC_CHAR_BIT: ::c_int = 101;
pub const _SC_CHAR_MAX: ::c_int = 102;
pub const _SC_CHAR_MIN: ::c_int = 103;
pub const _SC_INT_MAX: ::c_int = 104;
pub const _SC_INT_MIN: ::c_int = 105;
pub const _SC_LONG_BIT: ::c_int = 106;
pub const _SC_WORD_BIT: ::c_int = 107;
pub const _SC_MB_LEN_MAX: ::c_int = 108;
pub const _SC_SSIZE_MAX: ::c_int = 110;
pub const _SC_SCHAR_MAX: ::c_int = 111;
pub const _SC_SCHAR_MIN: ::c_int = 112;
pub const _SC_SHRT_MAX: ::c_int = 113;
pub const _SC_SHRT_MIN: ::c_int = 114;
pub const _SC_UCHAR_MAX: ::c_int = 115;
pub const _SC_UINT_MAX: ::c_int = 116;
pub const _SC_ULONG_MAX: ::c_int = 117;
pub const _SC_USHRT_MAX: ::c_int = 118;
pub const _SC_NL_ARGMAX: ::c_int = 119;
pub const _SC_NL_LANGMAX: ::c_int = 120;
pub const _SC_NL_MSGMAX: ::c_int = 121;
pub const _SC_NL_NMAX: ::c_int = 122;
pub const _SC_NL_SETMAX: ::c_int = 123;
pub const _SC_NL_TEXTMAX: ::c_int = 124;
pub const _SC_BASE: ::c_int = 134;
pub const _SC_C_LANG_SUPPORT: ::c_int = 135;
pub const _SC_C_LANG_SUPPORT_R: ::c_int = 136;
pub const _SC_DEVICE_IO: ::c_int = 140;
pub const _SC_DEVICE_SPECIFIC: ::c_int = 141;
pub const _SC_DEVICE_SPECIFIC_R: ::c_int = 142;
pub const _SC_FD_MGMT: ::c_int = 143;
pub const _SC_FIFO: ::c_int = 144;
pub const _SC_PIPE: ::c_int = 145;
pub const _SC_FILE_ATTRIBUTES: ::c_int = 146;
pub const _SC_FILE_LOCKING: ::c_int = 147;
pub const _SC_FILE_SYSTEM: ::c_int = 148;
pub const _SC_MULTI_PROCESS: ::c_int = 150;
pub const _SC_SINGLE_PROCESS: ::c_int = 151;
pub const _SC_NETWORKING: ::c_int = 152;
pub const _SC_REGEX_VERSION: ::c_int = 156;
pub const _SC_SIGNALS: ::c_int = 158;
pub const _SC_SYSTEM_DATABASE: ::c_int = 162;
pub const _SC_SYSTEM_DATABASE_R: ::c_int = 163;
pub const _SC_USER_GROUPS: ::c_int = 166;
pub const _SC_USER_GROUPS_R: ::c_int = 167;
pub const _SC_LEVEL1_ICACHE_SIZE: ::c_int = 185;
pub const _SC_LEVEL1_ICACHE_ASSOC: ::c_int = 186;
pub const _SC_LEVEL1_ICACHE_LINESIZE: ::c_int = 187;
pub const _SC_LEVEL1_DCACHE_SIZE: ::c_int = 188;
pub const _SC_LEVEL1_DCACHE_ASSOC: ::c_int = 189;
pub const _SC_LEVEL1_DCACHE_LINESIZE: ::c_int = 190;
pub const _SC_LEVEL2_CACHE_SIZE: ::c_int = 191;
pub const _SC_LEVEL2_CACHE_ASSOC: ::c_int = 192;
pub const _SC_LEVEL2_CACHE_LINESIZE: ::c_int = 193;
pub const _SC_LEVEL3_CACHE_SIZE: ::c_int = 194;
pub const _SC_LEVEL3_CACHE_ASSOC: ::c_int = 195;
pub const _SC_LEVEL3_CACHE_LINESIZE: ::c_int = 196;
pub const _SC_LEVEL4_CACHE_SIZE: ::c_int = 197;
pub const _SC_LEVEL4_CACHE_ASSOC: ::c_int = 198;
pub const _SC_LEVEL4_CACHE_LINESIZE: ::c_int = 199;
pub const O_ASYNC: ::c_int = 0x2000;
pub const O_NDELAY: ::c_int = 0x800;
pub const ST_RELATIME: ::c_ulong = 4096;
pub const NI_MAXHOST: ::socklen_t = 1025;
pub const ADFS_SUPER_MAGIC: ::c_int = 0x0000adf5;
pub const AFFS_SUPER_MAGIC: ::c_int = 0x0000adff;
pub const CODA_SUPER_MAGIC: ::c_int = 0x73757245;
pub const CRAMFS_MAGIC: ::c_int = 0x28cd3d45;
pub const EFS_SUPER_MAGIC: ::c_int = 0x00414a53;
pub const EXT2_SUPER_MAGIC: ::c_int = 0x0000ef53;
pub const EXT3_SUPER_MAGIC: ::c_int = 0x0000ef53;
pub const EXT4_SUPER_MAGIC: ::c_int = 0x0000ef53;
pub const HPFS_SUPER_MAGIC: ::c_int = 0xf995e849;
pub const HUGETLBFS_MAGIC: ::c_int = 0x958458f6;
pub const ISOFS_SUPER_MAGIC: ::c_int = 0x00009660;
pub const JFFS2_SUPER_MAGIC: ::c_int = 0x000072b6;
pub const MINIX_SUPER_MAGIC: ::c_int = 0x0000137f;
pub const MINIX_SUPER_MAGIC2: ::c_int = 0x0000138f;
pub const MINIX2_SUPER_MAGIC: ::c_int = 0x00002468;
pub const MINIX2_SUPER_MAGIC2: ::c_int = 0x00002478;
pub const MSDOS_SUPER_MAGIC: ::c_int = 0x00004d44;
pub const NCP_SUPER_MAGIC: ::c_int = 0x0000564c;
pub const NFS_SUPER_MAGIC: ::c_int = 0x00006969;
pub const OPENPROM_SUPER_MAGIC: ::c_int = 0x00009fa1;
pub const PROC_SUPER_MAGIC: ::c_int = 0x00009fa0;
pub const QNX4_SUPER_MAGIC: ::c_int = 0x0000002f;
pub const REISERFS_SUPER_MAGIC: ::c_int = 0x52654973;
pub const SMB_SUPER_MAGIC: ::c_int = 0x0000517b;
pub const TMPFS_MAGIC: ::c_int = 0x01021994;
pub const USBDEVICE_SUPER_MAGIC: ::c_int = 0x00009fa2;
pub const VEOF: usize = 4;
pub const VEOL: usize = 11;
pub const VEOL2: usize = 16;
pub const VMIN: usize = 6;
pub const IEXTEN: ::tcflag_t = 0x00008000;
pub const TOSTOP: ::tcflag_t = 0x00000100;
pub const FLUSHO: ::tcflag_t = 0x00001000;
pub const CPU_SETSIZE: ::c_int = 0x400;
pub const EXTPROC: ::tcflag_t = 0x00010000;
pub const PTRACE_TRACEME: ::c_uint = 0;
pub const PTRACE_PEEKTEXT: ::c_uint = 1;
pub const PTRACE_PEEKDATA: ::c_uint = 2;
pub const PTRACE_PEEKUSER: ::c_uint = 3;
pub const PTRACE_POKETEXT: ::c_uint = 4;
pub const PTRACE_POKEDATA: ::c_uint = 5;
pub const PTRACE_POKEUSER: ::c_uint = 6;
pub const PTRACE_CONT: ::c_uint = 7;
pub const PTRACE_KILL: ::c_uint = 8;
pub const PTRACE_SINGLESTEP: ::c_uint = 9;
pub const PTRACE_GETREGS: ::c_uint = 12;
pub const PTRACE_SETREGS: ::c_uint = 13;
pub const PTRACE_GETFPREGS: ::c_uint = 14;
pub const PTRACE_SETFPREGS: ::c_uint = 15;
pub const PTRACE_ATTACH: ::c_uint = 16;
pub const PTRACE_DETACH: ::c_uint = 17;
pub const PTRACE_SYSCALL: ::c_uint = 24;
pub const PTRACE_SETOPTIONS: ::c_uint = 0x4200;
pub const PTRACE_GETEVENTMSG: ::c_uint = 0x4201;
pub const PTRACE_GETSIGINFO: ::c_uint = 0x4202;
pub const PTRACE_SETSIGINFO: ::c_uint = 0x4203;
pub const PTRACE_GETREGSET: ::c_uint = 0x4204;
pub const PTRACE_SETREGSET: ::c_uint = 0x4205;
pub const PTRACE_SEIZE: ::c_uint = 0x4206;
pub const PTRACE_INTERRUPT: ::c_uint = 0x4207;
pub const PTRACE_LISTEN: ::c_uint = 0x4208;
pub const PTRACE_PEEKSIGINFO: ::c_uint = 0x4209;
pub const MCL_CURRENT: ::c_int = 0x0001;
pub const MCL_FUTURE: ::c_int = 0x0002;
pub const EPOLLWAKEUP: ::c_int = 0x20000000;
pub const MAP_HUGETLB: ::c_int = 0x040000;
pub const EFD_NONBLOCK: ::c_int = 0x800;
pub const F_RDLCK: ::c_int = 0;
pub const F_WRLCK: ::c_int = 1;
pub const F_UNLCK: ::c_int = 2;
pub const F_GETLK: ::c_int = 5;
pub const F_GETOWN: ::c_int = 9;
pub const F_SETOWN: ::c_int = 8;
pub const F_SETLK: ::c_int = 6;
pub const F_SETLKW: ::c_int = 7;
pub const SEEK_DATA: ::c_int = 3;
pub const SEEK_HOLE: ::c_int = 4;
pub const SFD_NONBLOCK: ::c_int = 0x0800;
pub const TCSANOW: ::c_int = 0;
pub const TCSADRAIN: ::c_int = 1;
pub const TCSAFLUSH: ::c_int = 2;
pub const TCGETS: ::c_ulong = 0x5401;
pub const TCSETS: ::c_ulong = 0x5402;
pub const TCSETSW: ::c_ulong = 0x5403;
pub const TCSETSF: ::c_ulong = 0x5404;
pub const TCGETA: ::c_ulong = 0x5405;
pub const TCSETA: ::c_ulong = 0x5406;
pub const TCSETAW: ::c_ulong = 0x5407;
pub const TCSETAF: ::c_ulong = 0x5408;
pub const TCSBRK: ::c_ulong = 0x5409;
pub const TCXONC: ::c_ulong = 0x540A;
pub const TCFLSH: ::c_ulong = 0x540B;
pub const TIOCGSOFTCAR: ::c_ulong = 0x5419;
pub const TIOCSSOFTCAR: ::c_ulong = 0x541A;
pub const TIOCINQ: ::c_ulong = 0x541B;
pub const TIOCLINUX: ::c_ulong = 0x541C;
pub const TIOCGSERIAL: ::c_ulong = 0x541E;
pub const TIOCEXCL: ::c_ulong = 0x540C;
pub const TIOCNXCL: ::c_ulong = 0x540D;
pub const TIOCSCTTY: ::c_ulong = 0x540E;
pub const TIOCGPGRP: ::c_ulong = 0x540F;
pub const TIOCSPGRP: ::c_ulong = 0x5410;
pub const TIOCOUTQ: ::c_ulong = 0x5411;
pub const TIOCSTI: ::c_ulong = 0x5412;
pub const TIOCGWINSZ: ::c_ulong = 0x5413;
pub const TIOCSWINSZ: ::c_ulong = 0x5414;
pub const TIOCMGET: ::c_ulong = 0x5415;
pub const TIOCMBIS: ::c_ulong = 0x5416;
pub const TIOCMBIC: ::c_ulong = 0x5417;
pub const TIOCMSET: ::c_ulong = 0x5418;
pub const FIONREAD: ::c_ulong = 0x541B;
pub const TIOCCONS: ::c_ulong = 0x541D;
pub const RTLD_DEEPBIND: ::c_int = 0x8;
pub const RTLD_GLOBAL: ::c_int = 0x100;
pub const RTLD_NOLOAD: ::c_int = 0x4;
pub const LINUX_REBOOT_MAGIC1: ::c_int = 0xfee1dead;
pub const LINUX_REBOOT_MAGIC2: ::c_int = 672274793;
pub const LINUX_REBOOT_MAGIC2A: ::c_int = 85072278;
pub const LINUX_REBOOT_MAGIC2B: ::c_int = 369367448;
pub const LINUX_REBOOT_MAGIC2C: ::c_int = 537993216;
pub const LINUX_REBOOT_CMD_RESTART: ::c_int = 0x01234567;
pub const LINUX_REBOOT_CMD_HALT: ::c_int = 0xCDEF0123;
pub const LINUX_REBOOT_CMD_CAD_ON: ::c_int = 0x89ABCDEF;
pub const LINUX_REBOOT_CMD_CAD_OFF: ::c_int = 0x00000000;
pub const LINUX_REBOOT_CMD_POWER_OFF: ::c_int = 0x4321FEDC;
pub const LINUX_REBOOT_CMD_RESTART2: ::c_int = 0xA1B2C3D4;
pub const LINUX_REBOOT_CMD_SW_SUSPEND: ::c_int = 0xD000FCE2;
pub const LINUX_REBOOT_CMD_KEXEC: ::c_int = 0x45584543;
pub const VTIME: usize = 5;
pub const VSWTC: usize = 7;
pub const VSTART: usize = 8;
pub const VSTOP: usize = 9;
pub const VSUSP: usize = 10;
pub const VREPRINT: usize = 12;
pub const VDISCARD: usize = 13;
pub const VWERASE: usize = 14;
pub const OLCUC: ::tcflag_t = 0o000002;
pub const ONLCR: ::tcflag_t = 0o000004;
pub const NLDLY: ::tcflag_t = 0o000400;
pub const CRDLY: ::tcflag_t = 0o003000;
pub const CR1: ::tcflag_t = 0x00000200;
pub const CR2: ::tcflag_t = 0x00000400;
pub const CR3: ::tcflag_t = 0x00000600;
pub const TABDLY: ::tcflag_t = 0o014000;
pub const TAB1: ::tcflag_t = 0x00000800;
pub const TAB2: ::tcflag_t = 0x00001000;
pub const TAB3: ::tcflag_t = 0x00001800;
pub const BSDLY: ::tcflag_t = 0o020000;
pub const BS1: ::tcflag_t = 0x00002000;
pub const FFDLY: ::tcflag_t = 0o100000;
pub const FF1: ::tcflag_t = 0x00008000;
pub const VTDLY: ::tcflag_t = 0o040000;
pub const VT1: ::tcflag_t = 0x00004000;
pub const XTABS: ::tcflag_t = 0o014000;
pub const TIOCM_LE: ::c_int = 0x001;
pub const TIOCM_DTR: ::c_int = 0x002;
pub const TIOCM_RTS: ::c_int = 0x004;
pub const TIOCM_ST: ::c_int = 0x008;
pub const TIOCM_SR: ::c_int = 0x010;
pub const TIOCM_CTS: ::c_int = 0x020;
pub const TIOCM_CAR: ::c_int = 0x040;
pub const TIOCM_RNG: ::c_int = 0x080;
pub const TIOCM_DSR: ::c_int = 0x100;
pub const TIOCM_CD: ::c_int = TIOCM_CAR;
pub const TIOCM_RI: ::c_int = TIOCM_RNG;
pub const SIGEV_THREAD_ID: ::c_int = 4;
pub const CBAUD: ::speed_t = 0o010017;
pub const B0: ::speed_t = 0o000000;
pub const B50: ::speed_t = 0o000001;
pub const B75: ::speed_t = 0o000002;
pub const B110: ::speed_t = 0o000003;
pub const B134: ::speed_t = 0o000004;
pub const B150: ::speed_t = 0o000005;
pub const B200: ::speed_t = 0o000006;
pub const B300: ::speed_t = 0o000007;
pub const B600: ::speed_t = 0o000010;
pub const B1200: ::speed_t = 0o000011;
pub const B1800: ::speed_t = 0o000012;
pub const B2400: ::speed_t = 0o000013;
pub const B4800: ::speed_t = 0o000014;
pub const B9600: ::speed_t = 0o000015;
pub const B19200: ::speed_t = 0o000016;
pub const B38400: ::speed_t = 0o000017;
pub const EXTA: ::speed_t = B19200;
pub const EXTB: ::speed_t = B38400;
pub const CSIZE: ::tcflag_t = 0o000060;
pub const CS6: ::tcflag_t = 0o000020;
pub const CS7: ::tcflag_t = 0o000040;
pub const CS8: ::tcflag_t = 0o000060;
pub const CSTOPB: ::tcflag_t = 0o000100;
pub const CREAD: ::tcflag_t = 0o000200;
pub const PARENB: ::tcflag_t = 0o000400;
pub const PARODD: ::tcflag_t = 0o001000;
pub const HUPCL: ::tcflag_t = 0o002000;
pub const CLOCAL: ::tcflag_t = 0o004000;
pub const CBAUDEX: ::tcflag_t = 0o010000;
pub const BOTHER: ::speed_t = 0o010000;
pub const B57600: ::speed_t = 0o010001;
pub const B115200: ::speed_t = 0o010002;
pub const B230400: ::speed_t = 0o010003;
pub const B460800: ::speed_t = 0o010004;
pub const B500000: ::speed_t = 0o010005;
pub const B576000: ::speed_t = 0o010006;
pub const B921600: ::speed_t = 0o010007;
pub const B1000000: ::speed_t = 0o010010;
pub const B1152000: ::speed_t = 0o010011;
pub const B1500000: ::speed_t = 0o010012;
pub const B2000000: ::speed_t = 0o010013;
pub const B2500000: ::speed_t = 0o010014;
pub const B3000000: ::speed_t = 0o010015;
pub const B3500000: ::speed_t = 0o010016;
pub const B4000000: ::speed_t = 0o010017;
pub const CIBAUD: ::tcflag_t = 0o02003600000;
pub const ISIG: ::tcflag_t = 0o000001;
pub const ICANON: ::tcflag_t = 0o000002;
pub const XCASE: ::tcflag_t = 0o000004;
pub const ECHOE: ::tcflag_t = 0o000020;
pub const ECHOK: ::tcflag_t = 0o000040;
pub const ECHONL: ::tcflag_t = 0o000100;
pub const NOFLSH: ::tcflag_t = 0o000200;
pub const ECHOCTL: ::tcflag_t = 0o001000;
pub const ECHOPRT: ::tcflag_t = 0o002000;
pub const ECHOKE: ::tcflag_t = 0o004000;
pub const PENDIN: ::tcflag_t = 0o040000;
pub const POLLWRNORM: ::c_short = 0x100;
pub const POLLWRBAND: ::c_short = 0x200;
pub const IXON: ::tcflag_t = 0o002000;
pub const IXOFF: ::tcflag_t = 0o010000;
pub const SYS_exit: ::c_long = 1;
pub const SYS_fork: ::c_long = 2;
pub const SYS_read: ::c_long = 3;
pub const SYS_write: ::c_long = 4;
pub const SYS_open: ::c_long = 5;
pub const SYS_close: ::c_long = 6;
pub const SYS_restart_syscall: ::c_long = 7;
pub const SYS_creat: ::c_long = 8;
pub const SYS_link: ::c_long = 9;
pub const SYS_unlink: ::c_long = 10;
pub const SYS_execve: ::c_long = 11;
pub const SYS_chdir: ::c_long = 12;
pub const SYS_mknod: ::c_long = 14;
pub const SYS_chmod: ::c_long = 15;
pub const SYS_lseek: ::c_long = 19;
pub const SYS_getpid: ::c_long = 20;
pub const SYS_mount: ::c_long = 21;
pub const SYS_umount: ::c_long = 22;
pub const SYS_ptrace: ::c_long = 26;
pub const SYS_alarm: ::c_long = 27;
pub const SYS_pause: ::c_long = 29;
pub const SYS_utime: ::c_long = 30;
pub const SYS_access: ::c_long = 33;
pub const SYS_nice: ::c_long = 34;
pub const SYS_sync: ::c_long = 36;
pub const SYS_kill: ::c_long = 37;
pub const SYS_rename: ::c_long = 38;
pub const SYS_mkdir: ::c_long = 39;
pub const SYS_rmdir: ::c_long = 40;
pub const SYS_dup: ::c_long = 41;
pub const SYS_pipe: ::c_long = 42;
pub const SYS_times: ::c_long = 43;
pub const SYS_brk: ::c_long = 45;
pub const SYS_signal: ::c_long = 48;
pub const SYS_acct: ::c_long = 51;
pub const SYS_umount2: ::c_long = 52;
pub const SYS_ioctl: ::c_long = 54;
pub const SYS_fcntl: ::c_long = 55;
pub const SYS_setpgid: ::c_long = 57;
pub const SYS_umask: ::c_long = 60;
pub const SYS_chroot: ::c_long = 61;
pub const SYS_ustat: ::c_long = 62;
pub const SYS_dup2: ::c_long = 63;
pub const SYS_getppid: ::c_long = 64;
pub const SYS_getpgrp: ::c_long = 65;
pub const SYS_setsid: ::c_long = 66;
pub const SYS_sigaction: ::c_long = 67;
pub const SYS_sigsuspend: ::c_long = 72;
pub const SYS_sigpending: ::c_long = 73;
pub const SYS_sethostname: ::c_long = 74;
pub const SYS_setrlimit: ::c_long = 75;
pub const SYS_getrusage: ::c_long = 77;
pub const SYS_gettimeofday: ::c_long = 78;
pub const SYS_settimeofday: ::c_long = 79;
pub const SYS_symlink: ::c_long = 83;
pub const SYS_readlink: ::c_long = 85;
pub const SYS_uselib: ::c_long = 86;
pub const SYS_swapon: ::c_long = 87;
pub const SYS_reboot: ::c_long = 88;
pub const SYS_readdir: ::c_long = 89;
pub const SYS_mmap: ::c_long = 90;
pub const SYS_munmap: ::c_long = 91;
pub const SYS_truncate: ::c_long = 92;
pub const SYS_ftruncate: ::c_long = 93;
pub const SYS_fchmod: ::c_long = 94;
pub const SYS_getpriority: ::c_long = 96;
pub const SYS_setpriority: ::c_long = 97;
pub const SYS_statfs: ::c_long = 99;
pub const SYS_fstatfs: ::c_long = 100;
pub const SYS_socketcall: ::c_long = 102;
pub const SYS_syslog: ::c_long = 103;
pub const SYS_setitimer: ::c_long = 104;
pub const SYS_getitimer: ::c_long = 105;
pub const SYS_stat: ::c_long = 106;
pub const SYS_lstat: ::c_long = 107;
pub const SYS_fstat: ::c_long = 108;
pub const SYS_lookup_dcookie: ::c_long = 110;
pub const SYS_vhangup: ::c_long = 111;
pub const SYS_idle: ::c_long = 112;
pub const SYS_wait4: ::c_long = 114;
pub const SYS_swapoff: ::c_long = 115;
pub const SYS_sysinfo: ::c_long = 116;
pub const SYS_ipc: ::c_long = 117;
pub const SYS_fsync: ::c_long = 118;
pub const SYS_sigreturn: ::c_long = 119;
pub const SYS_clone: ::c_long = 120;
pub const SYS_setdomainname: ::c_long = 121;
pub const SYS_uname: ::c_long = 122;
pub const SYS_adjtimex: ::c_long = 124;
pub const SYS_mprotect: ::c_long = 125;
pub const SYS_sigprocmask: ::c_long = 126;
pub const SYS_create_module: ::c_long = 127;
pub const SYS_init_module: ::c_long = 128;
pub const SYS_delete_module: ::c_long = 129;
pub const SYS_get_kernel_syms: ::c_long = 130;
pub const SYS_quotactl: ::c_long = 131;
pub const SYS_getpgid: ::c_long = 132;
pub const SYS_fchdir: ::c_long = 133;
pub const SYS_bdflush: ::c_long = 134;
pub const SYS_sysfs: ::c_long = 135;
pub const SYS_personality: ::c_long = 136;
pub const SYS_afs_syscall: ::c_long = 137; /* Syscall for Andrew File System */
pub const SYS_getdents: ::c_long = 141;
pub const SYS_flock: ::c_long = 143;
pub const SYS_msync: ::c_long = 144;
pub const SYS_readv: ::c_long = 145;
pub const SYS_writev: ::c_long = 146;
pub const SYS_getsid: ::c_long = 147;
pub const SYS_fdatasync: ::c_long = 148;
pub const SYS__sysctl: ::c_long = 149;
pub const SYS_mlock: ::c_long = 150;
pub const SYS_munlock: ::c_long = 151;
pub const SYS_mlockall: ::c_long = 152;
pub const SYS_munlockall: ::c_long = 153;
pub const SYS_sched_setparam: ::c_long = 154;
pub const SYS_sched_getparam: ::c_long = 155;
pub const SYS_sched_setscheduler: ::c_long = 156;
pub const SYS_sched_getscheduler: ::c_long = 157;
pub const SYS_sched_yield: ::c_long = 158;
pub const SYS_sched_get_priority_max: ::c_long = 159;
pub const SYS_sched_get_priority_min: ::c_long = 160;
pub const SYS_sched_rr_get_interval: ::c_long = 161;
pub const SYS_nanosleep: ::c_long = 162;
pub const SYS_mremap: ::c_long = 163;
pub const SYS_query_module: ::c_long = 167;
pub const SYS_poll: ::c_long = 168;
pub const SYS_nfsservctl: ::c_long = 169;
pub const SYS_prctl: ::c_long = 172;
pub const SYS_rt_sigreturn: ::c_long = 173;
pub const SYS_rt_sigaction: ::c_long = 174;
pub const SYS_rt_sigprocmask: ::c_long = 175;
pub const SYS_rt_sigpending: ::c_long = 176;
pub const SYS_rt_sigtimedwait: ::c_long = 177;
pub const SYS_rt_sigqueueinfo: ::c_long = 178;
pub const SYS_rt_sigsuspend: ::c_long = 179;
pub const SYS_pread64: ::c_long = 180;
pub const SYS_pwrite64: ::c_long = 181;
pub const SYS_getcwd: ::c_long = 183;
pub const SYS_capget: ::c_long = 184;
pub const SYS_capset: ::c_long = 185;
pub const SYS_sigaltstack: ::c_long = 186;
pub const SYS_sendfile: ::c_long = 187;
pub const SYS_getpmsg: ::c_long = 188;
pub const SYS_putpmsg: ::c_long = 189;
pub const SYS_vfork: ::c_long = 190;
pub const SYS_pivot_root: ::c_long = 217;
pub const SYS_mincore: ::c_long = 218;
pub const SYS_madvise: ::c_long = 219;
pub const SYS_getdents64: ::c_long = 220;
pub const SYS_readahead: ::c_long = 222;
pub const SYS_setxattr: ::c_long = 224;
pub const SYS_lsetxattr: ::c_long = 225;
pub const SYS_fsetxattr: ::c_long = 226;
pub const SYS_getxattr: ::c_long = 227;
pub const SYS_lgetxattr: ::c_long = 228;
pub const SYS_fgetxattr: ::c_long = 229;
pub const SYS_listxattr: ::c_long = 230;
pub const SYS_llistxattr: ::c_long = 231;
pub const SYS_flistxattr: ::c_long = 232;
pub const SYS_removexattr: ::c_long = 233;
pub const SYS_lremovexattr: ::c_long = 234;
pub const SYS_fremovexattr: ::c_long = 235;
pub const SYS_gettid: ::c_long = 236;
pub const SYS_tkill: ::c_long = 237;
pub const SYS_futex: ::c_long = 238;
pub const SYS_sched_setaffinity: ::c_long = 239;
pub const SYS_sched_getaffinity: ::c_long = 240;
pub const SYS_tgkill: ::c_long = 241;
pub const SYS_io_setup: ::c_long = 243;
pub const SYS_io_destroy: ::c_long = 244;
pub const SYS_io_getevents: ::c_long = 245;
pub const SYS_io_submit: ::c_long = 246;
pub const SYS_io_cancel: ::c_long = 247;
pub const SYS_exit_group: ::c_long = 248;
pub const SYS_epoll_create: ::c_long = 249;
pub const SYS_epoll_ctl: ::c_long = 250;
pub const SYS_epoll_wait: ::c_long = 251;
pub const SYS_set_tid_address: ::c_long = 252;
pub const SYS_fadvise64: ::c_long = 253;
pub const SYS_timer_create: ::c_long = 254;
pub const SYS_timer_settime: ::c_long = 255;
pub const SYS_timer_gettime: ::c_long = 256;
pub const SYS_timer_getoverrun: ::c_long = 257;
pub const SYS_timer_delete: ::c_long = 258;
pub const SYS_clock_settime: ::c_long = 259;
pub const SYS_clock_gettime: ::c_long = 260;
pub const SYS_clock_getres: ::c_long = 261;
pub const SYS_clock_nanosleep: ::c_long = 262;
pub const SYS_statfs64: ::c_long = 265;
pub const SYS_fstatfs64: ::c_long = 266;
pub const SYS_remap_file_pages: ::c_long = 267;
pub const SYS_mbind: ::c_long = 268;
pub const SYS_get_mempolicy: ::c_long = 269;
pub const SYS_set_mempolicy: ::c_long = 270;
pub const SYS_mq_open: ::c_long = 271;
pub const SYS_mq_unlink: ::c_long = 272;
pub const SYS_mq_timedsend: ::c_long = 273;
pub const SYS_mq_timedreceive: ::c_long = 274;
pub const SYS_mq_notify: ::c_long = 275;
pub const SYS_mq_getsetattr: ::c_long = 276;
pub const SYS_kexec_load: ::c_long = 277;
pub const SYS_add_key: ::c_long = 278;
pub const SYS_request_key: ::c_long = 279;
pub const SYS_keyctl: ::c_long = 280;
pub const SYS_waitid: ::c_long = 281;
pub const SYS_ioprio_set: ::c_long = 282;
pub const SYS_ioprio_get: ::c_long = 283;
pub const SYS_inotify_init: ::c_long = 284;
pub const SYS_inotify_add_watch: ::c_long = 285;
pub const SYS_inotify_rm_watch: ::c_long = 286;
pub const SYS_migrate_pages: ::c_long = 287;
pub const SYS_openat: ::c_long = 288;
pub const SYS_mkdirat: ::c_long = 289;
pub const SYS_mknodat: ::c_long = 290;
pub const SYS_fchownat: ::c_long = 291;
pub const SYS_futimesat: ::c_long = 292;
pub const SYS_unlinkat: ::c_long = 294;
pub const SYS_renameat: ::c_long = 295;
pub const SYS_linkat: ::c_long = 296;
pub const SYS_symlinkat: ::c_long = 297;
pub const SYS_readlinkat: ::c_long = 298;
pub const SYS_fchmodat: ::c_long = 299;
pub const SYS_faccessat: ::c_long = 300;
pub const SYS_pselect6: ::c_long = 301;
pub const SYS_ppoll: ::c_long = 302;
pub const SYS_unshare: ::c_long = 303;
pub const SYS_set_robust_list: ::c_long = 304;
pub const SYS_get_robust_list: ::c_long = 305;
pub const SYS_splice: ::c_long = 306;
pub const SYS_sync_file_range: ::c_long = 307;
pub const SYS_tee: ::c_long = 308;
pub const SYS_vmsplice: ::c_long = 309;
pub const SYS_move_pages: ::c_long = 310;
pub const SYS_getcpu: ::c_long = 311;
pub const SYS_epoll_pwait: ::c_long = 312;
pub const SYS_utimes: ::c_long = 313;
pub const SYS_fallocate: ::c_long = 314;
pub const SYS_utimensat: ::c_long = 315;
pub const SYS_signalfd: ::c_long = 316;
pub const SYS_timerfd: ::c_long = 317;
pub const SYS_eventfd: ::c_long = 318;
pub const SYS_timerfd_create: ::c_long = 319;
pub const SYS_timerfd_settime: ::c_long = 320;
pub const SYS_timerfd_gettime: ::c_long = 321;
pub const SYS_signalfd4: ::c_long = 322;
pub const SYS_eventfd2: ::c_long = 323;
pub const SYS_inotify_init1: ::c_long = 324;
pub const SYS_pipe2: ::c_long = 325;
pub const SYS_dup3: ::c_long = 326;
pub const SYS_epoll_create1: ::c_long = 327;
pub const SYS_preadv: ::c_long = 328;
pub const SYS_pwritev: ::c_long = 329;
pub const SYS_rt_tgsigqueueinfo: ::c_long = 330;
pub const SYS_perf_event_open: ::c_long = 331;
pub const SYS_fanotify_init: ::c_long = 332;
pub const SYS_fanotify_mark: ::c_long = 333;
pub const SYS_prlimit64: ::c_long = 334;
pub const SYS_name_to_handle_at: ::c_long = 335;
pub const SYS_open_by_handle_at: ::c_long = 336;
pub const SYS_clock_adjtime: ::c_long = 337;
pub const SYS_syncfs: ::c_long = 338;
pub const SYS_setns: ::c_long = 339;
pub const SYS_process_vm_readv: ::c_long = 340;
pub const SYS_process_vm_writev: ::c_long = 341;
pub const SYS_s390_runtime_instr: ::c_long = 342;
pub const SYS_kcmp: ::c_long = 343;
pub const SYS_finit_module: ::c_long = 344;
pub const SYS_sched_setattr: ::c_long = 345;
pub const SYS_sched_getattr: ::c_long = 346;
pub const SYS_renameat2: ::c_long = 347;
pub const SYS_seccomp: ::c_long = 348;
pub const SYS_getrandom: ::c_long = 349;
pub const SYS_memfd_create: ::c_long = 350;
pub const SYS_bpf: ::c_long = 351;
pub const SYS_s390_pci_mmio_write: ::c_long = 352;
pub const SYS_s390_pci_mmio_read: ::c_long = 353;
pub const SYS_execveat: ::c_long = 354;
pub const SYS_userfaultfd: ::c_long = 355;
pub const SYS_membarrier: ::c_long = 356;<|fim▁hole|>pub const SYS_socket: ::c_long = 359;
pub const SYS_socketpair: ::c_long = 360;
pub const SYS_bind: ::c_long = 361;
pub const SYS_connect: ::c_long = 362;
pub const SYS_listen: ::c_long = 363;
pub const SYS_accept4: ::c_long = 364;
pub const SYS_getsockopt: ::c_long = 365;
pub const SYS_setsockopt: ::c_long = 366;
pub const SYS_getsockname: ::c_long = 367;
pub const SYS_getpeername: ::c_long = 368;
pub const SYS_sendto: ::c_long = 369;
pub const SYS_sendmsg: ::c_long = 370;
pub const SYS_recvfrom: ::c_long = 371;
pub const SYS_recvmsg: ::c_long = 372;
pub const SYS_shutdown: ::c_long = 373;
pub const SYS_mlock2: ::c_long = 374;
pub const SYS_copy_file_range: ::c_long = 375;
pub const SYS_preadv2: ::c_long = 376;
pub const SYS_pwritev2: ::c_long = 377;
pub const SYS_lchown: ::c_long = 198;
pub const SYS_setuid: ::c_long = 213;
pub const SYS_getuid: ::c_long = 199;
pub const SYS_setgid: ::c_long = 214;
pub const SYS_getgid: ::c_long = 200;
pub const SYS_geteuid: ::c_long = 201;
pub const SYS_setreuid: ::c_long = 203;
pub const SYS_setregid: ::c_long = 204;
pub const SYS_getrlimit: ::c_long = 191;
pub const SYS_getgroups: ::c_long = 205;
pub const SYS_fchown: ::c_long = 207;
pub const SYS_setresuid: ::c_long = 208;
pub const SYS_setresgid: ::c_long = 210;
pub const SYS_getresgid: ::c_long = 211;
pub const SYS_select: ::c_long = 142;
pub const SYS_getegid: ::c_long = 202;
pub const SYS_setgroups: ::c_long = 206;
pub const SYS_getresuid: ::c_long = 209;
pub const SYS_chown: ::c_long = 212;
pub const SYS_setfsuid: ::c_long = 215;
pub const SYS_setfsgid: ::c_long = 216;
pub const SYS_newfstatat: ::c_long = 293;
#[link(name = "util")]
extern {
pub fn sysctl(name: *mut ::c_int,
namelen: ::c_int,
oldp: *mut ::c_void,
oldlenp: *mut ::size_t,
newp: *mut ::c_void,
newlen: ::size_t)
-> ::c_int;
pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int;
pub fn backtrace(buf: *mut *mut ::c_void,
sz: ::c_int) -> ::c_int;
pub fn glob64(pattern: *const ::c_char,
flags: ::c_int,
errfunc: ::Option<extern fn(epath: *const ::c_char,
errno: ::c_int)
-> ::c_int>,
pglob: *mut glob64_t) -> ::c_int;
pub fn globfree64(pglob: *mut glob64_t);
pub fn ptrace(request: ::c_uint, ...) -> ::c_long;
pub fn pthread_attr_getaffinity_np(attr: *const ::pthread_attr_t,
cpusetsize: ::size_t,
cpuset: *mut ::cpu_set_t) -> ::c_int;
pub fn pthread_attr_setaffinity_np(attr: *mut ::pthread_attr_t,
cpusetsize: ::size_t,
cpuset: *const ::cpu_set_t) -> ::c_int;
pub fn getpriority(which: ::__priority_which_t, who: ::id_t) -> ::c_int;
pub fn setpriority(which: ::__priority_which_t, who: ::id_t,
prio: ::c_int) -> ::c_int;
pub fn pthread_getaffinity_np(thread: ::pthread_t,
cpusetsize: ::size_t,
cpuset: *mut ::cpu_set_t) -> ::c_int;
pub fn pthread_setaffinity_np(thread: ::pthread_t,
cpusetsize: ::size_t,
cpuset: *const ::cpu_set_t) -> ::c_int;
pub fn sched_getcpu() -> ::c_int;
pub fn getcontext(ucp: *mut ucontext_t) -> ::c_int;
pub fn setcontext(ucp: *const ucontext_t) -> ::c_int;
pub fn makecontext(ucp: *mut ucontext_t,
func: extern fn (),
argc: ::c_int, ...);
pub fn swapcontext(uocp: *mut ucontext_t,
ucp: *const ucontext_t) -> ::c_int;
}
cfg_if! {
if #[cfg(libc_align)] {
mod align;
pub use self::align::*;
} else {
mod no_align;
pub use self::no_align::*;
}
}<|fim▁end|>
|
pub const SYS_recvmmsg: ::c_long = 357;
pub const SYS_sendmmsg: ::c_long = 358;
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>extern crate android_glue;
use libc;
use std::ffi::{CString};
use std::sync::mpsc::{Receiver, channel};
use {CreationError, Event, MouseCursor};
use CreationError::OsError;
use events::ElementState::{Pressed, Released};
use events::Event::{MouseInput, MouseMoved};
use events::MouseButton;
use std::collections::VecDeque;
use Api;
use BuilderAttribs;
use GlRequest;
use native_monitor::NativeMonitorId;
pub struct Window {
display: ffi::egl::types::EGLDisplay,
context: ffi::egl::types::EGLContext,
surface: ffi::egl::types::EGLSurface,
event_rx: Receiver<android_glue::Event>,
}
pub struct MonitorID;
mod ffi;
pub fn get_available_monitors() -> VecDeque <MonitorID> {
let mut rb = VecDeque::new();
rb.push_back(MonitorID);
rb
}
pub fn get_primary_monitor() -> MonitorID {
MonitorID
}
impl MonitorID {
pub fn get_name(&self) -> Option<String> {
Some("Primary".to_string())
}
pub fn get_native_identifier(&self) -> NativeMonitorId {
NativeMonitorId::Unavailable
}
pub fn get_dimensions(&self) -> (u32, u32) {
unimplemented!()
}
}
#[cfg(feature = "headless")]
pub struct HeadlessContext(i32);
#[cfg(feature = "headless")]
impl HeadlessContext {
/// See the docs in the crate root file.
pub fn new(_builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> {
unimplemented!()
}
/// See the docs in the crate root file.
pub unsafe fn make_current(&self) {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn is_current(&self) -> bool {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn get_proc_address(&self, _addr: &str) -> *const () {
unimplemented!()
}
pub fn get_api(&self) -> ::Api {
::Api::OpenGlEs
}
}
#[cfg(feature = "headless")]
unsafe impl Send for HeadlessContext {}
#[cfg(feature = "headless")]
unsafe impl Sync for HeadlessContext {}
pub struct PollEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
match self.window.event_rx.try_recv() {
Ok(event) => {
match event {
android_glue::Event::EventDown => Some(MouseInput(Pressed, MouseButton::Left)),
android_glue::Event::EventUp => Some(MouseInput(Released, MouseButton::Left)),
android_glue::Event::EventMove(x, y) => Some(MouseMoved((x as i32, y as i32))),
_ => None,
}
}
Err(_) => {
None
}
}
}
}
pub struct WaitEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
use std::time::Duration;
use std::old_io::timer;
loop {
// calling poll_events()
if let Some(ev) = self.window.poll_events().next() {
return Some(ev);
}
// TODO: Implement a proper way of sleeping on the event queue
timer::sleep(Duration::milliseconds(16));
}
}
}
impl Window {
pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> {
use std::{mem, ptr};
<|fim▁hole|> let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() {
return Err(OsError(format!("Android's native window is null")));
}
let display = unsafe {
let display = ffi::egl::GetDisplay(mem::transmute(ffi::egl::DEFAULT_DISPLAY));
if display.is_null() {
return Err(OsError("No EGL display connection available".to_string()));
}
display
};
android_glue::write_log("eglGetDisplay succeeded");
let (_major, _minor) = unsafe {
let mut major: ffi::egl::types::EGLint = mem::uninitialized();
let mut minor: ffi::egl::types::EGLint = mem::uninitialized();
if ffi::egl::Initialize(display, &mut major, &mut minor) == 0 {
return Err(OsError(format!("eglInitialize failed")))
}
(major, minor)
};
android_glue::write_log("eglInitialize succeeded");
let use_gles2 = match builder.gl_version {
GlRequest::Specific(Api::OpenGlEs, (2, _)) => true,
GlRequest::Specific(Api::OpenGlEs, _) => false,
GlRequest::Specific(_, _) => panic!("Only OpenGL ES is supported"), // FIXME: return a result
GlRequest::GlThenGles { opengles_version: (2, _), .. } => true,
_ => false,
};
let mut attribute_list = vec!();
if use_gles2 {
attribute_list.push_all(&[
ffi::egl::RENDERABLE_TYPE as i32,
ffi::egl::OPENGL_ES2_BIT as i32,
]);
}
{
let (red, green, blue) = match builder.color_bits.unwrap_or(24) {
24 => (8, 8, 8),
16 => (6, 5, 6),
_ => panic!("Bad color_bits"),
};
attribute_list.push_all(&[ffi::egl::RED_SIZE as i32, red]);
attribute_list.push_all(&[ffi::egl::GREEN_SIZE as i32, green]);
attribute_list.push_all(&[ffi::egl::BLUE_SIZE as i32, blue]);
}
attribute_list.push_all(&[
ffi::egl::DEPTH_SIZE as i32,
builder.depth_bits.unwrap_or(8) as i32,
]);
attribute_list.push(ffi::egl::NONE as i32);
let config = unsafe {
let mut num_config: ffi::egl::types::EGLint = mem::uninitialized();
let mut config: ffi::egl::types::EGLConfig = mem::uninitialized();
if ffi::egl::ChooseConfig(display, attribute_list.as_ptr(), &mut config, 1,
&mut num_config) == 0
{
return Err(OsError(format!("eglChooseConfig failed")))
}
if num_config <= 0 {
return Err(OsError(format!("eglChooseConfig returned no available config")))
}
config
};
android_glue::write_log("eglChooseConfig succeeded");
let context = unsafe {
let mut context_attributes = vec!();
if use_gles2 {
context_attributes.push_all(&[ffi::egl::CONTEXT_CLIENT_VERSION as i32, 2]);
}
context_attributes.push(ffi::egl::NONE as i32);
let context = ffi::egl::CreateContext(display, config, ptr::null(),
context_attributes.as_ptr());
if context.is_null() {
return Err(OsError(format!("eglCreateContext failed")))
}
context
};
android_glue::write_log("eglCreateContext succeeded");
let surface = unsafe {
let surface = ffi::egl::CreateWindowSurface(display, config, native_window, ptr::null());
if surface.is_null() {
return Err(OsError(format!("eglCreateWindowSurface failed")))
}
surface
};
android_glue::write_log("eglCreateWindowSurface succeeded");
let (tx, rx) = channel();
android_glue::add_sender(tx);
Ok(Window {
display: display,
context: context,
surface: surface,
event_rx: rx,
})
}
pub fn is_closed(&self) -> bool {
false
}
pub fn set_title(&self, _: &str) {
}
pub fn show(&self) {
}
pub fn hide(&self) {
}
pub fn get_position(&self) -> Option<(i32, i32)> {
None
}
pub fn set_position(&self, _x: i32, _y: i32) {
}
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() {
None
} else {
Some((
unsafe { ffi::ANativeWindow_getWidth(native_window) } as u32,
unsafe { ffi::ANativeWindow_getHeight(native_window) } as u32
))
}
}
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.get_inner_size()
}
pub fn set_inner_size(&self, _x: u32, _y: u32) {
}
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy
}
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator {
window: self
}
}
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator {
window: self
}
}
pub fn make_current(&self) {
unsafe {
ffi::egl::MakeCurrent(self.display, self.surface, self.surface, self.context);
}
}
pub fn is_current(&self) -> bool {
unsafe { ffi::egl::GetCurrentContext() == self.context }
}
pub fn get_proc_address(&self, addr: &str) -> *const () {
let addr = CString::from_slice(addr.as_bytes());
let addr = addr.as_ptr();
unsafe {
ffi::egl::GetProcAddress(addr) as *const ()
}
}
pub fn swap_buffers(&self) {
unsafe {
ffi::egl::SwapBuffers(self.display, self.surface);
}
}
pub fn platform_display(&self) -> *mut libc::c_void {
self.display as *mut libc::c_void
}
pub fn platform_window(&self) -> *mut libc::c_void {
unimplemented!()
}
pub fn get_api(&self) -> ::Api {
::Api::OpenGlEs
}
pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) {
}
pub fn set_cursor(&self, _: MouseCursor) {
}
pub fn hidpi_factor(&self) -> f32 {
1.0
}
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
unimplemented!();
}
}
unsafe impl Send for Window {}
unsafe impl Sync for Window {}
#[cfg(feature = "window")]
#[derive(Clone)]
pub struct WindowProxy;
impl WindowProxy {
pub fn wakeup_event_loop(&self) {
unimplemented!()
}
}
#[unsafe_destructor]
impl Drop for Window {
fn drop(&mut self) {
use std::ptr;
unsafe {
// we don't call MakeCurrent(0, 0) because we are not sure that the context
// is still the current one
android_glue::write_log("Destroying gl-init window");
ffi::egl::DestroySurface(self.display, self.surface);
ffi::egl::DestroyContext(self.display, self.context);
ffi::egl::Terminate(self.display);
}
}
}<|fim▁end|>
|
if builder.sharing.is_some() {
unimplemented!()
}
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>pub mod audio_io;
pub mod debug;
pub mod flow;
pub mod livecode;
use futures::executor;
use std::sync::Arc;
pub trait Module: Send {
fn new(ifc: Arc<flow::Interface>) -> Self
where
Self: Sized;
fn name() -> &'static str
where
Self: Sized;
fn start<Ex: executor::Executor>(&mut self, exec: Ex);<|fim▁hole|> fn ports(&self) -> Vec<Arc<flow::OpaquePort>>;
}<|fim▁end|>
|
fn stop(&mut self);
|
<|file_name|>result-get-panic.rs<|end_file_name|><|fim▁begin|>// run-fail
// error-pattern:called `Result::unwrap()` on an `Err` value
// ignore-emscripten no processes
<|fim▁hole|>
fn main() {
println!("{}", Err::<isize, String>("kitty".to_string()).unwrap());
}<|fim▁end|>
|
use std::result::Result::Err;
|
<|file_name|>parselocator_test.go<|end_file_name|><|fim▁begin|>package maidenhead
import (
"math"
"strings"
"testing"
)
// parsed locator must be translated to the same locator
// using GridSquare()
func TestParseLocator(t *testing.T) {
var locTests = map[string]Point{
"JN88RT": Point{48.791667, 17.416667},
"JN89HF": Point{49.208333, 16.583333},
"JN58TD": Point{48.125000, 11.583333},<|fim▁hole|> "GF15VC": Point{-34.916667, -56.250000},
"FM18LW": Point{38.916667, -77.083333},
"RE78IR": Point{-41.291667, 174.666667},
"PM45lm": Point{35.5, 128.916667},
}
for loc, p := range locTests {
point, err := ParseLocator(loc)
if err != nil {
t.Errorf("%s parsing error: %s", loc, err)
continue
}
l, err := point.GridSquare()
if err != nil {
t.Errorf("%s: %v to GridSquare(): %s", loc, point, err)
continue
}
if !strings.EqualFold(l, loc) {
t.Errorf("%s: parsed to %v produces %s\n", loc, point, l)
}
if !(almostEqual(p.Latitude, point.Latitude) && almostEqual(p.Longitude, point.Longitude)) {
t.Errorf("%s: at %s, expeted %s", loc, point, p)
}
}
}
func almostEqual(a, b float64) bool {
return math.Abs(a-b) < 1e-06
}<|fim▁end|>
| |
<|file_name|>destructured-local.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-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.
// ignore-android: FIXME(#10381)
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print a
// gdb-check:$1 = 1
// gdb-command:print b
// gdb-check:$2 = false
// gdb-command:print c
// gdb-check:$3 = 2
// gdb-command:print d
// gdb-check:$4 = 3
// gdb-command:print e
// gdb-check:$5 = 4
// gdb-command:print f
// gdb-check:$6 = 5
// gdb-command:print g
// gdb-check:$7 = {6, 7}
// gdb-command:print h
// gdb-check:$8 = 8
// gdb-command:print i
// gdb-check:$9 = {a = 9, b = 10}
// gdb-command:print j
// gdb-check:$10 = 11
// gdb-command:print k
// gdb-check:$11 = 12
// gdb-command:print l
// gdb-check:$12 = 13
// gdb-command:print m
// gdb-check:$13 = 14
// gdb-command:print n
// gdb-check:$14 = 16
// gdb-command:print o
// gdb-check:$15 = 18
// gdb-command:print p
// gdb-check:$16 = 19
// gdb-command:print q
// gdb-check:$17 = 20
// gdb-command:print r
// gdb-check:$18 = {a = 21, b = 22}
// gdb-command:print s
// gdb-check:$19 = 24
// gdb-command:print t
// gdb-check:$20 = 23
// gdb-command:print u
// gdb-check:$21 = 25
// gdb-command:print v
// gdb-check:$22 = 26
// gdb-command:print w
// gdb-check:$23 = 27
// gdb-command:print x
// gdb-check:$24 = 28
// gdb-command:print y
// gdb-check:$25 = 29
// gdb-command:print z
// gdb-check:$26 = 30
// gdb-command:print ae
// gdb-check:$27 = 31
// gdb-command:print oe
// gdb-check:$28 = 32
// gdb-command:print ue
// gdb-check:$29 = 33
// gdb-command:print aa
// gdb-check:$30 = {34, 35}
// gdb-command:print bb
// gdb-check:$31 = {36, 37}
// gdb-command:print cc
// gdb-check:$32 = 38
// gdb-command:print dd
// gdb-check:$33 = {40, 41, 42}
// gdb-command:print *ee
// gdb-check:$34 = {43, 44, 45}
// gdb-command:print *ff
// gdb-check:$35 = 46
// gdb-command:print gg
// gdb-check:$36 = {47, 48}
// gdb-command:print *hh
// gdb-check:$37 = 50
// gdb-command:print ii
// gdb-check:$38 = 51
// gdb-command:print *jj
// gdb-check:$39 = 52
// gdb-command:print kk
// gdb-check:$40 = 53
// gdb-command:print ll
// gdb-check:$41 = 54
// gdb-command:print mm
// gdb-check:$42 = 55
// gdb-command:print *nn
// gdb-check:$43 = 56
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print a
// lldb-check:[...]$0 = 1
// lldb-command:print b
// lldb-check:[...]$1 = false
// lldb-command:print c
// lldb-check:[...]$2 = 2
// lldb-command:print d
// lldb-check:[...]$3 = 3
// lldb-command:print e
// lldb-check:[...]$4 = 4
// lldb-command:print f
// lldb-check:[...]$5 = 5
// lldb-command:print g
// lldb-check:[...]$6 = (6, 7)
// lldb-command:print h
// lldb-check:[...]$7 = 8
// lldb-command:print i
// lldb-check:[...]$8 = Struct { a: 9, b: 10 }
// lldb-command:print j
// lldb-check:[...]$9 = 11
// lldb-command:print k
// lldb-check:[...]$10 = 12
// lldb-command:print l
// lldb-check:[...]$11 = 13
// lldb-command:print m
// lldb-check:[...]$12 = 14
// lldb-command:print n
// lldb-check:[...]$13 = 16
// lldb-command:print o
// lldb-check:[...]$14 = 18
// lldb-command:print p
// lldb-check:[...]$15 = 19
// lldb-command:print q
// lldb-check:[...]$16 = 20
// lldb-command:print r
// lldb-check:[...]$17 = Struct { a: 21, b: 22 }
// lldb-command:print s
// lldb-check:[...]$18 = 24
// lldb-command:print t
// lldb-check:[...]$19 = 23
// lldb-command:print u
// lldb-check:[...]$20 = 25
// lldb-command:print v
// lldb-check:[...]$21 = 26
// lldb-command:print w
// lldb-check:[...]$22 = 27<|fim▁hole|>// lldb-command:print z
// lldb-check:[...]$25 = 30
// lldb-command:print ae
// lldb-check:[...]$26 = 31
// lldb-command:print oe
// lldb-check:[...]$27 = 32
// lldb-command:print ue
// lldb-check:[...]$28 = 33
// lldb-command:print aa
// lldb-check:[...]$29 = (34, 35)
// lldb-command:print bb
// lldb-check:[...]$30 = (36, 37)
// lldb-command:print cc
// lldb-check:[...]$31 = 38
// lldb-command:print dd
// lldb-check:[...]$32 = (40, 41, 42)
// lldb-command:print *ee
// lldb-check:[...]$33 = (43, 44, 45)
// lldb-command:print *ff
// lldb-check:[...]$34 = 46
// lldb-command:print gg
// lldb-check:[...]$35 = (47, 48)
// lldb-command:print *hh
// lldb-check:[...]$36 = 50
// lldb-command:print ii
// lldb-check:[...]$37 = 51
// lldb-command:print *jj
// lldb-check:[...]$38 = 52
// lldb-command:print kk
// lldb-check:[...]$39 = 53
// lldb-command:print ll
// lldb-check:[...]$40 = 54
// lldb-command:print mm
// lldb-check:[...]$41 = 55
// lldb-command:print *nn
// lldb-check:[...]$42 = 56
#![allow(unused_variables)]
struct Struct {
a: i64,
b: i32
}
enum Univariant {
Unit(i32)
}
struct TupleStruct (f64, int);
fn main() {
// simple tuple
let (a, b) : (int, bool) = (1, false);
// nested tuple
let (c, (d, e)) : (int, (u16, u16)) = (2, (3, 4));
// bind tuple-typed value to one name (destructure only first level)
let (f, g) : (int, (u32, u32)) = (5, (6, 7));
// struct as tuple element
let (h, i, j) : (i16, Struct, i16) = (8, Struct { a: 9, b: 10 }, 11);
// struct pattern
let Struct { a: k, b: l } = Struct { a: 12, b: 13 };
// ignored tuple element
let (m, _, n) = (14i, 15i, 16i);
// ignored struct field
let Struct { b: o, .. } = Struct { a: 17, b: 18 };
// one struct destructured, one not
let (Struct { a: p, b: q }, r) = (Struct { a: 19, b: 20 }, Struct { a: 21, b: 22 });
// different order of struct fields
let Struct { b: s, a: t } = Struct { a: 23, b: 24 };
// complex nesting
let ((u, v), ((w, (x, Struct { a: y, b: z})), Struct { a: ae, b: oe }), ue) =
((25i, 26i), ((27i, (28i, Struct { a: 29, b: 30})), Struct { a: 31, b: 32 }), 33i);
// reference
let &aa = &(34i, 35i);
// reference
let &bb = &(36i, 37i);
// contained reference
let (&cc, _) = (&38i, 39i);
// unique pointer
let box dd = box() (40i, 41i, 42i);
// ref binding
let ref ee = (43i, 44i, 45i);
// ref binding in tuple
let (ref ff, gg) = (46i, (47i, 48i));
// ref binding in struct
let Struct { b: ref hh, .. } = Struct { a: 49, b: 50 };
// univariant enum
let Unit(ii) = Unit(51);
// univariant enum with ref binding
let &Unit(ref jj) = &Unit(52);
// tuple struct
let &TupleStruct(kk, ll) = &TupleStruct(53.0, 54);
// tuple struct with ref binding
let &TupleStruct(mm, ref nn) = &TupleStruct(55.0, 56);
zzz(); // #break
}
fn zzz() { () }<|fim▁end|>
|
// lldb-command:print x
// lldb-check:[...]$23 = 28
// lldb-command:print y
// lldb-check:[...]$24 = 29
|
<|file_name|>Console.cpp<|end_file_name|><|fim▁begin|>////////////////////////////////////////////////////////////////////////////
// Atol file manager project <http://atol.sf.net>
//
// This code is licensed under BSD license.See "license.txt" for more details.
//
// File: TOFIX
////////////////////////////////////////////////////////////////////////////
/*
* console.c: various interactive-prompt routines shared between
* the console PuTTY tools
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "putty.h"
#include "storage.h"
#include "ssh.h"
int console_batch_mode = FALSE;
/*
* Clean up and exit.
*/
void cleanup_exit(int code)
{
/*
* Clean up.
*/
//TOFIX
//sk_cleanup();
//WSACleanup();
if (cfg.protocol == PROT_SSH) {
random_save_seed();
#ifdef MSCRYPTOAPI
crypto_wrapup();
#endif
}
//exit(code);
}
void verify_ssh_host_key(CSshSession &session, char *host, int port, char *keytype, char *keystr, char *fingerprint)
{
int ret, choice = 0;
//HANDLE hin;
//DWORD savemode, i;
static const char absentmsg_batch[] =
"The server's host key is not cached in the registry. You\n"
"have no guarantee that the server is the computer you\n"
"think it is.\n"
"The server's key fingerprint is:\n"
"%s\n"
"Connection abandoned.\n";
static const char absentmsg[] =
"The server's host key is not cached in the registry. You\n"
"have no guarantee that the server is the computer you\n"
"think it is.\n"
"The server's key fingerprint is:\n"
"%s\n"
"If you trust this host, press \"Yes\" to add the key to\n"
"PuTTY's cache and carry on connecting.\n"
"If you want to carry on connecting just once, without\n"
"adding the key to the cache, press \"No\".\n"
"If you do not trust this host, press \"Cancel\" to abandon the\n"
"connection.\n"
"Store key in cache? (y/n) ";
static const char wrongmsg_batch[] =
"WARNING - POTENTIAL SECURITY BREACH!\n"
"The server's host key does not match the one PuTTY has\n"
"cached in the registry. This means that either the\n"
"server administrator has changed the host key, or you\n"
"have actually connected to another computer pretending\n"
"to be the server.\n"
"The new key fingerprint is:\n"
"%s\n"
"Connection abandoned.\n";
static const char wrongmsg[] =
"WARNING - POTENTIAL SECURITY BREACH!\n"
"The server's host key does not match the one PuTTY has\n"
"cached in the registry. This means that either the\n"
"server administrator has changed the host key, or you\n"
"have actually connected to another computer pretending\n"
"to be the server.\n"
"The new key fingerprint is:\n"
"%s\n"
"If you were expecting this change and trust the new key,\n"
"press \"Yes\" to update Atol cache and continue connecting.\n"
"If you want to carry on connecting but without updating\n"
"the cache, press \"No\".\n"
"If you want to abandon the connection completely, press\n"
"\"Cancel\". Pressing \"Cancel\" is the ONLY guaranteed\n"
"safe choice.\n"
"Update cached key? (y/n, \"Cancel\" cancels connection) ";
static const char abandoned[] = "Connection abandoned.\n";
// char line[32];
/*
* Verify the key against the registry.
*/
ret = verify_host_key(host, port, keytype, keystr);
if (ret == 0) /* success - key matched OK */
return;
char szBuffer[512];
if (ret == 2) { /* key was different */
if (console_batch_mode) {
//TOFIX fprintf(stderr, wrongmsg_batch, fingerprint);
sprintf(szBuffer, wrongmsg_batch, fingerprint);
if(session.m_fnKeyWarning)
session.m_fnKeyWarning(szBuffer, 0, session.m_fnKeyData);
cleanup_exit(1);
}
//TOFIX fprintf(stderr, wrongmsg, fingerprint);
//TOFIX fflush(stderr);
sprintf(szBuffer, wrongmsg, fingerprint);
if(session.m_fnKeyWarning)
choice = session.m_fnKeyWarning(szBuffer, 1, session.m_fnKeyData);
}
if (ret == 1) { /* key was absent */
if (console_batch_mode) {
//TOFIX fprintf(stderr, absentmsg_batch, fingerprint);
sprintf(szBuffer, absentmsg_batch, fingerprint);
if(session.m_fnKeyWarning)
session.m_fnKeyWarning(szBuffer, 0, session.m_fnKeyData);
cleanup_exit(1);
}
//TOFIX fprintf(stderr, absentmsg, fingerprint);
//TOFIX fflush(stderr);
sprintf(szBuffer, absentmsg, fingerprint);
if(session.m_fnKeyWarning)
choice = session.m_fnKeyWarning(szBuffer, 1, session.m_fnKeyData);
}
//hin = GetStdHandle(STD_INPUT_HANDLE);
//if(hin)
{
//GetConsoleMode(hin, &savemode);
//SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT |
// ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT));
//ReadFile(hin, line, sizeof(line) - 1, &i, NULL);
//SetConsoleMode(hin, savemode);
//if (line[0] != '\0' && line[0] != '\r' && line[0] != '\n') {
if(choice > 0){
//if (line[0] == 'y' || line[0] == 'Y')
if(1 == choice)
store_host_key(host, port, keytype, keystr);
} else {
//TOFIX fprintf(stderr, abandoned);
sprintf(szBuffer, abandoned, fingerprint);
if(session.m_fnKeyWarning)
session.m_fnKeyWarning(szBuffer, 0, session.m_fnKeyData);
cleanup_exit(0);
}
}
}
/*
* Ask whether the selected cipher is acceptable (since it was
* below the configured 'warn' threshold).
* cs: 0 = both ways, 1 = client->server, 2 = server->client
*/
void askcipher(char *ciphername, int cs)
{
HANDLE hin;
DWORD savemode, i;
static const char msg[] =
"The first %scipher supported by the server is\n"
"%s, which is below the configured warning threshold.\n"
"Continue with connection? (y/n) ";
static const char msg_batch[] =
"The first %scipher supported by the server is\n"
"%s, which is below the configured warning threshold.\n"
"Connection abandoned.\n";
static const char abandoned[] = "Connection abandoned.\n";
char line[32];
if (console_batch_mode) {
//TOFIX fprintf(stderr, msg_batch,
//TOFIX (cs == 0) ? "" :
//TOFIX (cs == 1) ? "client-to-server " : "server-to-client ",
//TOFIX ciphername);
cleanup_exit(1);
}
//TOFIX fprintf(stderr, msg,
//TOFIX (cs == 0) ? "" :
//TOFIX (cs == 1) ? "client-to-server " : "server-to-client ",
//TOFIX ciphername);
//fflush(stderr);
hin = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(hin, &savemode);
SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT |
ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT));
ReadFile(hin, line, sizeof(line) - 1, &i, NULL);
SetConsoleMode(hin, savemode);
if (line[0] == 'y' || line[0] == 'Y') {
return;
} else {
//TOFIX fprintf(stderr, abandoned);
cleanup_exit(0);
}
}
/*
* Ask whether to wipe a session log file before writing to it.
* Returns 2 for wipe, 1 for append, 0 for cancel (don't log).
*/
int askappend(char *filename)
{
HANDLE hin;
DWORD savemode, i;
static const char msgtemplate[] =
"The session log file \"%.*s\" already exists.\n"
"You can overwrite it with a new session log,\n"
"append your session log to the end of it,\n"
"or disable session logging for this session.\n"
"Enter \"y\" to wipe the file, \"n\" to append to it,\n"
"or just press Return to disable logging.\n"
"Wipe the log file? (y/n, Return cancels logging) ";
static const char msgtemplate_batch[] =
"The session log file \"%.*s\" already exists.\n"
"Logging will not be enabled.\n";
char line[32];
if (cfg.logxfovr != LGXF_ASK) {
return ((cfg.logxfovr == LGXF_OVR) ? 2 : 1);
}
if (console_batch_mode) {
//TOFIX fprintf(stderr, msgtemplate_batch, FILENAME_MAX, filename);
//TOFIX fflush(stderr);
return 0;
}
<|fim▁hole|> //TOFIX fprintf(stderr, msgtemplate, FILENAME_MAX, filename);
//fflush(stderr);
hin = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(hin, &savemode);
SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT |
ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT));
ReadFile(hin, line, sizeof(line) - 1, &i, NULL);
SetConsoleMode(hin, savemode);
if (line[0] == 'y' || line[0] == 'Y')
return 2;
else if (line[0] == 'n' || line[0] == 'N')
return 1;
else
return 0;
}
/*
* Warn about the obsolescent key file format.
*/
void old_keyfile_warning(void)
{
static const char message[] =
"You are loading an SSH 2 private key which has an\n"
"old version of the file format. This means your key\n"
"file is not fully tamperproof. Future versions of\n"
"PuTTY may stop supporting this private key format,\n"
"so we recommend you convert your key to the new\n"
"format.\n"
"\n"
"Once the key is loaded into PuTTYgen, you can perform\n"
"this conversion simply by saving it again.\n";
fputs(message, stderr);
}
//TOFIX move to CSshSession
void logevent(CSshSession &session, char *string)
{
if(session.m_dbgFn)
session.m_dbgFn(string, session.m_dwDbgData);
}
char *console_password = NULL;
int console_get_line(const char *prompt, char *str,
int maxlen, int is_pw)
{
HANDLE hin, hout;
DWORD savemode, newmode, i;
if (is_pw && console_password) {
static int tried_once = 0;
if (tried_once) {
return 0;
} else {
strncpy(str, console_password, maxlen);
str[maxlen - 1] = '\0';
tried_once = 1;
return 1;
}
}
if (console_batch_mode) {
if (maxlen > 0)
str[0] = '\0';
} else {
hin = GetStdHandle(STD_INPUT_HANDLE);
hout = GetStdHandle(STD_OUTPUT_HANDLE);
if (hin == INVALID_HANDLE_VALUE || hout == INVALID_HANDLE_VALUE) {
//TOFIX fprintf(stderr, "Cannot get standard input/output handles\n");
cleanup_exit(1);
}
if (hin == NULL || hout == NULL)
return 1;
GetConsoleMode(hin, &savemode);
newmode = savemode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
if (is_pw)
newmode &= ~ENABLE_ECHO_INPUT;
else
newmode |= ENABLE_ECHO_INPUT;
SetConsoleMode(hin, newmode);
WriteFile(hout, prompt, strlen(prompt), &i, NULL);
ReadFile(hin, str, maxlen - 1, &i, NULL);
SetConsoleMode(hin, savemode);
if ((int) i > maxlen)
i = maxlen - 1;
else
i = i - 2;
str[i] = '\0';
if (is_pw)
WriteFile(hout, "\r\n", 2, &i, NULL);
}
return 1;
}<|fim▁end|>
| |
<|file_name|>divider-demo.component.ts<|end_file_name|><|fim▁begin|>import { Component, OnInit } from '@angular/core';
@Component({
template: require('./divider.html')
})<|fim▁hole|>export class DividerDemoComponent implements OnInit {
constructor() { }
ngOnInit() { }
}<|fim▁end|>
| |
<|file_name|>client_test.go<|end_file_name|><|fim▁begin|>// Copyright 2012-2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package gomaasapi
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
)
type ClientSuite struct{}
var _ = gc.Suite(&ClientSuite{})
func (*ClientSuite) TestReadAndCloseReturnsEmptyStringForNil(c *gc.C) {
data, err := readAndClose(nil)
c.Assert(err, jc.ErrorIsNil)
c.Check(string(data), gc.Equals, "")
}
func (*ClientSuite) TestReadAndCloseReturnsContents(c *gc.C) {
content := "Stream contents."
stream := ioutil.NopCloser(strings.NewReader(content))
data, err := readAndClose(stream)
c.Assert(err, jc.ErrorIsNil)
c.Check(string(data), gc.Equals, content)
}
func (suite *ClientSuite) TestClientdispatchRequestReturnsServerError(c *gc.C) {
URI := "/some/url/?param1=test"
expectedResult := "expected:result"
server := newSingleServingServer(URI, expectedResult, http.StatusBadRequest)
defer server.Close()
client, err := NewAnonymousClient(server.URL, "1.0")
c.Assert(err, jc.ErrorIsNil)
request, err := http.NewRequest("GET", server.URL+URI, nil)
result, err := client.dispatchRequest(request)
expectedErrorString := fmt.Sprintf("ServerError: 400 Bad Request (%v)", expectedResult)
c.Check(err.Error(), gc.Equals, expectedErrorString)
svrError, ok := GetServerError(err)
c.Assert(ok, jc.IsTrue)
c.Check(svrError.StatusCode, gc.Equals, 400)
c.Check(string(result), gc.Equals, expectedResult)
}
func (suite *ClientSuite) TestClientdispatchRequestRetries503(c *gc.C) {
URI := "/some/url/?param1=test"
server := newFlakyServer(URI, 503, NumberOfRetries)
defer server.Close()
client, err := NewAnonymousClient(server.URL, "1.0")
c.Assert(err, jc.ErrorIsNil)
content := "content"
request, err := http.NewRequest("GET", server.URL+URI, ioutil.NopCloser(strings.NewReader(content)))
_, err = client.dispatchRequest(request)
c.Assert(err, jc.ErrorIsNil)
c.Check(*server.nbRequests, gc.Equals, NumberOfRetries+1)
expectedRequestsContent := make([][]byte, NumberOfRetries+1)
for i := 0; i < NumberOfRetries+1; i++ {
expectedRequestsContent[i] = []byte(content)
}
c.Check(*server.requests, jc.DeepEquals, expectedRequestsContent)
}
func (suite *ClientSuite) TestClientdispatchRequestDoesntRetry200(c *gc.C) {
URI := "/some/url/?param1=test"
server := newFlakyServer(URI, 200, 10)
defer server.Close()
client, err := NewAnonymousClient(server.URL, "1.0")
c.Assert(err, jc.ErrorIsNil)
request, err := http.NewRequest("GET", server.URL+URI, nil)
_, err = client.dispatchRequest(request)
c.Assert(err, jc.ErrorIsNil)
c.Check(*server.nbRequests, gc.Equals, 1)
}
func (suite *ClientSuite) TestClientdispatchRequestRetriesIsLimited(c *gc.C) {
URI := "/some/url/?param1=test"
// Make the server return 503 responses NumberOfRetries + 1 times.
server := newFlakyServer(URI, 503, NumberOfRetries+1)
defer server.Close()
client, err := NewAnonymousClient(server.URL, "1.0")
c.Assert(err, jc.ErrorIsNil)
request, err := http.NewRequest("GET", server.URL+URI, nil)
_, err = client.dispatchRequest(request)<|fim▁hole|>
c.Check(*server.nbRequests, gc.Equals, NumberOfRetries+1)
svrError, ok := GetServerError(err)
c.Assert(ok, jc.IsTrue)
c.Assert(svrError.StatusCode, gc.Equals, 503)
}
func (suite *ClientSuite) TestClientDispatchRequestReturnsNonServerError(c *gc.C) {
client, err := NewAnonymousClient("/foo", "1.0")
c.Assert(err, jc.ErrorIsNil)
// Create a bad request that will fail to dispatch.
request, err := http.NewRequest("GET", "/", nil)
c.Assert(err, jc.ErrorIsNil)
result, err := client.dispatchRequest(request)
c.Check(err, gc.NotNil)
// This type of failure is an error, but not a ServerError.
_, ok := GetServerError(err)
c.Assert(ok, jc.IsFalse)
// For this kind of error, result is guaranteed to be nil.
c.Check(result, gc.IsNil)
}
func (suite *ClientSuite) TestClientdispatchRequestSignsRequest(c *gc.C) {
URI := "/some/url/?param1=test"
expectedResult := "expected:result"
server := newSingleServingServer(URI, expectedResult, http.StatusOK)
defer server.Close()
client, err := NewAuthenticatedClient(server.URL, "the:api:key", "1.0")
c.Assert(err, jc.ErrorIsNil)
request, err := http.NewRequest("GET", server.URL+URI, nil)
c.Assert(err, jc.ErrorIsNil)
result, err := client.dispatchRequest(request)
c.Assert(err, jc.ErrorIsNil)
c.Check(string(result), gc.Equals, expectedResult)
c.Check((*server.requestHeader)["Authorization"][0], gc.Matches, "^OAuth .*")
}
func (suite *ClientSuite) TestClientGetFormatsGetParameters(c *gc.C) {
URI, err := url.Parse("/some/url")
c.Assert(err, jc.ErrorIsNil)
expectedResult := "expected:result"
params := url.Values{"test": {"123"}}
fullURI := URI.String() + "?test=123"
server := newSingleServingServer(fullURI, expectedResult, http.StatusOK)
defer server.Close()
client, err := NewAnonymousClient(server.URL, "1.0")
c.Assert(err, jc.ErrorIsNil)
result, err := client.Get(URI, "", params)
c.Assert(err, jc.ErrorIsNil)
c.Check(string(result), gc.Equals, expectedResult)
}
func (suite *ClientSuite) TestClientGetFormatsOperationAsGetParameter(c *gc.C) {
URI, err := url.Parse("/some/url")
c.Assert(err, jc.ErrorIsNil)
expectedResult := "expected:result"
fullURI := URI.String() + "?op=list"
server := newSingleServingServer(fullURI, expectedResult, http.StatusOK)
defer server.Close()
client, err := NewAnonymousClient(server.URL, "1.0")
c.Assert(err, jc.ErrorIsNil)
result, err := client.Get(URI, "list", nil)
c.Assert(err, jc.ErrorIsNil)
c.Check(string(result), gc.Equals, expectedResult)
}
func (suite *ClientSuite) TestClientPostSendsRequestWithParams(c *gc.C) {
URI, err := url.Parse("/some/url")
c.Assert(err, jc.ErrorIsNil)
expectedResult := "expected:result"
fullURI := URI.String() + "?op=list"
params := url.Values{"test": {"123"}}
server := newSingleServingServer(fullURI, expectedResult, http.StatusOK)
defer server.Close()
client, err := NewAnonymousClient(server.URL, "1.0")
c.Assert(err, jc.ErrorIsNil)
result, err := client.Post(URI, "list", params, nil)
c.Assert(err, jc.ErrorIsNil)
c.Check(string(result), gc.Equals, expectedResult)
postedValues, err := url.ParseQuery(*server.requestContent)
c.Assert(err, jc.ErrorIsNil)
expectedPostedValues, err := url.ParseQuery("test=123")
c.Assert(err, jc.ErrorIsNil)
c.Check(postedValues, jc.DeepEquals, expectedPostedValues)
}
// extractFileContent extracts from the request built using 'requestContent',
// 'requestHeader' and 'requestURL', the file named 'filename'.
func extractFileContent(requestContent string, requestHeader *http.Header, requestURL string, filename string) ([]byte, error) {
// Recreate the request from server.requestContent to use the parsing
// utility from the http package (http.Request.FormFile).
request, err := http.NewRequest("POST", requestURL, bytes.NewBufferString(requestContent))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", requestHeader.Get("Content-Type"))
file, _, err := request.FormFile("testfile")
if err != nil {
return nil, err
}
fileContent, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
return fileContent, nil
}
func (suite *ClientSuite) TestClientPostSendsMultipartRequest(c *gc.C) {
URI, err := url.Parse("/some/url")
c.Assert(err, jc.ErrorIsNil)
expectedResult := "expected:result"
fullURI := URI.String() + "?op=add"
server := newSingleServingServer(fullURI, expectedResult, http.StatusOK)
defer server.Close()
client, err := NewAnonymousClient(server.URL, "1.0")
c.Assert(err, jc.ErrorIsNil)
fileContent := []byte("content")
files := map[string][]byte{"testfile": fileContent}
result, err := client.Post(URI, "add", nil, files)
c.Assert(err, jc.ErrorIsNil)
c.Check(string(result), gc.Equals, expectedResult)
receivedFileContent, err := extractFileContent(*server.requestContent, server.requestHeader, fullURI, "testfile")
c.Assert(err, jc.ErrorIsNil)
c.Check(receivedFileContent, jc.DeepEquals, fileContent)
}
func (suite *ClientSuite) TestClientPutSendsRequest(c *gc.C) {
URI, err := url.Parse("/some/url")
c.Assert(err, jc.ErrorIsNil)
expectedResult := "expected:result"
params := url.Values{"test": {"123"}}
server := newSingleServingServer(URI.String(), expectedResult, http.StatusOK)
defer server.Close()
client, err := NewAnonymousClient(server.URL, "1.0")
c.Assert(err, jc.ErrorIsNil)
result, err := client.Put(URI, params)
c.Assert(err, jc.ErrorIsNil)
c.Check(string(result), gc.Equals, expectedResult)
c.Check(*server.requestContent, gc.Equals, "test=123")
}
func (suite *ClientSuite) TestClientDeleteSendsRequest(c *gc.C) {
URI, err := url.Parse("/some/url")
c.Assert(err, jc.ErrorIsNil)
expectedResult := "expected:result"
server := newSingleServingServer(URI.String(), expectedResult, http.StatusOK)
defer server.Close()
client, err := NewAnonymousClient(server.URL, "1.0")
c.Assert(err, jc.ErrorIsNil)
err = client.Delete(URI)
c.Assert(err, jc.ErrorIsNil)
}
func (suite *ClientSuite) TestNewAnonymousClientEnsuresTrailingSlash(c *gc.C) {
client, err := NewAnonymousClient("http://example.com/", "1.0")
c.Assert(err, jc.ErrorIsNil)
expectedURL, err := url.Parse("http://example.com/api/1.0/")
c.Assert(err, jc.ErrorIsNil)
c.Check(client.APIURL, jc.DeepEquals, expectedURL)
}
func (suite *ClientSuite) TestNewAuthenticatedClientEnsuresTrailingSlash(c *gc.C) {
client, err := NewAuthenticatedClient("http://example.com/", "a:b:c", "1.0")
c.Assert(err, jc.ErrorIsNil)
expectedURL, err := url.Parse("http://example.com/api/1.0/")
c.Assert(err, jc.ErrorIsNil)
c.Check(client.APIURL, jc.DeepEquals, expectedURL)
}
func (suite *ClientSuite) TestNewAuthenticatedClientParsesApiKey(c *gc.C) {
// NewAuthenticatedClient returns a plainTextOAuthSigneri configured
// to use the given API key.
consumerKey := "consumerKey"
tokenKey := "tokenKey"
tokenSecret := "tokenSecret"
keyElements := []string{consumerKey, tokenKey, tokenSecret}
apiKey := strings.Join(keyElements, ":")
client, err := NewAuthenticatedClient("http://example.com/", apiKey, "1.0")
c.Assert(err, jc.ErrorIsNil)
signer := client.Signer.(*plainTextOAuthSigner)
c.Check(signer.token.ConsumerKey, gc.Equals, consumerKey)
c.Check(signer.token.TokenKey, gc.Equals, tokenKey)
c.Check(signer.token.TokenSecret, gc.Equals, tokenSecret)
}
func (suite *ClientSuite) TestNewAuthenticatedClientFailsIfInvalidKey(c *gc.C) {
client, err := NewAuthenticatedClient("", "invalid-key", "1.0")
c.Check(err, gc.ErrorMatches, "invalid API key.*")
c.Check(client, gc.IsNil)
}
func (suite *ClientSuite) TestcomposeAPIURLReturnsURL(c *gc.C) {
apiurl, err := composeAPIURL("http://example.com/MAAS", "1.0")
c.Assert(err, jc.ErrorIsNil)
expectedURL, err := url.Parse("http://example.com/MAAS/api/1.0/")
c.Assert(err, jc.ErrorIsNil)
c.Assert(expectedURL, jc.DeepEquals, apiurl)
}<|fim▁end|>
| |
<|file_name|>test_common.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import pytest
import numpy as np
from pandas import Series, Timestamp
from pandas.compat import range, lmap
import pandas.core.common as com
import pandas.util.testing as tm
def test_mut_exclusive():
msg = "mutually exclusive arguments: '[ab]' and '[ab]'"
with tm.assert_raises_regex(TypeError, msg):
com._mut_exclusive(a=1, b=2)
assert com._mut_exclusive(a=1, b=None) == 1
assert com._mut_exclusive(major=None, major_axis=None) is None
def test_get_callable_name():
from functools import partial
getname = com._get_callable_name
def fn(x):
return x
lambda_ = lambda x: x
part1 = partial(fn)
part2 = partial(part1)
class somecall(object):
def __call__(self):
return x # noqa
assert getname(fn) == 'fn'
assert getname(lambda_)
assert getname(part1) == 'fn'
assert getname(part2) == 'fn'
assert getname(somecall()) == 'somecall'
assert getname(1) is None
def test_any_none():
assert (com._any_none(1, 2, 3, None))
assert (not com._any_none(1, 2, 3, 4))
def test_all_not_none():
assert (com._all_not_none(1, 2, 3, 4))
assert (not com._all_not_none(1, 2, 3, None))
assert (not com._all_not_none(None, None, None, None))
def test_iterpairs():
data = [1, 2, 3, 4]
expected = [(1, 2), (2, 3), (3, 4)]
result = list(com.iterpairs(data))
assert (result == expected)
def test_split_ranges():
def _bin(x, width):
"return int(x) as a base2 string of given width"
return ''.join(str((x >> i) & 1) for i in range(width - 1, -1, -1))
def test_locs(mask):
nfalse = sum(np.array(mask) == 0)
remaining = 0
for s, e in com.split_ranges(mask):
remaining += e - s
assert 0 not in mask[s:e]
# make sure the total items covered by the ranges are a complete cover
assert remaining + nfalse == len(mask)
# exhaustively test all possible mask sequences of length 8
ncols = 8
for i in range(2 ** ncols):
cols = lmap(int, list(_bin(i, ncols))) # count up in base2
mask = [cols[i] == 1 for i in range(len(cols))]
test_locs(mask)
# base cases
test_locs([])
test_locs([0])
test_locs([1])
def test_map_indices_py():
data = [4, 3, 2, 1]
expected = {4: 0, 3: 1, 2: 2, 1: 3}
<|fim▁hole|>
def test_union():
a = [1, 2, 3]
b = [4, 5, 6]
union = sorted(com.union(a, b))
assert ((a + b) == union)
def test_difference():
a = [1, 2, 3]
b = [1, 2, 3, 4, 5, 6]
inter = sorted(com.difference(b, a))
assert ([4, 5, 6] == inter)
def test_intersection():
a = [1, 2, 3]
b = [1, 2, 3, 4, 5, 6]
inter = sorted(com.intersection(a, b))
assert (a == inter)
def test_groupby():
values = ['foo', 'bar', 'baz', 'baz2', 'qux', 'foo3']
expected = {'f': ['foo', 'foo3'],
'b': ['bar', 'baz', 'baz2'],
'q': ['qux']}
grouped = com.groupby(values, lambda x: x[0])
for k, v in grouped:
assert v == expected[k]
def test_random_state():
import numpy.random as npr
# Check with seed
state = com._random_state(5)
assert state.uniform() == npr.RandomState(5).uniform()
# Check with random state object
state2 = npr.RandomState(10)
assert (com._random_state(state2).uniform() ==
npr.RandomState(10).uniform())
# check with no arg random state
assert com._random_state() is np.random
# Error for floats or strings
with pytest.raises(ValueError):
com._random_state('test')
with pytest.raises(ValueError):
com._random_state(5.5)
def test_maybe_match_name():
matched = com._maybe_match_name(
Series([1], name='x'), Series(
[2], name='x'))
assert (matched == 'x')
matched = com._maybe_match_name(
Series([1], name='x'), Series(
[2], name='y'))
assert (matched is None)
matched = com._maybe_match_name(Series([1]), Series([2], name='x'))
assert (matched is None)
matched = com._maybe_match_name(Series([1], name='x'), Series([2]))
assert (matched is None)
matched = com._maybe_match_name(Series([1], name='x'), [2])
assert (matched == 'x')
matched = com._maybe_match_name([1], Series([2], name='y'))
assert (matched == 'y')
def test_dict_compat():
data_datetime64 = {np.datetime64('1990-03-15'): 1,
np.datetime64('2015-03-15'): 2}
data_unchanged = {1: 2, 3: 4, 5: 6}
expected = {Timestamp('1990-3-15'): 1, Timestamp('2015-03-15'): 2}
assert (com._dict_compat(data_datetime64) == expected)
assert (com._dict_compat(expected) == expected)
assert (com._dict_compat(data_unchanged) == data_unchanged)<|fim▁end|>
|
result = com.map_indices_py(data)
assert (result == expected)
|
<|file_name|>base.py<|end_file_name|><|fim▁begin|>import os
import socket
import geoip2.database
from django.conf import settings
from django.core.validators import ipv4_re
from django.utils.ipv6 import is_valid_ipv6_address
from .resources import City, Country
# Creating the settings dictionary with any settings, if needed.
GEOIP_SETTINGS = {
'GEOIP_PATH': getattr(settings, 'GEOIP_PATH', None),
'GEOIP_CITY': getattr(settings, 'GEOIP_CITY', 'GeoLite2-City.mmdb'),
'GEOIP_COUNTRY': getattr(settings, 'GEOIP_COUNTRY', 'GeoLite2-Country.mmdb'),
}
class GeoIP2Exception(Exception):
pass
class GeoIP2:
# The flags for GeoIP memory caching.
# Try MODE_MMAP_EXT, MODE_MMAP, MODE_FILE in that order.
MODE_AUTO = 0
# Use the C extension with memory map.
MODE_MMAP_EXT = 1
# Read from memory map. Pure Python.
MODE_MMAP = 2
# Read database as standard file. Pure Python.
MODE_FILE = 4
# Load database into memory. Pure Python.
MODE_MEMORY = 8
cache_options = {opt: None for opt in (0, 1, 2, 4, 8)}
# Paths to the city & country binary databases.
_city_file = ''
_country_file = ''
# Initially, pointers to GeoIP file references are NULL.
_city = None
_country = None
def __init__(self, path=None, cache=0, country=None, city=None):
"""
Initialize the GeoIP object. No parameters are required to use default
settings. Keyword arguments may be passed in to customize the locations
of the GeoIP datasets.
* path: Base directory to where GeoIP data is located or the full path
to where the city or country data files (*.mmdb) are located.
Assumes that both the city and country data sets are located in
this directory; overrides the GEOIP_PATH setting.
* cache: The cache settings when opening up the GeoIP datasets. May be
an integer in (0, 1, 2, 4, 8) corresponding to the MODE_AUTO,
MODE_MMAP_EXT, MODE_MMAP, MODE_FILE, and MODE_MEMORY,
`GeoIPOptions` C API settings, respectively. Defaults to 0,
meaning MODE_AUTO.
* country: The name of the GeoIP country data file. Defaults to
'GeoLite2-Country.mmdb'; overrides the GEOIP_COUNTRY setting.
* city: The name of the GeoIP city data file. Defaults to
'GeoLite2-City.mmdb'; overrides the GEOIP_CITY setting.
"""
# Checking the given cache option.
if cache in self.cache_options:
self._cache = cache
else:
raise GeoIP2Exception('Invalid GeoIP caching option: %s' % cache)
# Getting the GeoIP data path.
if not path:
path = GEOIP_SETTINGS['GEOIP_PATH']
if not path:
raise GeoIP2Exception('GeoIP path must be provided via parameter or the GEOIP_PATH setting.')
if not isinstance(path, str):
raise TypeError('Invalid path type: %s' % type(path).__name__)
if os.path.isdir(path):
# Constructing the GeoIP database filenames using the settings
# dictionary. If the database files for the GeoLite country
# and/or city datasets exist, then try to open them.
country_db = os.path.join(path, country or GEOIP_SETTINGS['GEOIP_COUNTRY'])
if os.path.isfile(country_db):
self._country = geoip2.database.Reader(country_db, mode=cache)
self._country_file = country_db
city_db = os.path.join(path, city or GEOIP_SETTINGS['GEOIP_CITY'])
if os.path.isfile(city_db):
self._city = geoip2.database.Reader(city_db, mode=cache)
self._city_file = city_db
elif os.path.isfile(path):
# Otherwise, some detective work will be needed to figure out
# whether the given database path is for the GeoIP country or city
# databases.
reader = geoip2.database.Reader(path, mode=cache)
db_type = reader.metadata().database_type
if db_type.endswith('City'):
# GeoLite City database detected.
self._city = reader
self._city_file = path
elif db_type.endswith('Country'):
# GeoIP Country database detected.
self._country = reader
self._country_file = path
else:
raise GeoIP2Exception('Unable to recognize database edition: %s' % db_type)
else:
raise GeoIP2Exception('GeoIP path must be a valid file or directory.')
@property
def _reader(self):
if self._country:
return self._country
else:
return self._city
@property
def _country_or_city(self):
if self._country:
return self._country.country
else:
return self._city.city
def __del__(self):
# Cleanup any GeoIP file handles lying around.
if self._reader:
self._reader.close()
def __repr__(self):
meta = self._reader.metadata()
version = '[v%s.%s]' % (meta.binary_format_major_version, meta.binary_format_minor_version)
return '<%(cls)s %(version)s _country_file="%(country)s", _city_file="%(city)s">' % {
'cls': self.__class__.__name__,
'version': version,
'country': self._country_file,
'city': self._city_file,
}
def _check_query(self, query, country=False, city=False, city_or_country=False):
"Helper routine for checking the query and database availability."
# Making sure a string was passed in for the query.
if not isinstance(query, str):
raise TypeError('GeoIP query must be a string, not type %s' % type(query).__name__)
# Extra checks for the existence of country and city databases.
if city_or_country and not (self._country or self._city):
raise GeoIP2Exception('Invalid GeoIP country and city data files.')
elif country and not self._country:
raise GeoIP2Exception('Invalid GeoIP country data file: %s' % self._country_file)
elif city and not self._city:
raise GeoIP2Exception('Invalid GeoIP city data file: %s' % self._city_file)
# Return the query string back to the caller. GeoIP2 only takes IP addresses.
if not (ipv4_re.match(query) or is_valid_ipv6_address(query)):
query = socket.gethostbyname(query)
return query
def city(self, query):
"""
Return a dictionary of city information for the given IP address or
Fully Qualified Domain Name (FQDN). Some information in the dictionary
may be undefined (None).
"""
enc_query = self._check_query(query, city=True)
return City(self._city.city(enc_query))
def country_code(self, query):
"Return the country code for the given IP Address or FQDN."
enc_query = self._check_query(query, city_or_country=True)
return self.country(enc_query)['country_code']
def country_name(self, query):
"Return the country name for the given IP Address or FQDN."
enc_query = self._check_query(query, city_or_country=True)
return self.country(enc_query)['country_name']<|fim▁hole|> IP address or a Fully Qualified Domain Name (FQDN). For example, both
'24.124.1.80' and 'djangoproject.com' are valid parameters.
"""
# Returning the country code and name
enc_query = self._check_query(query, city_or_country=True)
return Country(self._country_or_city(enc_query))
# #### Coordinate retrieval routines ####
def coords(self, query, ordering=('longitude', 'latitude')):
cdict = self.city(query)
if cdict is None:
return None
else:
return tuple(cdict[o] for o in ordering)
def lon_lat(self, query):
"Return a tuple of the (longitude, latitude) for the given query."
return self.coords(query)
def lat_lon(self, query):
"Return a tuple of the (latitude, longitude) for the given query."
return self.coords(query, ('latitude', 'longitude'))
def geos(self, query):
"Return a GEOS Point object for the given query."
ll = self.lon_lat(query)
if ll:
from django.contrib.gis.geos import Point
return Point(ll, srid=4326)
else:
return None
# #### GeoIP Database Information Routines ####
@property
def info(self):
"Return information about the GeoIP library and databases in use."
meta = self._reader.metadata()
return 'GeoIP Library:\n\t%s.%s\n' % (meta.binary_format_major_version, meta.binary_format_minor_version)
@classmethod
def open(cls, full_path, cache):
return GeoIP2(full_path, cache)<|fim▁end|>
|
def country(self, query):
"""
Return a dictionary with the country code and name when given an
|
<|file_name|>admin.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from __future__ import absolute_import
from django.contrib import admin
from django.contrib.admin.models import DELETION
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Permission
from django.core.urlresolvers import reverse
from django.utils.html import escape
from admin.common_auth.logs import OSFLogEntry
from admin.common_auth.forms import UserRegistrationForm
from osf.models.user import OSFUser
class PermissionAdmin(admin.ModelAdmin):
search_fields = ['name', 'codename']
class CustomUserAdmin(UserAdmin):
add_form = UserRegistrationForm
list_display = ['username', 'given_name', 'is_active']
admin.site.register(OSFUser, CustomUserAdmin)
admin.site.register(Permission, PermissionAdmin)
class LogEntryAdmin(admin.ModelAdmin):
date_hierarchy = 'action_time'
readonly_fields = [f.name for f in OSFLogEntry._meta.get_fields()]
list_filter = [
'user',
'action_flag'
]
search_fields = [
'object_repr',
'change_message'
]
list_display = [
'action_time',
'user',
'object_link',
'object_id',
'message',
]
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return request.user.is_superuser and request.method != 'POST'
def has_delete_permission(self, request, obj=None):
return False
def object_link(self, obj):
if obj.action_flag == DELETION:
link = escape(obj.object_repr)
elif obj.content_type is None:
link = escape(obj.object_repr)
else:
ct = obj.content_type
link = u'<a href="%s">%s</a>' % (
reverse('admin:%s_%s_change' % (ct.app_label, ct.model), args=[obj.object_id]),
escape(obj.object_repr),
)
return link
object_link.allow_tags = True
object_link.admin_order_field = 'object_repr'
object_link.short_description = u'object'
def queryset(self, request):
return super(LogEntryAdmin, self).queryset(request) \
.prefetch_related('content_type')
admin.site.register(OSFLogEntry, LogEntryAdmin)<|fim▁end|>
| |
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2011 Nebula, 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.
import tempfile
from cloudfiles.errors import ContainerNotEmpty
from django import http
from django import template
from django.contrib import messages
from django.core.urlresolvers import reverse
from mox import IgnoreArg, IsA
from horizon import api
from horizon import test
from .tables import ContainersTable, ObjectsTable
CONTAINER_INDEX_URL = reverse('horizon:nova:containers:index')
class ContainerViewTests(test.BaseViewTests):
def setUp(self):
super(ContainerViewTests, self).setUp()
self.container = api.Container(None)
self.container.name = 'containerName'
self.container.size_used = 128
self.containers = (self.container,)
def test_index(self):
self.mox.StubOutWithMock(api, 'swift_get_containers')
api.swift_get_containers(
IsA(http.HttpRequest), marker=None).AndReturn(
([self.container], False))
self.mox.ReplayAll()
res = self.client.get(CONTAINER_INDEX_URL)
self.assertTemplateUsed(res, 'nova/containers/index.html')
self.assertIn('table', res.context)
containers = res.context['table'].data
self.assertEqual(len(containers), 1)
self.assertEqual(containers[0].name, 'containerName')
def test_delete_container(self):
self.mox.StubOutWithMock(api, 'swift_delete_container')
api.swift_delete_container(IsA(http.HttpRequest),
'containerName')
self.mox.ReplayAll()
action_string = "containers__delete__%s" % self.container.name
form_data = {"action": action_string}
req = self.factory.post(CONTAINER_INDEX_URL, form_data)
table = ContainersTable(req, self.containers)
handled = table.maybe_handle()
self.assertEqual(handled['location'], CONTAINER_INDEX_URL)
def test_delete_container_nonempty(self):
self.mox.StubOutWithMock(api, 'swift_delete_container')
exception = ContainerNotEmpty('containerNotEmpty')
api.swift_delete_container(
IsA(http.HttpRequest),
'containerName').AndRaise(exception)
self.mox.ReplayAll()
action_string = "containers__delete__%s" % self.container.name
form_data = {"action": action_string}
req = self.factory.post(CONTAINER_INDEX_URL, form_data)
table = ContainersTable(req, self.containers)
handled = table.maybe_handle()
self.assertEqual(handled['location'], CONTAINER_INDEX_URL)
def test_create_container_get(self):
res = self.client.get(reverse('horizon:nova:containers:create'))
self.assertTemplateUsed(res, 'nova/containers/create.html')
def test_create_container_post(self):
formData = {'name': 'containerName',
'method': 'CreateContainer'}
self.mox.StubOutWithMock(api, 'swift_create_container')
api.swift_create_container(
IsA(http.HttpRequest), u'containerName')
self.mox.ReplayAll()
res = self.client.post(reverse('horizon:nova:containers:create'),
formData)
self.assertRedirectsNoFollow(res, CONTAINER_INDEX_URL)
class ObjectViewTests(test.BaseViewTests):
CONTAINER_NAME = 'containerName'
def setUp(self):
class FakeCloudFile(object):
def __init__(self):
self.metadata = {}
def sync_metadata(self):
pass
super(ObjectViewTests, self).setUp()
swift_object = api.swift.SwiftObject(FakeCloudFile())
swift_object.name = "test_object"
swift_object.size = '128'
swift_object.container = api.swift.Container(None)
swift_object.container.name = 'container_name'
self.swift_objects = [swift_object]
def test_index(self):
self.mox.StubOutWithMock(api, 'swift_get_objects')
api.swift_get_objects(
IsA(http.HttpRequest),
self.CONTAINER_NAME,
marker=None).AndReturn((self.swift_objects, False))
self.mox.ReplayAll()
res = self.client.get(reverse('horizon:nova:containers:object_index',
args=[self.CONTAINER_NAME]))
self.assertTemplateUsed(res, 'nova/objects/index.html')
self.assertItemsEqual(res.context['table'].data, self.swift_objects)
def test_upload_index(self):
res = self.client.get(reverse('horizon:nova:containers:object_upload',
args=[self.CONTAINER_NAME]))
self.assertTemplateUsed(res, 'nova/objects/upload.html')
def test_upload(self):
OBJECT_DATA = 'objectData'
OBJECT_FILE = tempfile.TemporaryFile()
OBJECT_FILE.write(OBJECT_DATA)
OBJECT_FILE.flush()
OBJECT_FILE.seek(0)
OBJECT_NAME = 'objectName'
formData = {'method': 'UploadObject',
'container_name': self.CONTAINER_NAME,
'name': OBJECT_NAME,<|fim▁hole|> 'object_file': OBJECT_FILE}
self.mox.StubOutWithMock(api, 'swift_upload_object')
api.swift_upload_object(IsA(http.HttpRequest),
unicode(self.CONTAINER_NAME),
unicode(OBJECT_NAME),
OBJECT_DATA).AndReturn(self.swift_objects[0])
self.mox.ReplayAll()
res = self.client.get(reverse('horizon:nova:containers:object_upload',
args=[self.CONTAINER_NAME]))
self.assertContains(res, 'enctype="multipart/form-data"')
res = self.client.post(reverse('horizon:nova:containers:object_upload',
args=[self.CONTAINER_NAME]),
formData)
self.assertRedirectsNoFollow(res,
reverse('horizon:nova:containers:object_index',
args=[self.CONTAINER_NAME]))
def test_delete(self):
self.mox.StubOutWithMock(api, 'swift_delete_object')
api.swift_delete_object(
IsA(http.HttpRequest),
self.CONTAINER_NAME, self.swift_objects[0].name)
self.mox.ReplayAll()
OBJECT_INDEX_URL = reverse('horizon:nova:containers:object_index',
args=[self.CONTAINER_NAME])
action_string = "objects__delete__%s" % self.swift_objects[0].name
form_data = {"action": action_string}
req = self.factory.post(OBJECT_INDEX_URL, form_data)
kwargs = {"container_name": self.CONTAINER_NAME}
table = ObjectsTable(req, self.swift_objects, **kwargs)
handled = table.maybe_handle()
self.assertEqual(handled['location'], OBJECT_INDEX_URL)
def test_download(self):
OBJECT_DATA = 'objectData'
OBJECT_NAME = 'objectName'
self.mox.StubOutWithMock(api, 'swift_get_object_data')
self.mox.StubOutWithMock(api.swift, 'swift_get_object')
api.swift.swift_get_object(IsA(http.HttpRequest),
unicode(self.CONTAINER_NAME),
unicode(OBJECT_NAME)) \
.AndReturn(self.swift_objects[0])
api.swift_get_object_data(IsA(http.HttpRequest),
unicode(self.CONTAINER_NAME),
unicode(OBJECT_NAME)).AndReturn(OBJECT_DATA)
self.mox.ReplayAll()
res = self.client.get(reverse(
'horizon:nova:containers:object_download',
args=[self.CONTAINER_NAME, OBJECT_NAME]))
self.assertEqual(res.content, OBJECT_DATA)
self.assertTrue(res.has_header('Content-Disposition'))
def test_copy_index(self):
OBJECT_NAME = 'objectName'
container = self.mox.CreateMock(api.Container)
container.name = self.CONTAINER_NAME
self.mox.StubOutWithMock(api, 'swift_get_containers')
api.swift_get_containers(
IsA(http.HttpRequest)).AndReturn(([container], False))
self.mox.ReplayAll()
res = self.client.get(reverse('horizon:nova:containers:object_copy',
args=[self.CONTAINER_NAME,
OBJECT_NAME]))
self.assertTemplateUsed(res, 'nova/objects/copy.html')
def test_copy(self):
NEW_CONTAINER_NAME = self.CONTAINER_NAME
NEW_OBJECT_NAME = 'newObjectName'
ORIG_CONTAINER_NAME = 'origContainerName'
ORIG_OBJECT_NAME = 'origObjectName'
formData = {'method': 'CopyObject',
'new_container_name': NEW_CONTAINER_NAME,
'new_object_name': NEW_OBJECT_NAME,
'orig_container_name': ORIG_CONTAINER_NAME,
'orig_object_name': ORIG_OBJECT_NAME}
container = self.mox.CreateMock(api.Container)
container.name = self.CONTAINER_NAME
self.mox.StubOutWithMock(api, 'swift_get_containers')
api.swift_get_containers(
IsA(http.HttpRequest)).AndReturn(([container], False))
self.mox.StubOutWithMock(api, 'swift_copy_object')
api.swift_copy_object(IsA(http.HttpRequest),
ORIG_CONTAINER_NAME,
ORIG_OBJECT_NAME,
NEW_CONTAINER_NAME,
NEW_OBJECT_NAME)
self.mox.ReplayAll()
res = self.client.post(reverse('horizon:nova:containers:object_copy',
args=[ORIG_CONTAINER_NAME,
ORIG_OBJECT_NAME]),
formData)
self.assertRedirectsNoFollow(res,
reverse('horizon:nova:containers:object_index',
args=[NEW_CONTAINER_NAME]))<|fim▁end|>
| |
<|file_name|>uistuff.py<|end_file_name|><|fim▁begin|>import colorsys
import sys
import xml.etree.cElementTree as ET
# from io import BytesIO
from gi.repository import Gtk, Gdk, GObject, Pango
from gi.repository.GdkPixbuf import Pixbuf
from pychess.System import conf
from pychess.System.Log import log
from pychess.System.prefix import addDataPrefix
def createCombo(combo, data=[], name=None, ellipsize_mode=None):
if name is not None:
combo.set_name(name)
lst_store = Gtk.ListStore(Pixbuf, str)
for row in data:
lst_store.append(row)
combo.clear()
combo.set_model(lst_store)
crp = Gtk.CellRendererPixbuf()
crp.set_property('xalign', 0)
crp.set_property('xpad', 2)
combo.pack_start(crp, False)
combo.add_attribute(crp, 'pixbuf', 0)
crt = Gtk.CellRendererText()
crt.set_property('xalign', 0)
crt.set_property('xpad', 4)
combo.pack_start(crt, True)
combo.add_attribute(crt, 'text', 1)
if ellipsize_mode is not None:
crt.set_property('ellipsize', ellipsize_mode)
def updateCombo(combo, data):
def get_active(combobox):
model = combobox.get_model()
active = combobox.get_active()
if active < 0:
return None
return model[active][1]
last_active = get_active(combo)
lst_store = combo.get_model()
lst_store.clear()
new_active = 0
for i, row in enumerate(data):
lst_store.append(row)
if last_active == row[1]:
new_active = i
combo.set_active(new_active)
def genColor(n, startpoint=0):
assert n >= 1
# This splits the 0 - 1 segment in the pizza way
hue = (2 * n - 1) / (2.**(n - 1).bit_length()) - 1
hue = (hue + startpoint) % 1
# We set saturation based on the amount of green, scaled to the interval
# [0.6..0.8]. This ensures a consistent lightness over all colors.
rgb = colorsys.hsv_to_rgb(hue, 1, 1)
rgb = colorsys.hsv_to_rgb(hue, 1, (1 - rgb[1]) * 0.2 + 0.6)
# This algorithm ought to balance colors more precisely, but it overrates
# the lightness of yellow, and nearly makes it black
# yiq = colorsys.rgb_to_yiq(*rgb)
# rgb = colorsys.yiq_to_rgb(.125, yiq[1], yiq[2])
return rgb
def keepDown(scrolledWindow):
def changed(vadjust):
if not hasattr(vadjust, "need_scroll") or vadjust.need_scroll:
vadjust.set_value(vadjust.get_upper() - vadjust.get_page_size())
vadjust.need_scroll = True
scrolledWindow.get_vadjustment().connect("changed", changed)
def value_changed(vadjust):
vadjust.need_scroll = abs(vadjust.get_value() + vadjust.get_page_size() -
vadjust.get_upper()) < vadjust.get_step_increment()
scrolledWindow.get_vadjustment().connect("value-changed", value_changed)
# wrap analysis text column. thanks to
# http://www.islascruz.org/html/index.php?blog/show/Wrap-text-in-a-TreeView-column.html
def appendAutowrapColumn(treeview, name, **kvargs):
cell = Gtk.CellRendererText()
# cell.props.wrap_mode = Pango.WrapMode.WORD
# TODO:
# changed to ellipsize instead until "never ending grow" bug gets fixed
# see https://github.com/pychess/pychess/issues/1054
cell.props.ellipsize = Pango.EllipsizeMode.END
column = Gtk.TreeViewColumn(name, cell, **kvargs)
treeview.append_column(column)
def callback(treeview, allocation, column, cell):
otherColumns = [c for c in treeview.get_columns() if c != column]
newWidth = allocation.width - sum(c.get_width() for c in otherColumns)
hsep = GObject.Value()
hsep.init(GObject.TYPE_INT)
hsep.set_int(0)
treeview.style_get_property("horizontal-separator", hsep)
newWidth -= hsep.get_int() * (len(otherColumns) + 1) * 2
if cell.props.wrap_width == newWidth or newWidth <= 0:
return
cell.props.wrap_width = newWidth
store = treeview.get_model()
store_iter = store.get_iter_first()
while store_iter and store.iter_is_valid(store_iter):
store.row_changed(store.get_path(store_iter), store_iter)
store_iter = store.iter_next(store_iter)
treeview.set_size_request(0, -1)
# treeview.connect_after("size-allocate", callback, column, cell)
scroll = treeview.get_parent()
if isinstance(scroll, Gtk.ScrolledWindow):
scroll.set_policy(Gtk.PolicyType.NEVER, scroll.get_policy()[1])
return cell
METHODS = (
# Gtk.SpinButton should be listed prior to Gtk.Entry, as it is a
# subclass, but requires different handling
(Gtk.SpinButton, ("get_value", "set_value", "value-changed")),
(Gtk.Entry, ("get_text", "set_text", "changed")),
(Gtk.Expander, ("get_expanded", "set_expanded", "notify::expanded")),
(Gtk.ComboBox, ("get_active", "set_active", "changed")),
(Gtk.IconView, ("_get_active", "_set_active", "selection-changed")),
(Gtk.ToggleButton, ("get_active", "set_active", "toggled")),
(Gtk.CheckMenuItem, ("get_active", "set_active", "toggled")),
(Gtk.Range, ("get_value", "set_value", "value-changed")),
(Gtk.TreeSortable, ("get_value", "set_value", "sort-column-changed")),
(Gtk.Paned, ("get_position", "set_position", "notify::position")),
)
def keep(widget, key, get_value_=None, set_value_=None): # , first_value=None):
if widget is None:
raise AttributeError("key '%s' isn't in widgets" % key)
for class_, methods_ in METHODS:
# Use try-except just to make spinx happy...
try:
if isinstance(widget, class_):
getter, setter, signal = methods_
break
except TypeError:
getter, setter, signal = methods_
break
else:
raise AttributeError("I don't have any knowledge of type: '%s'" %
widget)
if get_value_:
def get_value():
return get_value_(widget)
else:
get_value = getattr(widget, getter)
if set_value_:
def set_value(v):
return set_value_(widget, v)
else:
set_value = getattr(widget, setter)
def setFromConf():
try:
v = conf.get(key)
except TypeError:
log.warning("uistuff.keep.setFromConf: Key '%s' from conf had the wrong type '%s', ignored" %
(key, type(conf.get(key))))
# print("uistuff.keep TypeError %s %s" % (key, conf.get(key)))
else:
set_value(v)
def callback(*args):
if not conf.hasKey(key) or conf.get(key) != get_value():
conf.set(key, get_value())
widget.connect(signal, callback)
conf.notify_add(key, lambda *args: setFromConf())
if conf.hasKey(key):
setFromConf()
elif conf.get(key) is not None:
conf.set(key, conf.get(key))<|fim▁hole|># loadDialogWidget() and saveDialogWidget() are similar to uistuff.keep() but are needed
# for saving widget values for Gtk.Dialog instances that are loaded with different
# sets of values/configurations and which also aren't instant save like in
# uistuff.keep(), but rather are saved later if and when the user clicks
# the dialog's OK button
def loadDialogWidget(widget,
widget_name,
config_number,
get_value_=None,
set_value_=None,
first_value=None):
key = widget_name + "-" + str(config_number)
if widget is None:
raise AttributeError("key '%s' isn't in widgets" % widget_name)
for class_, methods_ in METHODS:
if isinstance(widget, class_):
getter, setter, signal = methods_
break
else:
if set_value_ is None:
raise AttributeError("I don't have any knowledge of type: '%s'" %
widget)
if get_value_:
def get_value():
return get_value_(widget)
else:
get_value = getattr(widget, getter)
if set_value_:
def set_value(v):
return set_value_(widget, v)
else:
set_value = getattr(widget, setter)
if conf.hasKey(key):
try:
v = conf.get(key)
except TypeError:
log.warning("uistuff.loadDialogWidget: Key '%s' from conf had the wrong type '%s', ignored" %
(key, type(conf.get(key))))
if first_value is not None:
conf.set(key, first_value)
else:
conf.set(key, get_value())
else:
set_value(v)
elif first_value is not None:
conf.set(key, first_value)
set_value(conf.get(key))
else:
log.warning("Didn't load widget \"%s\": no conf value and no first_value arg" % widget_name)
def saveDialogWidget(widget, widget_name, config_number, get_value_=None):
key = widget_name + "-" + str(config_number)
if widget is None:
raise AttributeError("key '%s' isn't in widgets" % widget_name)
for class_, methods_ in METHODS:
if isinstance(widget, class_):
getter, setter, signal = methods_
break
else:
if get_value_ is None:
raise AttributeError("I don't have any knowledge of type: '%s'" %
widget)
if get_value_:
def get_value():
return get_value_(widget)
else:
get_value = getattr(widget, getter)
if not conf.hasKey(key) or conf.get(key) != get_value():
conf.set(key, get_value())
POSITION_NONE, POSITION_CENTER, POSITION_GOLDEN = range(3)
def keepWindowSize(key,
window,
defaultSize=None,
defaultPosition=POSITION_NONE):
""" You should call keepWindowSize before show on your windows """
key = key + "window"
def savePosition(window, *event):
log.debug("keepWindowSize.savePosition: %s" % window.get_title())
width = window.get_allocation().width
height = window.get_allocation().height
x_loc, y_loc = window.get_position()
if width <= 0:
log.error("Setting width = '%d' for %s to conf" % (width, key))
if height <= 0:
log.error("Setting height = '%d' for %s to conf" % (height, key))
log.debug("Saving window position width=%s height=%s x=%s y=%s" %
(width, height, x_loc, y_loc))
conf.set(key + "_width", width)
conf.set(key + "_height", height)
conf.set(key + "_x", x_loc)
conf.set(key + "_y", y_loc)
return False
window.connect("delete-event", savePosition, "delete-event")
def loadPosition(window):
# log.debug("keepWindowSize.loadPosition: %s" % window.title)
# Just to make sphinx happy...
try:
width, height = window.get_size_request()
except TypeError:
pass
if conf.hasKey(key + "_width") and conf.hasKey(key + "_height"):
width = conf.get(key + "_width")
height = conf.get(key + "_height")
log.debug("Resizing window to width=%s height=%s" %
(width, height))
window.resize(width, height)
elif defaultSize:
width, height = defaultSize
log.debug("Resizing window to width=%s height=%s" %
(width, height))
window.resize(width, height)
elif key == "mainwindow":
monitor_x, monitor_y, monitor_width, monitor_height = getMonitorBounds()
width = int(monitor_width / 2)
height = int(monitor_height / 4) * 3
log.debug("Resizing window to width=%s height=%s" %
(width, height))
window.resize(width, height)
elif key == "preferencesdialogwindow":
monitor_x, monitor_y, monitor_width, monitor_height = getMonitorBounds()
width = int(monitor_width / 2)
height = int(monitor_height / 4) * 3
window.resize(1, 1)
else:
monitor_x, monitor_y, monitor_width, monitor_height = getMonitorBounds()
width = int(monitor_width / 2)
height = int(monitor_height / 4) * 3
if conf.hasKey(key + "_x") and conf.hasKey(key + "_y"):
x = max(0, conf.get(key + "_x"))
y = max(0, conf.get(key + "_y"))
log.debug("Moving window to x=%s y=%s" % (x, y))
window.move(x, y)
elif defaultPosition in (POSITION_CENTER, POSITION_GOLDEN):
monitor_x, monitor_y, monitor_width, monitor_height = getMonitorBounds()
x_loc = int(monitor_width / 2 - width / 2) + monitor_x
if defaultPosition == POSITION_CENTER:
y_loc = int(monitor_height / 2 - height / 2) + monitor_y
else:
# Place the window on the upper golden ratio line
y_loc = int(monitor_height / 2.618 - height / 2) + monitor_y
log.debug("Moving window to x=%s y=%s" % (x_loc, y_loc))
window.move(x_loc, y_loc)
loadPosition(window)
# In rare cases, gtk throws some gtk_size_allocation error, which is
# probably a race condition. To avoid the window forgets its size in
# these cases, we add this extra hook
def callback(window):
loadPosition(window)
onceWhenReady(window, callback)
# Some properties can only be set, once the window is sufficiently initialized,
# This function lets you queue your request until that has happened.
def onceWhenReady(window, func, *args, **kwargs):
def cb(window, alloc, func, *args, **kwargs):
func(window, *args, **kwargs)
window.disconnect(handler_id)
handler_id = window.connect_after("size-allocate", cb, func, *args, **
kwargs)
def getMonitorBounds():
screen = Gdk.Screen.get_default()
root_window = screen.get_root_window()
# Just to make sphinx happy...
try:
ptr_window, mouse_x, mouse_y, mouse_mods = root_window.get_pointer()
current_monitor_number = screen.get_monitor_at_point(mouse_x, mouse_y)
monitor_geometry = screen.get_monitor_geometry(current_monitor_number)
return monitor_geometry.x, monitor_geometry.y, monitor_geometry.width, monitor_geometry.height
except TypeError:
return (0, 0, 0, 0)
def makeYellow(box):
def on_box_expose_event(box, context):
# box.style.paint_flat_box (box.window,
# Gtk.StateType.NORMAL, Gtk.ShadowType.NONE, None, box, "tooltip",
# box.allocation.x, box.allocation.y,
# box.allocation.width, box.allocation.height)
pass
def cb(box):
tooltip = Gtk.Window(Gtk.WindowType.POPUP)
tooltip.set_name('gtk-tooltip')
tooltip.ensure_style()
tooltipStyle = tooltip.get_style()
box.set_style(tooltipStyle)
box.connect("draw", on_box_expose_event)
onceWhenReady(box, cb)
class GladeWidgets:
""" A simple class that wraps a the glade get_widget function
into the python __getitem__ version """
def __init__(self, filename):
# TODO: remove this when upstream fixes translations with Python3+Windows
if sys.platform == "win32" and not conf.no_gettext:
tree = ET.parse(addDataPrefix("glade/%s" % filename))
for node in tree.iter():
if 'translatable' in node.attrib:
node.text = _(node.text)
del node.attrib['translatable']
if node.get('name') in ('pixbuf', 'logo'):
node.text = addDataPrefix("glade/%s" % node.text)
xml_text = ET.tostring(tree.getroot(), encoding='unicode', method='xml')
self.builder = Gtk.Builder.new_from_string(xml_text, -1)
else:
self.builder = Gtk.Builder()
if not conf.no_gettext:
self.builder.set_translation_domain("pychess")
self.builder.add_from_file(addDataPrefix("glade/%s" % filename))
def __getitem__(self, key):
return self.builder.get_object(key)
def getGlade(self):
return self.builder<|fim▁end|>
| |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from . import test_invoice_mode_weekly<|fim▁hole|><|fim▁end|>
|
from . import test_invoice_mode_weekly_is_it_today
|
<|file_name|>verify.rs<|end_file_name|><|fim▁begin|>use super::{Message,ObjectData,VersionData};
use super::pow::{ProofOfWork,VerifyError,network_pow_config};
use config::Config;
use std::time::{Duration,SystemTime};
use timegen::TimeType;
pub enum MessageVerifierError {
OurNonce,
OldVersion,
NoClockSync,
UnacceptablePow(VerifyError)
}
impl From<VerifyError> for MessageVerifierError {
fn from(err: VerifyError) -> MessageVerifierError {
MessageVerifierError::UnacceptablePow(err)
}
}
pub struct MessageVerifier {
config: Config,
time_type: TimeType
}
impl MessageVerifier {
pub fn new(config: &Config, time_type: TimeType) -> MessageVerifier {
MessageVerifier {
config: config.clone(),
time_type: time_type
}
}
pub fn verify(&self, message: &Message) -> Result<(), MessageVerifierError> {
match message {
&Message::Version(VersionData { nonce, version, timestamp, .. }) => {
try!(self.check_nonce(nonce));
try!(self.check_version_number(version));
try!(self.check_clock_difference(timestamp));
Ok(())
},
&Message::Object(ref object_data @ ObjectData { .. }) => {
try!(self.check_pow(object_data));
Ok(())
},
_ => Ok(())
}
}
fn check_nonce(&self, their_nonce: u64) -> Result<(), MessageVerifierError> {
let our_nonce = self.config.nonce();
if their_nonce == our_nonce {
return Err(MessageVerifierError::OurNonce);
}
Ok(())
}
fn check_version_number(&self, version: u32) -> Result<(), MessageVerifierError> {
match version {
0 ... 2 => Err(MessageVerifierError::OldVersion),
_ => Ok(())
}
}
fn check_clock_difference(&self, their_time: SystemTime) -> Result<(), MessageVerifierError> {
let difference = match their_time.elapsed() {
Ok(duration) => duration,
Err(system_time_error) => system_time_error.duration()
};
if difference > Duration::from_secs(3600) {
return Err(MessageVerifierError::NoClockSync);
}
Ok(())
}
fn check_pow(&self, object_data: &ObjectData) -> Result<(), MessageVerifierError> {
let pow_config = network_pow_config();
let pow = ProofOfWork::new(self.time_type);
try!(pow.verify(object_data, pow_config));
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{MessageVerifier,MessageVerifierError};
use config::Config;
use message::{Message,Object,ObjectData,VersionData};
use message::pow::VerifyError;
use net::to_socket_addr;
use std::time::{Duration,SystemTime,UNIX_EPOCH};
use timegen::TimeType;
#[test]
fn test_normal_version() {
let input = Message::Version(get_version_data());
assert!(run_test(input).is_ok());
}
#[test]
fn test_get_version_with_low_version_number() {
let normal_version = get_version_data();
let input = Message::Version(VersionData { version: 2, .. normal_version });
let result = run_test(input);
match result {
Err(MessageVerifierError::OldVersion) => {},
_ => panic!("Expected failure due to low version number")
}
}
#[test]
fn test_get_version_with_slow_clock() {
let slow_clock = SystemTime::now() - Duration::from_secs(5000);<|fim▁hole|>
let normal_version = get_version_data();
let input = Message::Version(VersionData { timestamp: slow_clock, .. normal_version });
let result = run_test(input);
match result {
Err(MessageVerifierError::NoClockSync) => {},
_ => panic!("Expected failure due to their clock too slow")
}
}
#[test]
fn test_get_version_with_fast_clock() {
let fast_clock = SystemTime::now() + Duration::from_secs(5000);
let normal_version = get_version_data();
let input = Message::Version(VersionData { timestamp: fast_clock, .. normal_version });
let result = run_test(input);
match result {
Err(MessageVerifierError::NoClockSync) => {},
_ => panic!("Expected failure due to their clock too fast")
}
}
fn get_version_data() -> VersionData {
VersionData {
version: 3,
services: 1,
timestamp: SystemTime::now(),
addr_recv: to_socket_addr("127.0.0.1:8555"),
addr_from: to_socket_addr("127.0.0.1:8444"),
nonce: 0x0102030405060708,
user_agent: "test".to_string(),
streams: vec![ 1 ]
}
}
#[test]
fn test_object_with_invalid_pow_is_rejected() {
let input = Message::Object(get_object_data());
let result = run_test(input);
match result {
Err(MessageVerifierError::UnacceptablePow(VerifyError::UnacceptableProof)) => {},
_ => panic!("Expected failure due to invalid POW")
}
}
#[test]
fn test_object_with_valid_pow_is_accepted() {
let normal_object = get_object_data();
let input = Message::Object(ObjectData { nonce: 899113, .. normal_object });
assert!(run_test(input).is_ok());
}
#[test]
fn test_object_with_too_short_ttl_is_rejected() {
let normal_object = get_object_data();
let day_before = UNIX_EPOCH - Duration::from_secs(86400);
let input = Message::Object(ObjectData { expiry: day_before, .. normal_object });
let result = run_test(input);
match result {
Err(MessageVerifierError::UnacceptablePow(VerifyError::ObjectAlreadyDied)) => {},
_ => panic!("Expected failure due to too short ttl")
}
}
#[test]
fn test_object_with_too_long_ttl_is_rejected() {
let normal_object = get_object_data();
let thirty_days_after = UNIX_EPOCH + Duration::from_secs(2592000);
let input = Message::Object(ObjectData { expiry: thirty_days_after, .. normal_object });
let result = run_test(input);
match result {
Err(MessageVerifierError::UnacceptablePow(VerifyError::ObjectLivesTooLong)) => {},
_ => panic!("Expected failure due to too long ttl")
}
}
fn get_object_data() -> ObjectData {
ObjectData {
nonce: 1,
expiry: UNIX_EPOCH + Duration::from_secs(86400), // a day later
version: 1,
stream: 1,
object: Object::Msg { encrypted: (vec![1, 2, 3]) }
}
}
fn run_test(input: Message) -> Result<(), MessageVerifierError> {
let config = Config::new();
let verifier = MessageVerifier::new(&config, TimeType::Fixed(UNIX_EPOCH));
let result = verifier.verify(&input);
match result {
Ok(_) => Ok(()),
Err(e) => Err(e)
}
}
}<|fim▁end|>
| |
<|file_name|>SQLFrom.java<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2013-2015 Uncharted Software Inc.
*
* Property of Uncharted(TM), formerly Oculus Info Inc.
* http://uncharted.software/
*
* Released under the MIT License.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/<|fim▁hole|>package influent.server.sql;
/**
* Represents a SQL FROM clause. This can be used to create complicated
* sub-selects that can still be chained together.
*
* @author cregnier
*
*/
public interface SQLFrom {
/**
* Sets the name of table to select results from.<br>
* This cannot be set if {@link #fromQuery(SQLSelect)} has also been set.
* @param name
* The name of an existing table in the database
* @return
*/
SQLFrom table(String name);
/**
* Adds an alias for the table.
* @param alias
* The name of the alias that will be used in the SQL statement.
* @return
*/
SQLFrom as(String alias);
/**
* Sets a subquery that should be used to select results from.<br>
* This cannot be set if {@link #table(String)} has also been set.
* @param fromQuery
* A subquery to select results from.
* @return
*/
SQLFrom fromQuery(SQLSelect fromQuery);
}<|fim▁end|>
| |
<|file_name|>ProjectChannelBean.java<|end_file_name|><|fim▁begin|>package com.example.channelmanager;
/**
* Created by Administrator on 2017/2/7.
* 频道列表
*/
public class ProjectChannelBean {
private String topicid;
// 设置该标签是否可编辑,如果出现在我的频道中,且值为1,则可在右上角显示删除按钮
private int editStatus;
private String cid;
private String tname;
private String ename;
// 标签类型,显示是我的频道还是更多频道
private int tabType;
private String tid;
private String column;
public ProjectChannelBean(){}
public ProjectChannelBean(String tname, String tid){
this.tname = tname;
this.tid = tid;
}
public ProjectChannelBean(String tname, String column, String tid){
this.tname = tname;
this.column = column;
this.tid = tid;
}
<|fim▁hole|>
public void setTname(String tname) {
this.tname = tname;
}
public int getTabType() {
return tabType;
}
public void setTabType(int tabType) {
this.tabType = tabType;
}
public int getEditStatus() {
return editStatus;
}
public void setEditStatus(int editStatus) {
this.editStatus = editStatus;
}
public String getTopicid() {
return topicid;
}
public void setTopicid(String topicid) {
this.topicid = topicid;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getTid() {
return tid;
}
public void setTid(String tid) {
this.tid = tid;
}
public String getColumn() {
return column;
}
public void setColumn(String column) {
this.column = column;
}
}<|fim▁end|>
|
public String getTname() {
return tname;
}
|
<|file_name|>Tree.py<|end_file_name|><|fim▁begin|>'''
Tree from:
http://www.quesucede.com/page/show/id/python-3-tree-implementation
'''
from urllib.parse import urlparse
import os
(_ROOT, _DEPTH, _BREADTH) = range(3)
class Node:
def __init__(self, identifier):
self.__identifier = identifier
self.__children = []
@property
def identifier(self):
return self.__identifier
@property
def children(self):
return self.__children
def add_child(self, identifier):
self.__children.append(identifier)
class Tree:
def __init__(self):
self.__nodes = {}
@property
def nodes(self):
return self.__nodes
def add_node(self, identifier, parent=None):
print("identifier: " + identifier + " parent= " + str(parent))
node = Node(identifier)
self[identifier] = node
if parent is not None:
self[parent].add_child(identifier)
return node
def display(self, identifier, depth=_ROOT):
children = self[identifier].children
if depth == _ROOT:
print("{0}".format(identifier))
else:
print("\t"*depth, "{0}".format(identifier))
depth += 1
for child in children:
print("\t"*depth, "{0}".format(identifier))
self.display(child, depth) # recursive call
def traverse(self, identifier, mode=_DEPTH):
yield identifier
queue = self[identifier].children
while queue:
yield queue[0]
expansion = self[queue[0]].children
if mode == _DEPTH:
queue = expansion + queue[1:] # depth-first
elif mode == _BREADTH:
queue = queue[1:] + expansion # width-first
def __getitem__(self, key):
return self.__nodes[key]
def __setitem__(self, key, item):
self.__nodes[key] = item
'''
tree = Tree()
t = print("{0}".format("palestras"))
tree.add_node("Harry") # root node<|fim▁hole|>tree.add_node("Bill", "Harry")
tree.add_node("Joe", "Jane")
tree.add_node("Diane", "Jane")
tree.add_node("George", "Diane")
tree.add_node("Mary", "Diane")
tree.add_node("Jill", "George")
tree.add_node("Carol", "Jill")
tree.add_node("Grace", "Bill")
tree.add_node("Mark", "Jane")
tree.display("Harry")
print("***** DEPTH-FIRST ITERATION *****")
for node in tree.traverse("Harry"):
print(node)
print("***** BREADTH-FIRST ITERATION *****")
for node in tree.traverse("Harry", mode=_BREADTH):
print(node)
'''<|fim▁end|>
|
tree.add_node("Jane", t)
|
<|file_name|>ui-list.js<|end_file_name|><|fim▁begin|>/*
* File: ui-list.js
* Author: Li XianJing <[email protected]>
* Brief: List
*
* Copyright (c) 2011 - 2015 Li XianJing <[email protected]>
*
*/
function UIList() {
return;
}
UIList.prototype = new UIElement();
UIList.prototype.isUIList = true;
UIList.prototype.isUILayout = true;
UIList.prototype.initUIList = function(type, border, itemHeight, bg) {
this.initUIElement(type);
this.setMargin(border, border);
this.setSizeLimit(100, 100, 1000, 1000);
this.setDefSize(400, itemHeight * 3 + 2 * border);
this.itemHeight = itemHeight;
this.widthAttr = UIElement.WIDTH_FILL_PARENT;
this.setTextType(Shape.TEXT_INPUT);
this.setImage(UIElement.IMAGE_DEFAULT, bg);
this.rectSelectable = false;
this.itemHeightVariable = false;
this.addEventNames(["onInit"]);
if(!bg) {
this.style.setFillColor("White");
}
return this;
}
UIList.prototype.getItemHeight = function() {
return this.itemHeight;
}
UIList.prototype.setItemHeight = function(itemHeight) {
this.itemHeight = itemHeight;
return;
}
UIList.prototype.shapeCanBeChild = function(shape) {
if(!shape.isUIListItem) {
return false;
}
return true;
}
UIList.prototype.childIsBuiltin = function(child) {
return child.name === "ui-list-item-update-status"
|| child.name === "ui-list-item-update-tips"
|| child.name === "ui-last"
|| child.name.indexOf("prebuild") >= 0
|| child.name.indexOf("builtin") >= 0;
}
UIList.FIRST_ITEM = -1;
UIList.LAST_ITEM = 1;
UIList.MIDDLE_ITEM = 0;
UIList.SINGLE_ITEM = 2;
UIList.prototype.fixListItemImage = function(item, position) {
var images = item.images;
for(var key in images) {
var value = images[key];
if(key != "display") {
var src = value.getImageSrc();
if(!src) {
continue;
}
switch(position) {
case UIList.FIRST_ITEM: {
src = src.replace(/\.single\./, ".first.");
src = src.replace(/\.middle\./, ".first.");
src = src.replace(/\.last\./, ".first.");
break;
}
case UIList.MIDDLE_ITEM: {
src = src.replace(/\.single\./, ".middle.");
src = src.replace(/\.first\./, ".middle.");
src = src.replace(/\.last\./, ".middle.");
break;
}
case UIList.LAST_ITEM: {
src = src.replace(/\.single\./, ".last.");
src = src.replace(/\.first\./, ".last.");
src = src.replace(/\.middle\./, ".last.");
break;
}
case UIList.SINGLE_ITEM: {
src = src.replace(/\.first\./, ".single.");
src = src.replace(/\.middle\./, ".single.");
src = src.replace(/\.last\./, ".single.");
break;
}
}
value.setImageSrc(src);
}
}
return;
}
UIList.prototype.relayoutChildren = function(animHint) {
if(this.disableRelayout) {
return;
}
var hMargin = this.getHMargin();
var vMargin = this.getVMargin();
var x = hMargin;
var y = vMargin;
var w = this.getWidth(true);
var itemHeight = this.getItemHeight();
var h = itemHeight;
var n = this.children.length;
var itemHeightVariable = this.itemHeightVariable;
for(var i = 0; i < n; i++) {
var config = {};
var animatable = false;
var child = this.children[i];
if(itemHeightVariable || child.isHeightVariable()) {
h = child.measureHeight(itemHeight);
}
else {
h = itemHeight;
}
if(n === 1) {
this.fixListItemImage(child, UIList.SINGLE_ITEM);
}
else if(i === 0) {
this.fixListItemImage(child, UIList.FIRST_ITEM);
}
else if(i === (n - 1)) {
this.fixListItemImage(child, UIList.LAST_ITEM);
}
else {
this.fixListItemImage(child, UIList.MIDDLE_ITEM);
}
if(this.h <= (y + vMargin + h)) {
this.h = y + vMargin + h;
}
animatable = (y < this.h) && (animHint || this.mode === Shape.MODE_EDITING);
if(animatable) {
child.setSize(w, h);
config.xStart = child.x;
config.yStart = child.y;
config.wStart = child.w;
config.hStart = child.h;
config.xEnd = x;
config.yEnd = y;
config.wEnd = w;
config.hEnd = h;
config.delay = 10;
config.duration = 1000;
config.element = child;
config.onDone = function (el) {
el.relayoutChildren();
}
child.animate(config);
}
else {
child.move(x, y);
child.setSize(w, h);
child.relayoutChildren();
}
child.setUserMovable(true);
child.widthAttr = UIElement.WIDTH_FILL_PARENT;
if(child.heightAttr === UIElement.HEIGHT_FILL_PARENT) {
child.heightAttr = UIElement.HEIGHT_FIX;
}
child.setUserResizable(itemHeightVariable || child.isHeightVariable());
if(!this.isUIScrollView) {
child.setDraggable(this.itemDraggable);
}
y += h;
}
return;
}
UIList.prototype.beforePaintChildren = function(canvas) {
canvas.beginPath();
canvas.rect(0, 0, this.w, this.h);
canvas.clip();
canvas.beginPath();
return;
}
UIList.prototype.afterPaintChildren = function(canvas) {
return;
}
UIList.prototype.afterChildAppended = function(shape) {
if(shape.view && this.mode === Shape.MODE_EDITING && shape.isCreatingElement()) {
this.sortChildren();
}
this.moveMustBeLastItemToLast();
shape.setUserMovable(true);
shape.setUserResizable(false);
shape.setCanRectSelectable(false, true);
shape.autoAdjustHeight = this.itemHeightVariable;
shape.setDraggable(this.itemDraggable);
return true;
}
UIList.prototype.sortChildren = function() {
this.children.sort(function(a, b) {
var bb = b.y;
var aa = (b.pointerDown && b.hitTestResult === Shape.HIT_TEST_MM) ? (a.y + a.h*0.8) : a.y;
return aa - bb;
});
return;
}
UIList.prototype.onKeyUpRunning = function(code) {
var targetShapeIndex = 0;
if(!this.children.length) {
return;
}
switch(code) {
case KeyEvent.DOM_VK_UP: {
targetShapeIndex = this.children.indexOf(this.targetShape) - 1;
break;
}
case KeyEvent.DOM_VK_DOWN: {
targetShapeIndex = this.children.indexOf(this.targetShape) + 1;
break;
}
default: {
return;
}
}
var n = this.children.length;
targetShapeIndex = (targetShapeIndex + this.children.length)%n;<|fim▁hole|> var targetShape = this.children[targetShapeIndex];
this.setTarget(targetShape);
this.postRedraw();
if(this.isUIListView) {
if(this.offset > targetShape.y) {
this.offset = targetShape.y;
}
if((this.offset + this.h) < (targetShape.y + targetShape.h)) {
this.offset = targetShape.y - (this.h - targetShape.h);
}
}
return;
}
UIList.prototype.onKeyDownRunning = function(code) {
}
UIList.prototype.getValue = function() {
var ret = null;
var n = this.children.length;
if(n < 1) return ret;
for(var i = 0; i < n; i++) {
var iter = this.children[i];
if(!iter.isUIListCheckableItem || !iter.value) continue;
if(iter.isRadio) {
return i;
}
else {
if(!ret) ret = [];
ret.push(i);
}
}
return ret;
}
UIList.prototype.setValue = function(value) {
var arr = null;
if(typeof value === "array") {
arr = value;
}
else if(typeof value === "number") {
arr = [value];
}
else {
arr = [];
}
var n = this.children.length;
for(var i = 0; i < n; i++) {
var item = this.children[i];
if(item.isUIListCheckableItem) {
item.setValue(false);
}
}
for(var i = 0; i < arr.length; i++) {
var index = arr[i];
if(index >= 0 && index < n) {
var item = this.children[index];
if(item.isUIListCheckableItem) {
item.setChecked(true);
}
}
}
return this;
}
function UIListCreator(border, itemHeight, bg) {
var args = ["ui-list", "ui-list", null, 1];
ShapeCreator.apply(this, args);
this.createShape = function(createReason) {
var g = new UIList();
return g.initUIList(this.type, border, itemHeight, bg);
}
return;
}
ShapeFactoryGet().addShapeCreator(new UIListCreator(5, 114, null));<|fim▁end|>
| |
<|file_name|>0007_auto_20170620_0011.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-06-20 00:11<|fim▁hole|>
class Migration(migrations.Migration):
dependencies = [
('blog', '0006_auto_20170620_0010'),
]
operations = [
migrations.AlterField(
model_name='post',
name='posted',
field=models.DateField(db_index=True, verbose_name='data'),
),
]<|fim▁end|>
|
from __future__ import unicode_literals
from django.db import migrations, models
|
<|file_name|>functions_bak.js<|end_file_name|><|fim▁begin|>log.enableAll();
(function(){
function animate() {
requestAnimationFrame(animate);
TWEEN.update();
}
animate();
})();
var transform = getStyleProperty('transform');
var getStyle = ( function() {
var getStyleFn = getComputedStyle ?
function( elem ) {
return getComputedStyle( elem, null );
} :
function( elem ) {
return elem.currentStyle;
};
return function getStyle( elem ) {
var style = getStyleFn( elem );
if ( !style ) {
log.error( 'Style returned ' + style +
'. Are you running this code in a hidden iframe on Firefox? ' +
'See http://bit.ly/getsizebug1' );
}
return style;
};
})();
var cache = {
imgW: 5100,
imgH: 852,
panOffsetX: 0,
ring: 0,
deg: 0,
runDeg: 0,
minOffsetDeg: 8,
rotationOffsetDeg: 0,
onceRotationOffsetDeg: 0,
nowOffset: 0,
len: 0,
touchLock: false,
timer: null
};
var tween1, tween2;
var util = {
setTranslateX: function setTranslateX(el, num) {
el.style[transform] = "translate3d(" + num + "px,0,0)";
}
};
var initPanoramaBox = function initPanoramaBox($el, opts) {
var elH = $el.height();
var elW = $el.width();
var $panoramaBox = $('<div class="panorama-box">' +
'<div class="panorama-item"></div>' +
'<div class="panorama-item"></div>' +
'</div>');
var $panoramaItem = $('.panorama-item', $panoramaBox);
var scal = elH / opts.height;
$panoramaItem.css({
width: opts.width,
height: opts.height
});
$panoramaBox.css({
width: elW / scal,
height: opts.height,
transform: 'scale3d(' + scal + ',' + scal + ',' + scal + ')',
'transform-origin': '0 0'
});
util.setTranslateX($panoramaItem.get(0), 0);
util.setTranslateX($panoramaItem.get(1), -opts.width);
$el.append($panoramaBox);
var offset = function offset(num) {
var width = opts.width;
var num1 = num % opts.width;
var num2;
if (num1 < -width / 2) {
num2 = width + num1 - 2;
} else {<|fim▁hole|> util.setTranslateX($panoramaItem.get(0), num1);
util.setTranslateX($panoramaItem.get(1), num2);
};
var run = function (subBox1, subBox2, width) {
return function offset(num) {
num = parseInt(num);
cache.len = num;
var num1 = num % width;
var num2;
if (num1 < -width / 2) {
num2 = width + num1 - 1;
} else {
num2 = -width + num1 + 2;
}
util.setTranslateX(subBox1, num1);
util.setTranslateX(subBox2, num2);
};
};
return run($panoramaItem.get(0), $panoramaItem.get(1), opts.width);
};
var $el = {};
$el.main = $('.wrapper');
var offset = initPanoramaBox($el.main, {
width: cache.imgW,
height: cache.imgH
});
var animOffset = function animOffset(length){
if(tween1){
tween1.stop();
}
tween1 = new TWEEN.Tween({x: cache.len});
tween1.to({x: length}, 600);
tween1.onUpdate(function(){
offset(this.x);
});
tween1.start();
};
var animPanEnd = function animPanEnd(velocityX){
if(tween2){
tween2.stop();
}
var oldLen = cache.len;
var offsetLen ;
tween2 = new TWEEN.Tween({x: cache.len});
tween2.to({x: cache.len - 200 * velocityX}, 600);
tween2.easing(TWEEN.Easing.Cubic.Out);
tween2.onUpdate(function(){
offset(this.x);
offsetLen =oldLen - this.x;
cache.nowOffset += + offsetLen;
cache.panOffsetX += + offsetLen;
});
tween2.start();
};
var initOrientationControl = function () {
FULLTILT.getDeviceOrientation({'type': 'world'})
.then(function (orientationControl) {
var orientationFunc = function orientationFunc() {
var screenAdjustedEvent = orientationControl.getScreenAdjustedEuler();
cache.navDeg = 360 - screenAdjustedEvent.alpha;
if (cache.navDeg > 270 && cache.navOldDeg < 90) {
cache.ring -= 1;
} else if (cache.navDeg < 90 && cache.navOldDeg > 270) {
cache.ring += 1;
}
cache.navOldDeg = cache.navDeg;
cache.oldDeg = cache.deg;
cache.deg = cache.ring * 360 + cache.navDeg;
var offsetDeg = cache.deg - cache.runDeg;
if (!cache.touchLock &&
(Math.abs(offsetDeg) > cache.minOffsetDeg)) {
var length = cache.imgW / 360 * -(cache.deg - cache.rotationOffsetDeg) + cache.panOffsetX;
cache.runDeg = cache.deg;
cache.nowOffset = length;
animOffset(length);
}
};
orientationControl.listen(orientationFunc);
})
.catch(function(e){
log.error(e);
});
};
var initTouch = function(){
var mc = new Hammer.Manager($el.main.get(0));
var pan = new Hammer.Pan();
$el.main.on('touchstart', function (evt) {
if (cache.timer) {
clearTimeout(cache.timer);
cache.timer = null;
}
cache.touchLock = true;
if(tween1){
tween1.stop();
}
if(tween2){
tween2.stop();
}
cache.nowOffset = cache.len;
});
$el.main.on('touchend', function (evt) {
cache.timer = setTimeout(function () {
cache.onceRotationOffsetDeg = cache.deg - cache.runDeg;
cache.runDeg = cache.deg + cache.onceRotationOffsetDeg;
cache.rotationOffsetDeg = cache.rotationOffsetDeg + cache.onceRotationOffsetDeg;
cache.touchLock = false;
}, 1000);
});
mc.add(pan);
mc.on('pan', function (evt) {
offset(cache.nowOffset + evt.deltaX);
});
mc.on('panend', function (evt) {
cache.nowOffset += + evt.deltaX;
cache.panOffsetX += + evt.deltaX;
//animPanEnd(evt.velocityX);
});
};
initTouch();
initOrientationControl();<|fim▁end|>
|
num2 = -width + num1 + 2;
}
|
<|file_name|>xcode.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: disable=invalid-name
"""Utility to invoke Xcode compiler toolchain"""
from __future__ import absolute_import as _abs
import os
import sys
import subprocess
import json
from .._ffi.base import py_str
from . import util
def xcrun(cmd):
"""Run xcrun and return the output.
Parameters
----------
cmd : list of str
The command sequence.
Returns
-------
out : str
The output string.
"""
cmd = ["xcrun"] + cmd
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(out, _) = proc.communicate()
return out.strip()
def codesign(lib):
"""Codesign the shared libary
This is an required step for library to be loaded in
the app.
Parameters
----------
lib : The path to the library.
"""
if "TVM_IOS_CODESIGN" not in os.environ:
raise RuntimeError("Require environment variable TVM_IOS_CODESIGN " " to be the signature")
signature = os.environ["TVM_IOS_CODESIGN"]
cmd = ["codesign", "--force", "--sign", signature]
cmd += [lib]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(out, _) = proc.communicate()
if proc.returncode != 0:
msg = "Codesign error:\n"
msg += py_str(out)
raise RuntimeError(msg)
def create_dylib(output, objects, arch, sdk="macosx"):
"""Create dynamic library.
Parameters
----------
output : str
The target shared library.
objects : list
List of object files.
options : str
The additional options.
arch : str
Target major architectures
sdk : str
The sdk to be used.
"""
clang = xcrun(["-sdk", sdk, "-find", "clang"])
sdk_path = xcrun(["-sdk", sdk, "--show-sdk-path"])
cmd = [clang]
cmd += ["-dynamiclib"]
cmd += ["-arch", arch]
cmd += ["-isysroot", sdk_path]
cmd += ["-o", output]
if isinstance(objects, str):
cmd += [objects]
else:
cmd += objects
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(out, _) = proc.communicate()
if proc.returncode != 0:
msg = "Compilation error:\n"
msg += py_str(out)
raise RuntimeError(msg)
# assign so as default output format
create_dylib.output_format = "dylib"<|fim▁hole|>
def compile_metal(code, path_target=None, sdk="macosx"):
"""Compile metal with CLI tool from env.
Parameters
----------
code : str
The cuda code.
path_target : str, optional
Output file.
sdk : str, optional
The target platform SDK.
Return
------
metallib : bytearray
The bytearray of the metallib
"""
temp = util.tempdir()
temp_code = temp.relpath("my_lib.metal")
temp_ir = temp.relpath("my_lib.air")
temp_target = temp.relpath("my_lib.metallib")
with open(temp_code, "w") as out_file:
out_file.write(code)
file_target = path_target if path_target else temp_target
# See:
# - https://developer.apple.com/documentation/metal/gpu_functions_libraries/building_a_library_with_metal_s_command-line_tools#overview # pylint: disable=line-too-long
#
# xcrun -sdk macosx metal -c MyLibrary.metal -o MyLibrary.air
# xcrun -sdk macosx metallib MyLibrary.air -o MyLibrary.metallib
cmd1 = ["xcrun", "-sdk", sdk, "metal", "-O3"]
cmd1 += ["-c", temp_code, "-o", temp_ir]
cmd2 = ["xcrun", "-sdk", sdk, "metallib"]
cmd2 += [temp_ir, "-o", file_target]
proc = subprocess.Popen(
" ".join(cmd1) + ";" + " ".join(cmd2),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
(out, _) = proc.communicate()
if proc.returncode != 0:
sys.stderr.write("Compilation error:\n")
sys.stderr.write(py_str(out))
sys.stderr.flush()
libbin = None
else:
libbin = bytearray(open(file_target, "rb").read())
return libbin
def compile_coreml(model, model_name="main", out_dir="."):
"""Compile coreml model and return the compiled model path."""
mlmodel_path = os.path.join(out_dir, model_name + ".mlmodel")
mlmodelc_path = os.path.join(out_dir, model_name + ".mlmodelc")
metadata = {"inputs": list(model.input_description), "outputs": list(model.output_description)}
# Use the description field to send info to CoreML runtime
model.short_description = json.dumps(metadata)
model.save(mlmodel_path)
res = xcrun(["coremlcompiler", "compile", mlmodel_path, out_dir])
if not os.path.isdir(mlmodelc_path):
raise RuntimeError("Compile failed: %s" % res)
return mlmodelc_path
class XCodeRPCServer(object):
"""Wrapper for RPC server
Parameters
----------
cmd : list of str
The command to run
lock: FileLock
Lock on the path
"""
def __init__(self, cmd, lock):
self.proc = subprocess.Popen(cmd)
self.lock = lock
def join(self):
"""Wait server to finish and release its resource"""
self.proc.wait()
self.lock.release()
def popen_test_rpc(host, port, key, destination, libs=None, options=None):
"""Launch rpc server via xcodebuild test through another process.
Parameters
----------
host : str
The address of RPC proxy host.
port : int
The port of RPC proxy host
key : str
The key of the RPC server
destination : str
Destination device of deployment, as in xcodebuild
libs : list of str
List of files to be packed into app/Frameworks/tvm
These can be dylibs that can be loaed remoted by RPC.
options : list of str
Additional options to xcodebuild
Returns
-------
proc : Popen
The test rpc server process.
Don't do wait() on proc, since it can terminate normally.
"""
if "TVM_IOS_RPC_ROOT" in os.environ:
rpc_root = os.environ["TVM_IOS_RPC_ROOT"]
else:
curr_path = os.path.dirname(os.path.realpath(os.path.expanduser(__file__)))
rpc_root = os.path.join(curr_path, "../../../apps/ios_rpc")
proj_path = os.path.realpath(os.path.join(rpc_root, "tvmrpc.xcodeproj"))
if not os.path.exists(proj_path):
raise RuntimeError(
"Cannot find tvmrpc.xcodeproj in %s,"
+ (" please set env TVM_IOS_RPC_ROOT correctly" % rpc_root)
)
# Lock the path so only one file can run
lock = util.filelock(os.path.join(rpc_root, "ios_rpc.lock"))
with open(os.path.join(rpc_root, "rpc_config.txt"), "w") as fo:
fo.write("%s %d %s\n" % (host, port, key))
libs = libs if libs else []
for file_name in libs:
fo.write("%s\n" % file_name)
cmd = [
"xcrun",
"xcodebuild",
"-scheme",
"tvmrpc",
"-project",
proj_path,
"-destination",
destination,
]
if options:
cmd += options
cmd += ["test"]
return XCodeRPCServer(cmd, lock)<|fim▁end|>
| |
<|file_name|>rich_helper.py<|end_file_name|><|fim▁begin|>from rich.console import Console
from rich.markdown import Markdown
from rich.syntax import Syntax
def process_syntax(code, lang, theme, line_numbers, code_width, word_wrap):
syntax = Syntax(
code,
lang,
theme=theme,
line_numbers=line_numbers,
code_width=code_width,
word_wrap=word_wrap,
)
return syntax
def display_markdown(code):
try:
markdown = Markdown(code)
console = Console()
console.print(markdown) # noqa
return True # Success
except Exception:
return False # Failure
def display_code(code):
try:
console = Console()
console.print(code) # noqa
return True # Success
except Exception:
return False # Failure
def fix_emoji_spacing(code):
try:
# Fix the display width of certain emojis that take up two spaces
double_width_emojis = [
"🗺️", "🖼️", "🗄️", "⏺️", "♻️", "🗂️", "🖥️", "🕹️", "🎞️"
]
for emoji in double_width_emojis:
if emoji in code:<|fim▁hole|> code = code.replace(emoji, emoji + " ")
except Exception:
pass
return code<|fim▁end|>
| |
<|file_name|>Formula.py<|end_file_name|><|fim▁begin|>from collections import deque
import re
class Formula(object):
"""
Formula allows translation from a prefix-notation expression in a string to a complex number.
This is eventually to be replaced with a cython, c++, or openCL implementation as I'm sure
the performance of this class is pretty horrible.
"""
def __init__(self, formulaString='+ ** z 2 c'):
self.formulaString = formulaString
self.functions = None
"""
Compile:
This method takes in a the prefix statement and evaluates it for given values z and c.
"""
def compile(self, c, z):
form = deque(self.formulaString.split(' '))
return self.parse(form, c, z)
def parse(self, queuestring, c, z=0.0):
value = queuestring.popleft()
if (value == '+'):
return self.parse(queuestring, c, z) + self.parse(queuestring, c, z)
elif (value == '-'):
return self.parse(queuestring, c, z) - self.parse(queuestring, c, z)
elif (value == '*'):
return self.parse(queuestring, c, z) * self.parse(queuestring, c, z)
elif (value == '/'):
return self.parse(queuestring, c, z) / self.parse(queuestring, c, z)
elif (value == '^' or value == '**'):
return self.parse(queuestring, c, z) ** self.parse(queuestring, c, z)
elif (value == 'mod' or value == '%'):
return self.parse(queuestring, c, z) % self.parse(queuestring, c, z)
elif (value == 'rpart'):
return complex(self.parse(queuestring, c, z)).real
elif (value == 'ipart'):
return complex(self.parse(queuestring, c, z)).imag
elif (value == 'z'):
return z
elif (value == 'c'):
return c
elif (re.compile('^[\d\.]+').match(value)):
return float(value)
elif (re.compile('^[\d\.]+[\+\-][\d\.]+i$').match(value)):
nums = re.split('[\+\-]', value)<|fim▁hole|><|fim▁end|>
|
return complex(float(nums[0], nums[1][:-1]))
else:
return EOFError
|
<|file_name|>SideNav.d.ts<|end_file_name|><|fim▁begin|>import * as React from "react";
import { InternationalProps, ForwardRefReturn, ReactAttr } from "../../../typings/shared";
export type SideNavTranslationKey = "carbon.sidenav.state.closed" | "carbon.sidenav.state.open";
export interface SideNavProps extends ReactAttr, InternationalProps<SideNavTranslationKey> {
addFocusListeners?: boolean | undefined;
addMouseListeners?: boolean | undefined;
defaultExpanded?: boolean | undefined;
expanded?: boolean | undefined;
isChildOfHeader?: boolean | undefined;
isFixedNav?: boolean | undefined;
isPersistent?: boolean | undefined;
isRail?: boolean | undefined;
onOverlayClick?(evt: React.MouseEvent<HTMLDivElement>): void;
onToggle?(event: React.FocusEvent<HTMLElement>, focus: boolean): void;<|fim▁hole|>}
declare const SideNav: ForwardRefReturn<HTMLElement, SideNavProps>;
export default SideNav;<|fim▁end|>
| |
<|file_name|>AutodocsLayout.js<|end_file_name|><|fim▁begin|>/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule AutodocsLayout
*/
var DocsSidebar = require('DocsSidebar');
var H = require('Header');
var Header = require('Header');
var HeaderWithGithub = require('HeaderWithGithub');
var Marked = require('Marked');
var Prism = require('Prism');
var React = require('React');
var Site = require('Site');
var slugify = require('slugify');
var styleReferencePattern = /^[^.]+\.propTypes\.style$/;
function renderEnumValue(value) {
// Use single quote strings even when we are given double quotes
if (value.match(/^"(.+)"$/)) {
return "'" + value.slice(1, -1) + "'";
}
return value;
}
function renderType(type) {
if (type.name === 'enum') {
if (typeof type.value === 'string') {
return type.value;
}
return 'enum(' + type.value.map((v) => renderEnumValue(v.value)).join(', ') + ')';
}
if (type.name === '$Enum') {
if (type.elements[0].signature.properties) {
return type.elements[0].signature.properties.map(p => `'${p.key}'`).join(' | ');
}
return type.name;
}
if (type.name === 'shape') {
return '{' + Object.keys(type.value).map((key => key + ': ' + renderType(type.value[key]))).join(', ') + '}';
}
if (type.name === 'union') {
if (type.value) {
return type.value.map(renderType).join(', ');
}
return type.elements.map(renderType).join(' | ');
}
if (type.name === 'arrayOf') {
return <span>[{renderType(type.value)}]</span>;
}
if (type.name === 'instanceOf') {
return type.value;
}
if (type.name === 'custom') {
if (styleReferencePattern.test(type.raw)) {
var name = type.raw.substring(0, type.raw.indexOf('.'));
return <a href={'docs/' + slugify(name) + '.html#style'}>{name}#style</a>;
}
if (type.raw === 'ColorPropType') {
return <a href={'docs/colors.html'}>color</a>;
}
if (type.raw === 'EdgeInsetsPropType') {
return '{top: number, left: number, bottom: number, right: number}';
}
return type.raw;
}
if (type.name === 'stylesheet') {
return 'style';
}
if (type.name === 'func') {
return 'function';
}
if (type.name === 'signature') {
return type.raw;
}
return type.name;
}
function sortByPlatform(props, nameA, nameB) {
var a = props[nameA];
var b = props[nameB];
if (a.platforms && !b.platforms) {
return 1;
}
if (b.platforms && !a.platforms) {
return -1;
}
// Cheap hack: use < on arrays of strings to compare the two platforms
if (a.platforms < b.platforms) {
return -1;
}
if (a.platforms > b.platforms) {
return 1;
}
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
}
function removeCommentsFromDocblock(docblock) {
return docblock
.trim('\n ')
.replace(/^\/\*+/, '')
.replace(/\*\/$/, '')
.split('\n')
.map(function(line) {
return line.trim().replace(/^\* ?/, '');
})
.join('\n');
}
var ComponentDoc = React.createClass({
renderProp: function(name, prop) {
return (
<div className="prop" key={name}>
<Header level={4} className="propTitle" toSlug={name}>
{prop.platforms && prop.platforms.map(platform =>
<span className="platform">{platform}</span>
)}
{name}
{' '}
{prop.type && <span className="propType">
{renderType(prop.type)}
</span>}
</Header>
{prop.deprecationMessage && <div className="deprecated">
<div className="deprecatedTitle">
<img className="deprecatedIcon" src="img/Warning.png" />
<span>Deprecated</span>
</div>
<div className="deprecatedMessage">
<Marked>{prop.deprecationMessage}</Marked>
</div>
</div>}
{prop.type && prop.type.name === 'stylesheet' &&
this.renderStylesheetProps(prop.type.value)}
{prop.description && <Marked>{prop.description}</Marked>}
</div>
);
},
renderCompose: function(name) {
return (
<div className="prop" key={name}>
<Header level={4} className="propTitle" toSlug={name}>
<a href={'docs/' + slugify(name) + '.html#props'}>{name} props...</a>
</Header>
</div>
);
},
renderStylesheetProp: function(name, prop) {
return (
<div className="prop" key={name}>
<h6 className="propTitle">
{prop.platforms && prop.platforms.map(platform =>
<span className="platform">{platform}</span>
)}
{name}
{' '}
{prop.type && <span className="propType">
{renderType(prop.type)}
</span>}
{' '}
{prop.description && <Marked>{prop.description}</Marked>}
</h6>
</div>
);
},
renderStylesheetProps: function(stylesheetName) {
var style = this.props.content.styles[stylesheetName];
this.extractPlatformFromProps(style.props);
return (
<div className="compactProps">
{(style.composes || []).map((name) => {
var link;
if (name === 'LayoutPropTypes') {
name = 'Flexbox';
link =
<a href={'docs/' + slugify(name) + '.html#proptypes'}>{name}...</a>;
} else if (name === 'TransformPropTypes') {
name = 'Transforms';
link =
<a href={'docs/' + slugify(name) + '.html#proptypes'}>{name}...</a>;
} else {
name = name.replace('StylePropTypes', '');
link =
<a href={'docs/' + slugify(name) + '.html#style'}>{name}#style...</a>;
}
return (
<div className="prop" key={name}>
<h6 className="propTitle">{link}</h6>
</div>
);
})}
{Object.keys(style.props)
.sort(sortByPlatform.bind(null, style.props))
.map((name) => this.renderStylesheetProp(name, style.props[name]))
}
</div>
);
},
renderProps: function(props, composes) {
return (
<div className="props">
{(composes || []).map((name) =>
this.renderCompose(name)
)}
{Object.keys(props)
.sort(sortByPlatform.bind(null, props))
.map((name) => this.renderProp(name, props[name]))
}
</div>
);
},
extractPlatformFromProps: function(props) {
for (var key in props) {
var prop = props[key];
var description = prop.description || '';
var platforms = description.match(/\@platform (.+)/);
platforms = platforms && platforms[1].replace(/ /g, '').split(',');
description = description.replace(/\@platform (.+)/, '');
prop.description = description;
prop.platforms = platforms;
}
},
renderMethod: function(method) {
return (
<Method
key={method.name}
name={method.name}
description={method.description}
params={method.params}
modifiers={method.modifiers}
returns={method.returns}
/>
);
},
renderMethods: function(methods) {
if (!methods || !methods.length) {
return null;
}
return (
<span>
<H level={3}>Methods</H>
<div className="props">
{methods.filter((method) => {
return method.name[0] !== '_';
}).map(this.renderMethod)}
</div>
</span>
);
},
render: function() {
var content = this.props.content;
this.extractPlatformFromProps(content.props);
return (
<div>
<Marked>
{content.description}
</Marked>
<H level={3}>Props</H>
{this.renderProps(content.props, content.composes)}
{this.renderMethods(content.methods)}
</div>
);
}
});
var APIDoc = React.createClass({
renderMethod: function(method) {
return (
<Method
key={method.name}
name={method.name}
description={method.docblock && removeCommentsFromDocblock(method.docblock)}
params={method.params}
modifiers={method.modifiers}
/>
);
},
renderMethods: function(methods) {
if (!methods.length) {
return null;
}
return (
<span>
<H level={3}>Methods</H>
<div className="props">
{methods.filter((method) => {
return method.name[0] !== '_';
}).map(this.renderMethod)}
</div>
</span>
);
},
renderProperty: function(property) {
return (
<div className="prop" key={property.name}>
<Header level={4} className="propTitle" toSlug={property.name}>
{property.name}
{property.type &&
<span className="propType">
{': ' + renderType(property.type)}
</span>
}
</Header>
{property.docblock && <Marked>
{removeCommentsFromDocblock(property.docblock)}
</Marked>}
</div>
);
},
renderProperties: function(properties) {
if (!properties || !properties.length) {
return null;
}
return (
<span>
<H level={3}>Properties</H>
<div className="props">
{properties.filter((property) => {
return property.name[0] !== '_';
}).map(this.renderProperty)}
</div>
</span>
);
},
renderClasses: function(classes) {
if (!classes || !classes.length) {
return null;
}
return (
<span>
<div>
{classes.filter((cls) => {
return cls.name[0] !== '_' && cls.ownerProperty[0] !== '_';
}).map((cls) => {
return (
<span key={cls.name}>
<Header level={2} toSlug={cls.name}>
class {cls.name}
</Header>
<ul>
{cls.docblock && <Marked>
{removeCommentsFromDocblock(cls.docblock)}
</Marked>}
{this.renderMethods(cls.methods)}
{this.renderProperties(cls.properties)}
</ul>
</span>
);
})}
</div>
</span>
);
},
render: function() {
var content = this.props.content;
if (!content.methods) {
throw new Error(
'No component methods found for ' + content.componentName
);
}
return (
<div>
<Marked>
{removeCommentsFromDocblock(content.docblock)}
</Marked>
{this.renderMethods(content.methods)}
{this.renderProperties(content.properties)}
{this.renderClasses(content.classes)}<|fim▁hole|>});
var Method = React.createClass({
renderTypehintRec: function(typehint) {
if (typehint.type === 'simple') {
return typehint.value;
}
if (typehint.type === 'generic') {
return this.renderTypehintRec(typehint.value[0]) + '<' + this.renderTypehintRec(typehint.value[1]) + '>';
}
return JSON.stringify(typehint);
},
renderTypehint: function(typehint) {
if (typeof typehint === 'object' && typehint.name) {
return renderType(typehint);
}
try {
var typehint = JSON.parse(typehint);
} catch (e) {
return typehint;
}
return this.renderTypehintRec(typehint);
},
render: function() {
return (
<div className="prop">
<Header level={4} className="propTitle" toSlug={this.props.name}>
{this.props.modifiers.length && <span className="propType">
{this.props.modifiers.join(' ') + ' '}
</span> || ''}
{this.props.name}
<span className="propType">
({this.props.params
.map((param) => {
var res = param.name;
if (param.type) {
res += ': ' + this.renderTypehint(param.type);
}
return res;
})
.join(', ')})
{this.props.returns && ': ' + this.renderTypehint(this.props.returns.type)}
</span>
</Header>
{this.props.description && <Marked>
{this.props.description}
</Marked>}
</div>
);
},
});
var EmbeddedSimulator = React.createClass({
render: function() {
if (!this.props.shouldRender) {
return null;
}
var metadata = this.props.metadata;
var imagePreview = metadata.platform === 'android'
? <img alt="Run example in simulator" width="170" height="338" src="img/uiexplorer_main_android.png" />
: <img alt="Run example in simulator" width="170" height="356" src="img/uiexplorer_main_ios.png" />;
return (
<div className="column-left">
<p><a className="modal-button-open"><strong>Run this example</strong></a></p>
<div className="modal-button-open modal-button-open-img">
{imagePreview}
</div>
<Modal metadata={metadata} />
</div>
);
}
});
var Modal = React.createClass({
render: function() {
var metadata = this.props.metadata;
var appParams = {route: metadata.title};
var encodedParams = encodeURIComponent(JSON.stringify(appParams));
var url = metadata.platform === 'android'
? `https://appetize.io/embed/q7wkvt42v6bkr0pzt1n0gmbwfr?device=nexus5&scale=65&autoplay=false&orientation=portrait&deviceColor=white¶ms=${encodedParams}`
: `https://appetize.io/embed/7vdfm9h3e6vuf4gfdm7r5rgc48?device=iphone6s&scale=60&autoplay=false&orientation=portrait&deviceColor=white¶ms=${encodedParams}`;
return (
<div>
<div className="modal">
<div className="modal-content">
<button className="modal-button-close">×</button>
<div className="center">
<iframe className="simulator" src={url} width="256" height="550" frameborder="0" scrolling="no"></iframe>
<p>Powered by <a target="_blank" href="https://appetize.io">appetize.io</a></p>
</div>
</div>
</div>
<div className="modal-backdrop" />
</div>
);
}
});
var Autodocs = React.createClass({
childContextTypes: {
permalink: React.PropTypes.string
},
getChildContext: function() {
return {permalink: this.props.metadata.permalink};
},
renderFullDescription: function(docs) {
if (!docs.fullDescription) {
return;
}
return (
<div>
<HeaderWithGithub
title="Description"
path={'docs/' + docs.componentName + '.md'}
/>
<Marked>
{docs.fullDescription}
</Marked>
</div>
);
},
renderExample: function(docs, metadata) {
if (!docs.example) {
return;
}
return (
<div>
<HeaderWithGithub
title="Examples"
path={docs.example.path}
metadata={metadata}
/>
<Prism>
{docs.example.content.replace(/^[\s\S]*?\*\//, '').trim()}
</Prism>
</div>
);
},
render: function() {
var metadata = this.props.metadata;
var docs = JSON.parse(this.props.children);
var content = docs.type === 'component' || docs.type === 'style' ?
<ComponentDoc content={docs} /> :
<APIDoc content={docs} apiName={metadata.title} />;
return (
<Site section="docs" title={metadata.title}>
<section className="content wrap documentationContent">
<DocsSidebar metadata={metadata} />
<div className="inner-content">
<a id="content" />
<HeaderWithGithub
title={metadata.title}
level={1}
path={metadata.path}
/>
{content}
{this.renderFullDescription(docs)}
{this.renderExample(docs, metadata)}
<div className="docs-prevnext">
{metadata.previous && <a className="docs-prev" href={'docs/' + metadata.previous + '.html#content'}>← Prev</a>}
{metadata.next && <a className="docs-next" href={'docs/' + metadata.next + '.html#content'}>Next →</a>}
</div>
</div>
<EmbeddedSimulator shouldRender={metadata.runnable} metadata={metadata} />
</section>
</Site>
);
}
});
module.exports = Autodocs;<|fim▁end|>
|
</div>
);
}
|
<|file_name|>0006_auto__add_field_userproject_drive_auth.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'UserProject.drive_auth'
db.add_column(u'user_project', 'drive_auth',
self.gf('django.db.models.fields.BooleanField')(default=False),
keep_default=False)
def backwards(self, orm):
# Deleting field 'UserProject.drive_auth'
db.delete_column(u'user_project', 'drive_auth')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'home.category': {
'Meta': {'object_name': 'Category', 'db_table': "u'category'"},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '150'})
},
'projects.project': {
'Meta': {'object_name': 'Project', 'db_table': "u'project'"},
'categories': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['home.Category']", 'null': 'True', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 27, 0, 0)', 'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image_name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'null': 'True', 'blank': 'True'}),
'image_original_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'licence': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 27, 0, 0)', 'null': 'True', 'blank': 'True'}),
'tags': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'type_field': ('django.db.models.fields.IntegerField', [], {'default': '1', 'null': 'True', 'db_column': "'type'", 'blank': 'True'})
},
'projects.projectpart': {
'Meta': {'object_name': 'ProjectPart', 'db_table': "u'project_part'"},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 27, 0, 0)', 'null': 'True', 'blank': 'True'}),
'created_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'projectpart_created_user'", 'to': "orm['auth.User']"}),
'drive_id': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 27, 0, 0)', 'null': 'True', 'blank': 'True'}),
'modified_user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'projectpart_modified_user'", 'null': 'True', 'to': "orm['auth.User']"}),
'order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.Project']"}),
'project_part': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.ProjectPart']", 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},<|fim▁hole|> 'created_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'userproject_created_user'", 'to': "orm['auth.User']"}),
'drive_auth': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'modified_user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'userproject_modified_user'", 'null': 'True', 'to': "orm['auth.User']"}),
'permission': ('django.db.models.fields.CharField', [], {'default': '0', 'max_length': '255'}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.Project']", 'db_column': "'project_id'"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
}
}
complete_apps = ['projects']<|fim▁end|>
|
'projects.userproject': {
'Meta': {'object_name': 'UserProject', 'db_table': "u'user_project'"},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 27, 0, 0)', 'null': 'True', 'blank': 'True'}),
|
<|file_name|>Windows.cpp<|end_file_name|><|fim▁begin|>/*****************************************************************************
* Copyright (c) 2014-2020 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#if defined(__MINGW32__) && !defined(WINVER) && !defined(_WIN32_WINNT)
// 0x0600 == vista
# define WINVER 0x0600
# define _WIN32_WINNT 0x0600
#endif // __MINGW32__
#ifdef _WIN32
// Windows.h needs to be included first
// clang-format off
# include <windows.h>
# include <shellapi.h>
// clang-format on
// Then the rest
# include "../OpenRCT2.h"
# include "../Version.h"
# include "../config/Config.h"
# include "../core/String.hpp"
# include "../localisation/Date.h"
# include "../localisation/Language.h"
# include "../rct2/RCT2.h"
# include "../util/Util.h"
# include "Platform2.h"
# include "platform.h"
# include <algorithm>
# include <array>
# include <iterator>
# include <lmcons.h>
# include <memory>
# include <psapi.h>
# include <shlobj.h>
# include <sys/stat.h>
// Native resource IDs
# include "../../../resources/resource.h"
// Enable visual styles
# pragma comment( \
linker, \
"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
// The name of the mutex used to prevent multiple instances of the game from running
# define SINGLE_INSTANCE_MUTEX_NAME "RollerCoaster Tycoon 2_GSKMUTEX"
# define OPENRCT2_DLL_MODULE_NAME "openrct2.dll"
# if _WIN32_WINNT < 0x600
# define swprintf_s(a, b, c, d, ...) swprintf(a, b, c, ##__VA_ARGS__)
# endif
bool platform_directory_exists(const utf8* path)
{
auto wPath = String::ToWideChar(path);
DWORD dwAttrib = GetFileAttributesW(wPath.c_str());
return dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY);
}
bool platform_original_game_data_exists(const utf8* path)
{
utf8 checkPath[MAX_PATH];
safe_strcpy(checkPath, path, MAX_PATH);
safe_strcat_path(checkPath, "Data", MAX_PATH);
safe_strcat_path(checkPath, "g1.dat", MAX_PATH);
return Platform::FileExists(checkPath);
}
bool platform_ensure_directory_exists(const utf8* path)
{
if (platform_directory_exists(path))
return 1;
auto wPath = String::ToWideChar(path);
auto success = CreateDirectoryW(wPath.c_str(), nullptr);
return success != FALSE;
}
<|fim▁hole|>bool platform_directory_delete(const utf8* path)
{
// Needs to be double-null terminated as pFrom is a null terminated array of strings
auto wPath = String::ToWideChar(path) + L"\0";
SHFILEOPSTRUCTW fileop;
fileop.hwnd = nullptr; // no status display
fileop.wFunc = FO_DELETE; // delete operation
fileop.pFrom = wPath.c_str(); // source file name as double null terminated string
fileop.pTo = nullptr; // no destination needed
fileop.fFlags = FOF_NOCONFIRMATION | FOF_SILENT; // do not prompt the user
fileop.fAnyOperationsAborted = FALSE;
fileop.lpszProgressTitle = nullptr;
fileop.hNameMappings = nullptr;
int32_t ret = SHFileOperationW(&fileop);
return (ret == 0);
}
bool platform_lock_single_instance()
{
HANDLE mutex, status;
// Check if operating system mutex exists
mutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, SINGLE_INSTANCE_MUTEX_NAME);
if (mutex == nullptr)
{
// Create new mutex
status = CreateMutex(nullptr, FALSE, SINGLE_INSTANCE_MUTEX_NAME);
if (status == nullptr)
log_error("unable to create mutex");
return true;
}
// Already running
CloseHandle(mutex);
return false;
}
int32_t platform_get_drives()
{
return GetLogicalDrives();
}
bool platform_file_copy(const utf8* srcPath, const utf8* dstPath, bool overwrite)
{
auto wSrcPath = String::ToWideChar(srcPath);
auto wDstPath = String::ToWideChar(dstPath);
auto success = CopyFileW(wSrcPath.c_str(), wDstPath.c_str(), overwrite ? FALSE : TRUE);
return success != FALSE;
}
bool platform_file_move(const utf8* srcPath, const utf8* dstPath)
{
auto wSrcPath = String::ToWideChar(srcPath);
auto wDstPath = String::ToWideChar(dstPath);
auto success = MoveFileW(wSrcPath.c_str(), wDstPath.c_str());
return success != FALSE;
}
bool platform_file_delete(const utf8* path)
{
auto wPath = String::ToWideChar(path);
auto success = DeleteFileW(wPath.c_str());
return success != FALSE;
}
bool platform_get_steam_path(utf8* outPath, size_t outSize)
{
wchar_t* wSteamPath;
HKEY hKey;
DWORD type, size;
LRESULT result;
if (RegOpenKeyW(HKEY_CURRENT_USER, L"Software\\Valve\\Steam", &hKey) != ERROR_SUCCESS)
return false;
// Get the size of the path first
if (RegQueryValueExW(hKey, L"SteamPath", nullptr, &type, nullptr, &size) != ERROR_SUCCESS)
{
RegCloseKey(hKey);
return false;
}
wSteamPath = reinterpret_cast<wchar_t*>(malloc(size));
result = RegQueryValueExW(hKey, L"SteamPath", nullptr, &type, reinterpret_cast<LPBYTE>(wSteamPath), &size);
if (result == ERROR_SUCCESS)
{
auto utf8SteamPath = String::ToUtf8(wSteamPath);
safe_strcpy(outPath, utf8SteamPath.c_str(), outSize);
safe_strcat_path(outPath, "steamapps\\common", outSize);
}
free(wSteamPath);
RegCloseKey(hKey);
return result == ERROR_SUCCESS;
}
std::string platform_get_rct1_steam_dir()
{
return "Rollercoaster Tycoon Deluxe";
}
std::string platform_get_rct2_steam_dir()
{
return "Rollercoaster Tycoon 2";
}
std::string platform_sanitise_filename(const std::string& path)
{
static constexpr std::array prohibited = { '<', '>', '*', '\\', ':', '|', '?', '"', '/' };
auto sanitised = path;
std::replace_if(
sanitised.begin(), sanitised.end(),
[](const std::string::value_type& ch) -> bool {
return std::find(prohibited.begin(), prohibited.end(), ch) != prohibited.end();
},
'_');
sanitised = String::Trim(sanitised);
return sanitised;
}
uint16_t platform_get_locale_language()
{
CHAR langCode[4];
if (GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SABBREVLANGNAME, reinterpret_cast<LPSTR>(&langCode), sizeof(langCode)) == 0)
{
return LANGUAGE_UNDEFINED;
}
if (strcmp(langCode, "ENG") == 0)
{
return LANGUAGE_ENGLISH_UK;
}
if (strcmp(langCode, "ENU") == 0)
{
return LANGUAGE_ENGLISH_US;
}
if (strcmp(langCode, "DEU") == 0)
{
return LANGUAGE_GERMAN;
}
if (strcmp(langCode, "NLD") == 0)
{
return LANGUAGE_DUTCH;
}
if (strcmp(langCode, "FRA") == 0)
{
return LANGUAGE_FRENCH;
}
if (strcmp(langCode, "HUN") == 0)
{
return LANGUAGE_HUNGARIAN;
}
if (strcmp(langCode, "PLK") == 0)
{
return LANGUAGE_POLISH;
}
if (strcmp(langCode, "ESP") == 0)
{
return LANGUAGE_SPANISH;
}
if (strcmp(langCode, "SVE") == 0)
{
return LANGUAGE_SWEDISH;
}
if (strcmp(langCode, "ITA") == 0)
{
return LANGUAGE_ITALIAN;
}
if (strcmp(langCode, "POR") == 0)
{
return LANGUAGE_PORTUGUESE_BR;
}
if (strcmp(langCode, "FIN") == 0)
{
return LANGUAGE_FINNISH;
}
if (strcmp(langCode, "NOR") == 0)
{
return LANGUAGE_NORWEGIAN;
}
if (strcmp(langCode, "DAN") == 0)
{
return LANGUAGE_DANISH;
}
return LANGUAGE_UNDEFINED;
}
time_t platform_file_get_modified_time(const utf8* path)
{
WIN32_FILE_ATTRIBUTE_DATA data{};
auto wPath = String::ToWideChar(path);
auto result = GetFileAttributesExW(wPath.c_str(), GetFileExInfoStandard, &data);
if (result != FALSE)
{
FILETIME localFileTime{};
result = FileTimeToLocalFileTime(&data.ftLastWriteTime, &localFileTime);
if (result != FALSE)
{
ULARGE_INTEGER ull{};
ull.LowPart = localFileTime.dwLowDateTime;
ull.HighPart = localFileTime.dwHighDateTime;
return ull.QuadPart / 10000000ULL - 11644473600ULL;
}
}
return 0;
}
CurrencyType platform_get_locale_currency()
{
CHAR currCode[4];
if (GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SINTLSYMBOL, reinterpret_cast<LPSTR>(&currCode), sizeof(currCode)) == 0)
{
return platform_get_currency_value(nullptr);
}
return platform_get_currency_value(currCode);
}
MeasurementFormat platform_get_locale_measurement_format()
{
UINT measurement_system;
if (GetLocaleInfo(
LOCALE_USER_DEFAULT, LOCALE_IMEASURE | LOCALE_RETURN_NUMBER, reinterpret_cast<LPSTR>(&measurement_system),
sizeof(measurement_system))
== 0)
{
return MeasurementFormat::Metric;
}
switch (measurement_system)
{
case 1:
return MeasurementFormat::Imperial;
case 0:
default:
return MeasurementFormat::Metric;
}
}
TemperatureUnit platform_get_locale_temperature_format()
{
UINT fahrenheit;
// GetLocaleInfo will set fahrenheit to 1 if the locale on this computer
// uses the United States measurement system or 0 otherwise.
if (GetLocaleInfo(
LOCALE_USER_DEFAULT, LOCALE_IMEASURE | LOCALE_RETURN_NUMBER, reinterpret_cast<LPSTR>(&fahrenheit),
sizeof(fahrenheit))
== 0)
{
// Assume celsius by default if function call fails
return TemperatureUnit::Celsius;
}
if (fahrenheit)
return TemperatureUnit::Fahrenheit;
return TemperatureUnit::Celsius;
}
uint8_t platform_get_locale_date_format()
{
# if _WIN32_WINNT >= 0x0600
// Retrieve short date format, eg "MM/dd/yyyy"
wchar_t dateFormat[20];
if (GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SSHORTDATE, dateFormat, static_cast<int>(std::size(dateFormat))) == 0)
{
return DATE_FORMAT_DAY_MONTH_YEAR;
}
// The only valid characters for format types are: dgyM
// We try to find 3 strings of format types, ignore any characters in between.
// We also ignore 'g', as it represents 'era' and we don't have that concept
// in our date formats.
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd317787(v=vs.85).aspx
//
wchar_t first[sizeof(dateFormat)];
wchar_t second[sizeof(dateFormat)];
if (swscanf_s(
dateFormat, L"%l[dyM]%*l[^dyM]%l[dyM]%*l[^dyM]%*l[dyM]", first, static_cast<uint32_t>(std::size(first)), second,
static_cast<uint32_t>(std::size(second)))
!= 2)
{
return DATE_FORMAT_DAY_MONTH_YEAR;
}
if (wcsncmp(L"d", first, 1) == 0)
{
return DATE_FORMAT_DAY_MONTH_YEAR;
}
if (wcsncmp(L"M", first, 1) == 0)
{
return DATE_FORMAT_MONTH_DAY_YEAR;
}
if (wcsncmp(L"y", first, 1) == 0)
{
if (wcsncmp(L"d", second, 1) == 0)
{
return DATE_FORMAT_YEAR_DAY_MONTH;
}
// Closest possible option
return DATE_FORMAT_YEAR_MONTH_DAY;
}
# endif
// Default fallback
return DATE_FORMAT_DAY_MONTH_YEAR;
}
# ifndef NO_TTF
bool platform_get_font_path(TTFFontDescriptor* font, utf8* buffer, size_t size)
{
# if !defined(__MINGW32__) \
&& ((NTDDI_VERSION >= NTDDI_VISTA) && !defined(_USING_V110_SDK71_) && !defined(_ATL_XP_TARGETING))
wchar_t* fontFolder;
if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Fonts, 0, nullptr, &fontFolder)))
{
// Convert wchar to utf8, then copy the font folder path to the buffer.
auto outPathTemp = String::ToUtf8(fontFolder);
safe_strcpy(buffer, outPathTemp.c_str(), size);
CoTaskMemFree(fontFolder);
// Append the requested font's file name.
safe_strcat_path(buffer, font->filename, size);
return true;
}
return false;
# else
log_warning("Compatibility hack: falling back to C:\\Windows\\Fonts");
safe_strcpy(buffer, "C:\\Windows\\Fonts\\", size);
safe_strcat_path(buffer, font->filename, size);
return true;
# endif
}
# endif // NO_TTF
std::string platform_get_absolute_path(const utf8* relativePath, const utf8* basePath)
{
std::string result;
if (relativePath != nullptr)
{
std::string pathToResolve;
if (basePath == nullptr)
{
pathToResolve = std::string(relativePath);
}
else
{
pathToResolve = std::string(basePath) + std::string("\\") + relativePath;
}
auto pathToResolveW = String::ToWideChar(pathToResolve);
wchar_t fullPathW[MAX_PATH]{};
auto fullPathLen = GetFullPathNameW(
pathToResolveW.c_str(), static_cast<DWORD>(std::size(fullPathW)), fullPathW, nullptr);
if (fullPathLen != 0)
{
result = String::ToUtf8(fullPathW);
}
}
return result;
}
datetime64 platform_get_datetime_now_utc()
{
// Get file time
FILETIME fileTime;
GetSystemTimeAsFileTime(&fileTime);
uint64_t fileTime64 = (static_cast<uint64_t>(fileTime.dwHighDateTime) << 32ULL)
| (static_cast<uint64_t>(fileTime.dwLowDateTime));
// File time starts from: 1601-01-01T00:00:00Z
// Convert to start from: 0001-01-01T00:00:00Z
datetime64 utcNow = fileTime64 - 504911232000000000ULL;
return utcNow;
}
std::string platform_get_username()
{
std::string result;
wchar_t usernameW[UNLEN + 1]{};
DWORD usernameLength = UNLEN + 1;
if (GetUserNameW(usernameW, &usernameLength))
{
result = String::ToUtf8(usernameW);
}
return result;
}
bool platform_process_is_elevated()
{
BOOL isElevated = FALSE;
HANDLE hToken = nullptr;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
{
TOKEN_ELEVATION Elevation;
DWORD tokenSize = sizeof(TOKEN_ELEVATION);
if (GetTokenInformation(hToken, TokenElevation, &Elevation, sizeof(Elevation), &tokenSize))
{
isElevated = Elevation.TokenIsElevated;
}
}
if (hToken)
{
CloseHandle(hToken);
}
return isElevated;
}
///////////////////////////////////////////////////////////////////////////////
// URI protocol association setup
///////////////////////////////////////////////////////////////////////////////
# define SOFTWARE_CLASSES L"Software\\Classes"
# define MUI_CACHE L"Local Settings\\Software\\Microsoft\\Windows\\Shell\\MuiCache"
bool platform_setup_uri_protocol()
{
# if _WIN32_WINNT >= 0x0600
log_verbose("Setting up URI protocol...");
// [HKEY_CURRENT_USER\Software\Classes]
HKEY hRootKey;
if (RegOpenKeyW(HKEY_CURRENT_USER, SOFTWARE_CLASSES, &hRootKey) == ERROR_SUCCESS)
{
// [hRootKey\openrct2]
HKEY hClassKey;
if (RegCreateKeyA(hRootKey, "openrct2", &hClassKey) == ERROR_SUCCESS)
{
if (RegSetValueA(hClassKey, nullptr, REG_SZ, "URL:openrct2", 0) == ERROR_SUCCESS)
{
if (RegSetKeyValueA(hClassKey, nullptr, "URL Protocol", REG_SZ, "", 0) == ERROR_SUCCESS)
{
// [hRootKey\openrct2\shell\open\command]
wchar_t exePath[MAX_PATH];
GetModuleFileNameW(nullptr, exePath, MAX_PATH);
wchar_t buffer[512];
swprintf_s(buffer, std::size(buffer), L"\"%s\" handle-uri \"%%1\"", exePath);
if (RegSetValueW(hClassKey, L"shell\\open\\command", REG_SZ, buffer, 0) == ERROR_SUCCESS)
{
// Not compulsory, but gives the application a nicer name
// [HKEY_CURRENT_USER\SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\Shell\MuiCache]
HKEY hMuiCacheKey;
if (RegCreateKeyW(hRootKey, MUI_CACHE, &hMuiCacheKey) == ERROR_SUCCESS)
{
swprintf_s(buffer, std::size(buffer), L"%s.FriendlyAppName", exePath);
// mingw-w64 used to define RegSetKeyValueW's signature incorrectly
// You need at least mingw-w64 5.0 including this commit:
// https://sourceforge.net/p/mingw-w64/mingw-w64/ci/da9341980a4b70be3563ac09b5927539e7da21f7/
RegSetKeyValueW(hMuiCacheKey, nullptr, buffer, REG_SZ, L"OpenRCT2", sizeof(L"OpenRCT2"));
}
log_verbose("URI protocol setup successful");
return true;
}
}
}
}
}
# endif
log_verbose("URI protocol setup failed");
return false;
}
///////////////////////////////////////////////////////////////////////////////
#endif<|fim▁end|>
| |
<|file_name|>GUICG2.py<|end_file_name|><|fim▁begin|># GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
#
#character generation, class (GUICG2)
import GemRB
import GameCheck
import GUICommon
import CommonTables
import LUCommon
from ie_stats import *
from GUIDefines import *
ClassWindow = 0
TextAreaControl = 0
DoneButton = 0
MyChar = 0
def OnLoad():
global ClassWindow, TextAreaControl, DoneButton, MyChar
GemRB.LoadWindowPack("GUICG", 640, 480)
ClassWindow = GemRB.LoadWindow(2)
MyChar = GemRB.GetVar ("Slot")
Race = CommonTables.Races.FindValue (3, GemRB.GetPlayerStat (MyChar, IE_RACE) )
RaceName = CommonTables.Races.GetRowName(Race)
ClassCount = CommonTables.Classes.GetRowCount()+1
j = 0
#radiobutton groups must be set up before doing anything else to them
for i in range(1,ClassCount):
ClassName = CommonTables.Classes.GetRowName (i-1)
if CommonTables.Classes.GetValue (ClassName, "MULTI"):
continue
if j>7:
Button = ClassWindow.GetControl(j+7)
else:
Button = ClassWindow.GetControl(j+2)
Button.SetFlags(IE_GUI_BUTTON_RADIOBUTTON, OP_OR)
Button.SetState(IE_GUI_BUTTON_DISABLED)
j = j+1
j = 0
GemRB.SetVar("MAGESCHOOL",0)
HasMulti = 0
for i in range(1,ClassCount):
ClassName = CommonTables.Classes.GetRowName(i-1)
Allowed = CommonTables.Classes.GetValue(ClassName, RaceName)
if CommonTables.Classes.GetValue (ClassName, "MULTI"):
if Allowed!=0:
HasMulti = 1
continue
if j>7:
Button = ClassWindow.GetControl(j+7)
else:
Button = ClassWindow.GetControl(j+2)
j = j+1
t = CommonTables.Classes.GetValue(ClassName, "NAME_REF")
Button.SetText(t )
if Allowed==0:
continue
if Allowed==2:
GemRB.SetVar("MAGESCHOOL",5) #illusionist
Button.SetState(IE_GUI_BUTTON_ENABLED)
Button.SetEvent(IE_GUI_BUTTON_ON_PRESS, ClassPress)
Button.SetVarAssoc("Class", i)
MultiClassButton = ClassWindow.GetControl(10)
MultiClassButton.SetText(11993)
if HasMulti == 0:
MultiClassButton.SetState(IE_GUI_BUTTON_DISABLED)
BackButton = ClassWindow.GetControl(14)
BackButton.SetText(15416)
BackButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR)
DoneButton = ClassWindow.GetControl(0)
DoneButton.SetText(11973)
DoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR)
TextAreaControl = ClassWindow.GetControl(13)
<|fim▁hole|> DoneButton.SetState(IE_GUI_BUTTON_DISABLED)
else:
TextAreaControl.SetText (CommonTables.Classes.GetValue (ClassName, "DESC_REF"))
DoneButton.SetState(IE_GUI_BUTTON_ENABLED)
MultiClassButton.SetEvent(IE_GUI_BUTTON_ON_PRESS, MultiClassPress)
DoneButton.SetEvent(IE_GUI_BUTTON_ON_PRESS, NextPress)
BackButton.SetEvent(IE_GUI_BUTTON_ON_PRESS, BackPress)
ClassWindow.SetVisible(WINDOW_VISIBLE)
return
def BackPress():
if ClassWindow:
ClassWindow.Unload()
GemRB.SetNextScript("CharGen3")
GemRB.SetVar("Class",0) #scrapping the class value
return
def SetClass():
# find the class from the class table
ClassIndex = GemRB.GetVar ("Class") - 1
ClassName = GUICommon.GetClassRowName (ClassIndex, "index")
Class = CommonTables.Classes.GetValue (ClassName, "ID")
GemRB.SetPlayerStat (MyChar, IE_CLASS, Class)
KitIndex = GemRB.GetVar ("Class Kit")
MageSchool = GemRB.GetVar ("MAGESCHOOL")
#multiclassed gnomes
if MageSchool and not KitIndex:
SchoolTable = GemRB.LoadTable ("magesch")
KitIndex = CommonTables.KitList.FindValue (6, SchoolTable.GetValue (MageSchool, 3) )
KitValue = (0x4000 + KitIndex)
GemRB.SetPlayerStat (MyChar, IE_KIT, KitValue)
# protect against barbarians; this stat will be overwritten later
GemRB.SetPlayerStat (MyChar, IE_HITPOINTS, ClassIndex)
#assign the correct XP
if ClassName == "BARBARIAN":
ClassName = "FIGHTER"
# bgt does this substitution for starting a game: soa->bg1, tutorial->soa, (tob->tob)
if GameCheck.IsTOB():
GemRB.SetPlayerStat (MyChar, IE_XP, CommonTables.ClassSkills.GetValue (ClassName, "STARTXP2"))
else:
if (GameCheck.HasBGT() or GameCheck.HasTutu()) and GemRB.GetVar ("PlayMode") != 1:
# not tutorial (=soa->bg1, tob would be caught before)
GemRB.SetPlayerStat (MyChar, IE_XP, 0)
else:
GemRB.SetPlayerStat (MyChar, IE_XP, CommonTables.ClassSkills.GetValue (ClassName, "STARTXP"))
#create an array to get all the classes from
NumClasses = 1
IsMulti = GUICommon.IsMultiClassed (MyChar, 1)
if IsMulti[0] > 1:
NumClasses = IsMulti[0]
Classes = [IsMulti[1], IsMulti[2], IsMulti[3]]
else:
Classes = [GemRB.GetPlayerStat (MyChar, IE_CLASS)]
#loop through each class and update it's level
xp = GemRB.GetPlayerStat (MyChar, IE_XP)/NumClasses
for i in range (NumClasses):
CurrentLevel = LUCommon.GetNextLevelFromExp (xp, Classes[i])
if i == 0:
GemRB.SetPlayerStat (MyChar, IE_LEVEL, CurrentLevel)
elif i <= 2:
GemRB.SetPlayerStat (MyChar, IE_LEVEL2+i-1, CurrentLevel)
def MultiClassPress():
GemRB.SetVar("Class Kit",0)
if ClassWindow:
ClassWindow.Unload()
GemRB.SetNextScript("GUICG10")
return
def ClassPress():
SetClass()
if ClassWindow:
ClassWindow.Unload()
GemRB.SetNextScript("GUICG22")
return
def NextPress ():
SetClass()
if ClassWindow:
ClassWindow.Unload()
GemRB.SetNextScript("CharGen4") #alignment
return<|fim▁end|>
|
ClassName = GUICommon.GetClassRowName (GemRB.GetVar ("Class")-1, "index")
if ClassName == "":
TextAreaControl.SetText(17242)
|
<|file_name|>option_unwrap.rs<|end_file_name|><|fim▁begin|>// The commoner has seen it all, and can handle any gift well.
// All gifts are handled explicitly using `match`.
fn give_commoner(gift: Option<&str>) {
// Specify a course of action for each case.
match gift {
Some("snake") => println!("Yuck! I'm throwing that snake in a fire."),
Some(inner) => println!("{}? How nice.", inner),
None => println!("No gift? Oh well."),
}
}
// Our sheltered princess will `panic` at the sight of snakes.
// All gifts are handled implicitly using `unwrap`.
fn give_princess(gift: Option<&str>) {<|fim▁hole|> if inside == "snake" { panic!("AAAaaaaa!!!!"); }
println!("I love {}s!!!!!", inside);
}
fn main() {
let food = Some("cabbage");
let snake = Some("snake");
let void = None;
give_commoner(food);
give_commoner(snake);
give_commoner(void);
let bird = Some("robin");
let nothing = None;
give_princess(bird);
give_princess(nothing);
}<|fim▁end|>
|
// `unwrap` returns a `panic` when it receives a `None`.
let inside = gift.unwrap();
|
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
#![deny(unused_must_use)]
pub mod backend;
mod backend_proto;
pub mod card;
pub mod cloze;
pub mod collection;
pub mod config;
pub mod dbcheck;
pub mod deckconf;
pub mod decks;
pub mod err;
pub mod filtered;
pub mod findreplace;
mod fluent_proto;<|fim▁hole|>pub mod latex;
pub mod log;
mod markdown;
pub mod media;
pub mod notes;
pub mod notetype;
mod preferences;
pub mod prelude;
pub mod revlog;
pub mod scheduler;
pub mod search;
pub mod serde;
mod stats;
pub mod storage;
mod sync;
pub mod tags;
pub mod template;
pub mod template_filters;
pub mod text;
pub mod timestamp;
pub mod types;
pub mod undo;
pub mod version;<|fim▁end|>
|
pub mod i18n;
|
<|file_name|>test_common_controls.py<|end_file_name|><|fim▁begin|># GUI Application automation and testing library
# Copyright (C) 2006 Mark Mc Mahon
#
# This library 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 library 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 library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
from __future__ import print_function
"Tests for classes in controls\common_controls.py"
__revision__ = "$Revision: 234 $"
import sys
import ctypes
import unittest
import time
import pprint
import pdb
import os
sys.path.append(".")
from pywinauto import six
from pywinauto.controls import common_controls
from pywinauto.controls.common_controls import *
from pywinauto.win32structures import RECT
from pywinauto.controls import WrapHandle
#from pywinauto.controls.HwndWrapper import HwndWrapper
from pywinauto import findbestmatch
from pywinauto.SendKeysCtypes import is_x64
from pywinauto.RemoteMemoryBlock import AccessDenied
from pywinauto.RemoteMemoryBlock import RemoteMemoryBlock
controlspy_folder = os.path.join(
os.path.dirname(__file__), "..\..\controlspy0998")
if is_x64():
controlspy_folder = os.path.join(controlspy_folder, 'x64')
class RemoteMemoryBlockTestCases(unittest.TestCase):
def test__init__fail(self):
self.assertRaises(AccessDenied, RemoteMemoryBlock, 0)
def test__init__fail(self):
self.assertRaises(AccessDenied, RemoteMemoryBlock, 0)
class ListViewTestCases(unittest.TestCase):
"Unit tests for the ListViewWrapper class"
def setUp(self):
"""Start the application set some data and ensure the application
is in the state we want it."""
# start the application
from pywinauto.application import Application
app = Application()
app_path = os.path.join(controlspy_folder, "List View.exe")
app.start_(app_path)
#print('app_path: ' + app_path)
self.texts = [
("Mercury", '57,910,000', '4,880', '3.30e23'),
("Venus", '108,200,000', '12,103.6', '4.869e24'),
("Earth", '149,600,000', '12,756.3', '5.9736e24'),
("Mars", '227,940,000', '6,794', '6.4219e23'),
("Jupiter", '778,330,000', '142,984', '1.900e27'),
("Saturn", '1,429,400,000', '120,536', '5.68e26'),
("Uranus", '2,870,990,000', '51,118', '8.683e25'),
("Neptune", '4,504,000,000', '49,532', '1.0247e26'),
("Pluto", '5,913,520,000', '2,274', '1.27e22'),
]
self.app = app
self.dlg = app.MicrosoftControlSpy #top_window_()
self.ctrl = app.MicrosoftControlSpy.ListView.WrapperObject()
#self.dlg.MenuSelect("Styles")
# select show selection always!
#app.ControlStyles.ListBox1.TypeKeys("{UP}" * 26 + "{SPACE}")
#self.app.ControlStyles.ListBox1.Select("LVS_SHOWSELALWAYS")
#self.app.ControlStyles.ApplyStylesSetWindowLong.Click()
#self.app.ControlStyles.SendMessage(win32defines.WM_CLOSE)
def tearDown(self):
"Close the application after tests"
# close the application
self.dlg.SendMessage(win32defines.WM_CLOSE)
def testFriendlyClass(self):
"Make sure the ListView friendly class is set correctly"
self.assertEquals (self.ctrl.FriendlyClassName(), "ListView")
def testColumnCount(self):
"Test the ListView ColumnCount method"
self.assertEquals (self.ctrl.ColumnCount(), 4)
def testItemCount(self):
"Test the ListView ItemCount method"
self.assertEquals (self.ctrl.ItemCount(), 9)
def testItemText(self):
"Test the ListView item.Text property"
item = self.ctrl.GetItem(1)
self.assertEquals(item['text'], "Venus")
def testItems(self):
"Test the ListView Items method"
flat_texts = []
for row in self.texts:
flat_texts.extend(row)
for i, item in enumerate(self.ctrl.Items()):
self.assertEquals(item['text'], flat_texts[i])
def testTexts(self):
"Test the ListView Texts method"
flat_texts = []
for row in self.texts:
flat_texts.extend(row)
self.assertEquals(flat_texts, self.ctrl.Texts()[1:])
def testGetItem(self):
"Test the ListView GetItem method"
for row in range(self.ctrl.ItemCount()):
for col in range(self.ctrl.ColumnCount()):
self.assertEquals(
self.ctrl.GetItem(row, col)['text'], self.texts[row][col])
def testGetItemText(self):
"Test the ListView GetItem method - with text this time"
for text in [row[0] for row in self.texts]:
self.assertEquals(
self.ctrl.GetItem(text)['text'], text)
self.assertRaises(ValueError, self.ctrl.GetItem, "Item not in this list")
def testColumn(self):
"Test the ListView Columns method"
cols = self.ctrl.Columns()
self.assertEqual (len(cols), self.ctrl.ColumnCount())
# TODO: add more checking of column values
#for col in cols:
# print(col)
def testGetSelectionCount(self):
"Test the ListView GetSelectedCount method"
self.assertEquals(self.ctrl.GetSelectedCount(), 0)
self.ctrl.Select(1)
self.ctrl.Select(7)
self.assertEquals(self.ctrl.GetSelectedCount(), 2)
# def testGetSelectionCount(self):
# "Test the ListView GetSelectedCount method"
#
# self.assertEquals(self.ctrl.GetSelectedCount(), 0)
#
# self.ctrl.Select(1)
# self.ctrl.Select(7)
#
# self.assertEquals(self.ctrl.GetSelectedCount(), 2)
def testIsSelected(self):
"Test ListView IsSelected for some items"
# ensure that the item is not selected
self.assertEquals(self.ctrl.IsSelected(1), False)
# select an item
self.ctrl.Select(1)
# now ensure that the item is selected
self.assertEquals(self.ctrl.IsSelected(1), True)
def _testFocused(self):
"Test checking the focus of some ListView items"
print("Select something quick!!")
import time
time.sleep(3)
#self.ctrl.Select(1)
print(self.ctrl.IsFocused(0))
print(self.ctrl.IsFocused(1))
print(self.ctrl.IsFocused(2))
print(self.ctrl.IsFocused(3))
print(self.ctrl.IsFocused(4))
print(self.ctrl.IsFocused(5))
#for col in cols:
# print(col)
def testSelect(self):
"Test ListView Selecting some items"
self.ctrl.Select(1)
self.ctrl.Select(3)
self.ctrl.Select(4)
self.assertRaises(IndexError, self.ctrl.Deselect, 23)
self.assertEquals(self.ctrl.GetSelectedCount(), 3)
def testSelectText(self):
"Test ListView Selecting some items"
self.ctrl.Select("Venus")
self.ctrl.Select("Jupiter")
self.ctrl.Select("Uranus")
self.assertRaises(ValueError, self.ctrl.Deselect, "Item not in list")
self.assertEquals(self.ctrl.GetSelectedCount(), 3)
def testDeselect(self):
"Test ListView Selecting some items"
self.ctrl.Select(1)
self.ctrl.Select(4)
self.ctrl.Deselect(3)
self.ctrl.Deselect(4)
self.assertRaises(IndexError, self.ctrl.Deselect, 23)
self.assertEquals(self.ctrl.GetSelectedCount(), 1)
def testGetProperties(self):
"Test getting the properties for the listview control"
props = self.ctrl.GetProperties()
self.assertEquals(
"ListView", props['FriendlyClassName'])
self.assertEquals(
self.ctrl.Texts(), props['Texts'])
for prop_name in props:
self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name])
self.assertEquals(props['ColumnCount'], 4)
self.assertEquals(props['ItemCount'], 9)
def testGetColumnTexts(self):
self.dlg.MenuSelect("Styles")
self.app.ControlStyles.StylesListBox.TypeKeys(
"{HOME}" + "{DOWN}"* 12 + "{SPACE}")
self.app.ControlStyles.ApplyStylesSetWindowLong.Click()
self.app.ControlStyles.SendMessage(win32defines.WM_CLOSE)
self.assertEquals(self.ctrl.GetColumn(0)['text'], "Planet")
self.assertEquals(self.ctrl.GetColumn(1)['text'], "Distance (km)")
self.assertEquals(self.ctrl.GetColumn(2)['text'], "Diameter (km)")
self.assertEquals(self.ctrl.GetColumn(3)['text'], "Mass (kg)")
#
# def testSubItems(self):
#
# for row in range(self.ctrl.ItemCount())
#
# for i in self.ctrl.Items():
#
# #self.assertEquals(item.Text, texts[i])
class TreeViewTestCases(unittest.TestCase):
"Unit tests for the TreeViewWrapper class"
def setUp(self):
"""Start the application set some data and ensure the application
is in the state we want it."""
# start the application
from pywinauto.application import Application
app = Application()
app.start_(os.path.join(controlspy_folder, "Tree View.exe"))
self.root_text = "The Planets"
self.texts = [
("Mercury", '57,910,000', '4,880', '3.30e23'),
("Venus", '108,200,000', '12,103.6', '4.869e24'),
("Earth", '149,600,000', '12,756.3', '5.9736e24'),
("Mars", '227,940,000', '6,794', '6.4219e23'),
("Jupiter", '778,330,000', '142,984', '1.900e27'),
("Saturn", '1,429,400,000', '120,536', '5.68e26'),
("Uranus", '2,870,990,000', '51,118', '8.683e25'),
("Neptune", '4,504,000,000', '49,532', '1.0247e26'),
("Pluto", '5,913,520,000', '2,274', '1.27e22'),
]
self.app = app
self.dlg = app.MicrosoftControlSpy #top_window_()
self.ctrl = app.MicrosoftControlSpy.TreeView.WrapperObject()
#self.dlg.MenuSelect("Styles")
# select show selection always, and show checkboxes
#app.ControlStyles.ListBox1.TypeKeys(
# "{HOME}{SPACE}" + "{DOWN}"* 12 + "{SPACE}")
#self.app.ControlStyles.ApplyStylesSetWindowLong.Click()
#self.app.ControlStyles.SendMessage(win32defines.WM_CLOSE)
def tearDown(self):
"Close the application after tests"
# close the application
self.dlg.SendMessage(win32defines.WM_CLOSE)
def testFriendlyClass(self):
"Make sure the friendly class is set correctly"
self.assertEquals (self.ctrl.FriendlyClassName(), "TreeView")
def testItemCount(self):
"Test the TreeView ItemCount method"
self.assertEquals (self.ctrl.ItemCount(), 37)
def testGetItem(self):
"Test the ItemCount method"
self.assertRaises(RuntimeError, self.ctrl.GetItem, "test\here\please")
self.assertRaises(IndexError, self.ctrl.GetItem, r"\test\here\please")
self.assertEquals(
self.ctrl.GetItem((0, 1, 2)).Text(), self.texts[1][3] + " kg")
self.assertEquals(
self.ctrl.GetItem(r"\The Planets\Venus\4.869").Text(), self.texts[1][3] + " kg")
self.assertEquals(
self.ctrl.GetItem(
["The Planets", "Venus", "4.869"]).Text(),
self.texts[1][3] + " kg")
def testItemText(self):
"Test the ItemCount method"
self.assertEquals(self.ctrl.Root().Text(), self.root_text)
self.assertEquals(
self.ctrl.GetItem((0, 1, 2)).Text(), self.texts[1][3] + " kg")
def testSelect(self):
"Test selecting an item"
self.ctrl.Select((0, 1, 2))
self.ctrl.GetItem((0, 1, 2)).State()
self.assertEquals(True, self.ctrl.IsSelected((0, 1, 2)))
def testEnsureVisible(self):
"make sure that the item is visible"
# note this is partially a fake test at the moment because
# just by getting an item - we usually make it visible
self.ctrl.EnsureVisible((0, 8, 2))
# make sure that the item is not hidden
self.assertNotEqual(None, self.ctrl.GetItem((0, 8, 2)).Rectangle())
def testGetProperties(self):
"Test getting the properties for the treeview control"
props = self.ctrl.GetProperties()
self.assertEquals(
"TreeView", props['FriendlyClassName'])
self.assertEquals(
self.ctrl.Texts(), props['Texts'])
for prop_name in props:
self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name])
class HeaderTestCases(unittest.TestCase):
"Unit tests for the Header class"
def setUp(self):
"""Start the application set some data and ensure the application
is in the state we want it."""
# start the application
from pywinauto.application import Application
app = Application()
app.start_(os.path.join(controlspy_folder, "Header.exe"))
self.texts = [u'Distance', u'Diameter', u'Mass']
self.item_rects = [
RECT(0, 0, 90, 26),
RECT(90, 0, 180, 26),
RECT(180, 0, 260, 26)]
self.app = app
self.dlg = app.MicrosoftControlSpy
self.ctrl = app.MicrosoftControlSpy.Header.WrapperObject()
def tearDown(self):
"Close the application after tests"
# close the application
self.dlg.SendMessage(win32defines.WM_CLOSE)
def testFriendlyClass(self):
"Make sure the friendly class is set correctly"
self.assertEquals (self.ctrl.FriendlyClassName(), "Header")
def testTexts(self):
"Make sure the texts are set correctly"
self.assertEquals (self.ctrl.Texts()[1:], self.texts)
def testGetProperties(self):
"Test getting the properties for the header control"
props = self.ctrl.GetProperties()
self.assertEquals(
self.ctrl.FriendlyClassName(), props['FriendlyClassName'])
self.assertEquals(
self.ctrl.Texts(), props['Texts'])
for prop_name in props:
self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name])
def testItemCount(self):
self.assertEquals(3, self.ctrl.ItemCount())
def testGetColumnRectangle(self):
for i in range(0, 3):
self.assertEquals(
self.item_rects[i],
self.ctrl.GetColumnRectangle(i))
def testClientRects(self):
test_rects = self.item_rects
test_rects.insert(0, self.ctrl.ClientRect())
self.assertEquals(
test_rects,
self.ctrl.ClientRects())
def testGetColumnText(self):
for i in range(0, 3):
self.assertEquals(
self.texts[i],
self.ctrl.GetColumnText(i))
class StatusBarTestCases(unittest.TestCase):
"Unit tests for the TreeViewWrapper class"
def setUp(self):
"""Start the application set some data and ensure the application
is in the state we want it."""
# start the application
from pywinauto.application import Application
app = Application()
app.start_(os.path.join(controlspy_folder, "Status bar.exe"))
self.texts = ["Long text", "", "Status Bar"]
self.part_rects = [
RECT(0, 2, 65, 20),
RECT(67, 2, 90, 20),
RECT(92, 2, 357, 20)]
self.app = app
self.dlg = app.MicrosoftControlSpy
self.ctrl = app.MicrosoftControlSpy.StatusBar.WrapperObject()
#self.dlg.MenuSelect("Styles")
# select show selection always, and show checkboxes
#app.ControlStyles.ListBox1.TypeKeys(
# "{HOME}{SPACE}" + "{DOWN}"* 12 + "{SPACE}")
#self.app.ControlStyles.ApplyStylesSetWindowLong.Click()
#self.app.ControlStyles.SendMessage(win32defines.WM_CLOSE)
def tearDown(self):
"Close the application after tests"
# close the application
self.dlg.SendMessage(win32defines.WM_CLOSE)
def testFriendlyClass(self):
"Make sure the friendly class is set correctly"
self.assertEquals (self.ctrl.FriendlyClassName(), "StatusBar")
def testTexts(self):
"Make sure the texts are set correctly"
self.assertEquals (self.ctrl.Texts()[1:], self.texts)
def testGetProperties(self):
"Test getting the properties for the status bar control"
props = self.ctrl.GetProperties()
self.assertEquals(
self.ctrl.FriendlyClassName(), props['FriendlyClassName'])
self.assertEquals(
self.ctrl.Texts(), props['Texts'])
for prop_name in props:
self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name])
def testBorderWidths(self):
"Make sure the border widths are retrieved correctly"
self.assertEquals (
self.ctrl.BorderWidths(),
dict(
Horizontal = 0,
Vertical = 2,
Inter = 2,
)
)
def testPartCount(self):
"Make sure the number of parts is retrieved correctly"
self.assertEquals (self.ctrl.PartCount(), 3)
def testPartRightEdges(self):
"Make sure the part widths are retrieved correctly"
for i in range(0, self.ctrl.PartCount()-1):
self.assertEquals (self.ctrl.PartRightEdges()[i], self.part_rects[i].right)
self.assertEquals(self.ctrl.PartRightEdges()[i+1], -1)
def testGetPartRect(self):
"Make sure the part rectangles are retrieved correctly"
for i in range(0, self.ctrl.PartCount()):
self.assertEquals (self.ctrl.GetPartRect(i), self.part_rects[i])
self.assertRaises(IndexError, self.ctrl.GetPartRect, 99)
def testClientRects(self):
self.assertEquals(self.ctrl.ClientRect(), self.ctrl.ClientRects()[0])
self.assertEquals(self.part_rects, self.ctrl.ClientRects()[1:])
def testGetPartText(self):
self.assertRaises(IndexError, self.ctrl.GetPartText, 99)
for i, text in enumerate(self.texts):
self.assertEquals(text, self.ctrl.GetPartText(i))
class TabControlTestCases(unittest.TestCase):
"Unit tests for the TreeViewWrapper class"
def setUp(self):
"""Start the application set some data and ensure the application
is in the state we want it."""
# start the application
from pywinauto.application import Application
app = Application()
app.start_(os.path.join(controlspy_folder, "Tab.exe"))
self.texts = [
"Pluto", "Neptune", "Uranus",
"Saturn", "Jupiter", "Mars",
"Earth", "Venus", "Mercury", "Sun"]
self.rects = [
RECT(2,2,80,21),
RECT(80,2,174,21),
RECT(174,2,261,21),
RECT(2,21,91,40),
RECT(91,21,180,40),
RECT(180,21,261,40),
RECT(2,40,64,59),
RECT(64,40,131,59),
RECT(131,40,206,59),
RECT(206,40,261,59),
]
self.app = app
self.dlg = app.MicrosoftControlSpy
self.ctrl = app.MicrosoftControlSpy.TabControl.WrapperObject()
#self.dlg.MenuSelect("Styles")
# select show selection always, and show checkboxes
#app.ControlStyles.ListBox1.TypeKeys(
# "{HOME}{SPACE}" + "{DOWN}"* 12 + "{SPACE}")
#self.app.ControlStyles.ApplyStylesSetWindowLong.Click()
#self.app.ControlStyles.SendMessage(win32defines.WM_CLOSE)
def tearDown(self):
"Close the application after tests"
# close the application
self.dlg.SendMessage(win32defines.WM_CLOSE)
def testFriendlyClass(self):
"Make sure the friendly class is set correctly"
self.assertEquals (self.ctrl.FriendlyClassName(), "TabControl")
def testTexts(self):
"Make sure the texts are set correctly"
self.assertEquals (self.ctrl.Texts()[1:], self.texts)
def testGetProperties(self):
"Test getting the properties for the tabcontrol"
props = self.ctrl.GetProperties()
self.assertEquals(
self.ctrl.FriendlyClassName(), props['FriendlyClassName'])
self.assertEquals(
self.ctrl.Texts(), props['Texts'])
for prop_name in props:
self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name])
def testRowCount(self):
self.assertEquals(3, self.ctrl.RowCount())
def testGetSelectedTab(self):
self.assertEquals(6, self.ctrl.GetSelectedTab())
self.ctrl.Select(0)
self.assertEquals(0, self.ctrl.GetSelectedTab())
self.ctrl.Select("Jupiter")
self.assertEquals(4, self.ctrl.GetSelectedTab())
def testTabCount(self):
"Make sure the number of parts is retrieved correctly"
self.assertEquals (self.ctrl.TabCount(), 10)
def testGetTabRect(self):
"Make sure the part rectangles are retrieved correctly"
for i, rect in enumerate(self.rects):
self.assertEquals (self.ctrl.GetTabRect(i), self.rects[i])
self.assertRaises(IndexError, self.ctrl.GetTabRect, 99)
# def testGetTabState(self):
# self.assertRaises(IndexError, self.ctrl.GetTabState, 99)
#
# self.dlg.StatementEdit.SetEditText ("MSG (TCM_HIGHLIGHTITEM,1,MAKELONG(TRUE,0))")
#
# time.sleep(.3)
# # use CloseClick to allow the control time to respond to the message
# self.dlg.Send.CloseClick()
# time.sleep(2)
# print("==\n",self.ctrl.TabStates())
#
# self.assertEquals (self.ctrl.GetTabState(1), 1)<|fim▁hole|># def testTabStates(self):
# print(self.ctrl.TabStates())
# raise "tabstates hiay"
def testGetTabText(self):
for i, text in enumerate(self.texts):
self.assertEquals(text, self.ctrl.GetTabText(i))
self.assertRaises(IndexError, self.ctrl.GetTabText, 99)
def testClientRects(self):
self.assertEquals(self.ctrl.ClientRect(), self.ctrl.ClientRects()[0])
self.assertEquals(self.rects, self.ctrl.ClientRects()[1:])
def testSelect(self):
self.assertEquals(6, self.ctrl.GetSelectedTab())
self.ctrl.Select(1)
self.assertEquals(1, self.ctrl.GetSelectedTab())
self.ctrl.Select("Mercury")
self.assertEquals(8, self.ctrl.GetSelectedTab())
self.assertRaises(IndexError, self.ctrl.Select, 99)
class ToolbarTestCases(unittest.TestCase):
"Unit tests for the UpDownWrapper class"
def setUp(self):
"""Start the application set some data and ensure the application
is in the state we want it."""
# start the application
from pywinauto.application import Application
app = Application()
app.start_(os.path.join(controlspy_folder, "toolbar.exe"))
self.app = app
self.dlg = app.MicrosoftControlSpy
self.ctrl = app.MicrosoftControlSpy.Toolbar.WrapperObject()
#self.dlg.MenuSelect("Styles")
# select show selection always, and show checkboxes
#app.ControlStyles.ListBox1.TypeKeys(
# "{HOME}{SPACE}" + "{DOWN}"* 12 + "{SPACE}")
#self.app.ControlStyles.ApplyStylesSetWindowLong.Click()
#self.app.ControlStyles.SendMessage(win32defines.WM_CLOSE)
def tearDown(self):
"Close the application after tests"
# close the application
self.dlg.SendMessage(win32defines.WM_CLOSE)
def testFriendlyClass(self):
"Make sure the friendly class is set correctly"
self.assertEquals (self.ctrl.FriendlyClassName(), "Toolbar")
def testTexts(self):
"Make sure the texts are set correctly"
for txt in self.ctrl.Texts():
self.assertEquals (isinstance(txt, six.string_types), True)
def testGetProperties(self):
"Test getting the properties for the toolbar control"
props = self.ctrl.GetProperties()
self.assertEquals(
self.ctrl.FriendlyClassName(), props['FriendlyClassName'])
self.assertEquals(
self.ctrl.Texts(), props['Texts'])
self.assertEquals(
self.ctrl.ButtonCount(), props['ButtonCount'])
for prop_name in props:
self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name])
def testButtonCount(self):
"Test the button count method of the toolbar"
self.assertEquals(self.ctrl.ButtonCount(), 14)
def testGetButton(self):
self.assertRaises(IndexError, self.ctrl.GetButton, 29)
def testGetButtonRect(self):
self.assertEquals(self.ctrl.GetButtonRect(0), RECT(6, 0, 29, 22))
def testGetToolTipsControls(self):
tips = self.ctrl.GetToolTipsControl()
self.assertEquals("Button ID 7" in tips.Texts(),True)
def testPressButton(self):
self.ctrl.PressButton(0)
#print(self.ctrl.Texts())
self.assertRaises(
findbestmatch.MatchError,
self.ctrl.PressButton,
"asdfdasfasdf")
# todo more tests for pressbutton
self.ctrl.PressButton("10")
class RebarTestCases(unittest.TestCase):
"Unit tests for the UpDownWrapper class"
def setUp(self):
"""Start the application set some data and ensure the application
is in the state we want it."""
# start the application
from pywinauto.application import Application
app = Application()
app.start_(os.path.join(controlspy_folder, "rebar.exe"))
self.app = app
self.dlg = app.MicrosoftControlSpy
self.ctrl = app.MicrosoftControlSpy.Rebar.WrapperObject()
#self.dlg.MenuSelect("Styles")
# select show selection always, and show checkboxes
#app.ControlStyles.ListBox1.TypeKeys(
# "{HOME}{SPACE}" + "{DOWN}"* 12 + "{SPACE}")
#self.app.ControlStyles.ApplyStylesSetWindowLong.Click()
#self.app.ControlStyles.SendMessage(win32defines.WM_CLOSE)
def tearDown(self):
"Close the application after tests"
# close the application
self.dlg.SendMessage(win32defines.WM_CLOSE)
def testFriendlyClass(self):
"Make sure the friendly class is set correctly"
self.assertEquals (self.ctrl.FriendlyClassName(), "ReBar")
def testTexts(self):
"Make sure the texts are set correctly"
for txt in self.ctrl.Texts():
self.assertEquals (isinstance(txt, six.string_types), True)
def testBandCount(self):
self.assertEquals(self.ctrl.BandCount(), 2)
def testGetBand(self):
self.assertRaises(IndexError, self.ctrl.GetBand, 99)
self.assertRaises(IndexError, self.ctrl.GetBand, 2)
band = self.ctrl.GetBand(0)
self.assertEquals(band.hwndChild, self.dlg.ToolBar.handle)
#self.assertEquals(band.text, "blah")
def testGetToolTipsControl(self):
self.assertEquals(self.ctrl.GetToolTipsControl(), None)
class ToolTipsTestCases(unittest.TestCase):
"Unit tests for the tooltips class"
def setUp(self):
"""Start the application set some data and ensure the application
is in the state we want it."""
self.texts = [u'Tooltip Tool 0', u'Tooltip Tool 1', u'Tooltip Tool 2']
# start the application
from pywinauto.application import Application
app = Application()
app.start_(os.path.join(controlspy_folder, "Tooltip.exe"))
self.app = app
self.dlg = app.MicrosoftControlSpy
tips = app.windows_(
visible_only = False,
enabled_only = False,
top_level_only = False,
class_name = "tooltips_class32")
self.ctrl = WrapHandle(tips[1])
#self.ctrl = HwndWrapper(tips[1])
#self.dlg.MenuSelect("Styles")
# select show selection always, and show checkboxes
#app.ControlStyles.ListBox1.TypeKeys(
# "{HOME}{SPACE}" + "{DOWN}"* 12 + "{SPACE}")
#self.app.ControlStyles.ApplyStylesSetWindowLong.Click()
#self.app.ControlStyles.SendMessage(win32defines.WM_CLOSE)
def tearDown(self):
"Close the application after tests"
# close the application
self.app.kill_()
def testFriendlyClass(self):
"Make sure the friendly class is set correctly"
self.assertEquals (self.ctrl.FriendlyClassName(), "ToolTips")
def testTexts(self):
"Make sure the texts are set correctly"
self.assertEquals (self.ctrl.Texts()[1:], self.texts)
def testGetProperties(self):
"Test getting the properties for the tooltips control"
props = self.ctrl.GetProperties()
self.assertEquals(
self.ctrl.FriendlyClassName(), props['FriendlyClassName'])
self.assertEquals(
self.ctrl.Texts(), props['Texts'])
for prop_name in props:
self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name])
def testGetTip(self):
self.assertRaises(IndexError, self.ctrl.GetTip, 99)
tip = self.ctrl.GetTip(1)
self.assertEquals(tip.text, self.texts[1])
def testToolCount(self):
self.assertEquals(3, self.ctrl.ToolCount())
def testGetTipText(self):
self.assertEquals(self.texts[1], self.ctrl.GetTipText(1))
def testTexts(self):
self.assertEquals(self.ctrl.Texts()[0], '')
self.assertEquals(self.ctrl.Texts()[1:], self.texts)
class UpDownTestCases(unittest.TestCase):
"Unit tests for the UpDownWrapper class"
def setUp(self):
"""Start the application set some data and ensure the application
is in the state we want it."""
# start the application
from pywinauto.application import Application
app = Application()
app.start_(os.path.join(controlspy_folder, "Up-Down.exe"))
self.app = app
self.dlg = app.MicrosoftControlSpy
self.ctrl = app.MicrosoftControlSpy.UpDown2.WrapperObject()
#self.dlg.MenuSelect("Styles")
# select show selection always, and show checkboxes
#app.ControlStyles.ListBox1.TypeKeys(
# "{HOME}{SPACE}" + "{DOWN}"* 12 + "{SPACE}")
#self.app.ControlStyles.ApplyStylesSetWindowLong.Click()
#self.app.ControlStyles.SendMessage(win32defines.WM_CLOSE)
def tearDown(self):
"Close the application after tests"
# close the application
self.dlg.SendMessage(win32defines.WM_CLOSE)
def testFriendlyClass(self):
"Make sure the friendly class is set correctly"
self.assertEquals (self.ctrl.FriendlyClassName(), "UpDown")
def testTexts(self):
"Make sure the texts are set correctly"
self.assertEquals (self.ctrl.Texts()[1:], [])
def testGetProperties(self):
"Test getting the properties for the updown control"
props = self.ctrl.GetProperties()
self.assertEquals(
self.ctrl.FriendlyClassName(), props['FriendlyClassName'])
self.assertEquals(
self.ctrl.Texts(), props['Texts'])
for prop_name in props:
self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name])
def testGetValue(self):
"Test getting up-down position"
self.assertEquals (self.ctrl.GetValue(), 0)
self.ctrl.SetValue(23)
self.assertEquals (self.ctrl.GetValue(), 23)
def testSetValue(self):
"Test setting up-down position"
self.assertEquals (self.ctrl.GetValue(), 0)
self.ctrl.SetValue(23)
self.assertEquals (self.ctrl.GetValue(), 23)
self.assertEquals(
int(self.ctrl.GetBuddyControl().Texts()[1]),
23)
def testGetBase(self):
"Test getting the base of the up-down control"
self.assertEquals (self.ctrl.GetBase(), 10)
self.dlg.StatementEdit.SetEditText ("MSG (UDM_SETBASE, 16, 0)")
# use CloseClick to allow the control time to respond to the message
self.dlg.Send.Click()
self.assertEquals (self.ctrl.GetBase(), 16)
def testGetRange(self):
"Test getting the range of the up-down control"
self.assertEquals((0, 9999), self.ctrl.GetRange())
def testGetBuddy(self):
"Test getting the buddy control"
self.assertEquals (self.ctrl.GetBuddyControl().handle, self.dlg.Edit6.handle)
def testIncrement(self):
"Test incremementing up-down position"
self.ctrl.Increment()
self.assertEquals (self.ctrl.GetValue(), 1)
def testDecrement(self):
"Test decrementing up-down position"
self.ctrl.SetValue(23)
self.ctrl.Decrement()
self.assertEquals (self.ctrl.GetValue(), 22)
if __name__ == "__main__":
unittest.main()<|fim▁end|>
|
#
|
<|file_name|>unreachable-lint.rs<|end_file_name|><|fim▁begin|>// check-pass
// edition:2018
#![deny(unreachable_code)]
<|fim▁hole|>async fn endless() -> ! {
loop {}
}
fn main() { }<|fim▁end|>
|
async fn foo() {
endless().await;
}
|
<|file_name|>__manifest__.py<|end_file_name|><|fim▁begin|># Copyright 2021 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Mozaik Website Event Track",
"summary": """
This module allows to see the event menu configuration
even without activated debug mode""",
"version": "14.0.1.0.0",
"license": "AGPL-3",
"author": "ACSONE SA/NV",
"website": "https://github.com/OCA/mozaik",
"depends": [
# Odoo<|fim▁hole|> ],
}<|fim▁end|>
|
"website_event_track",
],
"data": [
"views/event_event.xml",
|
<|file_name|>FiletramCom.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from pyload.plugin.internal.SimpleCrypter import SimpleCrypter
class FiletramCom(SimpleCrypter):
__name = "FiletramCom"
__type = "crypter"<|fim▁hole|> __config = [("use_premium" , "bool", "Use premium account if available" , True),
("use_subfolder" , "bool", "Save package to subfolder" , True),
("subfolder_per_pack", "bool", "Create a subfolder for each package", True)]
__description = """Filetram.com decrypter plugin"""
__license = "GPLv3"
__authors = [("igel", "[email protected]"),
("stickell", "[email protected]")]
LINK_PATTERN = r'\s+(http://.+)'
NAME_PATTERN = r'<title>(?P<N>.+?) - Free Download'<|fim▁end|>
|
__version = "0.03"
__pattern = r'http://(?:www\.)?filetram\.com/[^/]+/.+'
|
<|file_name|>0008_auto_20170529_1302.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import ckeditor.fields
from django.db import migrations
from django.db import models
<|fim▁hole|> ]
operations = [
migrations.AlterField(
model_name='proposal',
name='description',
field=ckeditor.fields.RichTextField(verbose_name='Description'),
),
migrations.AlterField(
model_name='proposal',
name='name',
field=models.CharField(max_length=120, verbose_name='Name'),
),
]<|fim▁end|>
|
class Migration(migrations.Migration):
dependencies = [
('meinberlin_budgeting', '0007_update-strings'),
|
<|file_name|>irc.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "irc.h"
#include "net.h"
#include "strlcpy.h"
#include "base58.h"
using namespace std;
using namespace boost;
int nGotIRCAddresses = 0;
void ThreadIRCSeed2(void* parg);
#pragma pack(push, 1)<|fim▁hole|>{
struct in_addr ip;
short port;
};
#pragma pack(pop)
string EncodeAddress(const CService& addr)
{
struct ircaddr tmp;
if (addr.GetInAddr(&tmp.ip))
{
tmp.port = htons(addr.GetPort());
vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
return string("u") + EncodeBase58Check(vch);
}
return "";
}
bool DecodeAddress(string str, CService& addr)
{
vector<unsigned char> vch;
if (!DecodeBase58Check(str.substr(1), vch))
return false;
struct ircaddr tmp;
if (vch.size() != sizeof(tmp))
return false;
memcpy(&tmp, &vch[0], sizeof(tmp));
addr = CService(tmp.ip, ntohs(tmp.port));
return true;
}
static bool Send(SOCKET hSocket, const char* pszSend)
{
if (strstr(pszSend, "PONG") != pszSend)
printf("IRC SENDING: %s\n", pszSend);
const char* psz = pszSend;
const char* pszEnd = psz + strlen(psz);
while (psz < pszEnd)
{
int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
if (ret < 0)
return false;
psz += ret;
}
return true;
}
bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
loop
{
bool fRet = RecvLine(hSocket, strLine);
if (fRet)
{
if (fShutdown)
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() >= 1 && vWords[0] == "PING")
{
strLine[1] = 'O';
strLine += '\r';
Send(hSocket, strLine.c_str());
continue;
}
}
return fRet;
}
}
int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
{
loop
{
string strLine;
strLine.reserve(10000);
if (!RecvLineIRC(hSocket, strLine))
return 0;
printf("IRC %s\n", strLine.c_str());
if (psz1 && strLine.find(psz1) != string::npos)
return 1;
if (psz2 && strLine.find(psz2) != string::npos)
return 2;
if (psz3 && strLine.find(psz3) != string::npos)
return 3;
if (psz4 && strLine.find(psz4) != string::npos)
return 4;
}
}
bool Wait(int nSeconds)
{
if (fShutdown)
return false;
printf("IRC waiting %d seconds to reconnect\n", nSeconds);
for (int i = 0; i < nSeconds; i++)
{
if (fShutdown)
return false;
Sleep(1000);
}
return true;
}
bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
{
strRet.clear();
loop
{
string strLine;
if (!RecvLineIRC(hSocket, strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
if (vWords[1] == psz1)
{
printf("IRC %s\n", strLine.c_str());
strRet = strLine;
return true;
}
}
}
bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
{
Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
string strLine;
if (!RecvCodeLine(hSocket, "302", strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 4)
return false;
string str = vWords[3];
if (str.rfind("@") == string::npos)
return false;
string strHost = str.substr(str.rfind("@")+1);
// Hybrid IRC used by lfnet always returns IP when you userhost yourself,
// but in case another IRC is ever used this should work.
printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
CNetAddr addr(strHost, true);
if (!addr.IsValid())
return false;
ipRet = addr;
return true;
}
void ThreadIRCSeed(void* parg)
{
// Make this thread recognisable as the IRC seeding thread
RenameThread("bitcoin-ircseed");
try
{
ThreadIRCSeed2(parg);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ThreadIRCSeed()");
} catch (...) {
PrintExceptionContinue(NULL, "ThreadIRCSeed()");
}
printf("ThreadIRCSeed exited\n");
}
void ThreadIRCSeed2(void* parg)
{
// Don't connect to IRC if we won't use IPv4 connections.
if (IsLimited(NET_IPV4))
return;
// ... or if we won't make outbound connections and won't accept inbound ones.
if (mapArgs.count("-connect") && fNoListen)
return;
// ... or if IRC is not enabled.
if (!GetBoolArg("-irc", true))
return;
printf("ThreadIRCSeed started\n");
int nErrorWait = 10;
int nRetryWait = 10;
int nNameRetry = 0;
while (!fShutdown)
{
CService addrConnect("188.122.74.140", 6667); // eu.undernet.org
CService addrIRC("irc.rizon.net", 6667, true);
if (addrIRC.IsValid())
addrConnect = addrIRC;
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
{
printf("IRC connect failed\n");
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
CService addrLocal;
string strMyName;
// Don't use our IP as our nick if we're not listening
// or if it keeps failing because the nick is already in use.
if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3)
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
if (strMyName == "")
strMyName = strprintf("x%"PRI64u"", GetRand(1000000000));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
if (nRet != 1)
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (nRet == 2)
{
printf("IRC name already in use\n");
nNameRetry++;
Wait(10);
continue;
}
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
nNameRetry = 0;
Sleep(500);
// Get our external IP from the IRC server and re-nick before joining the channel
CNetAddr addrFromIRC;
if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))
{
printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str());
// Don't use our IP as our nick if we're not listening
if (!fNoListen && addrFromIRC.IsRoutable())
{
// IRC lets you to re-nick
AddLocal(addrFromIRC, LOCAL_IRC);
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
}
}
if (fTestNet) {
Send(hSocket, "JOIN #AndroidsTokenTEST2\r");
Send(hSocket, "WHO #AndroidsTokenTEST2\r");
} else {
// randomly join #AndroidsToken00-#AndroidsToken05
// int channel_number = GetRandInt(5);
// Channel number is always 0 for initial release
int channel_number = 0;
Send(hSocket, strprintf("JOIN #AndroidsToken%02d\r", channel_number).c_str());
Send(hSocket, strprintf("WHO #AndroidsToken%02d\r", channel_number).c_str());
}
int64 nStart = GetTime();
string strLine;
strLine.reserve(10000);
while (!fShutdown && RecvLineIRC(hSocket, strLine))
{
if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
continue;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
char pszName[10000];
pszName[0] = '\0';
if (vWords[1] == "352" && vWords.size() >= 8)
{
// index 7 is limited to 16 characters
// could get full length name at index 10, but would be different from join messages
strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
printf("IRC got who\n");
}
if (vWords[1] == "JOIN" && vWords[0].size() > 1)
{
// :[email protected] JOIN :#channelname
strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
if (strchr(pszName, '!'))
*strchr(pszName, '!') = '\0';
printf("IRC got join\n");
}
if (pszName[0] == 'u')
{
CAddress addr;
if (DecodeAddress(pszName, addr))
{
addr.nTime = GetAdjustedTime();
if (addrman.Add(addr, addrConnect, 51 * 60))
printf("IRC got new address: %s\n", addr.ToString().c_str());
nGotIRCAddresses++;
}
else
{
printf("IRC decode failed\n");
}
}
}
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (GetTime() - nStart > 20 * 60)
{
nErrorWait /= 3;
nRetryWait /= 3;
}
nRetryWait = nRetryWait * 11 / 10;
if (!Wait(nRetryWait += 60))
return;
}
}
#ifdef TEST
int main(int argc, char *argv[])
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
{
printf("Error at WSAStartup()\n");
return false;
}
ThreadIRCSeed(NULL);
WSACleanup();
return 0;
}
#endif<|fim▁end|>
|
struct ircaddr
|
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![feature(raw)]
extern crate fixed_size_array;
use std::{ptr, raw};
use std::marker::PhantomData;
use std::raw::Repr;
use fixed_size_array::FixedSizeArray;
/// An iterator constructed by the `literator!` macro.
pub struct Literator<Array, Elem>
where Array: FixedSizeArray<Elem=Elem>
{
pos: isize,
array: Option<Array>,
phantom: PhantomData<[Elem; 17]>,
}
impl<Array, Elem> Literator<Array, Elem>
where Array: FixedSizeArray<Elem=Elem>
{
pub fn new(array: Array) -> Literator<Array, Elem> {
Literator {
pos: 0,
array: Some(array),
phantom: PhantomData,
}
}
fn as_mut_slice<'a>(&'a mut self) -> &'a mut [Elem] {
self.array.as_mut().unwrap().as_mut_slice()
}
}
impl<Array, Elem> Iterator for Literator<Array, Elem>
where Array: FixedSizeArray<Elem=Elem>
{
type Item = Elem;
fn next(&mut self) -> Option<Elem> {
let raw::Slice { data, len } = self.as_mut_slice().repr();
let i = self.pos;
if i as usize >= len {
None
} else {
self.pos += 1;
Some(unsafe {
// We know we'll never use this array location again,
// so it's okay to force a move out.
ptr::read(data.offset(i) as *mut Elem)
})
}
}
}
impl<Array, Elem> Drop for Literator<Array, Elem>
where Array: FixedSizeArray<Elem=Elem>
{
fn drop(&mut self) {
unsafe {
let raw::Slice { data, len } = self.as_mut_slice().repr();
let mut i = self.pos;
while (i as usize) < len {
// drop remaining elements
ptr::read(data.offset(i) as *mut Elem);
i += 1;
}
ptr::write(&mut self.array, None);
}
}
}
/// Given any number of values, produces an iterator that yields those
/// values one by one.
#[macro_export]
macro_rules! literator {
($($x:expr),*) => (
$crate::Literator::new([$($x),*])
)
}
/// Initialize any `FromIter` container from a sequence of elements.
///
/// If the elements are pairs, you can use the sugar `x => y`.
#[macro_export]
macro_rules! container {
($($x:expr),*) => (
::std::iter::FromIterator::from_iter(literator!($($x),*))
);
($($x:expr),*,) => (
container!($($x),*)
);
($( $x:expr => $y:expr),*) => (
container!($(($x, $y)),*)
);
($( $x:expr => $y:expr),*,) => (
container!($( $x => $y ),*)
);
}
#[cfg(test)]
mod test {
use std::collections::HashMap;
<|fim▁hole|>
let v: Vec<_> = container![1, 2, 3,];
assert_eq!(&v, &[1, 2, 3]);
let h: HashMap<_, _> = container! {
1 => 'x',
2 => 'y'
};
let mut v: Vec<_> = h.iter().collect();
v.sort();
assert_eq!(&v, &[(&1, &'x'), (&2, &'y')]);
let h: HashMap<_, _> = container! {
1 => 'x',
2 => 'y',
};
let mut v: Vec<_> = h.iter().collect();
v.sort();
assert_eq!(&v, &[(&1, &'x'), (&2, &'y')]);
}
}<|fim▁end|>
|
#[test]
fn smoke_test() {
let v: Vec<_> = container![1, 2, 3];
assert_eq!(&v, &[1, 2, 3]);
|
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# coding: utf-8<|fim▁hole|>
# Copyright (C) USC Information Sciences Institute
# Author: Vladimir M. Zaytsev <[email protected]>
# URL: <http://nlg.isi.edu/>
# For more information, see README.md
# For license information, see LICENSE
from django.conf.urls import url
from django.conf.urls import patterns
from django.shortcuts import redirect
urlpatterns = patterns(
"",
url(r"^$", "n7.web.n7.views.demo", name="demo"),
url(r"^triples/$", "n7.web.n7.views.trainer", name="trainer"),
url(r"^novels/$", "n7.web.n7.views.trainer_add", name="trainer_post"),
)<|fim▁end|>
| |
<|file_name|>repr-transparent-other-reprs.rs<|end_file_name|><|fim▁begin|>// Copyright 2017 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<|fim▁hole|>// except according to those terms.
#![feature(repr_align)]
// See also repr-transparent.rs
#[repr(transparent, C)] //~ ERROR cannot have other repr
struct TransparentPlusC {
ptr: *const u8
}
#[repr(transparent, packed)] //~ ERROR cannot have other repr
struct TransparentPlusPacked(*const u8);
#[repr(transparent, align(2))] //~ ERROR cannot have other repr
struct TransparentPlusAlign(u8);
#[repr(transparent)] //~ ERROR cannot have other repr
#[repr(C)]
struct SeparateAttributes(*mut u8);
fn main() {}<|fim▁end|>
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
|
<|file_name|>enum_builder.rs<|end_file_name|><|fim▁begin|>/* Some types from or based on types from elastic: https://github.com/elastic-rs/elastic
*
* Licensed under Apache 2.0: https://github.com/elastic-rs/elastic/blob/51298dd64278f34d2db911bd1a35eb757c336198/LICENSE-APACHE
*
* 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.
*/
use crate::api_generator::code_gen::url::url_builder::{IntoExpr, UrlBuilder};
use crate::api_generator::{code_gen::*, ApiEndpoint, Path};
use inflector::Inflector;
use syn;
/// Builder for request url parts enum
///
/// The output of this structure is an enum that only accepts valid parameter combinations,
/// based on what's given in the paths for an endpoint.
#[derive(Debug, Clone)]
pub struct EnumBuilder<'a> {
ident: syn::Ident,
api_name: String,
variants: Vec<syn::Variant>,
paths: Vec<&'a Path>,
has_lifetime: bool,
}
impl<'a> EnumBuilder<'a> {
pub fn new(prefix: &str) -> Self {
let name = Self::name(prefix);
let api_name = split_on_pascal_case(prefix);
EnumBuilder {
ident: ident(name),
api_name,
variants: vec![],
paths: vec![],
has_lifetime: false,
}
}
fn name(prefix: &str) -> String {
format!("{}Parts", prefix.to_pascal_case())
}
/// Whether this instance already contains a path with parts matching the given path
fn contains_path_with_parts(&self, path: &'a Path) -> bool {
let params = path.path.params();
self.paths.iter().any(|&p| p.path.params() == params)
}
/// Whether this instance contains only a single path with no parts
pub fn contains_single_parameterless_part(&self) -> bool {
match self.paths.len() {
1 => self.paths[0].parts.is_empty(),
_ => false,
}
}
pub fn with_path(mut self, path: &'a Path) -> Self {
if !self.contains_path_with_parts(path) {
let variant = match &path.parts.len() {
0 => Self::parts_none(),
_ => {
self.has_lifetime = true;
Self::parts(&path)
}
};
self.variants.push(variant);
self.paths.push(path);
}
self
}
/// AST for a parts variant.
fn parts(path: &Path) -> syn::Variant {
let params = &path.path.params();
let name = params
.iter()
.map(|k| k.to_pascal_case())
.collect::<Vec<_>>()
.join("");
let doc = match params.len() {
1 => doc(params[0].replace("_", " ").to_pascal_case()),
n => {
let mut d: String = params
.iter()
.enumerate()
.filter(|&(i, _)| i != n - 1)
.map(|(_, e)| e.replace("_", " ").to_pascal_case())
.collect::<Vec<_>>()
.join(", ");
d.push_str(
format!(" and {}", params[n - 1].replace("_", " ").to_pascal_case()).as_str(),
);
doc(d)
}
};
syn::Variant {
ident: ident(name),
attrs: vec![doc],
discriminant: None,
data: syn::VariantData::Tuple(
path.path
.params()
.iter()
.map(|&p| {
let ty = path.parts[p].ty;
syn::Field {
ident: None,
vis: syn::Visibility::Inherited,
attrs: vec![],
ty: typekind_to_ty(p, ty, true),
}
})
.collect(),
),
}
}
/// AST for a `None` parts variant.
fn parts_none() -> syn::Variant {
syn::Variant {
ident: ident("None"),
attrs: vec![doc("No parts".into())],
data: syn::VariantData::Unit,
discriminant: None,<|fim▁hole|>
fn match_path(ty: &syn::Ty, variant: &syn::Variant) -> syn::Path {
let mut path = ty.get_path().to_owned();
// Remove lifetimes from the enum type.
for segment in &mut path.segments {
segment.parameters = syn::PathParameters::none();
}
path.segments
.push(syn::PathSegment::from(variant.ident.to_string()));
path
}
/// Get the field names for the enum tuple variant to match.
fn match_fields(path: &Path) -> Vec<syn::Pat> {
path.path
.params()
.iter()
.map(|&p| {
syn::Pat::Ident(
syn::BindingMode::ByRef(syn::Mutability::Immutable),
ident(valid_name(p)),
None,
)
})
.collect()
}
/// Build this enum and return ASTs for its type, struct declaration and impl
pub fn build(self) -> (syn::Ty, syn::Item, syn::Item) {
let variants = match self.variants.len() {
0 => vec![Self::parts_none()],
_ => self.variants,
};
let (enum_ty, generics) = {
if self.has_lifetime {
(ty_b(self.ident.as_ref()), generics_b())
} else {
(ty(self.ident.as_ref()), generics_none())
}
};
let enum_impl = {
let mut arms = Vec::new();
for (variant, &path) in variants.iter().zip(self.paths.iter()) {
let match_path = Self::match_path(&enum_ty, variant);
let fields = Self::match_fields(path);
let arm = match fields.len() {
0 => syn::Pat::Path(None, match_path),
_ => syn::Pat::TupleStruct(match_path, fields, None),
};
let body = UrlBuilder::new(path).build();
arms.push(syn::Arm {
attrs: vec![],
pats: vec![arm],
guard: None,
body: Box::new(body),
});
}
let match_expr: syn::Expr =
syn::ExprKind::Match(Box::new(path_none("self").into_expr()), arms).into();
let fn_decl = syn::FnDecl {
inputs: vec![syn::FnArg::SelfValue(syn::Mutability::Immutable)],
output: syn::FunctionRetTy::Ty(ty("Cow<'static, str>")),
variadic: false,
};
let item = syn::ImplItem {
ident: ident("url"),
vis: syn::Visibility::Public,
defaultness: syn::Defaultness::Final,
attrs: vec![doc(format!(
"Builds a relative URL path to the {} API",
self.api_name
))],
node: syn::ImplItemKind::Method(
syn::MethodSig {
unsafety: syn::Unsafety::Normal,
constness: syn::Constness::NotConst,
abi: None,
decl: fn_decl,
generics: generics_none(),
},
syn::Block {
stmts: vec![match_expr.into_stmt()],
},
),
};
syn::Item {
ident: ident(""),
vis: syn::Visibility::Public,
attrs: vec![],
node: syn::ItemKind::Impl(
syn::Unsafety::Normal,
syn::ImplPolarity::Positive,
generics.clone(),
None,
Box::new(enum_ty.clone()),
vec![item],
),
}
};
let enum_decl = syn::Item {
ident: self.ident,
vis: syn::Visibility::Public,
attrs: vec![
syn::Attribute {
is_sugared_doc: false,
style: syn::AttrStyle::Outer,
value: syn::MetaItem::List(
ident("derive"),
vec![
syn::NestedMetaItem::MetaItem(syn::MetaItem::Word(ident("Debug"))),
syn::NestedMetaItem::MetaItem(syn::MetaItem::Word(ident("Clone"))),
syn::NestedMetaItem::MetaItem(syn::MetaItem::Word(ident("PartialEq"))),
],
),
},
doc(format!("API parts for the {} API", self.api_name)),
],
node: syn::ItemKind::Enum(variants, generics),
};
(enum_ty, enum_decl, enum_impl)
}
}
impl<'a> From<&'a (String, ApiEndpoint)> for EnumBuilder<'a> {
fn from(value: &'a (String, ApiEndpoint)) -> Self {
let endpoint = &value.1;
let mut builder = EnumBuilder::new(value.0.to_pascal_case().as_ref());
for path in &endpoint.url.paths {
builder = builder.with_path(&path);
}
builder
}
}
#[cfg(test)]
mod tests {
#![cfg_attr(rustfmt, rustfmt_skip)]
use super::*;
use crate::api_generator::{Url, Path, HttpMethod, Body, Deprecated, Type, TypeKind, Documentation, ast_eq};
use std::collections::BTreeMap;
use crate::api_generator::code_gen::url::url_builder::PathString;
#[test]
fn generate_parts_enum_from_endpoint() {
let endpoint = (
"search".to_string(),
ApiEndpoint {
documentation: Documentation {
description: None,
url: None,
},
stability: "stable".to_string(),
url: Url {
paths: vec![
Path {
path: PathString("/_search".to_string()),
methods: vec![HttpMethod::Get, HttpMethod::Post],
parts: BTreeMap::new(),
deprecated: None,
},
Path {
path: PathString("/{index}/_search".to_string()),
methods: vec![HttpMethod::Get, HttpMethod::Post],
parts: {
let mut map = BTreeMap::new();
map.insert("index".to_string(), Type {
ty: TypeKind::List,
description: Some("A comma-separated list of document types to search".to_string()),
options: vec![],
default: None,
});
map
},
deprecated: None,
},
Path {
path: PathString("/{index}/{type}/_search".to_string()),
methods: vec![HttpMethod::Get, HttpMethod::Post],
parts: {
let mut map = BTreeMap::new();
map.insert("index".to_string(), Type {
ty: TypeKind::List,
description: Some("A comma-separated list of index names to search".to_string()),
options: vec![],
default: None,
});
map.insert("type".to_string(), Type {
ty: TypeKind::List,
description: Some("A comma-separated list of document types to search".to_string()),
options: vec![],
default: None,
});
map
},
deprecated: Some(Deprecated {
version: "7.0.0".to_string(),
description: "types are going away".to_string()
}),
},
],
},
params: BTreeMap::new(),
body: Some(Body {
description: Some("The search request".to_string()),
required: Some(false),
serialize: None
}),
},
);
let (enum_ty, enum_decl, enum_impl) = EnumBuilder::from(&endpoint).build();
assert_eq!(ty_b("SearchParts"), enum_ty);
let expected_decl = quote!(
#[derive(Debug, Clone, PartialEq)]
#[doc = "API parts for the Search API"]
pub enum SearchParts<'b> {
#[doc = "No parts"]
None,
#[doc = "Index"]
Index(&'b [&'b str]),
#[doc = "Index and Type"]
IndexType(&'b [&'b str], &'b [&'b str]),
}
);
ast_eq(expected_decl, enum_decl);
let expected_impl = quote!(
impl<'b> SearchParts<'b> {
#[doc = "Builds a relative URL path to the Search API"]
pub fn url(self) -> Cow<'static, str> {
match self {
SearchParts::None => "/_search".into(),
SearchParts::Index(ref index) => {
let index_str = index.join(",");
let mut p = String::with_capacity(9usize + index_str.len());
p.push_str("/");
p.push_str(index_str.as_ref());
p.push_str("/_search");
p.into()
}
SearchParts::IndexType(ref index, ref ty) => {
let index_str = index.join(",");
let ty_str = ty.join(",");
let mut p = String::with_capacity(10usize + index_str.len() + ty_str.len());
p.push_str("/");
p.push_str(index_str.as_ref());
p.push_str("/");
p.push_str(ty_str.as_ref());
p.push_str("/_search");
p.into()
}
}
}
}
);
ast_eq(expected_impl, enum_impl);
}
}<|fim▁end|>
|
}
}
|
<|file_name|>glyphquery.py<|end_file_name|><|fim▁begin|>"""Glyph-specific queries on font-files"""
from ttfquery import describe
try:
from OpenGLContext.debug.logs import text_log
except ImportError:
text_log = None
def hasGlyph( font, char, encoding=None ):
"""Check to see if font appears to have explicit glyph for char"""
glyfName = explicitGlyph( font, char, encoding )
if glyfName is None:<|fim▁hole|>def explicitGlyph( font, char, encoding=None ):
"""Return glyphName or None if there is not explicit glyph for char"""
cmap = font['cmap']
if encoding is None:
encoding = describe.guessEncoding( font )
table = cmap.getcmap( *encoding )
glyfName = table.cmap.get( ord(char))
return glyfName
def glyphName( font, char, encoding=None, warnOnFailure=1 ):
"""Retrieve the glyph name for the given character
XXX
Not sure what the effect of the Unicode mapping
will be given the use of ord...
"""
glyfName = explicitGlyph( font, char, encoding )
if glyfName is None:
encoding = describe.guessEncoding( font ) #KH
cmap = font['cmap'] #KH
table = cmap.getcmap( *encoding ) #KH
glyfName = table.cmap.get( -1)
if glyfName is None:
glyfName = font['glyf'].glyphOrder[0]
if text_log and warnOnFailure:
text_log.warn(
"""Unable to find glyph name for %r, in %r using first glyph in table (%r)""",
char,
describe.shortName(font),
glyfName
)
return glyfName
def width( font, glyphName ):
"""Retrieve the width of the giving character for given font
The horizontal metrics table provides both the
width and the left side bearing, we should really
be using the left side bearing to adjust the
character, but that's a later project.
"""
try:
return font['hmtx'].metrics[ glyphName ][0]
except KeyError:
raise ValueError( """Couldn't find glyph for glyphName %r"""%(
glyphName,
))
def lineHeight( font ):
"""Get the base-line to base-line height for the font
XXX
There is some fudging going on here as I
workaround what appears to be a problem with the
specification for sTypoDescender, which states
that it should normally be a negative value, but
winds up being positive in at least one font that
defines points below the zero axis.
XXX The entire OS/2 table doesn't appear in a few
fonts (symbol fonts in particular), such as Corel's
BeeHive and BlackLight 686.
"""
return charHeight(font) + font['OS/2'].sTypoLineGap
def charHeight( font ):
"""Determine the general character height for the font (for scaling)"""
ascent = font['OS/2'].sTypoAscender
descent = font['OS/2'].sTypoDescender
if descent > 0:
descent = - descent
return ascent - descent
def charDescent( font ):
"""Determine the general descent for the font (for scaling)"""
return font['OS/2'].sTypoDescender<|fim▁end|>
|
return False
return True
|
<|file_name|>test_update_deps.py<|end_file_name|><|fim▁begin|>import unittest
import os
import subprocess
from test.stub_config import StubConfig, StubConfigOnStubProject
from test.stub_environment import StubEnvironment
from test.stub_stdout import StubStdout
from googkit.commands.update_deps import UpdateDepsCommand
from googkit.compat.unittest import mock
class TestUpdateDepsCommand(unittest.TestCase):
def setUp(self):
self.env = StubEnvironment()
self.cmd = UpdateDepsCommand(self.env)
self.cmd.config = StubConfig()
def test_needs_project_config(self):
self.assertTrue(UpdateDepsCommand.needs_project_config())
def test_update_deps_js(self):
MockPopen = mock.MagicMock()
MockPopen.return_value.returncode = 0
with mock.patch('subprocess.Popen', new=MockPopen) as mock_popen:
self.cmd.update_deps()
arg_format_dict = {
'depswriter_path': StubConfig.DEPSWRITER,
'js_dev_path': StubConfig.JS_DEV_DIR,
'relpath_from_base_js_to_js_dev': os.path.relpath(StubConfig.JS_DEV_DIR, os.path.dirname(StubConfig.BASE_JS)),
'deps_js_path': StubConfig.DEPS_JS
}
expected = ' '.join([
'python',<|fim▁hole|> '--root_with_prefix="{js_dev_path}',
'{relpath_from_base_js_to_js_dev}"',
'--output_file="{deps_js_path}"'
]).format(**arg_format_dict)
mock_popen.assert_called_once_with(expected, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
def test_update_tests(self):
self.assertEqual(
self.cmd.update_tests('DUMMY', ['dummy1', 'dummy2']),
'var testFiles = [\'dummy1\', \'dummy2\'];')
self.assertEqual(
self.cmd.update_tests('DUMMY', []),
'var testFiles = [];')
def test_update_testrunner(self):
# Use stub config for stub project directories.
self.cmd.config = StubConfigOnStubProject()
self.cmd.update_tests = mock.MagicMock()
self.cmd.update_tests.return_value = 'changed'
# Data will be given by open with for-in statement
read_data = '''\
DUMMY
change me/*@test_files@*/
DUMMY'''
# Expected data for write()
expected_wrote = '''\
DUMMY
changed/*@test_files@*/
DUMMY'''
# Use mock_open
mock_open = mock.mock_open(read_data=read_data)
# Context Manager is a return value of the mock_open.__enter__
mock_fp = mock_open.return_value.__enter__.return_value
# Read lines has "\n" at each last
mock_fp.__iter__.return_value = iter([(line + '\n') for line in read_data.split('\n')])
with mock.patch('googkit.commands.update_deps.open', mock_open, create=True), \
mock.patch('os.path.exists') as mock_exists:
mock_exists.return_value = True
self.cmd.update_testrunner()
# Expected the path is a related path from all_tests.html to js_dev/example_test.html
expected_file = os.path.join('js_dev', 'example_test.html')
self.cmd.update_tests.assert_called_once_with(
' change me/*@test_files@*/\n',
[expected_file])
# Expected open was called twice (for reading and writing)
mock_open.assert_any_call(StubConfigOnStubProject.TESTRUNNER)
mock_open.assert_any_call(StubConfigOnStubProject.TESTRUNNER, 'w')
self.assertEqual(mock_open.call_count, 2)
# Expected correct data was wrote
self.assertEqual(
mock_fp.write.call_args_list,
[mock.call(line + '\n',) for line in expected_wrote.split('\n')])
def test_run_internal(self):
dummy_project_root = os.path.normcase('/dir1/dir2')
self.cmd.update_deps = mock.MagicMock()
self.cmd.update_testrunner = mock.MagicMock()
with mock.patch('sys.stdout', new_callable=StubStdout), \
mock.patch('googkit.lib.path.project_root', return_value=dummy_project_root), \
mock.patch('googkit.commands.update_deps.working_directory'):
self.cmd.run_internal()
self.cmd.update_deps.assert_called_once_with()
self.cmd.update_testrunner.assert_called_once_with()
if __name__ == '__main__':
unittest.main()<|fim▁end|>
|
'{depswriter_path}',
|
<|file_name|>re6.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
import re
# Обработка телефонных номеров<|fim▁hole|># ('800', '555', '1212', '1234')
print phonePattern.search('800.555.1212 x1234').groups()
# ('800', '555', '1212', '1234')
print phonePattern.search('800-555-1212').groups()
# ('800', '555', '1212', '')
print phonePattern.search('(800)5551212 x1234')<|fim▁end|>
|
phonePattern = re.compile(r'^(\d{3})\D*(\d{3})\D*(\d{4})\D*(\d*)$')
print phonePattern.search('80055512121234').groups()
|
<|file_name|>m3.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<|fim▁hole|>// <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.
#![crate_type = "dylib"]
extern crate m2;
pub fn m3() { m2::m2() }<|fim▁end|>
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>from string import Template
import re
import os
import sys
import time
import json
import math
import os
import subprocess
import csv
def saveResults(resultsList, json_fname, csv_fname):
print(resultsList)<|fim▁hole|> json.dump(resultsList, outfile, indent=4, sort_keys=True)
keys = resultsList[0].keys()
with open(csv_fname, 'w') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(resultsList)<|fim▁end|>
|
print(json.dumps(resultsList, indent=4, sort_keys=True))
with open(json_fname, 'w') as outfile:
|
<|file_name|>app.ts<|end_file_name|><|fim▁begin|>import { Noise } from './noise';<|fim▁hole|>
private state: AppState = AppState.Stopped;
private noise: Noise;
constructor() {
this.noise = new Noise();
}
bootstrap(): void {
this.bindEvents();
this.enterState(AppState.Stopped);
}
private bindEvents(): void {
const controlStart = document.querySelector('.control.start') as HTMLButtonElement;
controlStart.addEventListener('click', () => {
this.updateState(AppState.Starting);
});
const controlStop = document.querySelector('.control.stop') as HTMLButtonElement;
controlStop.addEventListener('click', () => {
this.updateState(AppState.Stopping);
});
const maskLight = document.querySelector('.mask-light') as HTMLElement;
maskLight.addEventListener('transitionend', () => {
this.updateState(AppState.Playing);
});
const maskDark = document.querySelector('.mask-dark') as HTMLElement;
maskDark.addEventListener('transitionend', () => {
this.updateState(AppState.Stopped);
});
}
private updateState(newState: AppState): void {
this.leaveState(this.state);
this.enterState(newState);
this.state = newState;
}
private enterState(state: AppState): void {
document.body.classList.add(CSSClassesByState.get(state));
setTimeout(() => document.body.classList.add('run'), 10);
if (state === AppState.Playing) {
this.noise.start();
}
}
private leaveState(state: AppState): void {
document.body.classList.remove(CSSClassesByState.get(state));
document.body.classList.remove('run');
if (state === AppState.Playing) {
this.noise.stop();
}
}
}
const enum AppState {
Stopped,
Starting,
Playing,
Stopping,
}
const CSSClassesByState = new Map<AppState, string>([
[AppState.Stopped, 'stopped'],
[AppState.Starting, 'starting'],
[AppState.Playing, 'playing'],
[AppState.Stopping, 'stopping'],
]);<|fim▁end|>
|
export class App {
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>#[cfg(test)]
use game;
use ai;
use ai::run_match;
use constants::LINES;
use std::sync::Arc;
#[test]
fn match_mc() {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player = ai::mc::MonteCarloAI::new(1000);
let mut black_player = ai::mc::MonteCarloAI::new(1000);
run_match(structure, &mut white_player, &mut black_player);
}
#[test]
fn match_mc_tree() {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player = ai::mc::MonteCarloAI::new(1000);
let mut black_player =
ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets);
run_match(structure, &mut white_player, &mut black_player);
}
#[test]
fn match_tree() {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player =
ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets);
let mut black_player =
ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets);
run_match(structure, &mut white_player, &mut black_player);
}
#[test]
fn subset_coherence() {
// This is a property based test, see QuickCheck for more information.
use rand::{thread_rng, Rng};
<|fim▁hole|> // Ensure that all positions returned by the Subset iterator are
// contained in the Subset.
let subset = game::Subset(rng.next_u64());
for position in subset.iter() {
println!("{:?}", position);
assert!(subset.contains(position));
}
}
}<|fim▁end|>
|
let mut rng = thread_rng();
for _ in 0..10000 {
|
<|file_name|>compositor.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/. */
use CompositionPipeline;
use SendableFrameTree;
use app_units::Au;
use compositor_layer::{CompositorData, CompositorLayer, RcCompositorLayer, WantsScrollEventsFlag};
use compositor_thread::{CompositorProxy, CompositorReceiver};
use compositor_thread::{InitialCompositorState, Msg, RenderListener};
use delayed_composition::DelayedCompositionTimerProxy;
use euclid::point::TypedPoint2D;
use euclid::rect::TypedRect;
use euclid::scale_factor::ScaleFactor;
use euclid::size::TypedSize2D;
use euclid::{Matrix4D, Point2D, Rect, Size2D};
use gfx_traits::{ChromeToPaintMsg, PaintRequest, ScrollPolicy, StackingContextId};
use gfx_traits::{color, Epoch, FrameTreeId, FragmentType, LayerId, LayerKind, LayerProperties};
use gleam::gl;
use gleam::gl::types::{GLint, GLsizei};
use image::{DynamicImage, ImageFormat, RgbImage};
use ipc_channel::ipc::{self, IpcSender, IpcSharedMemory};
use ipc_channel::router::ROUTER;
use layers::geometry::{DevicePixel, LayerPixel};
use layers::layers::{BufferRequest, Layer, LayerBuffer, LayerBufferSet};
use layers::platform::surface::NativeDisplay;
use layers::rendergl;
use layers::rendergl::RenderContext;
use layers::scene::Scene;
use msg::constellation_msg::{Image, PixelFormat};
use msg::constellation_msg::{Key, KeyModifiers, KeyState, LoadData};
use msg::constellation_msg::{NavigationDirection, PipelineId, PipelineIndex, PipelineNamespaceId};
use msg::constellation_msg::{WindowSizeData, WindowSizeType};
use profile_traits::mem::{self, ReportKind, Reporter, ReporterRequest};
use profile_traits::time::{self, ProfilerCategory, profile};
use script_traits::CompositorEvent::{MouseMoveEvent, MouseButtonEvent, TouchEvent};
use script_traits::{AnimationState, AnimationTickType, ConstellationControlMsg};
use script_traits::{ConstellationMsg, LayoutControlMsg, MouseButton, MouseEventType};
use script_traits::{StackingContextScrollState, TouchpadPressurePhase, TouchEventType, TouchId};
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::mem as std_mem;
use std::rc::Rc;
use std::sync::mpsc::Sender;
use style_traits::viewport::ViewportConstraints;
use surface_map::SurfaceMap;
use time::{precise_time_ns, precise_time_s};
use touch::{TouchHandler, TouchAction};
use url::Url;
use util::geometry::{PagePx, ScreenPx, ViewportPx};
use util::print_tree::PrintTree;
use util::{opts, prefs};
use webrender;
use webrender_traits::{self, ScrollEventPhase};
use windowing::{self, MouseWindowEvent, WindowEvent, WindowMethods, WindowNavigateMsg};
#[derive(Debug, PartialEq)]
enum UnableToComposite {
NoContext,
WindowUnprepared,
NotReadyToPaintImage(NotReadyToPaint),
}
#[derive(Debug, PartialEq)]
enum NotReadyToPaint {
LayerHasOutstandingPaintMessages,
MissingRoot,
PendingSubpages(usize),
AnimationsActive,
JustNotifiedConstellation,
WaitingOnConstellation,
}
const BUFFER_MAP_SIZE: usize = 10000000;
// Default viewport constraints
const MAX_ZOOM: f32 = 8.0;
const MIN_ZOOM: f32 = 0.1;
trait ConvertPipelineIdFromWebRender {
fn from_webrender(&self) -> PipelineId;
}
impl ConvertPipelineIdFromWebRender for webrender_traits::PipelineId {
fn from_webrender(&self) -> PipelineId {
PipelineId {
namespace_id: PipelineNamespaceId(self.0),
index: PipelineIndex(self.1),
}
}
}
trait ConvertStackingContextFromWebRender {
fn from_webrender(&self) -> StackingContextId;
}
impl ConvertStackingContextFromWebRender for webrender_traits::ServoStackingContextId {
fn from_webrender(&self) -> StackingContextId {
StackingContextId::new_of_type(self.1, self.0.from_webrender())
}
}
trait ConvertFragmentTypeFromWebRender {
fn from_webrender(&self) -> FragmentType;
}
impl ConvertFragmentTypeFromWebRender for webrender_traits::FragmentType {
fn from_webrender(&self) -> FragmentType {
match *self {
webrender_traits::FragmentType::FragmentBody => FragmentType::FragmentBody,
webrender_traits::FragmentType::BeforePseudoContent => {
FragmentType::BeforePseudoContent
}
webrender_traits::FragmentType::AfterPseudoContent => FragmentType::AfterPseudoContent,
}
}
}
/// Holds the state when running reftests that determines when it is
/// safe to save the output image.
#[derive(Copy, Clone, PartialEq)]
enum ReadyState {
Unknown,
WaitingForConstellationReply,
ReadyToSaveImage,
}
/// NB: Never block on the constellation, because sometimes the constellation blocks on us.
pub struct IOCompositor<Window: WindowMethods> {
/// The application window.
window: Rc<Window>,
/// The display this compositor targets. Will be None when using webrender.
native_display: Option<NativeDisplay>,
/// The port on which we receive messages.
port: Box<CompositorReceiver>,
/// The render context. This will be `None` if the windowing system has not yet sent us a
/// `PrepareRenderingEvent`.
context: Option<RenderContext>,
/// The root pipeline.
root_pipeline: Option<CompositionPipeline>,
/// Tracks details about each active pipeline that the compositor knows about.
pipeline_details: HashMap<PipelineId, PipelineDetails>,
/// The canvas to paint a page.
scene: Scene<CompositorData>,
/// The application window size.
window_size: TypedSize2D<DevicePixel, u32>,
/// The overridden viewport.
viewport: Option<(TypedPoint2D<DevicePixel, u32>, TypedSize2D<DevicePixel, u32>)>,
/// "Mobile-style" zoom that does not reflow the page.
viewport_zoom: ScaleFactor<PagePx, ViewportPx, f32>,
/// Viewport zoom constraints provided by @viewport.
min_viewport_zoom: Option<ScaleFactor<PagePx, ViewportPx, f32>>,
max_viewport_zoom: Option<ScaleFactor<PagePx, ViewportPx, f32>>,
/// "Desktop-style" zoom that resizes the viewport to fit the window.
/// See `ViewportPx` docs in util/geom.rs for details.
page_zoom: ScaleFactor<ViewportPx, ScreenPx, f32>,
/// The device pixel ratio for this window.
scale_factor: ScaleFactor<ScreenPx, DevicePixel, f32>,
channel_to_self: Box<CompositorProxy + Send>,
/// A handle to the delayed composition timer.
delayed_composition_timer: DelayedCompositionTimerProxy,
/// The type of composition to perform
composite_target: CompositeTarget,
/// Tracks whether we should composite this frame.
composition_request: CompositionRequest,
/// Tracks whether we are in the process of shutting down, or have shut down and should close
/// the compositor.
shutdown_state: ShutdownState,
/// Tracks the last composite time.
last_composite_time: u64,
/// Tracks whether the zoom action has happened recently.
zoom_action: bool,
/// The time of the last zoom action has started.
zoom_time: f64,
/// Whether the page being rendered has loaded completely.
/// Differs from ReadyState because we can finish loading (ready)
/// many times for a single page.
got_load_complete_message: bool,
/// The current frame tree ID (used to reject old paint buffers)
frame_tree_id: FrameTreeId,
/// The channel on which messages can be sent to the constellation.
constellation_chan: Sender<ConstellationMsg>,
/// The channel on which messages can be sent to the time profiler.
time_profiler_chan: time::ProfilerChan,
/// The channel on which messages can be sent to the memory profiler.
mem_profiler_chan: mem::ProfilerChan,
/// Pending scroll to fragment event, if any
fragment_point: Option<Point2D<f32>>,
/// Touch input state machine
touch_handler: TouchHandler,
/// Pending scroll/zoom events.
pending_scroll_zoom_events: Vec<ScrollZoomEvent>,
/// Used by the logic that determines when it is safe to output an
/// image for the reftest framework.
ready_to_save_state: ReadyState,
/// A data structure to cache unused NativeSurfaces.
surface_map: SurfaceMap,
/// Pipeline IDs of subpages that the compositor has seen in a layer tree but which have not
/// yet been painted.
pending_subpages: HashSet<PipelineId>,
/// The id of the pipeline that was last sent a mouse move event, if any.
last_mouse_move_recipient: Option<PipelineId>,
/// Whether a scroll is in progress; i.e. whether the user's fingers are down.
scroll_in_progress: bool,
/// The webrender renderer, if enabled.
webrender: Option<webrender::Renderer>,
/// The webrender interface, if enabled.
webrender_api: Option<webrender_traits::RenderApi>,
}
#[derive(Copy, Clone)]
struct ScrollZoomEvent {
/// Change the pinch zoom level by this factor
magnification: f32,
/// Scroll by this offset
delta: TypedPoint2D<DevicePixel, f32>,
/// Apply changes to the frame at this location
cursor: TypedPoint2D<DevicePixel, i32>,
/// The scroll event phase.
phase: ScrollEventPhase,
}
#[derive(PartialEq, Debug)]
enum CompositionRequest {
NoCompositingNecessary,
DelayedComposite(u64),
CompositeNow(CompositingReason),
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum ShutdownState {
NotShuttingDown,
ShuttingDown,
FinishedShuttingDown,
}
struct HitTestResult {
/// The topmost layer containing the requested point
layer: Rc<Layer<CompositorData>>,
/// The point in client coordinates of the innermost window or frame containing `layer`
point: TypedPoint2D<LayerPixel, f32>,
}
struct PipelineDetails {
/// The pipeline associated with this PipelineDetails object.
pipeline: Option<CompositionPipeline>,
/// The current layout epoch that this pipeline wants to draw.
current_epoch: Epoch,
/// Whether animations are running
animations_running: bool,
/// Whether there are animation callbacks
animation_callbacks_running: bool,
/// Whether this pipeline is visible
visible: bool,
}
impl PipelineDetails {
fn new() -> PipelineDetails {
PipelineDetails {
pipeline: None,
current_epoch: Epoch(0),
animations_running: false,
animation_callbacks_running: false,
visible: true,
}
}
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum CompositeTarget {
/// Normal composition to a window
Window,
/// Compose as normal, but also return a PNG of the composed output
WindowAndPng,
/// Compose to a PNG, write it to disk, and then exit the browser (used for reftests)
PngFile
}
struct RenderTargetInfo {
framebuffer_ids: Vec<gl::GLuint>,
texture_ids: Vec<gl::GLuint>,
renderbuffer_ids: Vec<gl::GLuint>,
}
impl RenderTargetInfo {
fn empty() -> RenderTargetInfo {
RenderTargetInfo {
framebuffer_ids: Vec::new(),
texture_ids: Vec::new(),
renderbuffer_ids: Vec::new()
}
}
}
fn initialize_png(width: usize, height: usize) -> RenderTargetInfo {
let framebuffer_ids = gl::gen_framebuffers(1);
gl::bind_framebuffer(gl::FRAMEBUFFER, framebuffer_ids[0]);
let texture_ids = gl::gen_textures(1);
gl::bind_texture(gl::TEXTURE_2D, texture_ids[0]);
gl::tex_image_2d(gl::TEXTURE_2D, 0, gl::RGB as GLint, width as GLsizei,
height as GLsizei, 0, gl::RGB, gl::UNSIGNED_BYTE, None);
gl::tex_parameter_i(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as GLint);
gl::tex_parameter_i(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as GLint);
gl::framebuffer_texture_2d(gl::FRAMEBUFFER, gl::COLOR_ATTACHMENT0, gl::TEXTURE_2D,
texture_ids[0], 0);
gl::bind_texture(gl::TEXTURE_2D, 0);
let renderbuffer_ids = if opts::get().use_webrender {
let renderbuffer_ids = gl::gen_renderbuffers(1);
gl::bind_renderbuffer(gl::RENDERBUFFER, renderbuffer_ids[0]);
gl::renderbuffer_storage(gl::RENDERBUFFER,
gl::STENCIL_INDEX8,
width as GLsizei,
height as GLsizei);
gl::framebuffer_renderbuffer(gl::FRAMEBUFFER,
gl::STENCIL_ATTACHMENT,
gl::RENDERBUFFER,
renderbuffer_ids[0]);
renderbuffer_ids
} else {
Vec::new()
};
RenderTargetInfo {
framebuffer_ids: framebuffer_ids,
texture_ids: texture_ids,
renderbuffer_ids: renderbuffer_ids
}
}
fn reporter_name() -> String {
"compositor-reporter".to_owned()
}
struct RenderNotifier {
compositor_proxy: Box<CompositorProxy>,
constellation_chan: Sender<ConstellationMsg>,
}
impl RenderNotifier {
fn new(compositor_proxy: Box<CompositorProxy>,
constellation_chan: Sender<ConstellationMsg>) -> RenderNotifier {
RenderNotifier {
compositor_proxy: compositor_proxy,
constellation_chan: constellation_chan,
}
}
}
impl webrender_traits::RenderNotifier for RenderNotifier {
fn new_frame_ready(&mut self) {
self.compositor_proxy.recomposite(CompositingReason::NewWebRenderFrame);
}
fn pipeline_size_changed(&mut self,
pipeline_id: webrender_traits::PipelineId,
size: Option<Size2D<f32>>) {
let pipeline_id = pipeline_id.from_webrender();
if let Some(size) = size {
let msg = ConstellationMsg::FrameSize(pipeline_id, size);
if let Err(e) = self.constellation_chan.send(msg) {
warn!("Compositor resize to constellation failed ({}).", e);
}
}
}
}
impl<Window: WindowMethods> IOCompositor<Window> {
fn new(window: Rc<Window>, state: InitialCompositorState)
-> IOCompositor<Window> {
// Register this thread as a memory reporter, via its own channel.
let (reporter_sender, reporter_receiver) = ipc::channel()
.expect("Compositor reporter chan");
let compositor_proxy_for_memory_reporter = state.sender.clone_compositor_proxy();
ROUTER.add_route(reporter_receiver.to_opaque(), box move |reporter_request| {
match reporter_request.to::<ReporterRequest>() {
Err(e) => error!("Cast to ReporterRequest failed ({}).", e),
Ok(reporter_request) => {
let msg = Msg::CollectMemoryReports(reporter_request.reports_channel);
compositor_proxy_for_memory_reporter.send(msg);
},
}
});
let reporter = Reporter(reporter_sender);
state.mem_profiler_chan.send(
mem::ProfilerMsg::RegisterReporter(reporter_name(), reporter));
let window_size = window.framebuffer_size();
let scale_factor = window.scale_factor();
let composite_target = match opts::get().output_file {
Some(_) => CompositeTarget::PngFile,
None => CompositeTarget::Window
};
let webrender_api = state.webrender_api_sender.map(|sender| {
sender.create_api()
});
let native_display = if state.webrender.is_some() {
None
} else {
Some(window.native_display())
};
IOCompositor {
window: window,
native_display: native_display,
port: state.receiver,
context: None,
root_pipeline: None,
pipeline_details: HashMap::new(),
scene: Scene::new(Rect {
origin: Point2D::zero(),
size: window_size.as_f32(),
}),
window_size: window_size,
viewport: None,
scale_factor: scale_factor,
channel_to_self: state.sender.clone_compositor_proxy(),
delayed_composition_timer: DelayedCompositionTimerProxy::new(state.sender),
composition_request: CompositionRequest::NoCompositingNecessary,
touch_handler: TouchHandler::new(),
pending_scroll_zoom_events: Vec::new(),
composite_target: composite_target,
shutdown_state: ShutdownState::NotShuttingDown,
page_zoom: ScaleFactor::new(1.0),
viewport_zoom: ScaleFactor::new(1.0),
min_viewport_zoom: None,
max_viewport_zoom: None,
zoom_action: false,
zoom_time: 0f64,
got_load_complete_message: false,
frame_tree_id: FrameTreeId(0),
constellation_chan: state.constellation_chan,
time_profiler_chan: state.time_profiler_chan,
mem_profiler_chan: state.mem_profiler_chan,
fragment_point: None,
last_composite_time: 0,
ready_to_save_state: ReadyState::Unknown,
surface_map: SurfaceMap::new(BUFFER_MAP_SIZE),
pending_subpages: HashSet::new(),
last_mouse_move_recipient: None,
scroll_in_progress: false,
webrender: state.webrender,
webrender_api: webrender_api,
}
}
pub fn create(window: Rc<Window>, state: InitialCompositorState) -> IOCompositor<Window> {
let mut compositor = IOCompositor::new(window, state);
if let Some(ref mut webrender) = compositor.webrender {
let compositor_proxy_for_webrender = compositor.channel_to_self
.clone_compositor_proxy();
let render_notifier = RenderNotifier::new(compositor_proxy_for_webrender,
compositor.constellation_chan.clone());
webrender.set_render_notifier(Box::new(render_notifier));
}
// Set the size of the root layer.
compositor.update_zoom_transform();
// Tell the constellation about the initial window size.
compositor.send_window_size(WindowSizeType::Initial);
compositor
}
fn start_shutting_down(&mut self) {
debug!("Compositor sending Exit message to Constellation");
if let Err(e) = self.constellation_chan.send(ConstellationMsg::Exit) {
warn!("Sending exit message to constellation failed ({}).", e);
}
self.mem_profiler_chan.send(mem::ProfilerMsg::UnregisterReporter(reporter_name()));
self.shutdown_state = ShutdownState::ShuttingDown;
}
fn finish_shutting_down(&mut self) {
debug!("Compositor received message that constellation shutdown is complete");
// Clear out the compositor layers so that painting threads can destroy the buffers.
if let Some(ref root_layer) = self.scene.root {
root_layer.forget_all_tiles();
}
// Drain compositor port, sometimes messages contain channels that are blocking
// another thread from finishing (i.e. SetFrameTree).
while self.port.try_recv_compositor_msg().is_some() {}
// Tell the profiler, memory profiler, and scrolling timer to shut down.
match ipc::channel() {
Ok((sender, receiver)) => {
self.time_profiler_chan.send(time::ProfilerMsg::Exit(sender));
let _ = receiver.recv();
},
Err(_) => {},
}
self.mem_profiler_chan.send(mem::ProfilerMsg::Exit);
self.delayed_composition_timer.shutdown();
self.shutdown_state = ShutdownState::FinishedShuttingDown;
}
fn handle_browser_message(&mut self, msg: Msg) -> bool {
match (msg, self.shutdown_state) {
(_, ShutdownState::FinishedShuttingDown) => {
error!("compositor shouldn't be handling messages after shutting down");
return false
}
(Msg::Exit, _) => {
self.start_shutting_down();
}
(Msg::ShutdownComplete, _) => {
self.finish_shutting_down();
return false;
}
(Msg::ChangeRunningAnimationsState(pipeline_id, animation_state),
ShutdownState::NotShuttingDown) => {
self.change_running_animations_state(pipeline_id, animation_state);
}
(Msg::ChangePageTitle(pipeline_id, title), ShutdownState::NotShuttingDown) => {
self.change_page_title(pipeline_id, title);
}
(Msg::ChangePageUrl(pipeline_id, url), ShutdownState::NotShuttingDown) => {
self.change_page_url(pipeline_id, url);
}
(Msg::SetFrameTree(frame_tree, response_chan),
ShutdownState::NotShuttingDown) => {
self.set_frame_tree(&frame_tree, response_chan);
self.send_viewport_rects_for_all_layers();
self.title_for_main_frame();
}
(Msg::InitializeLayersForPipeline(pipeline_id, epoch, properties),
ShutdownState::NotShuttingDown) => {
debug!("initializing layers for pipeline: {:?}", pipeline_id);
self.pipeline_details(pipeline_id).current_epoch = epoch;
self.collect_old_layers(pipeline_id, &properties);
for (index, layer_properties) in properties.iter().enumerate() {
if index == 0 {
self.create_or_update_base_layer(pipeline_id, *layer_properties);
} else {
self.create_or_update_descendant_layer(pipeline_id, *layer_properties);
}
}
self.send_buffer_requests_for_all_layers();
self.dump_layer_tree();
}
(Msg::GetNativeDisplay(chan),
ShutdownState::NotShuttingDown) => {
if let Err(e) = chan.send(self.native_display.clone()) {
warn!("Sending response to get native display failed ({}).", e);
}
}
(Msg::AssignPaintedBuffers(pipeline_id, epoch, replies, frame_tree_id),
ShutdownState::NotShuttingDown) => {
self.pending_subpages.remove(&pipeline_id);
for (layer_id, new_layer_buffer_set) in replies {
self.assign_painted_buffers(pipeline_id,
layer_id,
new_layer_buffer_set,
epoch,
frame_tree_id);
}
}
(Msg::ReturnUnusedNativeSurfaces(native_surfaces),
ShutdownState::NotShuttingDown) => {
if let Some(ref native_display) = self.native_display {
self.surface_map.insert_surfaces(native_display, native_surfaces);
}
}
(Msg::ScrollFragmentPoint(pipeline_id, layer_id, point, _),
ShutdownState::NotShuttingDown) => {
self.scroll_fragment_to_point(pipeline_id, layer_id, point);
}
(Msg::MoveTo(point),
ShutdownState::NotShuttingDown) => {
self.window.set_position(point);
}
(Msg::ResizeTo(size),
ShutdownState::NotShuttingDown) => {
self.window.set_inner_size(size);
}
(Msg::GetClientWindow(send),
ShutdownState::NotShuttingDown) => {
let rect = self.window.client_window();
if let Err(e) = send.send(rect) {
warn!("Sending response to get client window failed ({}).", e);
}
}
(Msg::Status(message), ShutdownState::NotShuttingDown) => {
self.window.status(message);
}
(Msg::LoadStart(back, forward), ShutdownState::NotShuttingDown) => {
self.window.load_start(back, forward);
}
(Msg::LoadComplete(back, forward, root), ShutdownState::NotShuttingDown) => {
self.got_load_complete_message = true;
// If we're painting in headless mode, schedule a recomposite.
if opts::get().output_file.is_some() || opts::get().exit_after_load {
self.composite_if_necessary(CompositingReason::Headless);
}
// Inform the embedder that the load has finished.
//
// TODO(pcwalton): Specify which frame's load completed.
self.window.load_end(back, forward, root);
}
(Msg::DelayedCompositionTimeout(timestamp), ShutdownState::NotShuttingDown) => {
debug!("delayed composition timeout!");
if let CompositionRequest::DelayedComposite(this_timestamp) =
self.composition_request {
if timestamp == this_timestamp {
self.composition_request = CompositionRequest::CompositeNow(
CompositingReason::DelayedCompositeTimeout)
}
}
}
(Msg::Recomposite(reason), ShutdownState::NotShuttingDown) => {
self.composition_request = CompositionRequest::CompositeNow(reason)
}
(Msg::KeyEvent(key, state, modified), ShutdownState::NotShuttingDown) => {
if state == KeyState::Pressed {
self.window.handle_key(key, modified);
}
}
(Msg::TouchEventProcessed(result), ShutdownState::NotShuttingDown) => {
self.touch_handler.on_event_processed(result);
}
(Msg::SetCursor(cursor), ShutdownState::NotShuttingDown) => {
self.window.set_cursor(cursor)
}
(Msg::CreatePng(reply), ShutdownState::NotShuttingDown) => {
let res = self.composite_specific_target(CompositeTarget::WindowAndPng);
let img = res.unwrap_or(None);
if let Err(e) = reply.send(img) {
warn!("Sending reply to create png failed ({}).", e);
}
}
(Msg::PaintThreadExited(pipeline_id), _) => {
debug!("compositor learned about paint thread exiting: {:?}", pipeline_id);
self.remove_pipeline_root_layer(pipeline_id);
}
(Msg::ViewportConstrained(pipeline_id, constraints),
ShutdownState::NotShuttingDown) => {
self.constrain_viewport(pipeline_id, constraints);
}
(Msg::IsReadyToSaveImageReply(is_ready), ShutdownState::NotShuttingDown) => {
assert!(self.ready_to_save_state == ReadyState::WaitingForConstellationReply);
if is_ready {
self.ready_to_save_state = ReadyState::ReadyToSaveImage;
if opts::get().is_running_problem_test {
println!("ready to save image!");
}
} else {
self.ready_to_save_state = ReadyState::Unknown;
if opts::get().is_running_problem_test {
println!("resetting ready_to_save_state!");
}
}
self.composite_if_necessary(CompositingReason::Headless);
}
(Msg::NewFavicon(url), ShutdownState::NotShuttingDown) => {
self.window.set_favicon(url);
}
(Msg::HeadParsed, ShutdownState::NotShuttingDown) => {
self.window.head_parsed();
}
(Msg::CollectMemoryReports(reports_chan), ShutdownState::NotShuttingDown) => {
let name = "compositor-thread";
// These are both `ExplicitUnknownLocationSize` because the memory might be in the
// GPU or on the heap.
let reports = vec![mem::Report {
path: path![name, "surface-map"],
kind: ReportKind::ExplicitUnknownLocationSize,
size: self.surface_map.mem(),
}, mem::Report {
path: path![name, "layer-tree"],
kind: ReportKind::ExplicitUnknownLocationSize,
size: self.scene.get_memory_usage(),
}];
reports_chan.send(reports);
}
(Msg::PipelineVisibilityChanged(pipeline_id, visible), ShutdownState::NotShuttingDown) => {
self.pipeline_details(pipeline_id).visible = visible;
if visible {
self.process_animations();
}
}
(Msg::PipelineExited(pipeline_id, sender), _) => {
debug!("Compositor got pipeline exited: {:?}", pipeline_id);
self.pending_subpages.remove(&pipeline_id);
self.remove_pipeline_root_layer(pipeline_id);
let _ = sender.send(());
}
(Msg::GetScrollOffset(pipeline_id, layer_id, sender), ShutdownState::NotShuttingDown) => {
match self.find_layer_with_pipeline_and_layer_id(pipeline_id, layer_id) {
Some(ref layer) => {
let typed = layer.extra_data.borrow().scroll_offset;
let _ = sender.send(Point2D::new(typed.x.get(), typed.y.get()));
},
None => {
warn!("Can't find requested layer in handling Msg::GetScrollOffset");
},
}
}
// When we are shutting_down, we need to avoid performing operations
// such as Paint that may crash because we have begun tearing down
// the rest of our resources.
(_, ShutdownState::ShuttingDown) => { }
}
true
}
/// Sets or unsets the animations-running flag for the given pipeline, and schedules a
/// recomposite if necessary.
fn change_running_animations_state(&mut self,
pipeline_id: PipelineId,
animation_state: AnimationState) {
match animation_state {
AnimationState::AnimationsPresent => {
let visible = self.pipeline_details(pipeline_id).visible;
self.pipeline_details(pipeline_id).animations_running = true;
if visible {
self.composite_if_necessary(CompositingReason::Animation);
}
}
AnimationState::AnimationCallbacksPresent => {
let visible = self.pipeline_details(pipeline_id).visible;
self.pipeline_details(pipeline_id).animation_callbacks_running = true;
if visible {
self.tick_animations_for_pipeline(pipeline_id);
}
}
AnimationState::NoAnimationsPresent => {
self.pipeline_details(pipeline_id).animations_running = false;
}
AnimationState::NoAnimationCallbacksPresent => {
self.pipeline_details(pipeline_id).animation_callbacks_running = false;
}
}
}
fn pipeline_details(&mut self, pipeline_id: PipelineId) -> &mut PipelineDetails {
if !self.pipeline_details.contains_key(&pipeline_id) {
self.pipeline_details.insert(pipeline_id, PipelineDetails::new());
}
self.pipeline_details.get_mut(&pipeline_id).expect("Insert then get failed!")
}
pub fn pipeline(&self, pipeline_id: PipelineId) -> Option<&CompositionPipeline> {
match self.pipeline_details.get(&pipeline_id) {
Some(ref details) => details.pipeline.as_ref(),
None => {
warn!("Compositor layer has an unknown pipeline ({:?}).", pipeline_id);
None
}
}
}
fn change_page_title(&mut self, pipeline_id: PipelineId, title: Option<String>) {
let set_title = self.root_pipeline.as_ref().map_or(false, |root_pipeline| {
root_pipeline.id == pipeline_id
});
if set_title {
self.window.set_page_title(title);
}
}
fn change_page_url(&mut self, _: PipelineId, url: Url) {
self.window.set_page_url(url);
}
fn set_frame_tree(&mut self,
frame_tree: &SendableFrameTree,
response_chan: IpcSender<()>) {
if let Err(e) = response_chan.send(()) {
warn!("Sending reponse to set frame tree failed ({}).", e);
}
// There are now no more pending iframes.
self.pending_subpages.clear();
self.root_pipeline = Some(frame_tree.pipeline.clone());
if let Some(ref webrender_api) = self.webrender_api {
let pipeline_id = frame_tree.pipeline.id.to_webrender();
webrender_api.set_root_pipeline(pipeline_id);
}
// If we have an old root layer, release all old tiles before replacing it.
let old_root_layer = self.scene.root.take();
if let Some(ref old_root_layer) = old_root_layer {
old_root_layer.clear_all_tiles(self)
}
self.scene.root = Some(self.create_root_layer_for_pipeline_and_size(&frame_tree.pipeline,
None));
self.scene.set_root_layer_size(self.window_size.as_f32());
self.create_pipeline_details_for_frame_tree(&frame_tree);
self.send_window_size(WindowSizeType::Initial);
self.frame_tree_id.next();
self.composite_if_necessary_if_not_using_webrender(CompositingReason::NewFrameTree);
}
fn create_root_layer_for_pipeline_and_size(&mut self,
pipeline: &CompositionPipeline,
frame_size: Option<TypedSize2D<PagePx, f32>>)
-> Rc<Layer<CompositorData>> {
let layer_properties = LayerProperties {
id: LayerId::null(),
parent_id: None,
rect: Rect::zero(),
background_color: color::transparent(),
scroll_policy: ScrollPolicy::Scrollable,
transform: Matrix4D::identity(),
perspective: Matrix4D::identity(),
subpage_pipeline_id: None,
establishes_3d_context: true,
scrolls_overflow_area: false,
};
let root_layer = CompositorData::new_layer(pipeline.id,
layer_properties,
WantsScrollEventsFlag::WantsScrollEvents,
opts::get().tile_size);
self.pipeline_details(pipeline.id).pipeline = Some(pipeline.clone());
// All root layers mask to bounds.
*root_layer.masks_to_bounds.borrow_mut() = true;
if let Some(ref frame_size) = frame_size {
let frame_size = frame_size.to_untyped();
root_layer.bounds.borrow_mut().size = Size2D::from_untyped(&frame_size);
}
root_layer
}
fn create_pipeline_details_for_frame_tree(&mut self, frame_tree: &SendableFrameTree) {
self.pipeline_details(frame_tree.pipeline.id).pipeline = Some(frame_tree.pipeline.clone());
for kid in &frame_tree.children {
self.create_pipeline_details_for_frame_tree(kid);
}
}
fn find_pipeline_root_layer(&self, pipeline_id: PipelineId)
-> Option<Rc<Layer<CompositorData>>> {
if !self.pipeline_details.contains_key(&pipeline_id) {
warn!("Tried to create or update layer for unknown pipeline");
return None;
}
self.find_layer_with_pipeline_and_layer_id(pipeline_id, LayerId::null())
}
fn collect_old_layers(&mut self,
pipeline_id: PipelineId,
new_layers: &[LayerProperties]) {
let root_layer = match self.scene.root {
Some(ref root_layer) => root_layer.clone(),
None => return,
};
let mut pipelines_removed = Vec::new();
root_layer.collect_old_layers(self, pipeline_id, new_layers, &mut pipelines_removed);
for pipeline_removed in pipelines_removed.into_iter() {
self.pending_subpages.remove(&pipeline_removed);
}
}
fn remove_pipeline_root_layer(&mut self, pipeline_id: PipelineId) {
let root_layer = match self.scene.root {
Some(ref root_layer) => root_layer.clone(),
None => return,
};
// Remove all the compositor layers for this pipeline and recache
// any buffers that they owned.
root_layer.remove_root_layer_with_pipeline_id(self, pipeline_id);
self.pipeline_details.remove(&pipeline_id);
}
fn update_layer_if_exists(&mut self,
pipeline_id: PipelineId,
properties: LayerProperties)
-> bool {
if let Some(subpage_id) = properties.subpage_pipeline_id {
match self.find_layer_with_pipeline_and_layer_id(subpage_id, LayerId::null()) {
Some(layer) => {
*layer.bounds.borrow_mut() = Rect::from_untyped(
&Rect::new(Point2D::zero(), properties.rect.size));
}
None => warn!("Tried to update non-existent subpage root layer: {:?}", subpage_id),
}
}
match self.find_layer_with_pipeline_and_layer_id(pipeline_id, properties.id) {
Some(existing_layer) => {
// If this layer contains a subpage, then create the root layer for that subpage
// now.
if properties.subpage_pipeline_id.is_some() {
self.create_root_layer_for_subpage_if_necessary(properties,
existing_layer.clone())
}
existing_layer.update_layer(properties);
true
}
None => false,
}
}
fn create_or_update_base_layer(&mut self,
pipeline_id: PipelineId,
layer_properties: LayerProperties) {
debug_assert!(layer_properties.parent_id.is_none());
let root_layer = match self.find_pipeline_root_layer(pipeline_id) {
Some(root_layer) => root_layer,
None => {
debug!("Ignoring CreateOrUpdateBaseLayer message for pipeline \
({:?}) shutting down.",
pipeline_id);
return;
}
};
let need_new_base_layer = !self.update_layer_if_exists(pipeline_id, layer_properties);
if need_new_base_layer {
root_layer.update_layer_except_bounds(layer_properties);
let base_layer = CompositorData::new_layer(
pipeline_id,
layer_properties,
WantsScrollEventsFlag::DoesntWantScrollEvents,
opts::get().tile_size);
// Add the base layer to the front of the child list, so that child
// iframe layers are painted on top of the base layer. These iframe
// layers were added previously when creating the layer tree
// skeleton in create_frame_tree_root_layers.
root_layer.children().insert(0, base_layer);
}
self.scroll_layer_to_fragment_point_if_necessary(pipeline_id,
layer_properties.id);
}
fn create_or_update_descendant_layer(&mut self,
pipeline_id: PipelineId,
layer_properties: LayerProperties) {
debug_assert!(layer_properties.parent_id.is_some());
if !self.update_layer_if_exists(pipeline_id, layer_properties) {
self.create_descendant_layer(pipeline_id, layer_properties);
}
self.update_subpage_size_if_necessary(&layer_properties);
self.scroll_layer_to_fragment_point_if_necessary(pipeline_id,
layer_properties.id);
}
fn create_descendant_layer(&mut self,
pipeline_id: PipelineId,
layer_properties: LayerProperties) {
let parent_id = match layer_properties.parent_id {
None => return error!("Creating descendent layer without a parent id."),
Some(parent_id) => parent_id,
};
if let Some(parent_layer) = self.find_layer_with_pipeline_and_layer_id(pipeline_id,
parent_id) {
let wants_scroll_events = if layer_properties.scrolls_overflow_area {
WantsScrollEventsFlag::WantsScrollEvents
} else {
WantsScrollEventsFlag::DoesntWantScrollEvents
};
let new_layer = CompositorData::new_layer(pipeline_id,
layer_properties,
wants_scroll_events,
parent_layer.tile_size);
if layer_properties.scrolls_overflow_area {
*new_layer.masks_to_bounds.borrow_mut() = true
}
// If this layer contains a subpage, then create the root layer for that subpage now.
if layer_properties.subpage_pipeline_id.is_some() {
self.create_root_layer_for_subpage_if_necessary(layer_properties,
new_layer.clone())
}
parent_layer.add_child(new_layer.clone());
}
self.dump_layer_tree();
}
fn create_root_layer_for_subpage_if_necessary(&mut self,
layer_properties: LayerProperties,
parent_layer: Rc<Layer<CompositorData>>) {
if parent_layer.children
.borrow()
.iter()
.any(|child| child.extra_data.borrow().subpage_info.is_some()) {
return
}
let subpage_pipeline_id =
layer_properties.subpage_pipeline_id
.expect("create_root_layer_for_subpage() called for non-subpage?!");
let subpage_layer_properties = LayerProperties {
id: LayerId::null(),
parent_id: None,
rect: Rect::new(Point2D::zero(), layer_properties.rect.size),
background_color: layer_properties.background_color,
scroll_policy: ScrollPolicy::Scrollable,
transform: Matrix4D::identity(),
perspective: Matrix4D::identity(),
subpage_pipeline_id: Some(subpage_pipeline_id),
establishes_3d_context: true,
scrolls_overflow_area: true,
};
let wants_scroll_events = if subpage_layer_properties.scrolls_overflow_area {
WantsScrollEventsFlag::WantsScrollEvents
} else {
WantsScrollEventsFlag::DoesntWantScrollEvents
};
let subpage_layer = CompositorData::new_layer(subpage_pipeline_id,
subpage_layer_properties,
wants_scroll_events,
parent_layer.tile_size);
*subpage_layer.masks_to_bounds.borrow_mut() = true;
parent_layer.add_child(subpage_layer);
self.pending_subpages.insert(subpage_pipeline_id);
}
fn send_window_size(&self, size_type: WindowSizeType) {
let dppx = self.page_zoom * self.device_pixels_per_screen_px();
let initial_viewport = self.window_size.as_f32() / dppx;
let visible_viewport = initial_viewport / self.viewport_zoom;
let msg = ConstellationMsg::WindowSize(WindowSizeData {
device_pixel_ratio: dppx,
initial_viewport: initial_viewport,
visible_viewport: visible_viewport,
}, size_type);
if let Err(e) = self.constellation_chan.send(msg) {
warn!("Sending window resize to constellation failed ({}).", e);
}
}
/// Sends the size of the given subpage up to the constellation. This will often trigger a
/// reflow of that subpage.
fn update_subpage_size_if_necessary(&self, layer_properties: &LayerProperties) {
let subpage_pipeline_id = match layer_properties.subpage_pipeline_id {
Some(ref subpage_pipeline_id) => subpage_pipeline_id,
None => return,
};
let msg = ConstellationMsg::FrameSize(*subpage_pipeline_id, layer_properties.rect.size);
if let Err(e) = self.constellation_chan.send(msg) {
warn!("Sending subpage resize to constellation failed ({}).", e);
}
}
fn move_layer(&self,
pipeline_id: PipelineId,
layer_id: LayerId,
origin: TypedPoint2D<LayerPixel, f32>)
-> bool {
match self.find_layer_with_pipeline_and_layer_id(pipeline_id, layer_id) {
Some(ref layer) => {
if layer.wants_scroll_events() == WantsScrollEventsFlag::WantsScrollEvents {
layer.clamp_scroll_offset_and_scroll_layer(Point2D::typed(0f32, 0f32) - origin);
}
true
}
None => false,
}
}
fn scroll_layer_to_fragment_point_if_necessary(&mut self,
pipeline_id: PipelineId,
layer_id: LayerId) {
if let Some(point) = self.fragment_point.take() {
if !self.move_layer(pipeline_id, layer_id, Point2D::from_untyped(&point)) {
return warn!("Compositor: Tried to scroll to fragment with unknown layer.");
}
self.perform_updates_after_scroll();
}
}
fn schedule_delayed_composite_if_necessary(&mut self) {
match self.composition_request {
CompositionRequest::CompositeNow(_) |
CompositionRequest::DelayedComposite(_) => return,
CompositionRequest::NoCompositingNecessary => {}
}
let timestamp = precise_time_ns();
self.delayed_composition_timer.schedule_composite(timestamp);
self.composition_request = CompositionRequest::DelayedComposite(timestamp);
}
fn assign_painted_buffers(&mut self,
pipeline_id: PipelineId,
layer_id: LayerId,
new_layer_buffer_set: Box<LayerBufferSet>,
epoch: Epoch,
frame_tree_id: FrameTreeId) {
// If the frame tree id has changed since this paint request was sent,
// reject the buffers and send them back to the paint thread. If this isn't handled
// correctly, the content_age in the tile grid can get out of sync when iframes are
// loaded and the frame tree changes. This can result in the compositor thinking it
// has already drawn the most recently painted buffer, and missing a frame.
if frame_tree_id == self.frame_tree_id {
if let Some(layer) = self.find_layer_with_pipeline_and_layer_id(pipeline_id,
layer_id) {
let requested_epoch = layer.extra_data.borrow().requested_epoch;
if requested_epoch == epoch {
self.assign_painted_buffers_to_layer(layer, new_layer_buffer_set, epoch);
return
} else {
debug!("assign_painted_buffers epoch mismatch {:?} {:?} req={:?} actual={:?}",
pipeline_id,
layer_id,
requested_epoch,
epoch);
}
}
}
self.cache_unused_buffers(new_layer_buffer_set.buffers);
}
fn assign_painted_buffers_to_layer(&mut self,
layer: Rc<Layer<CompositorData>>,
new_layer_buffer_set: Box<LayerBufferSet>,
epoch: Epoch) {
debug!("compositor received new frame at size {:?}x{:?}",
self.window_size.width.get(),
self.window_size.height.get());
// From now on, if we destroy the buffers, they will leak.
let mut new_layer_buffer_set = new_layer_buffer_set;
new_layer_buffer_set.mark_will_leak();
// FIXME(pcwalton): This is going to cause problems with inconsistent frames since
// we only composite one layer at a time.
layer.add_buffers(self, new_layer_buffer_set, epoch);
self.composite_if_necessary_if_not_using_webrender(CompositingReason::NewPaintedBuffers);
}
fn scroll_fragment_to_point(&mut self,
pipeline_id: PipelineId,
layer_id: LayerId,
point: Point2D<f32>) {
if self.move_layer(pipeline_id, layer_id, Point2D::from_untyped(&point)) {
self.perform_updates_after_scroll();
self.send_viewport_rects_for_all_layers()
} else {
self.fragment_point = Some(point)
}
}
fn handle_window_message(&mut self, event: WindowEvent) {
match event {
WindowEvent::Idle => {}
WindowEvent::Refresh => {
self.composite();
}
WindowEvent::InitializeCompositing => {
self.initialize_compositing();
}
WindowEvent::Viewport(point, size) => {
self.viewport = Some((point, size));
}
WindowEvent::Resize(size) => {
self.on_resize_window_event(size);
}
WindowEvent::LoadUrl(url_string) => {
self.on_load_url_window_event(url_string);
}
WindowEvent::MouseWindowEventClass(mouse_window_event) => {
self.on_mouse_window_event_class(mouse_window_event);
}
WindowEvent::MouseWindowMoveEventClass(cursor) => {
self.on_mouse_window_move_event_class(cursor);
}
WindowEvent::Touch(event_type, identifier, location) => {
match event_type {
TouchEventType::Down => self.on_touch_down(identifier, location),
TouchEventType::Move => self.on_touch_move(identifier, location),
TouchEventType::Up => self.on_touch_up(identifier, location),
TouchEventType::Cancel => self.on_touch_cancel(identifier, location),
}
}
WindowEvent::Scroll(delta, cursor, phase) => {
match phase {
TouchEventType::Move => self.on_scroll_window_event(delta, cursor),
TouchEventType::Up | TouchEventType::Cancel => {
self.on_scroll_end_window_event(delta, cursor);
}
TouchEventType::Down => {
self.on_scroll_start_window_event(delta, cursor);
}
}
}
WindowEvent::Zoom(magnification) => {
self.on_zoom_window_event(magnification);
}
WindowEvent::ResetZoom => {
self.on_zoom_reset_window_event();
}
WindowEvent::PinchZoom(magnification) => {
self.on_pinch_zoom_window_event(magnification);
}
WindowEvent::Navigation(direction) => {
self.on_navigation_window_event(direction);
}
WindowEvent::TouchpadPressure(cursor, pressure, stage) => {
self.on_touchpad_pressure_event(cursor, pressure, stage);
}
WindowEvent::KeyEvent(key, state, modifiers) => {
self.on_key_event(key, state, modifiers);
}
WindowEvent::Quit => {
if self.shutdown_state == ShutdownState::NotShuttingDown {
debug!("Shutting down the constellation for WindowEvent::Quit");
self.start_shutting_down();
}
}
WindowEvent::Reload => {
let msg = ConstellationMsg::Reload;
if let Err(e) = self.constellation_chan.send(msg) {
warn!("Sending reload to constellation failed ({}).", e);
}
}
}
}
fn on_resize_window_event(&mut self, new_size: TypedSize2D<DevicePixel, u32>) {
debug!("compositor resizing to {:?}", new_size.to_untyped());
// A size change could also mean a resolution change.
let new_scale_factor = self.window.scale_factor();
if self.scale_factor != new_scale_factor {
self.scale_factor = new_scale_factor;
self.update_zoom_transform();
}
if self.window_size == new_size {
return;
}
self.window_size = new_size;
self.scene.set_root_layer_size(new_size.as_f32());
self.send_window_size(WindowSizeType::Resize);
}
fn on_load_url_window_event(&mut self, url_string: String) {
debug!("osmain: loading URL `{}`", url_string);
self.got_load_complete_message = false;
match Url::parse(&url_string) {
Ok(url) => {
self.window.set_page_url(url.clone());
let msg = match self.scene.root {
Some(ref layer) => ConstellationMsg::LoadUrl(layer.pipeline_id(), LoadData::new(url, None, None)),
None => ConstellationMsg::InitLoadUrl(url)
};
if let Err(e) = self.constellation_chan.send(msg) {
warn!("Sending load url to constellation failed ({}).", e);
}
},
Err(e) => error!("Parsing URL {} failed ({}).", url_string, e),
}
}
fn on_mouse_window_event_class(&mut self, mouse_window_event: MouseWindowEvent) {
if opts::get().convert_mouse_to_touch {
match mouse_window_event {
MouseWindowEvent::Click(_, _) => {}
MouseWindowEvent::MouseDown(_, p) => self.on_touch_down(TouchId(0), p),
MouseWindowEvent::MouseUp(_, p) => self.on_touch_up(TouchId(0), p),
}
return
}
let point = match mouse_window_event {
MouseWindowEvent::Click(_, p) => p,
MouseWindowEvent::MouseDown(_, p) => p,
MouseWindowEvent::MouseUp(_, p) => p,
};
if self.webrender_api.is_some() {
let root_pipeline_id = match self.get_root_pipeline_id() {
Some(root_pipeline_id) => root_pipeline_id,
None => return,
};
if let Some(pipeline) = self.pipeline(root_pipeline_id) {
let dppx = self.page_zoom * self.device_pixels_per_screen_px();
let translated_point = (point / dppx).to_untyped();
let event_to_send = match mouse_window_event {
MouseWindowEvent::Click(button, _) => {
MouseButtonEvent(MouseEventType::Click, button, translated_point)
}
MouseWindowEvent::MouseDown(button, _) => {
MouseButtonEvent(MouseEventType::MouseDown, button, translated_point)
}
MouseWindowEvent::MouseUp(button, _) => {
MouseButtonEvent(MouseEventType::MouseUp, button, translated_point)
}
};
let msg = ConstellationControlMsg::SendEvent(root_pipeline_id, event_to_send);
if let Err(e) = pipeline.script_chan.send(msg) {
warn!("Sending control event to script failed ({}).", e);
}
}
return
}
match self.find_topmost_layer_at_point(point / self.scene.scale) {
Some(result) => result.layer.send_mouse_event(self, mouse_window_event, result.point),
None => {},
}
}
fn on_mouse_window_move_event_class(&mut self, cursor: TypedPoint2D<DevicePixel, f32>) {
if opts::get().convert_mouse_to_touch {
self.on_touch_move(TouchId(0), cursor);
return
}
if self.webrender_api.is_some() {
let root_pipeline_id = match self.get_root_pipeline_id() {
Some(root_pipeline_id) => root_pipeline_id,
None => return,
};
if self.pipeline(root_pipeline_id).is_none() {
return;
}
let dppx = self.page_zoom * self.device_pixels_per_screen_px();
let event_to_send = MouseMoveEvent(Some((cursor / dppx).to_untyped()));
let msg = ConstellationControlMsg::SendEvent(root_pipeline_id, event_to_send);
if let Some(pipeline) = self.pipeline(root_pipeline_id) {
if let Err(e) = pipeline.script_chan.send(msg) {
warn!("Sending mouse control event to script failed ({}).", e);
}
}
return
}
match self.find_topmost_layer_at_point(cursor / self.scene.scale) {
Some(result) => {
// In the case that the mouse was previously over a different layer,
// that layer must update its state.
if let Some(last_pipeline_id) = self.last_mouse_move_recipient {
if last_pipeline_id != result.layer.pipeline_id() {
if let Some(pipeline) = self.pipeline(last_pipeline_id) {
let _ = pipeline.script_chan
.send(ConstellationControlMsg::SendEvent(
last_pipeline_id.clone(),
MouseMoveEvent(None)));
}
}
}
self.last_mouse_move_recipient = Some(result.layer.pipeline_id());
result.layer.send_mouse_move_event(self, result.point);
}
None => {}
}
}
fn on_touch_down(&mut self, identifier: TouchId, point: TypedPoint2D<DevicePixel, f32>) {
self.touch_handler.on_touch_down(identifier, point);
if let Some(result) = self.find_topmost_layer_at_point(point / self.scene.scale) {
result.layer.send_event(self, TouchEvent(TouchEventType::Down, identifier,
result.point.to_untyped()));
}
}
fn on_touch_move(&mut self, identifier: TouchId, point: TypedPoint2D<DevicePixel, f32>) {
match self.touch_handler.on_touch_move(identifier, point) {
TouchAction::Scroll(delta) => {
match point.cast() {
Some(point) => self.on_scroll_window_event(delta, point),
None => error!("Point cast failed."),
}
}
TouchAction::Zoom(magnification, scroll_delta) => {
let cursor = Point2D::typed(-1, -1); // Make sure this hits the base layer.
self.pending_scroll_zoom_events.push(ScrollZoomEvent {
magnification: magnification,
delta: scroll_delta,
cursor: cursor,
phase: ScrollEventPhase::Move(true),
});
self.composite_if_necessary_if_not_using_webrender(CompositingReason::Zoom);
}
TouchAction::DispatchEvent => {
if let Some(result) = self.find_topmost_layer_at_point(point / self.scene.scale) {
result.layer.send_event(self, TouchEvent(TouchEventType::Move, identifier,
result.point.to_untyped()));
}
}
_ => {}
}
}
fn on_touch_up(&mut self, identifier: TouchId, point: TypedPoint2D<DevicePixel, f32>) {
if let Some(result) = self.find_topmost_layer_at_point(point / self.scene.scale) {
result.layer.send_event(self, TouchEvent(TouchEventType::Up, identifier,
result.point.to_untyped()));
}
if let TouchAction::Click = self.touch_handler.on_touch_up(identifier, point) {
self.simulate_mouse_click(point);
}
}
fn on_touch_cancel(&mut self, identifier: TouchId, point: TypedPoint2D<DevicePixel, f32>) {
// Send the event to script.
self.touch_handler.on_touch_cancel(identifier, point);
if let Some(result) = self.find_topmost_layer_at_point(point / self.scene.scale) {
result.layer.send_event(self, TouchEvent(TouchEventType::Cancel, identifier,
result.point.to_untyped()));
}
}
/// http://w3c.github.io/touch-events/#mouse-events
fn simulate_mouse_click(&self, p: TypedPoint2D<DevicePixel, f32>) {
match self.find_topmost_layer_at_point(p / self.scene.scale) {
Some(HitTestResult { layer, point }) => {
let button = MouseButton::Left;
layer.send_mouse_move_event(self, point);
layer.send_mouse_event(self, MouseWindowEvent::MouseDown(button, p), point);
layer.send_mouse_event(self, MouseWindowEvent::MouseUp(button, p), point);
layer.send_mouse_event(self, MouseWindowEvent::Click(button, p), point);
}
None => {},
}
}
fn on_scroll_window_event(&mut self,
delta: TypedPoint2D<DevicePixel, f32>,
cursor: TypedPoint2D<DevicePixel, i32>) {
self.pending_scroll_zoom_events.push(ScrollZoomEvent {
magnification: 1.0,
delta: delta,
cursor: cursor,
phase: ScrollEventPhase::Move(self.scroll_in_progress),
});
self.composite_if_necessary_if_not_using_webrender(CompositingReason::Scroll);
}
fn on_scroll_start_window_event(&mut self,
delta: TypedPoint2D<DevicePixel, f32>,
cursor: TypedPoint2D<DevicePixel, i32>) {
self.scroll_in_progress = true;
self.pending_scroll_zoom_events.push(ScrollZoomEvent {
magnification: 1.0,
delta: delta,
cursor: cursor,
phase: ScrollEventPhase::Start,
});
self.composite_if_necessary_if_not_using_webrender(CompositingReason::Scroll);
}
fn on_scroll_end_window_event(&mut self,
delta: TypedPoint2D<DevicePixel, f32>,
cursor: TypedPoint2D<DevicePixel, i32>) {
self.scroll_in_progress = false;
self.pending_scroll_zoom_events.push(ScrollZoomEvent {
magnification: 1.0,
delta: delta,
cursor: cursor,
phase: ScrollEventPhase::End,
});
self.composite_if_necessary_if_not_using_webrender(CompositingReason::Scroll);
}
fn process_pending_scroll_events(&mut self) {
let had_events = self.pending_scroll_zoom_events.len() > 0;
match self.webrender_api {
Some(ref webrender_api) => {
// Batch up all scroll events into one, or else we'll do way too much painting.
let mut last_combined_event: Option<ScrollZoomEvent> = None;
for scroll_event in self.pending_scroll_zoom_events.drain(..) {
let this_delta = scroll_event.delta;
let this_cursor = scroll_event.cursor;
if let Some(combined_event) = last_combined_event {
if combined_event.phase != scroll_event.phase {
webrender_api.scroll(
(combined_event.delta / self.scene.scale).to_untyped(),
(combined_event.cursor.as_f32() / self.scene.scale).to_untyped(),
combined_event.phase);
last_combined_event = None
}
}
match last_combined_event {
None => {
last_combined_event = Some(ScrollZoomEvent {
magnification: scroll_event.magnification,
delta: this_delta,
cursor: this_cursor,
phase: scroll_event.phase,
})
}
Some(ref mut last_combined_event) => {
last_combined_event.delta = last_combined_event.delta + this_delta;
}
}
}
// TODO(gw): Support zoom (WR issue #28).
if let Some(combined_event) = last_combined_event {
webrender_api.scroll(
(combined_event.delta / self.scene.scale).to_untyped(),
(combined_event.cursor.as_f32() / self.scene.scale).to_untyped(),
combined_event.phase);
}
}
None => {
for event in std_mem::replace(&mut self.pending_scroll_zoom_events,
Vec::new()) {
let delta = event.delta / self.scene.scale;
let cursor = event.cursor.as_f32() / self.scene.scale;
if let Some(ref mut layer) = self.scene.root {
layer.handle_scroll_event(delta, cursor);
}
if event.magnification != 1.0 {
self.zoom_action = true;
self.zoom_time = precise_time_s();
self.viewport_zoom = ScaleFactor::new(
(self.viewport_zoom.get() * event.magnification)
.min(self.max_viewport_zoom.as_ref().map_or(MAX_ZOOM, ScaleFactor::get))
.max(self.min_viewport_zoom.as_ref().map_or(MIN_ZOOM, ScaleFactor::get)));
self.update_zoom_transform();
}
self.perform_updates_after_scroll();
}
}
}
if had_events {
self.send_viewport_rects_for_all_layers();
}
}
/// Computes new display ports for each layer, taking the scroll position into account, and
/// sends them to layout as necessary. This ultimately triggers a rerender of the content.
fn send_updated_display_ports_to_layout(&mut self) {
fn process_layer(layer: &Layer<CompositorData>,
window_size: &TypedSize2D<LayerPixel, f32>,
new_display_ports: &mut HashMap<PipelineId, Vec<(LayerId, Rect<Au>)>>) {
let visible_rect =
Rect::new(Point2D::zero(), *window_size).translate(&-*layer.content_offset.borrow())
.intersection(&*layer.bounds.borrow())
.unwrap_or(Rect::zero())
.to_untyped();
let visible_rect = Rect::new(Point2D::new(Au::from_f32_px(visible_rect.origin.x),
Au::from_f32_px(visible_rect.origin.y)),
Size2D::new(Au::from_f32_px(visible_rect.size.width),
Au::from_f32_px(visible_rect.size.height)));
let extra_layer_data = layer.extra_data.borrow();
if !new_display_ports.contains_key(&extra_layer_data.pipeline_id) {
new_display_ports.insert(extra_layer_data.pipeline_id, Vec::new());
}
if let Some(new_display_port) = new_display_ports.get_mut(&extra_layer_data.pipeline_id) {
new_display_port.push((extra_layer_data.id, visible_rect));
}
for kid in &*layer.children.borrow() {
process_layer(&*kid, window_size, new_display_ports)
}
}
let dppx = self.page_zoom * self.device_pixels_per_screen_px();
let window_size = self.window_size.as_f32() / dppx * ScaleFactor::new(1.0);
let mut new_visible_rects = HashMap::new();
if let Some(ref layer) = self.scene.root {
process_layer(&**layer, &window_size, &mut new_visible_rects)
}
for (pipeline_id, new_visible_rects) in &new_visible_rects {
if let Some(pipeline_details) = self.pipeline_details.get(&pipeline_id) {
if let Some(ref pipeline) = pipeline_details.pipeline {
let msg = LayoutControlMsg::SetVisibleRects((*new_visible_rects).clone());
if let Err(e) = pipeline.layout_chan.send(msg) {<|fim▁hole|> }
}
}
/// Performs buffer requests and starts the scrolling timer or schedules a recomposite as
/// necessary.
fn perform_updates_after_scroll(&mut self) {
self.send_updated_display_ports_to_layout();
if opts::get().use_webrender {
return
}
if self.send_buffer_requests_for_all_layers() {
self.schedule_delayed_composite_if_necessary();
} else {
self.channel_to_self.send(Msg::Recomposite(CompositingReason::ContinueScroll));
}
}
/// If there are any animations running, dispatches appropriate messages to the constellation.
fn process_animations(&mut self) {
let mut pipeline_ids = vec![];
for (pipeline_id, pipeline_details) in &self.pipeline_details {
if (pipeline_details.animations_running ||
pipeline_details.animation_callbacks_running) &&
pipeline_details.visible {
pipeline_ids.push(*pipeline_id);
}
}
for pipeline_id in &pipeline_ids {
self.tick_animations_for_pipeline(*pipeline_id)
}
}
fn tick_animations_for_pipeline(&mut self, pipeline_id: PipelineId) {
self.schedule_delayed_composite_if_necessary();
let animation_callbacks_running = self.pipeline_details(pipeline_id).animation_callbacks_running;
let animation_type = if animation_callbacks_running {
AnimationTickType::Script
} else {
AnimationTickType::Layout
};
let msg = ConstellationMsg::TickAnimation(pipeline_id, animation_type);
if let Err(e) = self.constellation_chan.send(msg) {
warn!("Sending tick to constellation failed ({}).", e);
}
}
fn constrain_viewport(&mut self, pipeline_id: PipelineId, constraints: ViewportConstraints) {
let is_root = self.root_pipeline.as_ref().map_or(false, |root_pipeline| {
root_pipeline.id == pipeline_id
});
if is_root {
// TODO: actual viewport size
self.viewport_zoom = constraints.initial_zoom;
self.min_viewport_zoom = constraints.min_zoom;
self.max_viewport_zoom = constraints.max_zoom;
self.update_zoom_transform();
}
}
fn device_pixels_per_screen_px(&self) -> ScaleFactor<ScreenPx, DevicePixel, f32> {
match opts::get().device_pixels_per_px {
Some(device_pixels_per_px) => ScaleFactor::new(device_pixels_per_px),
None => match opts::get().output_file {
Some(_) => ScaleFactor::new(1.0),
None => self.scale_factor
}
}
}
fn device_pixels_per_page_px(&self) -> ScaleFactor<PagePx, DevicePixel, f32> {
self.viewport_zoom * self.page_zoom * self.device_pixels_per_screen_px()
}
fn update_zoom_transform(&mut self) {
let scale = self.device_pixels_per_page_px();
self.scene.scale = ScaleFactor::new(scale.get());
// We need to set the size of the root layer again, since the window size
// has changed in unscaled layer pixels.
self.scene.set_root_layer_size(self.window_size.as_f32());
}
fn on_zoom_reset_window_event(&mut self) {
self.page_zoom = ScaleFactor::new(1.0);
self.update_zoom_transform();
self.send_window_size(WindowSizeType::Resize);
}
fn on_zoom_window_event(&mut self, magnification: f32) {
self.page_zoom = ScaleFactor::new((self.page_zoom.get() * magnification)
.max(MIN_ZOOM).min(MAX_ZOOM));
self.update_zoom_transform();
self.send_window_size(WindowSizeType::Resize);
}
/// Simulate a pinch zoom
fn on_pinch_zoom_window_event(&mut self, magnification: f32) {
self.pending_scroll_zoom_events.push(ScrollZoomEvent {
magnification: magnification,
delta: Point2D::typed(0.0, 0.0), // TODO: Scroll to keep the center in view?
cursor: Point2D::typed(-1, -1), // Make sure this hits the base layer.
phase: ScrollEventPhase::Move(true),
});
self.composite_if_necessary_if_not_using_webrender(CompositingReason::Zoom);
}
fn on_navigation_window_event(&self, direction: WindowNavigateMsg) {
let direction = match direction {
windowing::WindowNavigateMsg::Forward => NavigationDirection::Forward(1),
windowing::WindowNavigateMsg::Back => NavigationDirection::Back(1),
};
let msg = ConstellationMsg::Navigate(None, direction);
if let Err(e) = self.constellation_chan.send(msg) {
warn!("Sending navigation to constellation failed ({}).", e);
}
}
fn on_touchpad_pressure_event(&self, cursor: TypedPoint2D<DevicePixel, f32>, pressure: f32,
phase: TouchpadPressurePhase) {
if let Some(true) = prefs::get_pref("dom.forcetouch.enabled").as_boolean() {
match self.find_topmost_layer_at_point(cursor / self.scene.scale) {
Some(result) => result.layer.send_touchpad_pressure_event(self, result.point, pressure, phase),
None => {},
}
}
}
fn on_key_event(&self, key: Key, state: KeyState, modifiers: KeyModifiers) {
let msg = ConstellationMsg::KeyEvent(key, state, modifiers);
if let Err(e) = self.constellation_chan.send(msg) {
warn!("Sending key event to constellation failed ({}).", e);
}
}
fn fill_paint_request_with_cached_layer_buffers(&mut self, paint_request: &mut PaintRequest) {
for buffer_request in &mut paint_request.buffer_requests {
if self.surface_map.mem() == 0 {
return;
}
let size = Size2D::new(buffer_request.screen_rect.size.width as i32,
buffer_request.screen_rect.size.height as i32);
if let Some(mut native_surface) = self.surface_map.find(size) {
native_surface.mark_wont_leak();
buffer_request.native_surface = Some(native_surface);
}
}
}
fn convert_buffer_requests_to_pipeline_requests_map(&mut self,
requests: Vec<(Rc<Layer<CompositorData>>,
Vec<BufferRequest>)>)
-> HashMap<PipelineId, Vec<PaintRequest>> {
let scale = self.device_pixels_per_page_px();
let mut results: HashMap<PipelineId, Vec<PaintRequest>> = HashMap::new();
for (layer, mut layer_requests) in requests {
let pipeline_id = layer.pipeline_id();
let current_epoch = self.pipeline_details(pipeline_id).current_epoch;
layer.extra_data.borrow_mut().requested_epoch = current_epoch;
let vec = match results.entry(pipeline_id) {
Occupied(entry) => {
entry.into_mut()
}
Vacant(entry) => {
entry.insert(Vec::new())
}
};
// All the BufferRequests are in layer/device coordinates, but the paint thread
// wants to know the page coordinates. We scale them before sending them.
for request in &mut layer_requests {
request.page_rect = request.page_rect / scale.get();
}
let layer_kind = if layer.transform_state.borrow().has_transform {
LayerKind::HasTransform
} else {
LayerKind::NoTransform
};
let mut paint_request = PaintRequest {
buffer_requests: layer_requests,
scale: scale.get(),
layer_id: layer.extra_data.borrow().id,
epoch: layer.extra_data.borrow().requested_epoch,
layer_kind: layer_kind,
};
self.fill_paint_request_with_cached_layer_buffers(&mut paint_request);
vec.push(paint_request);
}
results
}
fn send_viewport_rect_for_layer(&self, layer: Rc<Layer<CompositorData>>) {
if layer.extra_data.borrow().id == LayerId::null() {
let layer_rect = Rect::new(-layer.extra_data.borrow().scroll_offset.to_untyped(),
layer.bounds.borrow().size.to_untyped());
if let Some(pipeline) = self.pipeline(layer.pipeline_id()) {
let msg = ConstellationControlMsg::Viewport(pipeline.id.clone(), layer_rect);
if let Err(e) = pipeline.script_chan.send(msg) {
warn!("Send viewport to script failed ({})", e);
}
}
}
for kid in &*layer.children() {
self.send_viewport_rect_for_layer(kid.clone());
}
}
fn send_viewport_rects_for_all_layers(&self) {
if opts::get().use_webrender {
return self.send_webrender_viewport_rects()
}
if let Some(ref root) = self.scene.root {
self.send_viewport_rect_for_layer(root.clone())
}
}
fn send_webrender_viewport_rects(&self) {
let mut stacking_context_scroll_states_per_pipeline = HashMap::new();
if let Some(ref webrender_api) = self.webrender_api {
for scroll_layer_state in webrender_api.get_scroll_layer_state() {
let stacking_context_scroll_state = StackingContextScrollState {
stacking_context_id: scroll_layer_state.stacking_context_id.from_webrender(),
scroll_offset: scroll_layer_state.scroll_offset,
};
let pipeline_id = scroll_layer_state.pipeline_id;
stacking_context_scroll_states_per_pipeline
.entry(pipeline_id)
.or_insert(vec![])
.push(stacking_context_scroll_state);
}
for (pipeline_id, stacking_context_scroll_states) in
stacking_context_scroll_states_per_pipeline {
if let Some(pipeline) = self.pipeline(pipeline_id.from_webrender()) {
let msg = LayoutControlMsg::SetStackingContextScrollStates(
stacking_context_scroll_states);
let _ = pipeline.layout_chan.send(msg);
}
}
}
}
/// Returns true if any buffer requests were sent or false otherwise.
fn send_buffer_requests_for_all_layers(&mut self) -> bool {
if self.webrender.is_some() {
return false;
}
if let Some(ref root_layer) = self.scene.root {
root_layer.update_transform_state(&Matrix4D::identity(),
&Matrix4D::identity(),
&Point2D::zero());
}
let mut layers_and_requests = Vec::new();
let mut unused_buffers = Vec::new();
self.scene.get_buffer_requests(&mut layers_and_requests, &mut unused_buffers);
// Return unused tiles first, so that they can be reused by any new BufferRequests.
self.cache_unused_buffers(unused_buffers);
if layers_and_requests.is_empty() {
return false;
}
// We want to batch requests for each pipeline to avoid race conditions
// when handling the resulting BufferRequest responses.
let pipeline_requests =
self.convert_buffer_requests_to_pipeline_requests_map(layers_and_requests);
for (pipeline_id, requests) in pipeline_requests {
let msg = ChromeToPaintMsg::Paint(requests, self.frame_tree_id);
if let Some(pipeline) = self.pipeline(pipeline_id) {
if let Err(e) = pipeline.chrome_to_paint_chan.send(msg) {
warn!("Sending paint message failed ({}).", e);
}
}
}
true
}
/// Check if a layer (or its children) have any outstanding paint
/// results to arrive yet.
fn does_layer_have_outstanding_paint_messages(&self, layer: &Rc<Layer<CompositorData>>)
-> bool {
let layer_data = layer.extra_data.borrow();
let current_epoch = match self.pipeline_details.get(&layer_data.pipeline_id) {
None => return false,
Some(ref details) => details.current_epoch,
};
// Only check layers that have requested the current epoch, as there may be
// layers that are not visible in the current viewport, and therefore
// have not requested a paint of the current epoch.
// If a layer has sent a request for the current epoch, but it hasn't
// arrived yet then this layer is waiting for a paint message.
//
// Also don't check the root layer, because the paint thread won't paint
// anything for it after first layout.
if layer_data.id != LayerId::null() &&
layer_data.requested_epoch == current_epoch &&
layer_data.painted_epoch != current_epoch {
return true;
}
for child in &*layer.children() {
if self.does_layer_have_outstanding_paint_messages(child) {
return true;
}
}
false
}
// Check if any pipelines currently have active animations or animation callbacks.
fn animations_active(&self) -> bool {
for (_, details) in &self.pipeline_details {
// If animations are currently running, then don't bother checking
// with the constellation if the output image is stable.
if details.animations_running {
return true;
}
if details.animation_callbacks_running {
return true;
}
}
false
}
/// Query the constellation to see if the current compositor
/// output matches the current frame tree output, and if the
/// associated script threads are idle.
fn is_ready_to_paint_image_output(&mut self) -> Result<(), NotReadyToPaint> {
match self.ready_to_save_state {
ReadyState::Unknown => {
// Unsure if the output image is stable.
// Check if any layers are waiting for paints to complete
// of their current epoch request. If so, early exit
// from this check.
match self.scene.root {
Some(ref root_layer) => {
if self.does_layer_have_outstanding_paint_messages(root_layer) {
return Err(NotReadyToPaint::LayerHasOutstandingPaintMessages);
}
}
None => {
return Err(NotReadyToPaint::MissingRoot);
}
}
// Check if there are any pending frames. If so, the image is not stable yet.
if self.pending_subpages.len() > 0 {
return Err(NotReadyToPaint::PendingSubpages(self.pending_subpages.len()));
}
// Collect the currently painted epoch of each pipeline that is
// complete (i.e. has *all* layers painted to the requested epoch).
// This gets sent to the constellation for comparison with the current
// frame tree.
let mut pipeline_epochs = HashMap::new();
for (id, details) in &self.pipeline_details {
if let Some(ref webrender) = self.webrender {
let webrender_pipeline_id = id.to_webrender();
if let Some(webrender_traits::Epoch(epoch)) = webrender.current_epoch(webrender_pipeline_id) {
let epoch = Epoch(epoch);
pipeline_epochs.insert(*id, epoch);
}
} else {
pipeline_epochs.insert(*id, details.current_epoch);
}
}
// Pass the pipeline/epoch states to the constellation and check
// if it's safe to output the image.
let msg = ConstellationMsg::IsReadyToSaveImage(pipeline_epochs);
if let Err(e) = self.constellation_chan.send(msg) {
warn!("Sending ready to save to constellation failed ({}).", e);
}
self.ready_to_save_state = ReadyState::WaitingForConstellationReply;
Err(NotReadyToPaint::JustNotifiedConstellation)
}
ReadyState::WaitingForConstellationReply => {
// If waiting on a reply from the constellation to the last
// query if the image is stable, then assume not ready yet.
Err(NotReadyToPaint::WaitingOnConstellation)
}
ReadyState::ReadyToSaveImage => {
// Constellation has replied at some point in the past
// that the current output image is stable and ready
// for saving.
// Reset the flag so that we check again in the future
// TODO: only reset this if we load a new document?
if opts::get().is_running_problem_test {
println!("was ready to save, resetting ready_to_save_state");
}
self.ready_to_save_state = ReadyState::Unknown;
Ok(())
}
}
}
fn composite(&mut self) {
let target = self.composite_target;
match self.composite_specific_target(target) {
Ok(_) => if opts::get().output_file.is_some() || opts::get().exit_after_load {
println!("Shutting down the Constellation after generating an output file or exit flag specified");
self.start_shutting_down();
},
Err(e) => if opts::get().is_running_problem_test {
if e != UnableToComposite::NotReadyToPaintImage(NotReadyToPaint::WaitingOnConstellation) {
println!("not ready to composite: {:?}", e);
}
},
}
}
/// Composite either to the screen or to a png image or both.
/// Returns Ok if composition was performed or Err if it was not possible to composite
/// for some reason. If CompositeTarget is Window or Png no image data is returned;
/// in the latter case the image is written directly to a file. If CompositeTarget
/// is WindowAndPng Ok(Some(png::Image)) is returned.
fn composite_specific_target(&mut self,
target: CompositeTarget)
-> Result<Option<Image>, UnableToComposite> {
if self.context.is_none() && self.webrender.is_none() {
return Err(UnableToComposite::NoContext)
}
let (width, height) =
(self.window_size.width.get() as usize, self.window_size.height.get() as usize);
if !self.window.prepare_for_composite(width, height) {
return Err(UnableToComposite::WindowUnprepared)
}
if let Some(ref mut webrender) = self.webrender {
assert!(self.context.is_none());
webrender.update();
}
let wait_for_stable_image = match target {
CompositeTarget::WindowAndPng | CompositeTarget::PngFile => true,
CompositeTarget::Window => opts::get().exit_after_load,
};
if wait_for_stable_image {
match self.is_ready_to_paint_image_output() {
Ok(()) => {
// The current image is ready to output. However, if there are animations active,
// tick those instead and continue waiting for the image output to be stable AND
// all active animations to complete.
if self.animations_active() {
self.process_animations();
return Err(UnableToComposite::NotReadyToPaintImage(NotReadyToPaint::AnimationsActive));
}
}
Err(result) => {
return Err(UnableToComposite::NotReadyToPaintImage(result))
}
}
}
let render_target_info = match target {
CompositeTarget::Window => RenderTargetInfo::empty(),
_ => initialize_png(width, height)
};
profile(ProfilerCategory::Compositing, None, self.time_profiler_chan.clone(), || {
debug!("compositor: compositing");
self.dump_layer_tree();
// Adjust the layer dimensions as necessary to correspond to the size of the window.
self.scene.viewport = match self.viewport {
Some((point, size)) => Rect {
origin: point.as_f32(),
size: size.as_f32(),
},
None => Rect {
origin: Point2D::zero(),
size: self.window_size.as_f32(),
}
};
// Paint the scene.
if let Some(ref mut webrender) = self.webrender {
assert!(self.context.is_none());
webrender.render(self.window_size.to_untyped());
} else if let Some(ref layer) = self.scene.root {
match self.context {
Some(context) => {
if let Some((point, size)) = self.viewport {
let point = point.to_untyped();
let size = size.to_untyped();
gl::scissor(point.x as GLint, point.y as GLint,
size.width as GLsizei, size.height as GLsizei);
gl::enable(gl::SCISSOR_TEST);
rendergl::render_scene(layer.clone(), context, &self.scene);
gl::disable(gl::SCISSOR_TEST);
}
else {
rendergl::render_scene(layer.clone(), context, &self.scene);
}
}
None => {
debug!("compositor: not compositing because context not yet set up")
}
}
}
});
let rv = match target {
CompositeTarget::Window => None,
CompositeTarget::WindowAndPng => {
let img = self.draw_img(render_target_info,
width,
height);
Some(Image {
width: img.width(),
height: img.height(),
format: PixelFormat::RGB8,
bytes: IpcSharedMemory::from_bytes(&*img),
id: None,
})
}
CompositeTarget::PngFile => {
profile(ProfilerCategory::ImageSaving, None, self.time_profiler_chan.clone(), || {
match opts::get().output_file.as_ref() {
Some(path) => match File::create(path) {
Ok(mut file) => {
let img = self.draw_img(render_target_info, width, height);
let dynamic_image = DynamicImage::ImageRgb8(img);
if let Err(e) = dynamic_image.save(&mut file, ImageFormat::PNG) {
error!("Failed to save {} ({}).", path, e);
}
},
Err(e) => error!("Failed to create {} ({}).", path, e),
},
None => error!("No file specified."),
}
});
None
}
};
// Perform the page flip. This will likely block for a while.
self.window.present();
self.last_composite_time = precise_time_ns();
self.composition_request = CompositionRequest::NoCompositingNecessary;
if !opts::get().use_webrender {
self.process_pending_scroll_events();
}
self.process_animations();
self.start_scrolling_bounce_if_necessary();
Ok(rv)
}
fn draw_img(&self,
render_target_info: RenderTargetInfo,
width: usize,
height: usize)
-> RgbImage {
let mut pixels = gl::read_pixels(0, 0,
width as gl::GLsizei,
height as gl::GLsizei,
gl::RGB, gl::UNSIGNED_BYTE);
gl::bind_framebuffer(gl::FRAMEBUFFER, 0);
gl::delete_buffers(&render_target_info.texture_ids);
gl::delete_frame_buffers(&render_target_info.framebuffer_ids);
if opts::get().use_webrender {
gl::delete_renderbuffers(&render_target_info.renderbuffer_ids);
}
// flip image vertically (texture is upside down)
let orig_pixels = pixels.clone();
let stride = width * 3;
for y in 0..height {
let dst_start = y * stride;
let src_start = (height - y - 1) * stride;
let src_slice = &orig_pixels[src_start .. src_start + stride];
(&mut pixels[dst_start .. dst_start + stride]).clone_from_slice(&src_slice[..stride]);
}
RgbImage::from_raw(width as u32, height as u32, pixels).expect("Flipping image failed!")
}
fn composite_if_necessary(&mut self, reason: CompositingReason) {
if self.composition_request == CompositionRequest::NoCompositingNecessary {
if opts::get().is_running_problem_test {
println!("updating composition_request ({:?})", reason);
}
self.composition_request = CompositionRequest::CompositeNow(reason)
} else if opts::get().is_running_problem_test {
println!("composition_request is already {:?}", self.composition_request);
}
}
fn composite_if_necessary_if_not_using_webrender(&mut self, reason: CompositingReason) {
if !opts::get().use_webrender {
self.composite_if_necessary(reason)
}
}
fn initialize_compositing(&mut self) {
if self.webrender.is_none() {
let show_debug_borders = opts::get().show_debug_borders;
// We can unwrap native_display because it's only None when using webrender.
self.context = Some(rendergl::RenderContext::new(self.native_display
.expect("n_d should be Some when not using wr").clone(),
show_debug_borders,
opts::get().output_file.is_some()))
}
}
fn find_topmost_layer_at_point_for_layer(&self,
layer: Rc<Layer<CompositorData>>,
point_in_parent_layer: TypedPoint2D<LayerPixel, f32>,
clip_rect_in_parent_layer: &TypedRect<LayerPixel, f32>)
-> Option<HitTestResult> {
let layer_bounds = *layer.bounds.borrow();
let masks_to_bounds = *layer.masks_to_bounds.borrow();
if layer_bounds.is_empty() && masks_to_bounds {
return None;
}
let scroll_offset = layer.extra_data.borrow().scroll_offset;
// Total offset from parent coordinates to this layer's coordinates.
// FIXME: This offset is incorrect for fixed-position layers.
let layer_offset = scroll_offset + layer_bounds.origin;
let clipped_layer_bounds = match clip_rect_in_parent_layer.intersection(&layer_bounds) {
Some(rect) => rect,
None => return None,
};
let clip_rect_for_children = if masks_to_bounds {
&clipped_layer_bounds
} else {
clip_rect_in_parent_layer
}.translate(&-layer_offset);
let child_point = point_in_parent_layer - layer_offset;
for child in layer.children().iter().rev() {
// Translate the clip rect into the child's coordinate system.
let result = self.find_topmost_layer_at_point_for_layer(child.clone(),
child_point,
&clip_rect_for_children);
if let Some(mut result) = result {
// Return the point in layer coordinates of the topmost frame containing the point.
let pipeline_id = layer.extra_data.borrow().pipeline_id;
let child_pipeline_id = result.layer.extra_data.borrow().pipeline_id;
if pipeline_id == child_pipeline_id {
result.point = result.point + layer_offset;
}
return Some(result);
}
}
if !clipped_layer_bounds.contains(&point_in_parent_layer) {
return None;
}
Some(HitTestResult { layer: layer, point: point_in_parent_layer })
}
fn find_topmost_layer_at_point(&self,
point: TypedPoint2D<LayerPixel, f32>)
-> Option<HitTestResult> {
match self.scene.root {
Some(ref layer) => {
self.find_topmost_layer_at_point_for_layer(layer.clone(),
point,
&*layer.bounds.borrow())
}
None => None,
}
}
fn find_layer_with_pipeline_and_layer_id(&self,
pipeline_id: PipelineId,
layer_id: LayerId)
-> Option<Rc<Layer<CompositorData>>> {
match self.scene.root {
Some(ref layer) =>
find_layer_with_pipeline_and_layer_id_for_layer(layer.clone(),
pipeline_id,
layer_id),
None => None,
}
}
pub fn cache_unused_buffers<B>(&mut self, buffers: B)
where B: IntoIterator<Item=Box<LayerBuffer>>
{
let surfaces = buffers.into_iter().map(|buffer| buffer.native_surface);
if let Some(ref native_display) = self.native_display {
self.surface_map.insert_surfaces(native_display, surfaces);
}
}
fn get_root_pipeline_id(&self) -> Option<PipelineId> {
self.scene.root.as_ref().map(|root_layer| root_layer.extra_data.borrow().pipeline_id)
}
#[allow(dead_code)]
fn dump_layer_tree(&self) {
if !opts::get().dump_layer_tree {
return;
}
let mut print_tree = PrintTree::new("Layer tree".to_owned());
if let Some(ref layer) = self.scene.root {
self.dump_layer_tree_layer(&**layer, &mut print_tree);
}
}
#[allow(dead_code)]
fn dump_layer_tree_layer(&self, layer: &Layer<CompositorData>, print_tree: &mut PrintTree) {
let data = layer.extra_data.borrow();
let layer_string = if data.id == LayerId::null() {
format!("Root Layer (pipeline={})", data.pipeline_id)
} else {
"Layer".to_owned()
};
let masks_string = if *layer.masks_to_bounds.borrow() {
" (masks children)"
} else {
""
};
let establishes_3d_context_string = if layer.establishes_3d_context {
" (3D context)"
} else {
""
};
let fixed_string = if data.scroll_policy == ScrollPolicy::FixedPosition {
" (fixed)"
} else {
""
};
let layer_string = format!("{} ({:?}) ({},{} at {},{}){}{}{}",
layer_string,
layer.extra_data.borrow().id,
(*layer.bounds.borrow()).size.to_untyped().width,
(*layer.bounds.borrow()).size.to_untyped().height,
(*layer.bounds.borrow()).origin.to_untyped().x,
(*layer.bounds.borrow()).origin.to_untyped().y,
masks_string,
establishes_3d_context_string,
fixed_string);
let children = layer.children();
if !children.is_empty() {
print_tree.new_level(layer_string);
for kid in &*children {
self.dump_layer_tree_layer(&**kid, print_tree);
}
print_tree.end_level();
} else {
print_tree.add_item(layer_string);
}
}
fn start_scrolling_bounce_if_necessary(&mut self) {
if self.scroll_in_progress {
return
}
match self.webrender {
Some(ref webrender) if webrender.layers_are_bouncing_back() => {}
_ => return,
}
if let Some(ref webrender_api) = self.webrender_api {
webrender_api.tick_scrolling_bounce_animations();
self.send_webrender_viewport_rects()
}
}
pub fn handle_events(&mut self, messages: Vec<WindowEvent>) -> bool {
// Check for new messages coming from the other threads in the system.
while let Some(msg) = self.port.try_recv_compositor_msg() {
if !self.handle_browser_message(msg) {
break
}
}
if self.shutdown_state == ShutdownState::FinishedShuttingDown {
return false;
}
// Handle any messages coming from the windowing system.
for message in messages {
self.handle_window_message(message);
}
// If a pinch-zoom happened recently, ask for tiles at the new resolution
if self.zoom_action && precise_time_s() - self.zoom_time > 0.3 {
self.zoom_action = false;
self.scene.mark_layer_contents_as_changed_recursively();
self.send_buffer_requests_for_all_layers();
}
if !self.pending_scroll_zoom_events.is_empty() && opts::get().use_webrender {
self.process_pending_scroll_events()
}
match self.composition_request {
CompositionRequest::NoCompositingNecessary |
CompositionRequest::DelayedComposite(_) => {}
CompositionRequest::CompositeNow(_) => {
self.composite()
}
}
self.shutdown_state != ShutdownState::FinishedShuttingDown
}
/// Repaints and recomposites synchronously. You must be careful when calling this, as if a
/// paint is not scheduled the compositor will hang forever.
///
/// This is used when resizing the window.
pub fn repaint_synchronously(&mut self) {
if self.webrender.is_none() {
while self.shutdown_state != ShutdownState::ShuttingDown {
let msg = self.port.recv_compositor_msg();
let received_new_buffers = match msg {
Msg::AssignPaintedBuffers(..) => true,
_ => false,
};
let keep_going = self.handle_browser_message(msg);
if received_new_buffers {
self.composite();
break
}
if !keep_going {
break
}
}
} else {
while self.shutdown_state != ShutdownState::ShuttingDown {
let msg = self.port.recv_compositor_msg();
let need_recomposite = match msg {
Msg::Recomposite(_) => true,
_ => false,
};
let keep_going = self.handle_browser_message(msg);
if need_recomposite {
self.composite();
break
}
if !keep_going {
break
}
}
}
}
pub fn pinch_zoom_level(&self) -> f32 {
self.viewport_zoom.get() as f32
}
pub fn title_for_main_frame(&self) {
let root_pipeline_id = match self.root_pipeline {
None => return,
Some(ref root_pipeline) => root_pipeline.id,
};
let msg = ConstellationMsg::GetPipelineTitle(root_pipeline_id);
if let Err(e) = self.constellation_chan.send(msg) {
warn!("Failed to send pipeline title ({}).", e);
}
}
}
fn find_layer_with_pipeline_and_layer_id_for_layer(layer: Rc<Layer<CompositorData>>,
pipeline_id: PipelineId,
layer_id: LayerId)
-> Option<Rc<Layer<CompositorData>>> {
if layer.extra_data.borrow().pipeline_id == pipeline_id &&
layer.extra_data.borrow().id == layer_id {
return Some(layer);
}
for kid in &*layer.children() {
let result = find_layer_with_pipeline_and_layer_id_for_layer(kid.clone(),
pipeline_id,
layer_id);
if result.is_some() {
return result;
}
}
None
}
/// Why we performed a composite. This is used for debugging.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum CompositingReason {
/// We hit the delayed composition timeout. (See `delayed_composition.rs`.)
DelayedCompositeTimeout,
/// The window has been scrolled and we're starting the first recomposite.
Scroll,
/// A scroll has continued and we need to recomposite again.
ContinueScroll,
/// We're performing the single composite in headless mode.
Headless,
/// We're performing a composite to run an animation.
Animation,
/// A new frame tree has been loaded.
NewFrameTree,
/// New painted buffers have been received.
NewPaintedBuffers,
/// The window has been zoomed.
Zoom,
/// A new WebRender frame has arrived.
NewWebRenderFrame,
}<|fim▁end|>
|
warn!("Sending layout control message failed ({}).", e);
}
}
|
<|file_name|>downloads.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Module for the downloading, checking, and unpacking of necessary files into the source tree.
"""
import argparse
import configparser
import enum
import hashlib
import shutil
import subprocess
import sys
import urllib.request
from pathlib import Path
from _common import ENCODING, USE_REGISTRY, ExtractorEnum, get_logger, \
get_chromium_version, add_common_params
from _extraction import extract_tar_file, extract_with_7z, extract_with_winrar
sys.path.insert(0, str(Path(__file__).parent / 'third_party'))
import schema #pylint: disable=wrong-import-position
sys.path.pop(0)
# Constants
class HashesURLEnum(str, enum.Enum):
"""Enum for supported hash URL schemes"""
chromium = 'chromium'
class HashMismatchError(BaseException):
"""Exception for computed hashes not matching expected hashes"""<|fim▁hole|>class DownloadInfo: #pylint: disable=too-few-public-methods
"""Representation of an downloads.ini file for downloading files"""
_hashes = ('md5', 'sha1', 'sha256', 'sha512')
hash_url_delimiter = '|'
_nonempty_keys = ('url', 'download_filename')
_optional_keys = (
'version',
'strip_leading_dirs',
)
_passthrough_properties = (*_nonempty_keys, *_optional_keys, 'extractor', 'output_path')
_ini_vars = {
'_chromium_version': get_chromium_version(),
}
@staticmethod
def _is_hash_url(value):
return value.count(DownloadInfo.hash_url_delimiter) == 2 and value.split(
DownloadInfo.hash_url_delimiter)[0] in iter(HashesURLEnum)
_schema = schema.Schema({
schema.Optional(schema.And(str, len)): {
**{x: schema.And(str, len)
for x in _nonempty_keys},
'output_path': (lambda x: str(Path(x).relative_to(''))),
**{schema.Optional(x): schema.And(str, len)
for x in _optional_keys},
schema.Optional('extractor'): schema.Or(ExtractorEnum.TAR, ExtractorEnum.SEVENZIP,
ExtractorEnum.WINRAR),
schema.Optional(schema.Or(*_hashes)): schema.And(str, len),
schema.Optional('hash_url'): lambda x: DownloadInfo._is_hash_url(x), #pylint: disable=unnecessary-lambda
}
})
class _DownloadsProperties: #pylint: disable=too-few-public-methods
def __init__(self, section_dict, passthrough_properties, hashes):
self._section_dict = section_dict
self._passthrough_properties = passthrough_properties
self._hashes = hashes
def has_hash_url(self):
"""
Returns a boolean indicating whether the current
download has a hash URL"""
return 'hash_url' in self._section_dict
def __getattr__(self, name):
if name in self._passthrough_properties:
return self._section_dict.get(name, fallback=None)
if name == 'hashes':
hashes_dict = {}
for hash_name in (*self._hashes, 'hash_url'):
value = self._section_dict.get(hash_name, fallback=None)
if value:
if hash_name == 'hash_url':
value = value.split(DownloadInfo.hash_url_delimiter)
hashes_dict[hash_name] = value
return hashes_dict
raise AttributeError('"{}" has no attribute "{}"'.format(type(self).__name__, name))
def _parse_data(self, path):
"""
Parses an INI file located at path
Raises schema.SchemaError if validation fails
"""
def _section_generator(data):
for section in data:
if section == configparser.DEFAULTSECT:
continue
yield section, dict(
filter(lambda x: x[0] not in self._ini_vars, data.items(section)))
new_data = configparser.ConfigParser(defaults=self._ini_vars)
with path.open(encoding=ENCODING) as ini_file:
new_data.read_file(ini_file, source=str(path))
try:
self._schema.validate(dict(_section_generator(new_data)))
except schema.SchemaError as exc:
get_logger().error('downloads.ini failed schema validation (located in %s)', path)
raise exc
return new_data
def __init__(self, ini_paths):
"""Reads an iterable of pathlib.Path to download.ini files"""
self._data = configparser.ConfigParser()
for path in ini_paths:
self._data.read_dict(self._parse_data(path))
def __getitem__(self, section):
"""
Returns an object with keys as attributes and
values already pre-processed strings
"""
return self._DownloadsProperties(self._data[section], self._passthrough_properties,
self._hashes)
def __contains__(self, item):
"""
Returns True if item is a name of a section; False otherwise.
"""
return self._data.has_section(item)
def __iter__(self):
"""Returns an iterator over the section names"""
return iter(self._data.sections())
def properties_iter(self):
"""Iterator for the download properties sorted by output path"""
return sorted(
map(lambda x: (x, self[x]), self), key=(lambda x: str(Path(x[1].output_path))))
class _UrlRetrieveReportHook: #pylint: disable=too-few-public-methods
"""Hook for urllib.request.urlretrieve to log progress information to console"""
def __init__(self):
self._max_len_printed = 0
self._last_percentage = None
def __call__(self, block_count, block_size, total_size):
# Use total_blocks to handle case total_size < block_size
# total_blocks is ceiling of total_size / block_size
# Ceiling division from: https://stackoverflow.com/a/17511341
total_blocks = -(-total_size // block_size)
if total_blocks > 0:
# Do not needlessly update the console. Since the console is
# updated synchronously, we don't want updating the console to
# bottleneck downloading. Thus, only refresh the output when the
# displayed value should change.
percentage = round(block_count / total_blocks, ndigits=3)
if percentage == self._last_percentage:
return
self._last_percentage = percentage
print('\r' + ' ' * self._max_len_printed, end='')
status_line = 'Progress: {:.1%} of {:,d} B'.format(percentage, total_size)
else:
downloaded_estimate = block_count * block_size
status_line = 'Progress: {:,d} B of unknown size'.format(downloaded_estimate)
self._max_len_printed = len(status_line)
print('\r' + status_line, end='')
def _download_via_urllib(url, file_path, show_progress, disable_ssl_verification):
reporthook = None
if show_progress:
reporthook = _UrlRetrieveReportHook()
if disable_ssl_verification:
import ssl
# TODO: Remove this or properly implement disabling SSL certificate verification
orig_https_context = ssl._create_default_https_context #pylint: disable=protected-access
ssl._create_default_https_context = ssl._create_unverified_context #pylint: disable=protected-access
try:
urllib.request.urlretrieve(url, str(file_path), reporthook=reporthook)
finally:
# Try to reduce damage of hack by reverting original HTTPS context ASAP
if disable_ssl_verification:
ssl._create_default_https_context = orig_https_context #pylint: disable=protected-access
if show_progress:
print()
def _download_if_needed(file_path, url, show_progress, disable_ssl_verification):
"""
Downloads a file from url to the specified path file_path if necessary.
If show_progress is True, download progress is printed to the console.
"""
if file_path.exists():
get_logger().info('%s already exists. Skipping download.', file_path)
return
# File name for partially download file
tmp_file_path = file_path.with_name(file_path.name + '.partial')
if tmp_file_path.exists():
get_logger().debug('Resuming downloading URL %s ...', url)
else:
get_logger().debug('Downloading URL %s ...', url)
# Perform download
if shutil.which('curl'):
get_logger().debug('Using curl')
try:
subprocess.run(['curl', '-L', '-o', str(tmp_file_path), '-C', '-', url], check=True)
except subprocess.CalledProcessError as exc:
get_logger().error('curl failed. Re-run the download command to resume downloading.')
raise exc
else:
get_logger().debug('Using urllib')
_download_via_urllib(url, tmp_file_path, show_progress, disable_ssl_verification)
# Download complete; rename file
tmp_file_path.rename(file_path)
def _chromium_hashes_generator(hashes_path):
with hashes_path.open(encoding=ENCODING) as hashes_file:
hash_lines = hashes_file.read().splitlines()
for hash_name, hash_hex, _ in map(lambda x: x.lower().split(' '), hash_lines):
if hash_name in hashlib.algorithms_available:
yield hash_name, hash_hex
else:
get_logger().warning('Skipping unknown hash algorithm: %s', hash_name)
def _get_hash_pairs(download_properties, cache_dir):
"""Generator of (hash_name, hash_hex) for the given download"""
for entry_type, entry_value in download_properties.hashes.items():
if entry_type == 'hash_url':
hash_processor, hash_filename, _ = entry_value
if hash_processor == 'chromium':
yield from _chromium_hashes_generator(cache_dir / hash_filename)
else:
raise ValueError('Unknown hash_url processor: %s' % hash_processor)
else:
yield entry_type, entry_value
def retrieve_downloads(download_info, cache_dir, show_progress, disable_ssl_verification=False):
"""
Retrieve downloads into the downloads cache.
download_info is the DowloadInfo of downloads to retrieve.
cache_dir is the pathlib.Path to the downloads cache.
show_progress is a boolean indicating if download progress is printed to the console.
disable_ssl_verification is a boolean indicating if certificate verification
should be disabled for downloads using HTTPS.
Raises FileNotFoundError if the downloads path does not exist.
Raises NotADirectoryError if the downloads path is not a directory.
"""
if not cache_dir.exists():
raise FileNotFoundError(cache_dir)
if not cache_dir.is_dir():
raise NotADirectoryError(cache_dir)
for download_name, download_properties in download_info.properties_iter():
get_logger().info('Downloading "%s" to "%s" ...', download_name,
download_properties.download_filename)
download_path = cache_dir / download_properties.download_filename
_download_if_needed(download_path, download_properties.url, show_progress,
disable_ssl_verification)
if download_properties.has_hash_url():
get_logger().info('Downloading hashes for "%s"', download_name)
_, hash_filename, hash_url = download_properties.hashes['hash_url']
_download_if_needed(cache_dir / hash_filename, hash_url, show_progress,
disable_ssl_verification)
def check_downloads(download_info, cache_dir):
"""
Check integrity of the downloads cache.
download_info is the DownloadInfo of downloads to unpack.
cache_dir is the pathlib.Path to the downloads cache.
Raises source_retrieval.HashMismatchError when the computed and expected hashes do not match.
"""
for download_name, download_properties in download_info.properties_iter():
get_logger().info('Verifying hashes for "%s" ...', download_name)
download_path = cache_dir / download_properties.download_filename
with download_path.open('rb') as file_obj:
archive_data = file_obj.read()
for hash_name, hash_hex in _get_hash_pairs(download_properties, cache_dir):
get_logger().debug('Verifying %s hash...', hash_name)
hasher = hashlib.new(hash_name, data=archive_data)
if not hasher.hexdigest().lower() == hash_hex.lower():
raise HashMismatchError(download_path)
def unpack_downloads(download_info, cache_dir, output_dir, extractors=None):
"""
Unpack downloads in the downloads cache to output_dir. Assumes all downloads are retrieved.
download_info is the DownloadInfo of downloads to unpack.
cache_dir is the pathlib.Path directory containing the download cache
output_dir is the pathlib.Path directory to unpack the downloads to.
extractors is a dictionary of PlatformEnum to a command or path to the
extractor binary. Defaults to 'tar' for tar, and '_use_registry' for 7-Zip and WinRAR.
May raise undetermined exceptions during archive unpacking.
"""
for download_name, download_properties in download_info.properties_iter():
download_path = cache_dir / download_properties.download_filename
get_logger().info('Unpacking "%s" to %s ...', download_name,
download_properties.output_path)
extractor_name = download_properties.extractor or ExtractorEnum.TAR
if extractor_name == ExtractorEnum.SEVENZIP:
extractor_func = extract_with_7z
elif extractor_name == ExtractorEnum.WINRAR:
extractor_func = extract_with_winrar
elif extractor_name == ExtractorEnum.TAR:
extractor_func = extract_tar_file
else:
raise NotImplementedError(extractor_name)
if download_properties.strip_leading_dirs is None:
strip_leading_dirs_path = None
else:
strip_leading_dirs_path = Path(download_properties.strip_leading_dirs)
extractor_func(
archive_path=download_path,
output_dir=output_dir / Path(download_properties.output_path),
relative_to=strip_leading_dirs_path,
extractors=extractors)
def _add_common_args(parser):
parser.add_argument(
'-i',
'--ini',
type=Path,
nargs='+',
help='The downloads INI to parse for downloads. Can be specified multiple times.')
parser.add_argument(
'-c', '--cache', type=Path, required=True, help='Path to the directory to cache downloads.')
def _retrieve_callback(args):
retrieve_downloads(
DownloadInfo(args.ini), args.cache, args.show_progress, args.disable_ssl_verification)
try:
check_downloads(DownloadInfo(args.ini), args.cache)
except HashMismatchError as exc:
get_logger().error('File checksum does not match: %s', exc)
sys.exit(1)
def _unpack_callback(args):
extractors = {
ExtractorEnum.SEVENZIP: args.sevenz_path,
ExtractorEnum.WINRAR: args.winrar_path,
ExtractorEnum.TAR: args.tar_path,
}
unpack_downloads(DownloadInfo(args.ini), args.cache, args.output, extractors)
def main():
"""CLI Entrypoint"""
parser = argparse.ArgumentParser(description=__doc__)
add_common_params(parser)
subparsers = parser.add_subparsers(title='Download actions', dest='action')
# retrieve
retrieve_parser = subparsers.add_parser(
'retrieve',
help='Retrieve and check download files',
description=('Retrieves and checks downloads without unpacking. '
'The downloader will attempt to use CLI command "curl". '
'If it is not present, Python\'s urllib will be used. However, only '
'the CLI-based downloaders can be resumed if the download is aborted.'))
_add_common_args(retrieve_parser)
retrieve_parser.add_argument(
'--hide-progress-bar',
action='store_false',
dest='show_progress',
help='Hide the download progress.')
retrieve_parser.add_argument(
'--disable-ssl-verification',
action='store_true',
help='Disables certification verification for downloads using HTTPS.')
retrieve_parser.set_defaults(callback=_retrieve_callback)
# unpack
unpack_parser = subparsers.add_parser(
'unpack',
help='Unpack download files',
description='Verifies hashes of and unpacks download files into the specified directory.')
_add_common_args(unpack_parser)
unpack_parser.add_argument(
'--tar-path',
default='tar',
help=('(Linux and macOS only) Command or path to the BSD or GNU tar '
'binary for extraction. Default: %(default)s'))
unpack_parser.add_argument(
'--7z-path',
dest='sevenz_path',
default=USE_REGISTRY,
help=('Command or path to 7-Zip\'s "7z" binary. If "_use_registry" is '
'specified, determine the path from the registry. Default: %(default)s'))
unpack_parser.add_argument(
'--winrar-path',
dest='winrar_path',
default=USE_REGISTRY,
help=('Command or path to WinRAR\'s "winrar" binary. If "_use_registry" is '
'specified, determine the path from the registry. Default: %(default)s'))
unpack_parser.add_argument('output', type=Path, help='The directory to unpack to.')
unpack_parser.set_defaults(callback=_unpack_callback)
args = parser.parse_args()
args.callback(args)
if __name__ == '__main__':
main()<|fim▁end|>
| |
<|file_name|>feed_parse_extract夢見る世界.py<|end_file_name|><|fim▁begin|>def extract夢見る世界(item):
"""
Parser for '夢見る世界'<|fim▁hole|> if 'Otome Games' in item['tags']:
return None
if 'Drama CDs' in item['tags']:
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
tagmap = [
('Miss Appraiser and Gallery Demon', 'Miss Appraiser and Gallery Demon', 'translated'),
('Light Beyond Road\'s End', 'Light Beyond (LN)', 'translated'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False<|fim▁end|>
|
"""
|
<|file_name|>cache.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from cachy import CacheManager
from cachy.serializers import PickleSerializer<|fim▁hole|>
class Cache(CacheManager):
_serializers = {
'pickle': PickleSerializer()
}<|fim▁end|>
| |
<|file_name|>test_imperative_signal_handler.py<|end_file_name|><|fim▁begin|># Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
import signal
import unittest
import multiprocessing
import time
import paddle.compat as cpt
from paddle.fluid import core
from paddle.fluid.framework import _test_eager_guard
def set_child_signal_handler(self, child_pid):
core._set_process_pids(id(self), tuple([child_pid]))
current_handler = signal.getsignal(signal.SIGCHLD)
if not callable(current_handler):
current_handler = None
def __handler__(signum, frame):
core._throw_error_if_process_failed()
if current_handler is not None:
current_handler(signum, frame)
signal.signal(signal.SIGCHLD, __handler__)
class DygraphDataLoaderSingalHandler(unittest.TestCase):
def func_child_process_exit_with_error(self):
def __test_process__():
core._set_process_signal_handler()
sys.exit(1)
def try_except_exit():
exception = None
try:
test_process = multiprocessing.Process(target=__test_process__)
test_process.start()
set_child_signal_handler(id(self), test_process.pid)
time.sleep(5)
except SystemError as ex:<|fim▁hole|> exception = ex
return exception
try_time = 10
exception = None
for i in range(try_time):
exception = try_except_exit()
if exception is not None:
break
self.assertIsNotNone(exception)
def test_child_process_exit_with_error(self):
with _test_eager_guard():
self.func_child_process_exit_with_error()
self.func_child_process_exit_with_error()
def func_child_process_killed_by_sigsegv(self):
def __test_process__():
core._set_process_signal_handler()
os.kill(os.getpid(), signal.SIGSEGV)
def try_except_exit():
exception = None
try:
test_process = multiprocessing.Process(target=__test_process__)
test_process.start()
set_child_signal_handler(id(self), test_process.pid)
time.sleep(5)
except SystemError as ex:
self.assertIn("Segmentation fault",
cpt.get_exception_message(ex))
exception = ex
return exception
try_time = 10
exception = None
for i in range(try_time):
exception = try_except_exit()
if exception is not None:
break
self.assertIsNotNone(exception)
def test_child_process_killed_by_sigsegv(self):
with _test_eager_guard():
self.func_child_process_killed_by_sigsegv()
self.func_child_process_killed_by_sigsegv()
def func_child_process_killed_by_sigbus(self):
def __test_process__():
core._set_process_signal_handler()
os.kill(os.getpid(), signal.SIGBUS)
def try_except_exit():
exception = None
try:
test_process = multiprocessing.Process(target=__test_process__)
test_process.start()
set_child_signal_handler(id(self), test_process.pid)
time.sleep(5)
except SystemError as ex:
self.assertIn("Bus error", cpt.get_exception_message(ex))
exception = ex
return exception
try_time = 10
exception = None
for i in range(try_time):
exception = try_except_exit()
if exception is not None:
break
self.assertIsNotNone(exception)
def test_child_process_killed_by_sigbus(self):
with _test_eager_guard():
self.func_child_process_killed_by_sigbus()
self.func_child_process_killed_by_sigbus()
def func_child_process_killed_by_sigterm(self):
def __test_process__():
core._set_process_signal_handler()
time.sleep(10)
test_process = multiprocessing.Process(target=__test_process__)
test_process.daemon = True
test_process.start()
set_child_signal_handler(id(self), test_process.pid)
time.sleep(1)
def test_child_process_killed_by_sigterm(self):
with _test_eager_guard():
self.func_child_process_killed_by_sigterm()
self.func_child_process_killed_by_sigterm()
if __name__ == '__main__':
unittest.main()<|fim▁end|>
|
self.assertIn("Fatal", cpt.get_exception_message(ex))
|
<|file_name|>ip.rs<|end_file_name|><|fim▁begin|>use std::borrow::Cow;
use std::net::IpAddr;
use std::str::FromStr;
/// Validates whether the given string is an IP V4
#[must_use]
pub fn validate_ip_v4<'a, T>(val: T) -> bool
where
T: Into<Cow<'a, str>>,
{
IpAddr::from_str(val.into().as_ref()).map_or(false, |i| i.is_ipv4())
}
/// Validates whether the given string is an IP V6
#[must_use]
pub fn validate_ip_v6<'a, T>(val: T) -> bool
where
T: Into<Cow<'a, str>>,
{
IpAddr::from_str(val.into().as_ref()).map_or(false, |i| i.is_ipv6())
}
/// Validates whether the given string is an IP
#[must_use]
pub fn validate_ip<'a, T>(val: T) -> bool
where
T: Into<Cow<'a, str>>,
{
IpAddr::from_str(val.into().as_ref()).is_ok()
}
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use super::{validate_ip, validate_ip_v4, validate_ip_v6};
#[test]
fn test_validate_ip() {
let tests = vec![
("1.1.1.1", true),
("255.0.0.0", true),
("0.0.0.0", true),
("256.1.1.1", false),
("25.1.1.", false),
("25,1,1,1", false),<|fim▁hole|> ("fe80::223:6cff:fe8a:2e8a", true),
("::ffff:254.42.16.14", true),
("2a02::223:6cff :fe8a:2e8a", false),
];
for (input, expected) in tests {
assert_eq!(validate_ip(input), expected);
}
}
#[test]
fn test_validate_ip_cow() {
let test: Cow<'static, str> = "1.1.1.1".into();
assert_eq!(validate_ip(test), true);
let test: Cow<'static, str> = String::from("1.1.1.1").into();
assert_eq!(validate_ip(test), true);
let test: Cow<'static, str> = "2a02::223:6cff :fe8a:2e8a".into();
assert_eq!(validate_ip(test), false);
let test: Cow<'static, str> = String::from("2a02::223:6cff :fe8a:2e8a").into();
assert_eq!(validate_ip(test), false);
}
#[test]
fn test_validate_ip_v4() {
let tests = vec![
("1.1.1.1", true),
("255.0.0.0", true),
("0.0.0.0", true),
("256.1.1.1", false),
("25.1.1.", false),
("25,1,1,1", false),
("25.1 .1.1", false),
("1.1.1.1\n", false),
("٧.2٥.3٣.243", false),
];
for (input, expected) in tests {
assert_eq!(validate_ip_v4(input), expected);
}
}
#[test]
fn test_validate_ip_v4_cow() {
let test: Cow<'static, str> = "1.1.1.1".into();
assert_eq!(validate_ip_v4(test), true);
let test: Cow<'static, str> = String::from("1.1.1.1").into();
assert_eq!(validate_ip_v4(test), true);
let test: Cow<'static, str> = "٧.2٥.3٣.243".into();
assert_eq!(validate_ip_v4(test), false);
let test: Cow<'static, str> = String::from("٧.2٥.3٣.243").into();
assert_eq!(validate_ip_v4(test), false);
}
#[test]
fn test_validate_ip_v6() {
let tests = vec![
("fe80::223:6cff:fe8a:2e8a", true),
("2a02::223:6cff:fe8a:2e8a", true),
("1::2:3:4:5:6:7", true),
("::", true),
("::a", true),
("2::", true),
("::ffff:254.42.16.14", true),
("::ffff:0a0a:0a0a", true),
("::254.42.16.14", true),
("::0a0a:0a0a", true),
("foo", false),
("127.0.0.1", false),
("12345::", false),
("1::2::3::4", false),
("1::zzz", false),
("1:2", false),
("fe80::223: 6cff:fe8a:2e8a", false),
("2a02::223:6cff :fe8a:2e8a", false),
("::ffff:999.42.16.14", false),
("::ffff:zzzz:0a0a", false),
];
for (input, expected) in tests {
assert_eq!(validate_ip_v6(input), expected);
}
}
#[test]
fn test_validate_ip_v6_cow() {
let test: Cow<'static, str> = "fe80::223:6cff:fe8a:2e8a".into();
assert_eq!(validate_ip_v6(test), true);
let test: Cow<'static, str> = String::from("fe80::223:6cff:fe8a:2e8a").into();
assert_eq!(validate_ip_v6(test), true);
let test: Cow<'static, str> = "::ffff:zzzz:0a0a".into();
assert_eq!(validate_ip_v6(test), false);
let test: Cow<'static, str> = String::from("::ffff:zzzz:0a0a").into();
assert_eq!(validate_ip_v6(test), false);
}
}<|fim▁end|>
| |
<|file_name|>bitcoin_nb.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="nb" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About scrypt</source>
<translation>Om scrypt</translation>
</message>
<message>
<location line="+39"/>
<source><b>scrypt</b> version</source>
<translation><b>scrypt</b> versjon</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>
Dette er eksperimentell programvare.
Distribuert under MIT/X11 programvarelisensen, se medfølgende fil COPYING eller http://www.opensource.org/licenses/mit-license.php.
Dette produktet inneholder programvare utviklet av OpenSSL prosjektet for bruk i OpenSSL Toolkit (http://www.openssl.org/) og kryptografisk programvare skrevet av Eric Young ([email protected]) og UPnP programvare skrevet av Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The scrypt developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adressebok</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Dobbeltklikk for å redigere adresse eller merkelapp</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Lag en ny adresse</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopier den valgte adressen til systemets utklippstavle</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Ny Adresse</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your scrypt 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>Dette er dine scrypt-adresser for mottak av betalinger. Du kan gi forskjellige adresser til alle som skal betale deg for å holde bedre oversikt.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Kopier Adresse</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Vis &QR Kode</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a scrypt address</source>
<translation>Signer en melding for å bevise at du eier en scrypt-adresse</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Signér &Melding</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Slett den valgte adressen fra listen.</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Eksporter data fra nåværende fane til fil</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 scrypt address</source>
<translation>Verifiser en melding for å være sikker på at den ble signert av en angitt scrypt-adresse</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verifiser Melding</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Slett</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your scrypt 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>Kopier &Merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Rediger</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Send &Coins</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Eksporter adressebok</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommaseparert fil (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Feil ved eksportering</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kunne ikke skrive til filen %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Merkelapp</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(ingen merkelapp)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Dialog for Adgangsfrase</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Angi adgangsfrase</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Ny adgangsfrase</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Gjenta ny adgangsfrase</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>Skriv inn den nye adgangsfrasen for lommeboken.<br/>Vennligst bruk en adgangsfrase med <b>10 eller flere tilfeldige tegn</b>, eller <b>åtte eller flere ord</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Krypter lommebok</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Denne operasjonen krever adgangsfrasen til lommeboken for å låse den opp.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Lås opp lommebok</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Denne operasjonen krever adgangsfrasen til lommeboken for å dekryptere den.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Dekrypter lommebok</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Endre adgangsfrase</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Skriv inn gammel og ny adgangsfrase for lommeboken.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Bekreft kryptering av lommebok</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR SCRYPTS</b>!</source>
<translation>Advarsel: Hvis du krypterer lommeboken og mister adgangsfrasen, så vil du <b>MISTE ALLE DINE SCRYPTS</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Er du sikker på at du vil kryptere lommeboken?</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>VIKTIG: Tidligere sikkerhetskopier av din lommebok-fil, bør erstattes med den nylig genererte, krypterte filen, da de blir ugyldiggjort av sikkerhetshensyn så snart du begynner å bruke den nye krypterte lommeboken.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Advarsel: Caps Lock er på !</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Lommebok kryptert</translation>
</message>
<message>
<location line="-56"/>
<source>scrypt will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your scrypts from being stolen by malware infecting your computer.</source>
<translation>scrypt vil nå lukkes for å fullføre krypteringsprosessen. Husk at kryptering av lommeboken ikke fullt ut kan beskytte dine scrypts fra å bli stjålet om skadevare infiserer datamaskinen.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Kryptering av lommebok feilet</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Kryptering av lommebok feilet på grunn av en intern feil. Din lommebok ble ikke kryptert.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>De angitte adgangsfrasene er ulike.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Opplåsing av lommebok feilet</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Adgangsfrasen angitt for dekryptering av lommeboken var feil.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Dekryptering av lommebok feilet</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Adgangsfrase for lommebok endret.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Signer &melding...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Synkroniserer med nettverk...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Oversikt</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Vis generell oversikt over lommeboken</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transaksjoner</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Vis transaksjonshistorikk</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Rediger listen over adresser og deres merkelapper</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Vis listen over adresser for mottak av betalinger</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Avslutt</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Avslutt applikasjonen</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about scrypt</source>
<translation>Vis informasjon om scrypt</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Om &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Vis informasjon om Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Innstillinger...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Krypter Lommebok...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>Lag &Sikkerhetskopi av Lommebok...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Endre Adgangsfrase...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Importere blokker...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Re-indekserer blokker på disk...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a scrypt address</source>
<translation>Send til en scrypt-adresse</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for scrypt</source>
<translation>Endre oppsett for scrypt</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Sikkerhetskopiér lommebok til annet sted</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Endre adgangsfrasen brukt for kryptering av lommebok</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Feilsøkingsvindu</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Åpne konsoll for feilsøk og diagnostikk</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Verifiser melding...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>scrypt</source>
<translation>scrypt</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Lommebok</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Send</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Motta</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Adressebok</translation>
</message>
<message>
<location line="+22"/>
<source>&About scrypt</source>
<translation>&Om scrypt</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Gjem / vis</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Vis eller skjul hovedvinduet</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Krypter de private nøklene som tilhører lommeboken din</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your scrypt addresses to prove you own them</source>
<translation>Signér en melding for å bevise at du eier denne adressen</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified scrypt addresses</source>
<translation>Bekreft meldinger for å være sikker på at de ble signert av en angitt scrypt-adresse</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Fil</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Innstillinger</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Hjelp</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Verktøylinje for faner</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnett]</translation>
</message>
<message>
<location line="+47"/>
<source>scrypt client</source>
<translation>scryptklient</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to scrypt network</source>
<translation><numerusform>%n aktiv forbindelse til scrypt-nettverket</numerusform><numerusform>%n aktive forbindelser til scrypt-nettverket</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>Lastet %1 blokker med transaksjonshistorikk.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><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>Transaksjoner etter dette vil ikke være synlige enda.</translation>
</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>Denne transaksjonen overstiger størrelsesbegrensningen. Du kan likevel sende den med et gebyr på %1, som går til nodene som prosesserer transaksjonen din og støtter nettverket. Vil du betale gebyret?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Ajour</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Kommer ajour...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Bekreft transaksjonsgebyr</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Sendt transaksjon</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Innkommende transaksjon</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Dato: %1
Beløp: %2
Type: %3
Adresse: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>URI håndtering</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid scrypt address or malformed URI parameters.</source>
<translation>URI kunne ikke tolkes! Dette kan forårsakes av en ugyldig scrypt-adresse eller feil i URI-parametere.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Lommeboken er <b>kryptert</b> og for tiden <b>ulåst</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Lommeboken er <b>kryptert</b> og for tiden <b>låst</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. scrypt can no longer continue safely and will quit.</source>
<translation>En fatal feil har inntruffet. Det er ikke trygt å fortsette og scrypt må derfor avslutte.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Nettverksvarsel</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Rediger adresse</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Merkelapp</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Merkelappen koblet til denne adressen i adresseboken</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adresse</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>Adressen til denne oppføringen i adresseboken. Denne kan kun endres for utsendingsadresser.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Ny mottaksadresse</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Ny utsendingsadresse</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Rediger mottaksadresse</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Rediger utsendingsadresse</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Den oppgitte adressen "%1" er allerede i adresseboken.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid scrypt address.</source>
<translation>Den angitte adressed "%1" er ikke en gyldig scrypt-adresse.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Kunne ikke låse opp lommeboken.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Generering av ny nøkkel feilet.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>scrypt-Qt</source>
<translation>scrypt-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versjon</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Bruk:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>kommandolinjevalg</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>valg i brukergrensesnitt</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Sett språk, for eksempel "nb_NO" (standardverdi: fra operativsystem)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Start minimert
</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Vis splashskjerm ved oppstart (standardverdi: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Innstillinger</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Hoved</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>Betal transaksjons&gebyr</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start scrypt after logging in to the system.</source>
<translation>Start scrypt automatisk etter innlogging.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start scrypt on system login</source>
<translation>&Start scrypt ved systeminnlogging</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>&Nettverk</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the scrypt client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Åpne automatisk scrypt klientporten på ruteren. Dette virker kun om din ruter støtter UPnP og dette er påslått.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Sett opp port vha. &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the scrypt network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Koble til scrypt-nettverket gjennom en SOCKS proxy (f.eks. ved tilkobling gjennom Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Koble til gjenom SOCKS proxy:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP-adresse for mellomtjener (f.eks. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Proxyens port (f.eks. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Versjon:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Proxyens SOCKS versjon (f.eks. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Vindu</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Vis kun ikon i systemkurv etter minimering av vinduet.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimer til systemkurv istedenfor oppgavelinjen</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>Minimerer vinduet istedenfor å avslutte applikasjonen når vinduet lukkes. Når dette er slått på avsluttes applikasjonen kun ved å velge avslutt i menyen.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimer ved lukking</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Visning</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Språk for brukergrensesnitt</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting scrypt.</source>
<translation>Språket for brukergrensesnittet kan settes her. Innstillingen trer i kraft ved omstart av scrypt.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Enhet for visning av beløper:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Velg standard delt enhet for visning i grensesnittet og for sending av scrypts.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show scrypt addresses in the transaction list or not.</source>
<translation>Om scrypt-adresser skal vises i transaksjonslisten eller ikke.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Vis adresser i transaksjonslisten</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Avbryt</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Bruk</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>standardverdi</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>Advarsel</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting scrypt.</source>
<translation>Denne innstillingen trer i kraft etter omstart av scrypt.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Angitt proxyadresse er ugyldig.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Skjema</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the scrypt network after a connection is established, but this process has not completed yet.</source>
<translation>Informasjonen som vises kan være foreldet. Din lommebok synkroniseres automatisk med scrypt-nettverket etter at tilkobling er opprettet, men denne prosessen er ikke ferdig enda.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Ubekreftet</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Lommebok</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Umoden:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Minet saldo har ikke modnet enda</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Siste transaksjoner</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Din nåværende saldo</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>Totalt antall ubekreftede transaksjoner som ikke telles med i saldo enda</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>ute av synk</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start scrypt: click-to-pay handler</source>
<translation>Kan ikke starte scrypt: klikk-og-betal håndterer</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Dialog for QR Kode</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Etterspør Betaling</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Beløp:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Merkelapp:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Melding:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Lagre Som...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Feil ved koding av URI i QR kode.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Angitt beløp er ugyldig.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Resulterende URI for lang, prøv å redusere teksten for merkelapp / melding.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Lagre QR Kode</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG bilder (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Klientnavn</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>Klientversjon</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informasjon</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Bruker OpenSSL versjon</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Oppstartstidspunkt</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Nettverk</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Antall tilkoblinger</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>På testnett</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blokkjeden</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Nåværende antall blokker</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Estimert totalt antall blokker</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Tidspunkt for siste blokk</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Åpne</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Kommandolinjevalg</translation>
</message>
<message>
<location line="+7"/>
<source>Show the scrypt-Qt help message to get a list with possible scrypt command-line options.</source>
<translation>Vis scrypt-Qt hjelpemelding for å få en liste med mulige kommandolinjevalg.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Vis</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsoll</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Byggedato</translation>
</message>
<message>
<location line="-104"/>
<source>scrypt - Debug window</source>
<translation>scrypt - vindu for feilsøk</translation>
</message>
<message>
<location line="+25"/>
<source>scrypt Core</source>
<translation>scrypt Kjerne</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Loggfil for feilsøk</translation>
</message>
<message>
<location line="+7"/>
<source>Open the scrypt debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Åpne scrypt loggfil for feilsøk fra datamappen. Dette kan ta noen sekunder for store loggfiler.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Tøm konsoll</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the scrypt RPC console.</source>
<translation>Velkommen til scrypt RPC konsoll.</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>Bruk opp og ned pil for å navigere historikken, og <b>Ctrl-L</b> for å tømme skjermen.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Skriv <b>help</b> for en oversikt over kommandoer.</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>Send scrypts</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Send til flere enn én mottaker</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Legg til Mottaker</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Fjern alle transaksjonsfelter</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Fjern &Alt</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Bekreft sending</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>S&end</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> til %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Bekreft sending av scrypts</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Er du sikker på at du vil sende %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> og </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Adresse for mottaker er ugyldig.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Beløpen som skal betales må være over 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Beløpet overstiger saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Totalbeløpet overstiger saldo etter at %1 transaksjonsgebyr er lagt til.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Duplikate adresser funnet. Kan bare sende én gang til hver adresse per operasjon.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Feil: Opprettelse av transaksjon feilet </translation>
</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>Feil: Transaksjonen ble avvist. Dette kan skje om noe av beløpet allerede var brukt, f.eks. hvis du kopierte wallet.dat og noen scrypts ble brukt i kopien men ikke ble markert som brukt her.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Skjema</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>&Beløp:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Betal &Til:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Adressen betalingen skal sendes til (f.eks. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</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>Skriv inn en merkelapp for denne adressen for å legge den til i din adressebok</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Merkelapp:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source><|fim▁hole|> <translation>Velg adresse fra adresseboken</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>Lim inn adresse fra utklippstavlen</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>Fjern denne mottakeren</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a scrypt address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Skriv inn en scrypt adresse (f.eks. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signaturer - Signer / Verifiser en melding</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Signér Melding</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>Du kan signere meldinger med dine adresser for å bevise at du eier dem. Ikke signér vage meldinger da phishing-angrep kan prøve å lure deg til å signere din identitet over til andre. Signér kun fullt detaljerte utsagn som du er enig i.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Adressen for signering av meldingen (f.eks. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Velg en adresse fra adresseboken</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>Lim inn adresse fra utklippstavlen</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>Skriv inn meldingen du vil signere her</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>Kopier valgt signatur til utklippstavle</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this scrypt address</source>
<translation>Signer meldingen for å bevise at du eier denne scrypt-adressen</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>Tilbakestill alle felter for meldingssignering</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Fjern &Alt</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Verifiser Melding</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>Angi adresse for signering, melding (vær sikker på at du kopierer linjeskift, mellomrom, tab, etc. helt nøyaktig) og signatur under for å verifisere meldingen. Vær forsiktig med at du ikke gir signaturen mer betydning enn det som faktisk står i meldingen, for å unngå å bli lurt av såkalte "man-in-the-middle" angrep.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Adressen meldingen var signert med (f.eks. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified scrypt address</source>
<translation>Verifiser meldingen for å være sikker på at den ble signert av den angitte scrypt-adressen</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>Tilbakestill alle felter for meldingsverifikasjon</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a scrypt address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Skriv inn en scrypt adresse (f.eks. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Klikk "Signer Melding" for å generere signatur</translation>
</message>
<message>
<location line="+3"/>
<source>Enter scrypt signature</source>
<translation>Angi scrypt signatur</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Angitt adresse er ugyldig.</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>Vennligst sjekk adressen og prøv igjen.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Angitt adresse refererer ikke til en nøkkel.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Opplåsing av lommebok ble avbrutt.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Privat nøkkel for den angitte adressen er ikke tilgjengelig.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Signering av melding feilet.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Melding signert.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Signaturen kunne ikke dekodes.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Vennligst sjekk signaturen og prøv igjen.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Signaturen passer ikke til meldingen.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Verifikasjon av melding feilet.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Melding verifisert.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The scrypt developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnett]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Åpen til %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/frakoblet</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/ubekreftet</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 bekreftelser</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, kringkast gjennom %n node</numerusform><numerusform>, kringkast gjennom %n noder</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Kilde</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generert</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Fra</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Til</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>egen adresse</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>merkelapp</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Kredit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>blir moden om %n blokk</numerusform><numerusform>blir moden om %n blokker</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>ikke akseptert</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debet</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transaksjonsgebyr</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Nettobeløp</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Melding</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Kommentar</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Transaksjons-ID</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 4 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>Genererte scrypts må modnes 4 blokker før de kan brukes. Da du genererte denne blokken ble den kringkastet til nettverket for å legges til i blokkjeden. Hvis den ikke kommer inn i kjeden får den tilstanden "ikke akseptert" og vil ikke kunne brukes. Dette skjer noen ganger hvis en annen node genererer en blokk noen sekunder fra din.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Informasjon for feilsøk</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaksjon</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Inndata</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>sann</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>usann</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, har ikke blitt kringkastet uten problemer enda.</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>ukjent</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transaksjonsdetaljer</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Her vises en detaljert beskrivelse av transaksjonen</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Åpen til %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Frakoblet (%1 bekreftelser)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Ubekreftet (%1 av %2 bekreftelser)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Bekreftet (%1 bekreftelser)</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>Minet saldo blir tilgjengelig når den modner om %n blokk</numerusform><numerusform>Minet saldo blir tilgjengelig når den modner om %n blokker</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>Denne blokken har ikke blitt mottatt av noen andre noder og vil sannsynligvis ikke bli akseptert!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generert men ikke akseptert</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Mottatt med</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Mottatt fra</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Sendt til</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Betaling til deg selv</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Utvunnet</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>Transaksjonsstatus. Hold muspekeren over dette feltet for å se antall bekreftelser.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Dato og tid for da transaksjonen ble mottat.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Type transaksjon.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Mottaksadresse for transaksjonen</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Beløp fjernet eller lagt til saldo.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Alle</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>I dag</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Denne uken</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Denne måneden</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Forrige måned</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Dette året</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Intervall...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Mottatt med</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Sendt til</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Til deg selv</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Utvunnet</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Andre</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Skriv inn adresse eller merkelapp for søk</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minimumsbeløp</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopier adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopier merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopiér beløp</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Kopier transaksjons-ID</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Rediger merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Vis transaksjonsdetaljer</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Eksporter transaksjonsdata</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommaseparert fil (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Bekreftet</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Feil ved eksport</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kunne ikke skrive til filen %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Intervall:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>til</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Send scrypts</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>Eksporter data fra nåværende fane til fil</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Sikkerhetskopier lommebok</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Lommebokdata (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Sikkerhetskopiering feilet</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>En feil oppstod under lagringen av lommeboken til den nye plasseringen.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Sikkerhetskopiering fullført</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Lommebokdata ble lagret til den nye plasseringen. </translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>scrypt version</source>
<translation>scrypt versjon</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Bruk:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or scryptd</source>
<translation>Send kommando til -server eller scryptd</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>List opp kommandoer</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Vis hjelpetekst for en kommando</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Innstillinger:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: scrypt.conf)</source>
<translation>Angi konfigurasjonsfil (standardverdi: scrypt.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: scryptd.pid)</source>
<translation>Angi pid-fil (standardverdi: scryptd.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Angi mappe for datafiler</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Sett størrelse på mellomlager for database i megabytes (standardverdi: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 7461 or testnet: 17461)</source>
<translation>Lytt etter tilkoblinger på <port> (standardverdi: 7461 eller testnet: 17461)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Hold maks <n> koblinger åpne til andre noder (standardverdi: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Koble til node for å hente adresser til andre noder, koble så fra igjen</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Angi din egen offentlige adresse</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Grenseverdi for å koble fra noder med dårlig oppførsel (standardverdi: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Antall sekunder noder med dårlig oppførsel hindres fra å koble til på nytt (standardverdi: 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>En feil oppstod ved opprettelse av RPC port %u for lytting: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 7462 or testnet: 17462)</source>
<translation>Lytt etter JSON-RPC tilkoblinger på <port> (standardverdi: 7462 or testnet: 17462)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Ta imot kommandolinje- og JSON-RPC-kommandoer</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Kjør i bakgrunnen som daemon og ta imot kommandoer</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Bruk testnettverket</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Ta imot tilkoblinger fra utsiden (standardverdi: 1 hvis uten -proxy eller -connect)</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=scryptrpc
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 "scrypt Alert" [email protected]
</source>
<translation>%s, du må angi rpcpassord i konfigurasjonsfilen.
%s
Det anbefales at du bruker det følgende tilfeldige passordet:
rpcbruker=scryptrpc
rpcpassord=%s
(du behøver ikke å huske passordet)
Brukernavnet og passordet MÅ IKKE være like.
Om filen ikke eksisterer, opprett den nå med eier-kun-les filrettigheter.
Det er også anbefalt at å sette varselsmelding slik du får melding om problemer.
For eksempel: varselmelding=echo %%s | mail -s "scrypt varsel" [email protected]</translation>
</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>En feil oppstod under oppsettet av RPC port %u for IPv6, tilbakestilles til IPv4: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Bind til angitt adresse. Bruk [vertsmaskin]:port notasjon for IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. scrypt 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>Kjør kommando når relevant varsel blir mottatt (%s i cmd er erstattet med TxID)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Kjør kommando når en lommeboktransaksjon endres (%s i cmd er erstattet med TxID)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Sett maks størrelse for transaksjoner med høy prioritet / lavt gebyr, i bytes (standardverdi: 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>Advarsel: -paytxfee er satt veldig høyt! Dette er transaksjonsgebyret du betaler når du sender transaksjoner.</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>Advarsel: Viste transaksjoner kan være feil! Du, eller andre noder, kan trenge en oppgradering.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong scrypt will not work properly.</source>
<translation>Advarsel: Vennligst undersøk at din datamaskin har riktig dato og klokkeslett! Hvis klokken er stilt feil vil ikke scrypt fungere riktig.</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>Valg for opprettelse av blokker:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Koble kun til angitt(e) node(r)</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Oppdaget korrupt blokkdatabase</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Oppdag egen IP-adresse (standardverdi: 1 ved lytting og uten -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Ønsker du å gjenopprette blokkdatabasen nå?</translation>
</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>Feil under oppstart av lommebokdatabasemiljø %s!</translation>
</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>Feil under åpning av blokkdatabase</translation>
</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>Kunne ikke lytte på noen port. Bruk -listen=0 hvis det er dette du vil.</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>Finn andre noder gjennom DNS-oppslag (standardverdi: 1 med mindre -connect er oppgit)</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>Gjenopprett blokkjedeindex fra blk000??.dat filer</translation>
</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>Verifiserer blokker...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Verifiserer lommebok...</translation>
</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>Ugyldig -tor adresse: '%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>Maks mottaksbuffer per forbindelse, <n>*1000 bytes (standardverdi: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maks sendebuffer per forbindelse, <n>*1000 bytes (standardverdi: 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>Koble kun til noder i nettverket <nett> (IPv4, IPv6 eller Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Skriv ekstra informasjon for feilsøk. Medfører at alle -debug* valg tas med</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Skriv ekstra informasjon for feilsøk av nettverk</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Sett tidsstempel på debugmeldinger</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the scrypt Wiki for SSL setup instructions)</source>
<translation>SSL valg: (se scrypt Wiki for instruksjoner for oppsett av SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Velg versjon av socks proxy (4-5, standardverdi 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Send spor/debug informasjon til konsollet istedenfor debug.log filen</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Send spor/debug informasjon til debugger</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Sett maks blokkstørrelse i bytes (standardverdi: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Sett minimum blokkstørrelse i bytes (standardverdi: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Krymp debug.log filen når klienten starter (standardverdi: 1 hvis uten -debug)</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>Angi tidsavbrudd for forbindelse i millisekunder (standardverdi: 5000)</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>Bruk UPnP for lytteport (standardverdi: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Bruk UPnP for lytteport (standardverdi: 1 ved lytting)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Bruk en proxy for å nå skjulte tor tjenester (standardverdi: samme som -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Brukernavn for JSON-RPC forbindelser</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>Advarsel: Denne versjonen er foreldet, oppgradering kreves!</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>Passord for JSON-RPC forbindelser</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Tillat JSON-RPC tilkoblinger fra angitt IP-adresse</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Send kommandoer til node på <ip> (standardverdi: 127.0.0.1)</translation>
</message>
<message>
<location line="-4"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Eksekvér kommando når beste blokk endrer seg (%s i kommandoen erstattes med blokkens hash)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Oppgradér lommebok til nyeste format</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Angi størrelse på nøkkel-lager til <n> (standardverdi: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Se gjennom blokk-kjeden etter manglende lommeboktransaksjoner</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Bruk OpenSSL (https) for JSON-RPC forbindelser</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Servers sertifikat (standardverdi: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Servers private nøkkel (standardverdi: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Akseptable krypteringsmetoder (standardverdi: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Denne hjelpemeldingen</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Kan ikke binde til %s på denne datamaskinen (bind returnerte feil %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Koble til gjennom socks proxy</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Tillat DNS oppslag for -addnode, -seednode og -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Laster adresser...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Feil ved lasting av wallet.dat: Lommeboken er skadet</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of scrypt</source>
<translation>Feil ved lasting av wallet.dat: Lommeboken krever en nyere versjon av scrypt</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart scrypt to complete</source>
<translation>Lommeboken måtte skrives om: start scrypt på nytt for å fullføre</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Feil ved lasting av wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Ugyldig -proxy adresse: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Ukjent nettverk angitt i -onlynet '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Ukjent -socks proxy versjon angitt: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Kunne ikke slå opp -bind adresse: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Kunne ikke slå opp -externalip adresse: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Ugyldig beløp for -paytxfee=<beløp>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Ugyldig beløp</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Utilstrekkelige midler</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Laster blokkindeks...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Legg til node for tilkobling og hold forbindelsen åpen</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. scrypt is probably already running.</source>
<translation>Kan ikke binde til %s på denne datamaskinen. Sannsynligvis kjører scrypt allerede.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Gebyr per KB for transaksjoner du sender</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Laster lommebok...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Kan ikke nedgradere lommebok</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Kan ikke skrive standardadresse</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Leser gjennom...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Ferdig med lasting</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>For å bruke %s opsjonen</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Feil</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>Du må sette rpcpassword=<passord> i konfigurasjonsfilen:
%s
Hvis filen ikke finnes, opprett den med leserettighet kun for eier av filen.</translation>
</message>
</context>
</TS><|fim▁end|>
| |
<|file_name|>content_plugins.py<|end_file_name|><|fim▁begin|>"""
Definition of the plugin.
"""
from django.utils.translation import ugettext_lazy as _
from fluent_contents.extensions import ContentPlugin, plugin_pool
from . import models<|fim▁hole|>@plugin_pool.register
class LocationPlugin(ContentPlugin):
model = models.LocationItem
category = _('Assets')
render_template = 'icekit/plugins/location/item.html'
raw_id_fields = ['location', ]<|fim▁end|>
| |
<|file_name|>history_test.go<|end_file_name|><|fim▁begin|>/*
* Trap
* An anti-pryer server for better privacy
*
* This file is a part of Trap project
*
* Copyright 2016 Rain Lee <[email protected]>
*
* 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 server
import (
"github.com/raincious/trap/trap/core/types"
"testing"
"time"
)
func TestHistoriesGetSlot(t *testing.T) {
currentTime := time.Now()
histories := Histories{}
// Test to add invalid amount of items, it should loops around and
// not cause any problem of that
for i := types.Int64(1); i <= HISTORY_LENGTH*2; i++ {
record := histories.GetSlot(
currentTime.Add(-(time.Duration(i) * time.Hour)))
if record.Hours != i+1 {
t.Errorf("Histories.GetSlot() can't create slot correctly. "+
"Expecting 'Hours' to be '%d', got '%d'",
i, record.Hours)
return
}
if record.Marked != 0 {
t.Errorf("Histories.GetSlot() can't create slot correctly. "+
"Expecting 'Marked' to be '%d', got '%d'",
0, record.Marked)
return
}
if record.Inbound != 0 {
t.Errorf("Histories.GetSlot() can't create slot correctly. "+
"Expecting 'Inbound' to be '%d', got '%d'",
0, record.Inbound)
return
}
if record.Hit != 0 {
t.Errorf("Histories.GetSlot() can't create slot correctly. "+
"Expecting 'Hit' to be '%d', got '%d'",
0, record.Hit)
return
}
}
if types.Int64(len(histories.Histories())) != HISTORY_LENGTH {
t.Error("Histories.GetSlot() creates unexpected amount of items")
return
}
}
func TestHistoriesHistories(t *testing.T) {
currentTime := time.Now()
histories := Histories{}
if types.Int64(len(histories.Histories())) != 0 {
t.Error("Histories.Histories() exports unexpected amount of items")
return
}
histories.GetSlot(currentTime.Add(-(1 * time.Hour)))
if types.Int64(len(histories.Histories())) != 1 {
t.Error("Histories.Histories() exports unexpected amount of items")
return
}<|fim▁hole|> -(time.Duration(HISTORY_LENGTH+1) * time.Hour)))
if types.Int64(len(histories.Histories())) != 1 {
t.Error("Histories.Histories() exports unexpected amount of items")
return
}
// More one more step, we should now have to items exported
histories.GetSlot(currentTime.Add(
-(time.Duration(HISTORY_LENGTH+2) * time.Hour)))
if types.Int64(len(histories.Histories())) != 2 {
t.Error("Histories.Histories() exports unexpected amount of items")
return
}
// And we should actually be able to get the item at the 2 hour slot
// in every each circles
histories.GetSlot(currentTime.Add(-(2 * time.Hour)))
// No new item created (still export 2 items)
if types.Int64(len(histories.Histories())) != 2 {
t.Error("Histories.Histories() exports unexpected amount of items")
return
}
}<|fim▁end|>
|
// Loop it back, we should get the same data as we created earlier on
histories.GetSlot(currentTime.Add(
|
<|file_name|>environ.rs<|end_file_name|><|fim▁begin|>use std::env;
use std::collections::BTreeSet;
use regex::{Regex, escape};
use failure::{Error, err_msg, ResultExt};
use crate::config::read_settings::MergedSettings;
<|fim▁hole|> for item in patterns {
if var_pattern.len() > 0 {
var_pattern.push('|');
}
var_pattern.push('^');
var_pattern.push_str(&escape(item).replace(r"\*", ".*"));
var_pattern.push('$');
}
debug!("Propagation pattern: {:?}", var_pattern);
Ok(Regex::new(&var_pattern)?)
}
pub fn set_initial_vaggaenv_vars(
propagate_env: Vec<String>, set_env: Vec<String>,
settings: &MergedSettings)
-> Result<(), Error>
{
for k in propagate_env.into_iter() {
if k.chars().find(|&c| c == '=').is_some() {
return Err(err_msg("Environment variable name \
(for option `-e`/`--use-env`) \
can't contain equals `=` character. \
To set key-value pair use `-E`/`--environ` option"));
} else {
env::set_var(&("VAGGAENV_".to_string() + &k[..]),
env::var_os(&k).unwrap_or(From::from("")));
}
}
for pair in set_env.into_iter() {
let mut pairiter = pair[..].splitn(2, '=');
let key = "VAGGAENV_".to_string() + pairiter.next().unwrap();
if let Some(value) = pairiter.next() {
env::set_var(&key, value.to_string());
} else {
env::remove_var(&key);
}
}
if settings.propagate_environ.len() > 0 {
let regex = patterns_to_regex(&settings.propagate_environ)
.context("can't compile propagate-environ patterns")?;
for (key, value) in env::vars() {
if regex.is_match(&key) {
let key = "VAGGAENV_".to_string() + &key;
if env::var_os(&key).is_some() {
continue;
}
env::set_var(key, value);
}
}
}
Ok(())
}<|fim▁end|>
|
fn patterns_to_regex(patterns: &BTreeSet<String>) -> Result<Regex, Error> {
let mut var_pattern = String::with_capacity(100);
|
<|file_name|>patch_4.py<|end_file_name|><|fim▁begin|># Copyright 2008-2015 Canonical<|fim▁hole|># 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/>.
#
# For further info, check http://launchpad.net/filesync-server
"""Add db_worker_unseen table to keep track of unseen items on the database
side.
"""
SQL = [
"""
CREATE TABLE txlog.db_worker_unseen (
id INTEGER NOT NULL,
worker_id TEXT NOT NULL,
created TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT \
timezone('UTC'::text, now())
)
""",
"""
GRANT SELECT, INSERT, UPDATE, DELETE
ON TABLE txlog.db_worker_unseen
TO storage, webapp
""",
"""
CREATE INDEX db_worker_unseen_idx
ON txlog.db_worker_unseen(worker_id, created, id)
"""
]
def apply(store):
"""Apply the patch"""
for statement in SQL:
store.execute(statement)<|fim▁end|>
|
#
# 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
|
<|file_name|>ActionListenerSettingsControl.java<|end_file_name|><|fim▁begin|>package de.turnierverwaltung.control.settingsdialog;
import java.awt.Dialog;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.sql.SQLException;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import de.turnierverwaltung.control.ExceptionHandler;
import de.turnierverwaltung.control.MainControl;
import de.turnierverwaltung.control.Messages;
import de.turnierverwaltung.control.PropertiesControl;
import de.turnierverwaltung.control.ratingdialog.DWZListToSQLITEControl;
import de.turnierverwaltung.control.ratingdialog.ELOListToSQLITEControl;
import de.turnierverwaltung.control.sqlite.SaveTournamentControl;
import de.turnierverwaltung.model.TournamentConstants;
import de.turnierverwaltung.view.settingsdialog.SettingsView;
import say.swing.JFontChooser;
public class ActionListenerSettingsControl {
private final MainControl mainControl;
private final SettingsControl esControl;
private JDialog dialog;
public ActionListenerSettingsControl(final MainControl mainControl, final SettingsControl esControl) {
super();
this.mainControl = mainControl;
this.esControl = esControl;
addPropertiesActionListener();
}
public void addActionListeners() {
esControl.getEigenschaftenView().getFontChooserButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JFontChooser fontChooser = esControl.getEigenschaftenView().getFontChooser();
fontChooser.setSelectedFont(mainControl.getPropertiesControl().getFont());
final int result = fontChooser.showDialog(esControl.getEigenschaftenView());
if (result == JFontChooser.OK_OPTION) {
final Font selectedFont = fontChooser.getSelectedFont();
MainControl.setUIFont(selectedFont);
mainControl.getPropertiesControl().setFont(selectedFont);
mainControl.getPropertiesControl().writeProperties();
}
}
});
esControl.getEigenschaftenView().getOkButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent arg0) {
mainControl.getPropertiesControl().writeSettingsDialogProperties(dialog.getBounds().x,
dialog.getBounds().y, dialog.getBounds().width, dialog.getBounds().height);
dialog.dispose();
final PropertiesControl ppC = mainControl.getPropertiesControl();
final SettingsView settingsView = esControl.getEigenschaftenView();
ppC.setTableComumnBlack(settingsView.getBlackTextField().getText());
ppC.setTableComumnWhite(settingsView.getWhiteTextField().getText());
ppC.setTableComumnMeeting(settingsView.getMeetingTextField().getText());
ppC.setTableComumnNewDWZ(settingsView.getNewDWZTextField().getText());
ppC.setTableComumnOldDWZ(settingsView.getOldDWZTextField().getText());
ppC.setTableComumnNewELO(settingsView.getNewELOTextField().getText());
ppC.setTableComumnOldELO(settingsView.getOldELOTextField().getText());
ppC.setTableComumnPlayer(settingsView.getPlayerTextField().getText());
ppC.setTableComumnPoints(settingsView.getPointsTextField().getText());
ppC.setTableComumnRanking(settingsView.getRankingTextField().getText());
ppC.setTableComumnResult(settingsView.getResultTextField().getText());
ppC.setTableComumnSonnebornBerger(settingsView.getSbbTextField().getText());
ppC.setTableComumnRound(settingsView.getRoundTextField().getText());
ppC.setSpielfrei(settingsView.getSpielfreiTextField().getText());
if (mainControl.getPlayerListControl() != null) {
mainControl.getPlayerListControl().testPlayerListForDoubles();
}
ppC.setCutForename(settingsView.getForenameLengthBox().getValue());
ppC.setCutSurname(settingsView.getSurnameLengthBox().getValue());
ppC.setWebserverPath(settingsView.getWebserverPathTextField().getText());
ppC.checkCrossTableColumnForDoubles();
ppC.checkMeetingTableColumnForDoubles();
ppC.setCSSTable(settingsView.getTableCSSTextField().getText());
ppC.writeProperties();
esControl.setTableColumns();
}
});
esControl.getEigenschaftenView().getOpenVereineCSVButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
// vereine.csv
final File path = new File(mainControl.getPropertiesControl().getDefaultPath());
final JFileChooser fc = new JFileChooser(path);
final FileFilter filter = new FileNameExtensionFilter("CSV file", "csv", "CSV");
fc.setFileFilter(filter);
final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView());
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File file = fc.getSelectedFile();
// This is where a real application would open the
// file.
mainControl.getPropertiesControl().setPathToVereineCVS(file.getAbsolutePath());
mainControl.getPropertiesControl().writeProperties();
esControl.getEigenschaftenView()
.setOpenVereineCSVLabel(mainControl.getPropertiesControl().getPathToVereineCVS());
}
}
});
esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent arg0) {
final DWZListToSQLITEControl dwzL = new DWZListToSQLITEControl(mainControl);
dwzL.convertDWZListToSQLITE();
esControl.getEigenschaftenView()
.setOpenPlayersCSVLabel(mainControl.getPropertiesControl().getPathToPlayersCSV());
esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false);
}
});
esControl.getEigenschaftenView().getOpenPlayersCSVButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
// spieler.csv
final File path = new File(mainControl.getPropertiesControl().getDefaultPath());
final JFileChooser fc = new JFileChooser(path);
final FileFilter filter = new FileNameExtensionFilter("CSV or SQLite file", "csv", "CSV", "sqlite",
"SQLite");
fc.setFileFilter(filter);
final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView());
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File file = fc.getSelectedFile();
// This is where a real application would open the
// file.
mainControl.getPropertiesControl().setPathToPlayersCSV(file.getAbsolutePath());
mainControl.getPropertiesControl().writeProperties();
esControl.getEigenschaftenView()
.setOpenPlayersCSVLabel(mainControl.getPropertiesControl().getPathToPlayersCSV());
final String filename = file.getName();
final int positionEXT = filename.lastIndexOf('.');
if (positionEXT > 0) {
final String newFile = filename.substring(positionEXT);
if (newFile.equals(".sqlite")) {
esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false);
} else {
esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(true);
}
}
}
}
});
esControl.getEigenschaftenView().getConvertELOToSQLITEButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent arg0) {
final ELOListToSQLITEControl eloL = new ELOListToSQLITEControl(mainControl);
eloL.convertELOListToSQLITE();
esControl.getEigenschaftenView()
.setOpenPlayersELOLabel(mainControl.getPropertiesControl().getPathToPlayersELO());
esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false);
}
});
esControl.getEigenschaftenView().getOpenPlayersELOButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
// spieler.csv
final File path = new File(mainControl.getPropertiesControl().getDefaultPath());
final JFileChooser fc = new JFileChooser(path);
final FileFilter filter = new FileNameExtensionFilter("TXT or SQLite file", "txt", "TXT", "sqlite",
"SQLite");
fc.setFileFilter(filter);
final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView());
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File file = fc.getSelectedFile();
// This is where a real application would open the
// file.
mainControl.getPropertiesControl().setPathToPlayersELO(file.getAbsolutePath());
mainControl.getPropertiesControl().writeProperties();
esControl.getEigenschaftenView()
.setOpenPlayersELOLabel(mainControl.getPropertiesControl().getPathToPlayersELO());
final String filename = file.getName();
final int positionEXT = filename.lastIndexOf('.');
if (positionEXT > 0) {
final String newFile = filename.substring(positionEXT);
if (newFile.equals(".sqlite")) {
esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false);
} else {
esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(true);
}
}
}
}
});
esControl.getEigenschaftenView().getOpenDefaultPathButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final File path = new File(mainControl.getPropertiesControl().getDefaultPath());
final JFileChooser fc = new JFileChooser(path);
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setMultiSelectionEnabled(false);
final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView());
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File file = fc.getSelectedFile();
// This is where a real application would open the
// file.
mainControl.getPropertiesControl().setDefaultPath(file.getAbsolutePath());
mainControl.getPropertiesControl().writeProperties();
esControl.getEigenschaftenView()
.setOpenDefaultPathLabel(mainControl.getPropertiesControl().getDefaultPath());
}
}
});
esControl.getEigenschaftenView()
.setOpenVereineCSVLabel(mainControl.getPropertiesControl().getPathToVereineCVS());
esControl.getEigenschaftenView()
.setOpenPlayersCSVLabel(mainControl.getPropertiesControl().getPathToPlayersCSV());
esControl.getEigenschaftenView()
.setOpenPlayersELOLabel(mainControl.getPropertiesControl().getPathToPlayersELO());
esControl.getEigenschaftenView().getGermanLanguageCheckBox().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
mainControl.getLanguagePropertiesControl().setLanguageToGerman();
mainControl.getPropertiesControl().writeProperties();
}
});
esControl.getEigenschaftenView().getEnglishLanguageCheckBox().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {<|fim▁hole|> });
esControl.getEigenschaftenView().getSpielerListeAuswahlBox().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final int anzahlProTab = esControl.getEigenschaftenView().getSpielerListeAuswahlBox()
.getSelectedIndex();
mainControl.getPropertiesControl().setSpielerProTab(anzahlProTab);
mainControl.getPropertiesControl().writeProperties();
}
});
esControl.getEigenschaftenView().getTurnierListeAuswahlBox().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent arg0) {
final int anzahlProTab = esControl.getEigenschaftenView().getTurnierListeAuswahlBox()
.getSelectedIndex();
mainControl.getPropertiesControl().setTurniereProTab(anzahlProTab);
mainControl.getPropertiesControl().writeProperties();
}
});
String filename = mainControl.getPropertiesControl().getPathToPlayersELO();
int positionEXT = filename.lastIndexOf('.');
if (positionEXT > 0) {
final String newFile = filename.substring(positionEXT);
if (newFile.equals(".sqlite")) {
esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false);
} else {
esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(true);
}
} else {
esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false);
}
filename = mainControl.getPropertiesControl().getPathToPlayersCSV();
positionEXT = filename.lastIndexOf('.');
if (positionEXT > 0) {
final String newFile = filename.substring(positionEXT);
if (newFile.equals(".sqlite")) {
esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false);
} else {
esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(true);
}
} else {
esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false);
}
esControl.getEigenschaftenView().getResetPropertiesButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final int abfrage = beendenHinweis();
if (abfrage > 0) {
if (mainControl.getHauptPanel().getTabCount() == TournamentConstants.TAB_ACTIVE_TOURNAMENT + 1) {
if (mainControl.getChangedGames().isEmpty() == false) {
final SaveTournamentControl saveTournament = new SaveTournamentControl(mainControl);
try {
saveTournament.saveChangedPartien();
} catch (final SQLException e1) {
final ExceptionHandler eh = new ExceptionHandler(mainControl);
eh.fileSQLError(e1.getMessage());
}
}
}
}
mainControl.getPropertiesControl().resetProperties();
mainControl.getPropertiesControl().writeProperties();
JOptionPane.showMessageDialog(null, Messages.getString("EigenschaftenControl.29"),
Messages.getString("EigenschaftenControl.28"), JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
});
}
private void addPropertiesActionListener() {
mainControl.getNaviView().getPropertiesButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent arg0) {
mainControl.getSettingsControl().setEigenschaftenView(new SettingsView());
final SettingsView eigenschaftenView = mainControl.getSettingsControl().getEigenschaftenView();
mainControl.getSettingsControl().setItemListenerControl(
new ItemListenerSettingsControl(mainControl, mainControl.getSettingsControl()));
mainControl.getSettingsControl().getItemListenerControl().addItemListeners();
if (dialog == null) {
dialog = new JDialog();
} else {
dialog.dispose();
dialog = new JDialog();
}
// dialog.setAlwaysOnTop(true);
dialog.getContentPane().add(eigenschaftenView);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setBounds(mainControl.getPropertiesControl().getSettingsDialogX(),
mainControl.getPropertiesControl().getSettingsDialogY(),
mainControl.getPropertiesControl().getSettingsDialogWidth(),
mainControl.getPropertiesControl().getSettingsDialogHeight());
dialog.setEnabled(true);
if (mainControl.getPropertiesControl() == null) {
mainControl.setPropertiesControl(new PropertiesControl(mainControl));
}
final PropertiesControl ppC = mainControl.getPropertiesControl();
ppC.readProperties();
eigenschaftenView.getCheckBoxHeaderFooter().setSelected(ppC.getOnlyTables());
eigenschaftenView.getCheckBoxohneDWZ().setSelected(ppC.getNoDWZ());
eigenschaftenView.getCheckBoxohneFolgeDWZ().setSelected(ppC.getNoFolgeDWZ());
eigenschaftenView.getCheckBoxohneELO().setSelected(ppC.getNoELO());
eigenschaftenView.getCheckBoxohneFolgeELO().setSelected(ppC.getNoFolgeELO());
eigenschaftenView.getSpielerListeAuswahlBox().setSelectedIndex(ppC.getSpielerProTab());
eigenschaftenView.getTurnierListeAuswahlBox().setSelectedIndex(ppC.getTurniereProTab());
eigenschaftenView.getForenameLengthBox().setValue(ppC.getCutForename());
eigenschaftenView.getSurnameLengthBox().setValue(ppC.getCutSurname());
eigenschaftenView.getWebserverPathTextField().setText(ppC.getWebserverPath());
// eigenschaftenView.getCheckBoxohneDWZ().setSelected(ppC.getNoDWZ());
eigenschaftenView.getCheckBoxhtmlToClipboard().setSelected(ppC.gethtmlToClipboard());
if (eigenschaftenView.getCheckBoxohneDWZ().isSelected() == true) {
eigenschaftenView.getCheckBoxohneFolgeDWZ().setSelected(true);
eigenschaftenView.getCheckBoxohneFolgeDWZ().setEnabled(false);
ppC.setNoFolgeDWZ(true);
}
if (eigenschaftenView.getCheckBoxohneELO().isSelected() == true) {
eigenschaftenView.getCheckBoxohneFolgeELO().setSelected(true);
eigenschaftenView.getCheckBoxohneFolgeELO().setEnabled(false);
ppC.setNoFolgeELO(true);
}
eigenschaftenView.getCheckBoxPDFLinks().setSelected(ppC.getPDFLinks());
eigenschaftenView.getWebserverPathTextField().setEnabled(ppC.getPDFLinks());
if (mainControl.getPropertiesControl().getLanguage().equals("german")) { //$NON-NLS-1$
eigenschaftenView.getGermanLanguageCheckBox().setSelected(true);
eigenschaftenView.getEnglishLanguageCheckBox().setSelected(false);
mainControl.getLanguagePropertiesControl().setLanguageToGerman();
} else if (mainControl.getPropertiesControl().getLanguage().equals("english")) { //$NON-NLS-1$
eigenschaftenView.getGermanLanguageCheckBox().setSelected(false);
eigenschaftenView.getEnglishLanguageCheckBox().setSelected(true);
mainControl.getLanguagePropertiesControl().setLanguageToEnglish();
}
eigenschaftenView.setOpenDefaultPathLabel(ppC.getDefaultPath());
eigenschaftenView.getTableCSSTextField().setText(ppC.getCSSTable());
esControl.setTableColumns();
addActionListeners();
esControl.getItemListenerControl().addItemListeners();
dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
dialog.setVisible(true);
}
});
}
private int beendenHinweis() {
int abfrage = 0;
if (mainControl.getHauptPanel().getTabCount() == TournamentConstants.TAB_ACTIVE_TOURNAMENT + 1) {
if (mainControl.getChangedGames().isEmpty() == false) {
final String hinweisText = Messages.getString("NaviController.21") //$NON-NLS-1$
+ Messages.getString("NaviController.22") //$NON-NLS-1$
+ Messages.getString("NaviController.33"); //$NON-NLS-1$
abfrage = 1;
// Custom button text
final Object[] options = { Messages.getString("NaviController.24"), //$NON-NLS-1$
Messages.getString("NaviController.25") }; //$NON-NLS-1$
abfrage = JOptionPane.showOptionDialog(mainControl, hinweisText,
Messages.getString("NaviController.26"), //$NON-NLS-1$
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]);
}
}
return abfrage;
}
}<|fim▁end|>
|
mainControl.getLanguagePropertiesControl().setLanguageToEnglish();
mainControl.getPropertiesControl().writeProperties();
}
|
<|file_name|>messagetcp.go<|end_file_name|><|fim▁begin|>package coap
import (
"encoding/binary"
"errors"
"io"
)
// TcpMessage is a CoAP Message that can encode itself for TCP
// transport.
type TcpMessage struct {
Message
}
func (m *TcpMessage) MarshalBinary() ([]byte, error) {
bin, err := m.Message.MarshalBinary()
if err != nil {
return nil, err
}
/*
A CoAP TCP message looks like:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Message Length |Ver| T | TKL | Code |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<|fim▁hole|> | Options (if any) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|1 1 1 1 1 1 1 1| Payload (if any) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
l := []byte{0, 0}
binary.BigEndian.PutUint16(l, uint16(len(bin)))
return append(l, bin...), nil
}
func (m *TcpMessage) UnmarshalBinary(data []byte) error {
if len(data) < 4 {
return errors.New("short packet")
}
return m.Message.UnmarshalBinary(data)
}
// Decode reads a single message from its input.
func Decode(r io.Reader) (*TcpMessage, error) {
var ln uint16
err := binary.Read(r, binary.BigEndian, &ln)
if err != nil {
return nil, err
}
packet := make([]byte, ln)
_, err = io.ReadFull(r, packet)
if err != nil {
return nil, err
}
m := TcpMessage{}
err = m.UnmarshalBinary(packet)
return &m, err
}<|fim▁end|>
|
| Token (if any, TKL bytes) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
<|file_name|>Details.test.tsx<|end_file_name|><|fim▁begin|>import React from 'react';
import { render, waitForElement } from 'react-testing-library';
import FakeDataProvider from '@olimat/web/utils/test/FakeDataProvider';
import MockErrorProvider from '@olimat/web/utils/test/MockErrorProvider';
import MockNextContext from '@olimat/web/utils/test/MockNextContext';
import { renderApollo } from '@olimat/web/utils/test/test-utils';
import ExamDetails from './Details';
const MockExamDetails = () => (
<MockNextContext router={{ query: { id: 'theExamId1' } }}>
<ExamDetails />
</MockNextContext>
);
// Talvez uma solução melhor seria criar um mock para o contexto do Next.js
// https://github.com/zeit/next.js/issues/5205
// Outra opção é exportar o componente sem embrulhá-lo com os HoC, e passar os mocks
// https://stackoverflow.com/questions/44204828
describe('<ExamDetails />', () => {
test.skip('renders loading state initially', () => {
const { getByText } = renderApollo(<MockExamDetails />);
getByText(/loading/i);
});
test('renders the details of an exam', async () => {
const customResolvers = {
// We need to update the GraphQL API as well
Exam: () => ({
title: '2017 - Fase 3 - Ano 5',
}),
};
const { getByText, getByTestId } = render(
<FakeDataProvider customResolvers={customResolvers}>
<MockExamDetails />
</FakeDataProvider>,<|fim▁hole|> await waitForElement(() => getByText(customResolvers.Exam().title));
const questionListNode = getByTestId('questionList');
expect(questionListNode).toBeInTheDocument();
// toBe(10) couples the test with the mocked server
// https://youtu.be/K445DtQ5oHY?t=1476
expect(questionListNode.children.length).toBe(10);
});
test('renders error message', async () => {
const errorMsg = 'Que pena';
const { getByText } = render(
<MockErrorProvider graphqlErrors={[{ message: errorMsg }]}>
<MockExamDetails />
</MockErrorProvider>,
);
await waitForElement(() => getByText(errorMsg, { exact: false }));
});
});<|fim▁end|>
|
);
|
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>"""
Django Admin pages for DiscountRestrictionConfig.
"""
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from openedx.core.djangoapps.config_model_utils.admin import StackedConfigModelAdmin
from .models import DiscountPercentageConfig, DiscountRestrictionConfig
class DiscountRestrictionConfigAdmin(StackedConfigModelAdmin):
"""
Admin to configure discount restrictions
"""
fieldsets = (
('Context', {
'fields': DiscountRestrictionConfig.KEY_FIELDS,
'description': _(
'These define the context to disable lms-controlled discounts on. '
'If no values are set, then the configuration applies globally. '
'If a single value is set, then the configuration applies to all courses '
'within that context. At most one value can be set at a time.<br>'
'If multiple contexts apply to a course (for example, if configuration '
'is specified for the course specifically, and for the org that the course '<|fim▁hole|> 'fields': ('disabled',),
'description': _(
'If any of these values is left empty or "Unknown", then their value '
'at runtime will be retrieved from the next most specific context that applies. '
'For example, if "Disabled" is left as "Unknown" in the course context, then that '
'course will be Disabled only if the org that it is in is Disabled.'
),
})
)
raw_id_fields = ('course',)
admin.site.register(DiscountRestrictionConfig, DiscountRestrictionConfigAdmin)
class DiscountPercentageConfigAdmin(StackedConfigModelAdmin):
"""
Admin to configure discount percentage
"""
fieldsets = (
('Context', {
'fields': DiscountRestrictionConfig.KEY_FIELDS,
'description': _(
'These define the context to configure the percentage for the first purchase discount.'
'If multiple contexts apply to a course (for example, if configuration '
'is specified for the course specifically, and for the org that the course '
'is in, then the more specific context overrides the more general context.'
),
}),
('Configuration', {
'fields': ('percentage',),
})
)
raw_id_fields = ('course',)
admin.site.register(DiscountPercentageConfig, DiscountPercentageConfigAdmin)<|fim▁end|>
|
'is in, then the more specific context overrides the more general context.'
),
}),
('Configuration', {
|
<|file_name|>prod.py<|end_file_name|><|fim▁begin|>"""
Production settings
Debug OFF
Djeroku Defaults:
Mandrill Email -- Requires Mandrill addon
dj_database_url and django-postgrespool for heroku postgres configuration
memcachify for heroku memcache configuration<|fim▁hole|> ALLOWED_HOSTS - You MUST add your site urls here if they don't match
the included defaults. If you have trouble, try prepending your url with
a . - eg: '.yourproject.herokuapp.com'.
Optional - Update your production environment SECRET_KEY (created and set
automatically by during project creation by the djeroku setup)
Email:
Defaults to mandril, which is already set up when added to your app
There is also a commented version that uses your gmail address.
For more control, you can set any of the following keys in your
environment:
EMAIL_HOST, EMAIL_HOST_PASSWORD, EMAIL_HOST_USER, EMAIL_PORT
"""
from os import environ
import dj_database_url
# automagically sets up whatever memcache heroku addon you have as the cache
# https://github.com/rdegges/django-heroku-memcacheify
from memcacheify import memcacheify
# use redisify instead of memcacheify if you prefer
# https://github.com/dirn/django-heroku-redisify
# from redisify import redisify
from project.settings.common import * # NOQA
# ALLOWED HOSTS
# https://docs.djangoproject.com/en/1.8/ref/settings/#allowed-hosts
ALLOWED_HOSTS = [
'.{{ project_name }}.herokuapp.com',
'.{{ project_name}}-staging.herokuapp.com'
]
# you MUST add your domain names here, check the link for details
# END ALLOWED HOSTS
# EMAIL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-host
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-host-password
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-host-user
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-port
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-use-tls
EMAIL_HOST = environ.get('EMAIL_HOST', 'smtp.mandrillapp.com')
EMAIL_HOST_PASSWORD = environ.get('MANDRILL_APIKEY', '')
EMAIL_HOST_USER = environ.get('MANDRILL_USERNAME', '')
EMAIL_PORT = environ.get('EMAIL_PORT', 587)
EMAIL_USE_TLS = True
# use this to channel your emails through a gmail powered account instead
# EMAIL_HOST = environ.get('EMAIL_HOST', 'smtp.gmail.com')
# EMAIL_HOST_USER = environ.get('EMAIL_HOST_USER', '[email protected]')
# EMAIL_HOST_PASSWORD = environ.get('EMAIL_HOST_PASSWORD', '')
# EMAIL_PORT = environ.get('EMAIL_PORT', 587)
# EMAIL_USE_TLS = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix
EMAIL_SUBJECT_PREFIX = '[%s] ' % SITE_NAME
# See: https://docs.djangoproject.com/en/dev/ref/settings/#server-email
SERVER_EMAIL = EMAIL_HOST_USER
# END EMAIL CONFIGURATION
# DATABASE CONFIGURATION
DATABASES['default'] = dj_database_url.config()
DATABASES['default']['ENGINE'] = 'django_postgrespool'
# END DATABASE CONFIGURATION
# CACHE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#caches
CACHES = memcacheify()
# CACHES = redisify()
# END CACHE CONFIGURATION
# Simplest redis-based config possible
# *very* easy to overload free redis/MQ connection limits
# You MUST update REDIS_SERVER_URL or use djeroku_redis to set it automatically
BROKER_POOL_LIMIT = 0
BROKER_URL = environ.get('REDIS_SERVER_URL')
CELERY_IGNORE_RESULT = True
CELERY_STORE_ERRORS_EVEN_IF_IGNORED = True
# END CELERY CONFIGURATION
# SECRET CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = environ.get('SECRET_KEY', SECRET_KEY)
# END SECRET CONFIGURATION
# ADDITIONAL MIDDLEWARE
MIDDLEWARE_CLASSES += ()
# END ADDITIONAL MIDDLEWARE<|fim▁end|>
|
Commented out by default - redisify for heroku redis cache configuration
What you need to set in your heroku environment (heroku config:set key=value):
|
<|file_name|>products.js<|end_file_name|><|fim▁begin|>(function(){
angular.module('list-products', [])
.directive('productInfo', function() {
return {
restrict: 'E',
templateUrl: 'partials/product-info.html'
}
})
.directive('productForm', function() {
return {
restrict: 'E',
templateUrl: 'partials/product-form.html',
controller: function() {
this.review = {};
this.item = {mark:{}};
this.addReview = function(item) {
item.reviews.push(this.review);
this.review = {};
};
},
controllerAs: 'reviewCtrl',
scope: {
items: "=",
marks: "="
}
};
})
.directive('productPanels', function() {<|fim▁hole|> restrict: 'E',
templateUrl: 'partials/product-panels.html',
controller: function(){
this.tab = 1;
this.selectTab = function(setTab) {
this.tab = setTab;
};
this.isSelected = function(checkTab) {
return checkTab === this.tab;
};
},
controllerAs: 'panelCtrl',
scope: {
items: "=",
marks: "="
}
};
});
})();<|fim▁end|>
|
return {
|
<|file_name|>actors.js<|end_file_name|><|fim▁begin|>var fs = require('fs')
, child_process = require('child_process')
, _glob = require('glob')
, bunch = require('./bunch')
;
exports.loadEnv = function loadEnv(env, cb) {
var loaders = []
function load(name, cb) {<|fim▁hole|> }
for (var name in env) {
loaders.push([load, name])
}
bunch(loaders, cb)
}
exports.commandActor = function command(executable) {
return function command(args, opts, cb) {
if (!cb) {
cb = opts;
opts = {}
}
var cmd = child_process.spawn(executable, args, opts);
function log(b) { console.log(b.toString()) }
cmd.stdout.on('data', log);
cmd.stderr.on('data', log);
cmd.on('exit', function(code) {
if (code) {
cb(new Error(executable + ' exited with status ' + code));
} else {
cb();
}
});
return cmd;
}
}
exports.jsonParse = function(str, cb) {
try {
cb(null, JSON.parse(str));
} catch (ex) {
cb(ex);
}
}
exports.jsonStringify = function(obj, cb) {
try {
cb(null, JSON.stringify(obj));
} catch (ex) {
cb(ex);
}
}
exports.glob = function glob(pattern, cb) {
console.log('pattern', pattern);
_glob(pattern, function(error, files) {
cb(error, [files]);
});
}<|fim▁end|>
|
fs.readFile(env[name], function(error, data) {
env[name] = env[name].match(/.*\.json$/) ? JSON.parse(data) : data;
cb(error, data)
})
|
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>#-*- coding: utf-8 -*-
from PIL import Image, ImageChops, ImageDraw
from django.contrib.auth.models import User
from filer.models.foldermodels import Folder
from filer.models.clipboardmodels import Clipboard, ClipboardItem
def create_superuser():
superuser = User.objects.create_superuser('admin',<|fim▁hole|> 'secret')
return superuser
def create_folder_structure(depth=2, sibling=2, parent=None):
"""
This method creates a folder structure of the specified depth.
* depth: is an integer (default=2)
* sibling: is an integer (default=2)
* parent: is the folder instance of the parent.
"""
if depth > 0 and sibling > 0:
depth_range = range(1, depth+1)
depth_range.reverse()
for d in depth_range:
for s in range(1,sibling+1):
name = "folder: %s -- %s" %(str(d), str(s))
folder = Folder(name=name, parent=parent)
folder.save()
create_folder_structure(depth=d-1, sibling=sibling, parent=folder)
def create_clipboard_item(user, file):
clipboard, was_clipboard_created = Clipboard.objects.get_or_create(user=user)
clipboard_item = ClipboardItem(clipboard=clipboard, file=file)
return clipboard_item
def create_image(mode='RGB', size=(800, 600)):
image = Image.new(mode, size)
draw = ImageDraw.Draw(image)
x_bit, y_bit = size[0] // 10, size[1] // 10
draw.rectangle((x_bit, y_bit * 2, x_bit * 7, y_bit * 3), 'red')
draw.rectangle((x_bit * 2, y_bit, x_bit * 3, y_bit * 8), 'red')
return image<|fim▁end|>
| |
<|file_name|>ejs.js<|end_file_name|><|fim▁begin|>/*
基本测试,ejs 模版 测试 例子
*/
var should = require('should');
var request = require('request');
var path = require('path');
var testconf = require('./testconf.js');
module.exports.rrestjsconfig = {
listenPort:3000,
tempSet:'ejs',
tempFolder :'/static',
baseDir: path.join(__dirname),
};
var chtml='';
var dhtml = '';
var fhtml = '';
var http = require('http'),
rrest = require('../'),
i=0,
server = http.createServer(function (req, res) {
var pname = req.pathname;
if(pname === '/a'){
res.render('/ejs');
}
else if(pname === '/b'){
res.render('/ejs.ejs', {"name":'hello world'});
}
else if(pname === '/c'){
res.render('/ejs',function(err, html){//测试不加后缀名是否可以render成功
chtml = html;
});
<|fim▁hole|> dhtml = html;
});
}
else if(pname === '/e'){
res.render('/ejs.ejs', 1, {"usersex":'hello world'});
}
else if(pname === '/f'){
res.render('/ejs', 2, {}, function(err, html){
fhtml = html;
});
}
else if(pname === '/g'){
res.compiletemp('/ejs.ejs', function(err, html){
res.sendjson({'data':html});
});
}
else if(pname === '/h'){
res.compiletemp('/ejs.ejs', 3, {"name":'hello world'}, function(err, html){
res.sendjson({'data':html});
});
}
else if(pname === '/i'){
res.compiletemp('/ejs2', 3, {"name":'hello world'}, function(err, html){
res.sendjson({'data':html});
});
}
}).listen(rrest.config.listenPort);
//设置全局的模版option
rrest.tploption.userid = function(req,res){return req.ip};
rrest.tploption.name = 'rrestjs default';
rrest.tploption.usersex = 'male';
http.globalAgent.maxSockets = 10;
var i = 9;
var r = 0
var result = function(name){
var num = ++r;
console.log('%s test done, receive %d/%d', name, num, i);
if(num>=i){
console.log('ejs.js test done.')
process.exit();
}
}
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/a',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>')
result('/a request')
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/b',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>')
result('/b request')
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/c',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
setTimeout(function(){
should.strictEqual(chtml, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
result('/c request')
},100)
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/d',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
setTimeout(function(){
should.strictEqual(dhtml, '<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
result('/d request')
},100)
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/e',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>hello world</li><form></form>');
result('/e request')
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/f',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
setTimeout(function(){
should.strictEqual(fhtml, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
result('/f request')
},100)
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/g',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '{\"data\":\"<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>\"}');
result('/g request')
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/h',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '{\"data\":\"<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>\"}');
result('/h request')
});
setTimeout(function(){
rrest.ejs.open ='{{'
rrest.ejs.close ='}}'
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/i',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '{\"data\":\"<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>\"}');
result('/h request')
});
},1000)<|fim▁end|>
|
}
else if(pname === '/d'){
res.render('/ejs.ejs', {"name":'hello world'}, function(err, html){
|
<|file_name|>square-every-digit.js<|end_file_name|><|fim▁begin|>// Welcome. In this kata, you are asked to square every digit of a number.
//
// For example, if we run 9119 through the function, 811181 will come out.
//
// Note: The function accepts an integer and returns an integer
function squareDigits(num){
let digits = (""+num).split("");
let arr=[];
for (var i = 0; i < digits.length; i++) {
arr.push(Math.pow(digits[i],2));<|fim▁hole|> }
return +arr.join('')
}
//top codewars solution
function squareDigits(num){
return Number(('' + num).split('').map(function (val) { return val * val;}).join(''));
}<|fim▁end|>
| |
<|file_name|>log_test.go<|end_file_name|><|fim▁begin|>/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package rest
import (
"testing"
"k8s.io/apimachinery/pkg/api/errors"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/generic"
genericregistry "k8s.io/apiserver/pkg/registry/generic/registry"
api "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/registry/registrytest"
)
func TestPodLogValidates(t *testing.T) {
config, server := registrytest.NewEtcdStorage(t, "")
defer server.Terminate(t)
s, destroyFunc, err := generic.NewRawStorage(config)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
defer destroyFunc()
store := &genericregistry.Store{
Storage: genericregistry.DryRunnableStorage{Storage: s},
}
logRest := &LogREST{Store: store, KubeletConn: nil}
negativeOne := int64(-1)
testCases := []*api.PodLogOptions{
{SinceSeconds: &negativeOne},<|fim▁hole|>
for _, tc := range testCases {
_, err := logRest.Get(genericapirequest.NewDefaultContext(), "test", tc)
if !errors.IsInvalid(err) {
t.Fatalf("Unexpected error: %v", err)
}
}
}<|fim▁end|>
|
{TailLines: &negativeOne},
}
|
<|file_name|>test_photos.py<|end_file_name|><|fim▁begin|>import base64
import os
import pytest
import six
from pytest_bdd import parsers, scenarios, then, when
from spud import media, models
scenarios('photos.feature')
@when('we create a photo called <name> using <filename>')
def step_create_photo(session, name, filename, data_files):
url = "/api/photos/"
path = os.path.join(data_files, filename)
data = {
'title': name,
'description': 'description',
'utc_offset': 660,
'datetime': '2012-12-20 12:34:56',
'level': 0,
'sha256_hash': base64.encodebytes(media.get_media(path).get_sha256_hash()),
}
files = {'photo': open(path, 'rb')}
session.post(url, data=data, files=files)
@when('we update a photo called <name>')
def step_update_photo(session, photos, name):
desired_photo = models.photo.objects.get(title=name)
url = "/api/photos/%d/" % desired_photo.id
data = {
'title': name,
'description': 'new description',
'utc_offset': 660,
'datetime': '2012-12-20 12:34:56',
'level': 0,
}
session.put(url, json=data)
@when('we patch a photo called <name>')
def step_patch_photo(session, photos, name):
desired_photo = models.photo.objects.get(title=name)
url = "/api/photos/%d/" % desired_photo.id
data = {
'description': 'new description',
}
session.patch(url, json=data)
@when('we get a photo called <name>')
def step_get_photo(session, photos, name):
desired_photo = models.photo.objects.get(title=name)
url = "/api/photos/%d/" % desired_photo.id
session.get(url)
@when('we delete a photo called <name>')
def step_delete_photo(session, photos, name):
desired_photo = models.photo.objects.get(title=name)
url = "/api/photos/%d/" % desired_photo.id
session.delete(url)
@when('we list all photos')
def step_list_photos(session, photos):
url = "/api/photos/"
session.get(url)
@then(parsers.cfparse(
'the photo <name> description should be {description}'))
def step_test_photo_description(name, description):
photo = models.photo.objects.get(title=name)
assert photo.description == description
@then('the photo called <name> should exist')
def step_test_photo_valid(name):
models.photo.objects.get(title=name)
@then('the photo called <name> should not exist')
def step_test_photo_not_exist(name):
with pytest.raises(models.photo.DoesNotExist):
models.photo.objects.get(title=name)
@then('we should get a valid photo called <name>')
def step_test_r_valid_photo(session, name):
photo = session.obj
assert photo['title'] == name
assert isinstance(photo['description'], six.string_types)
assert isinstance(photo['title'], six.string_types)
@then(parsers.cfparse(<|fim▁hole|> assert photo['description'] == description
@then(parsers.cfparse('we should get {number:d} valid photos'))
def step_test_r_n_results(session, number):
data = session.obj
assert data['count'] == number
assert len(data['results']) == number
for photo in data['results']:
assert isinstance(photo['description'], six.string_types)
assert isinstance(photo['title'], six.string_types)<|fim▁end|>
|
'we should get a photo with description {description}'))
def step_test_r_photo_description(session, description):
photo = session.obj
|
<|file_name|>config_directory_backend.go<|end_file_name|><|fim▁begin|>// +build ignore
package directory
import (
"github.com/corestoreio/csfw/config/element"
"github.com/corestoreio/csfw/config/model"
)
// Backend will be initialized in the init() function together with ConfigStructure.
var Backend *PkgBackend
// PkgBackend just exported for the sake of documentation. See fields
// for more information. The PkgBackend handles the reading and writing
// of configuration values within this package.
type PkgBackend struct {
model.PkgBackend
// CurrencyOptionsBase => Base Currency.
// Base currency is used for all online payment transactions. If you have more
// than one store view, the base currency scope is defined by the catalog
// price scope ("Catalog" > "Price" > "Catalog Price Scope").
// Path: currency/options/base
// BackendModel: Otnegam\Config\Model\Config\Backend\Currency\Base
// SourceModel: Otnegam\Config\Model\Config\Source\Locale\Currency
CurrencyOptionsBase model.Str
// CurrencyOptionsDefault => Default Display Currency.
// Path: currency/options/default
// BackendModel: Otnegam\Config\Model\Config\Backend\Currency\DefaultCurrency
// SourceModel: Otnegam\Config\Model\Config\Source\Locale\Currency
CurrencyOptionsDefault model.Str
// CurrencyOptionsAllow => Allowed Currencies.
// Path: currency/options/allow
// BackendModel: Otnegam\Config\Model\Config\Backend\Currency\Allow
// SourceModel: Otnegam\Config\Model\Config\Source\Locale\Currency
CurrencyOptionsAllow model.StringCSV
// CurrencyWebservicexTimeout => Connection Timeout in Seconds.
// Path: currency/webservicex/timeout
CurrencyWebservicexTimeout model.Str
// CurrencyImportEnabled => Enabled.
// Path: currency/import/enabled
// SourceModel: Otnegam\Config\Model\Config\Source\Yesno
CurrencyImportEnabled model.Bool
// CurrencyImportErrorEmail => Error Email Recipient.
// Path: currency/import/error_email
CurrencyImportErrorEmail model.Str
// CurrencyImportErrorEmailIdentity => Error Email Sender.
// Path: currency/import/error_email_identity
// SourceModel: Otnegam\Config\Model\Config\Source\Email\Identity
CurrencyImportErrorEmailIdentity model.Str
// CurrencyImportErrorEmailTemplate => Error Email Template.
// Email template chosen based on theme fallback when "Default" option is
// selected.
// Path: currency/import/error_email_template
// SourceModel: Otnegam\Config\Model\Config\Source\Email\Template
CurrencyImportErrorEmailTemplate model.Str
// CurrencyImportFrequency => Frequency.
// Path: currency/import/frequency
// SourceModel: Otnegam\Cron\Model\Config\Source\Frequency
CurrencyImportFrequency model.Str
// CurrencyImportService => Service.
// Path: currency/import/service
// BackendModel: Otnegam\Config\Model\Config\Backend\Currency\Cron
// SourceModel: Otnegam\Directory\Model\Currency\Import\Source\Service
CurrencyImportService model.Str
// CurrencyImportTime => Start Time.
// Path: currency/import/time
CurrencyImportTime model.Str
// SystemCurrencyInstalled => Installed Currencies.
// Path: system/currency/installed
// BackendModel: Otnegam\Config\Model\Config\Backend\Locale
// SourceModel: Otnegam\Config\Model\Config\Source\Locale\Currency\All
SystemCurrencyInstalled model.StringCSV
// GeneralCountryOptionalZipCountries => Zip/Postal Code is Optional for.
// Path: general/country/optional_zip_countries
// SourceModel: Otnegam\Directory\Model\Config\Source\Country
GeneralCountryOptionalZipCountries model.StringCSV
// GeneralRegionStateRequired => State is Required for.
// Path: general/region/state_required
// SourceModel: Otnegam\Directory\Model\Config\Source\Country
GeneralRegionStateRequired model.StringCSV
// GeneralRegionDisplayAll => Allow to Choose State if It is Optional for Country.
// Path: general/region/display_all
// SourceModel: Otnegam\Config\Model\Config\Source\Yesno
GeneralRegionDisplayAll model.Bool<|fim▁hole|> // GeneralLocaleWeightUnit => Weight Unit.
// Path: general/locale/weight_unit
// SourceModel: Otnegam\Directory\Model\Config\Source\WeightUnit
GeneralLocaleWeightUnit model.Str
}
// NewBackend initializes the global Backend variable. See init()
func NewBackend(cfgStruct element.SectionSlice) *PkgBackend {
return (&PkgBackend{}).init(cfgStruct)
}
func (pp *PkgBackend) init(cfgStruct element.SectionSlice) *PkgBackend {
pp.Lock()
defer pp.Unlock()
pp.CurrencyOptionsBase = model.NewStr(`currency/options/base`, model.WithConfigStructure(cfgStruct))
pp.CurrencyOptionsDefault = model.NewStr(`currency/options/default`, model.WithConfigStructure(cfgStruct))
pp.CurrencyOptionsAllow = model.NewStringCSV(`currency/options/allow`, model.WithConfigStructure(cfgStruct))
pp.CurrencyWebservicexTimeout = model.NewStr(`currency/webservicex/timeout`, model.WithConfigStructure(cfgStruct))
pp.CurrencyImportEnabled = model.NewBool(`currency/import/enabled`, model.WithConfigStructure(cfgStruct))
pp.CurrencyImportErrorEmail = model.NewStr(`currency/import/error_email`, model.WithConfigStructure(cfgStruct))
pp.CurrencyImportErrorEmailIdentity = model.NewStr(`currency/import/error_email_identity`, model.WithConfigStructure(cfgStruct))
pp.CurrencyImportErrorEmailTemplate = model.NewStr(`currency/import/error_email_template`, model.WithConfigStructure(cfgStruct))
pp.CurrencyImportFrequency = model.NewStr(`currency/import/frequency`, model.WithConfigStructure(cfgStruct))
pp.CurrencyImportService = model.NewStr(`currency/import/service`, model.WithConfigStructure(cfgStruct))
pp.CurrencyImportTime = model.NewStr(`currency/import/time`, model.WithConfigStructure(cfgStruct))
pp.SystemCurrencyInstalled = model.NewStringCSV(`system/currency/installed`, model.WithConfigStructure(cfgStruct))
pp.GeneralCountryOptionalZipCountries = model.NewStringCSV(`general/country/optional_zip_countries`, model.WithConfigStructure(cfgStruct))
pp.GeneralRegionStateRequired = model.NewStringCSV(`general/region/state_required`, model.WithConfigStructure(cfgStruct))
pp.GeneralRegionDisplayAll = model.NewBool(`general/region/display_all`, model.WithConfigStructure(cfgStruct))
pp.GeneralLocaleWeightUnit = model.NewStr(`general/locale/weight_unit`, model.WithConfigStructure(cfgStruct))
return pp
}<|fim▁end|>
| |
<|file_name|>pool.go<|end_file_name|><|fim▁begin|>package models
import "fmt"
// Room Pool containing all rooms currently active
var RoomPool = make([] *Room, 0)
func AddRoom(r *Room) {
RoomPool = append(RoomPool, r)
}
// FindRoom finds a room in the RoomPool
// and returns its index and value.
// If the room does not exist in pool returns -1
// If the RoomPool is empty returns -1
func FindRoom(d string) (int, *Room) {
for i, v := range RoomPool {
if v.Name == d {
return i, v
}
}
return -1, &Room{}
}
// RemoveRoom removes domain from the DomainPool
func RemoveRoom(r *Room) {
index, _ := FindRoom(r.Name)
if index != -1 {
RoomPool = append(RoomPool[:index], RoomPool[index + 1:]...)
}
}
// RemoveClient removes a client from a room
// if the client is the only client in the room
// the room is also removed from the RoomPool
func RemoveClient(c *Client) {
for _, room := range RoomPool{
if room.Name == c.Room {
if room.HasClient(c) {
room.DeleteClient(c)
if room.ClientCount() == 0 {
RemoveRoom(room)
// client side debug, on every client disconnection, broadcast server status
PoolBroadcast(NewMessage(map[string]string{
"connectedClients": fmt.Sprintf("%v", GetAllClients()),
"numberOfRooms": fmt.Sprintf("%v", GetNumberOfRooms()),
}))<|fim▁hole|> }
}
// ListRooms return the number of registered rooms and
// a slice of strings with all room names in pool
func ListRooms() (int, []string) {
pool := make([]string, 0)
for _, obj := range RoomPool {
pool = append(pool, obj.Name)
}
return len(RoomPool), pool
}
// PoolBroadcast send a message to all clients of the Pool
func PoolBroadcast(m Message) {
for _, room := range RoomPool {
room.RoomBroadcast(m)
}
}
// GetAllClients returns the number of all connected clients
func GetAllClients() int {
clientSum := 0
for _, room := range RoomPool {
clientSum += len(room.ClientPool)
}
return clientSum
}
// GetNumberOfRooms get the number of all rooms
func GetNumberOfRooms() int{
return len(RoomPool)
}<|fim▁end|>
|
}
}
}
|
<|file_name|>rgb_depth_exclusion.py<|end_file_name|><|fim▁begin|>import cv2
import os
import scipy.misc as misc
path = os.getcwd()
for x in xrange(15):
rgb = cv2.imread(path + '/output/rgb_img_' + str(x) + '.jpg')
depth = cv2.imread(path + '/output/depth_img_' + str(x) + '.jpg')
depth_inquiry = depth.copy()
# depth_inquiry[depth_inquiry > 180] = 0
# Depth threshold test - gets rid of near
depth_inquiry[depth_inquiry < 50] = 0
<|fim▁hole|>
median = cv2.cvtColor(median, cv2.COLOR_BGR2GRAY)
cv2.imshow('depth', median)
cv2.waitKey(0)
depth_params = (424, 512)
rgb_params = (1080, 1920)
depth_adjusted = (rgb_params[0], depth_params[1]*rgb_params[0]/depth_params[0])
rgb_cropped = rgb[:, rgb_params[1]/2-depth_adjusted[1]/2:rgb_params[1]/2+depth_adjusted[1]/2]
resized_median = cv2.resize(median, (depth_adjusted[1], depth_adjusted[0]), interpolation = cv2.INTER_AREA)
and_result = cv2.bitwise_and(rgb_cropped,rgb_cropped,mask=resized_median)
cv2.imshow('and', and_result)
cv2.imwrite(path +'/output/rgb_depth_adjusted_' + str(x) + '.jpg', rgb_cropped )<|fim▁end|>
|
# depth_inquiry[depth_inquiry > 0] = 255
median = cv2.medianBlur(depth_inquiry,5)
|
<|file_name|>app.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import json
from flask import Flask
from flask import request
from flask import jsonify
import time
from psutil import net_io_counters
from asyncftp import __version__
import threading
from asyncftp.Logger import _LogFormatter
t = time.time()
net = net_io_counters()
formatter = _LogFormatter(color=False)
log_message = str()
def make_app(server, queue):
app = Flask(__name__)
@app.route('/api/info', methods=['GET'])
def speed():
if request.method == 'GET':
global t
global net
temp_t = time.time()
p = net_io_counters()
result = dict()
result['speed'] = dict(
up=(p[0] - net[0]) / (temp_t - t),
down=(p[1] - net[1]) / (temp_t - t)
)
result['up_time'] = server.up_time
result['running'] = True if server.up_time else False
t = temp_t
net = p
return jsonify(result)
@app.route('/api/start', methods=['GET'])
def run_server():
if not server.running:
thread = threading.Thread(target=server.run)
thread.start()
return 'ok'
@app.route('/api/stop', methods=['GET'])
def close_server():
server.close()<|fim▁hole|> @app.route('/api/config', methods=['GET', 'POST'])
def config():
if request.method == 'GET':
return jsonify({
'host': server.host,
'port': str(server.port),
'version': __version__,
'refuse_ip': server.ip_refuse
})
if request.method == 'POST':
data = json.loads(request.data.decode('utf-8'))
for ip in data['refuse_ip']:
server.add_refuse_ip(ip)
return 'ok'
@app.route('/api/log', methods=['GET'])
def log():
if request.method == 'GET':
result = str()
while not queue.empty():
record = queue.get(block=False)
result += formatter.format(record) + '\n'
global log_message
log_message += result
return log_message
return app<|fim▁end|>
|
return 'ok'
|
<|file_name|>transaction.rs<|end_file_name|><|fim▁begin|>// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Transaction data structure.
use std::ops::Deref;
use rlp::*;
use util::sha3::Hashable;
use util::{H256, Address, U256, Bytes, HeapSizeOf};
use ethkey::{Signature, Secret, Public, recover, public_to_address, Error as EthkeyError};
use error::*;
use evm::Schedule;
use header::BlockNumber;
use ethjson;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", binary)]
/// Transaction action type.
pub enum Action {
/// Create creates new contract.
Create,
/// Calls contract at given address.
/// In the case of a transfer, this is the receiver's address.'
Call(Address),
}
impl Default for Action {
fn default() -> Action { Action::Create }
}
impl Decodable for Action {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let rlp = decoder.as_rlp();
if rlp.is_empty() {
Ok(Action::Create)
} else {
Ok(Action::Call(rlp.as_val()?))
}
}
}
/// Transaction activation condition.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", binary)]
pub enum Condition {
/// Valid at this block number or later.
Number(BlockNumber),
/// Valid at this unix time or later.
Timestamp(u64),
}
/// A set of information describing an externally-originating message call
/// or contract creation operation.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", binary)]
pub struct Transaction {
/// Nonce.
pub nonce: U256,
/// Gas price.
pub gas_price: U256,
/// Gas paid up front for transaction execution.
pub gas: U256,
/// Action, can be either call or contract create.
pub action: Action,
/// Transfered value.
pub value: U256,
/// Transaction data.
pub data: Bytes,
}
impl Transaction {
/// Append object with a without signature into RLP stream
pub fn rlp_append_unsigned_transaction(&self, s: &mut RlpStream, network_id: Option<u64>) {
s.begin_list(if network_id.is_none() { 6 } else { 9 });
s.append(&self.nonce);
s.append(&self.gas_price);
s.append(&self.gas);
match self.action {
Action::Create => s.append_empty_data(),
Action::Call(ref to) => s.append(to)
};
s.append(&self.value);
s.append(&self.data);
if let Some(n) = network_id {
s.append(&n);
s.append(&0u8);
s.append(&0u8);
}
}
}
impl HeapSizeOf for Transaction {
fn heap_size_of_children(&self) -> usize {
self.data.heap_size_of_children()
}
}
impl From<ethjson::state::Transaction> for SignedTransaction {
fn from(t: ethjson::state::Transaction) -> Self {
let to: Option<ethjson::hash::Address> = t.to.into();
let secret = Secret::from_slice(&t.secret.0).expect("Valid secret expected.");
Transaction {
nonce: t.nonce.into(),
gas_price: t.gas_price.into(),
gas: t.gas_limit.into(),
action: match to {
Some(to) => Action::Call(to.into()),
None => Action::Create
},
value: t.value.into(),
data: t.data.into(),
}.sign(&secret, None)
}
}
impl From<ethjson::transaction::Transaction> for UnverifiedTransaction {
fn from(t: ethjson::transaction::Transaction) -> Self {
let to: Option<ethjson::hash::Address> = t.to.into();
UnverifiedTransaction {
unsigned: Transaction {
nonce: t.nonce.into(),
gas_price: t.gas_price.into(),
gas: t.gas_limit.into(),
action: match to {
Some(to) => Action::Call(to.into()),
None => Action::Create
},
value: t.value.into(),
data: t.data.into(),
},
r: t.r.into(),
s: t.s.into(),
v: t.v.into(),
hash: 0.into(),
}.compute_hash()
}
}
impl Transaction {
/// The message hash of the transaction.
pub fn hash(&self, network_id: Option<u64>) -> H256 {
let mut stream = RlpStream::new();
self.rlp_append_unsigned_transaction(&mut stream, network_id);
stream.as_raw().sha3()
}
/// Signs the transaction as coming from `sender`.
pub fn sign(self, secret: &Secret, network_id: Option<u64>) -> SignedTransaction {
let sig = ::ethkey::sign(secret, &self.hash(network_id))
.expect("data is valid and context has signing capabilities; qed");
SignedTransaction::new(self.with_signature(sig, network_id))
.expect("secret is valid so it's recoverable")
}
/// Signs the transaction with signature.
pub fn with_signature(self, sig: Signature, network_id: Option<u64>) -> UnverifiedTransaction {
UnverifiedTransaction {
unsigned: self,
r: sig.r().into(),
s: sig.s().into(),
v: sig.v() as u64 + if let Some(n) = network_id { 35 + n * 2 } else { 27 },
hash: 0.into(),
}.compute_hash()
}
/// Useful for test incorrectly signed transactions.
#[cfg(test)]
pub fn invalid_sign(self) -> UnverifiedTransaction {
UnverifiedTransaction {
unsigned: self,
r: U256::default(),
s: U256::default(),
v: 0,
hash: 0.into(),
}.compute_hash()
}
/// Specify the sender; this won't survive the serialize/deserialize process, but can be cloned.
pub fn fake_sign(self, from: Address) -> SignedTransaction {
SignedTransaction {
transaction: UnverifiedTransaction {
unsigned: self,
r: U256::default(),
s: U256::default(),
v: 0,
hash: 0.into(),
}.compute_hash(),
sender: from,
public: Public::default(),
}
}
/// Get the transaction cost in gas for the given params.
pub fn gas_required_for(is_create: bool, data: &[u8], schedule: &Schedule) -> u64 {
data.iter().fold(
(if is_create {schedule.tx_create_gas} else {schedule.tx_gas}) as u64,
|g, b| g + (match *b { 0 => schedule.tx_data_zero_gas, _ => schedule.tx_data_non_zero_gas }) as u64
)
}
/// Get the transaction cost in gas for this transaction.
pub fn gas_required(&self, schedule: &Schedule) -> u64 {
Self::gas_required_for(match self.action{Action::Create=>true, Action::Call(_)=>false}, &self.data, schedule)
}
}
/// Signed transaction information.
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "ipc", binary)]
pub struct UnverifiedTransaction {
/// Plain Transaction.
unsigned: Transaction,
/// The V field of the signature; the LS bit described which half of the curve our point falls
/// in. The MS bits describe which network this transaction is for. If 27/28, its for all networks.
v: u64,
/// The R field of the signature; helps describe the point on the curve.
r: U256,
/// The S field of the signature; helps describe the point on the curve.
s: U256,
/// Hash of the transaction
hash: H256,
}
impl Deref for UnverifiedTransaction {
type Target = Transaction;
fn deref(&self) -> &Self::Target {
&self.unsigned
}
}
impl Decodable for UnverifiedTransaction {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp();
if d.item_count() != 9 {
return Err(DecoderError::RlpIncorrectListLen);
}
let hash = decoder.as_raw().sha3();
Ok(UnverifiedTransaction {
unsigned: Transaction {
nonce: d.val_at(0)?,
gas_price: d.val_at(1)?,
gas: d.val_at(2)?,
action: d.val_at(3)?,
value: d.val_at(4)?,
data: d.val_at(5)?,
},
v: d.val_at(6)?,
r: d.val_at(7)?,
s: d.val_at(8)?,
hash: hash,
})
}<|fim▁hole|>}
impl UnverifiedTransaction {
/// Used to compute hash of created transactions
fn compute_hash(mut self) -> UnverifiedTransaction {
let hash = (&*self.rlp_bytes()).sha3();
self.hash = hash;
self
}
/// Append object with a signature into RLP stream
fn rlp_append_sealed_transaction(&self, s: &mut RlpStream) {
s.begin_list(9);
s.append(&self.nonce);
s.append(&self.gas_price);
s.append(&self.gas);
match self.action {
Action::Create => s.append_empty_data(),
Action::Call(ref to) => s.append(to)
};
s.append(&self.value);
s.append(&self.data);
s.append(&self.v);
s.append(&self.r);
s.append(&self.s);
}
/// Reference to unsigned part of this transaction.
pub fn as_unsigned(&self) -> &Transaction {
&self.unsigned
}
/// 0 if `v` would have been 27 under "Electrum" notation, 1 if 28 or 4 if invalid.
pub fn standard_v(&self) -> u8 { match self.v { v if v == 27 || v == 28 || v > 36 => ((v - 1) % 2) as u8, _ => 4 } }
/// The `v` value that appears in the RLP.
pub fn original_v(&self) -> u64 { self.v }
/// The network ID, or `None` if this is a global transaction.
pub fn network_id(&self) -> Option<u64> {
match self.v {
v if v > 36 => Some((v - 35) / 2),
_ => None,
}
}
/// Construct a signature object from the sig.
pub fn signature(&self) -> Signature {
Signature::from_rsv(&self.r.into(), &self.s.into(), self.standard_v())
}
/// Checks whether the signature has a low 's' value.
pub fn check_low_s(&self) -> Result<(), Error> {
if !self.signature().is_low_s() {
Err(EthkeyError::InvalidSignature.into())
} else {
Ok(())
}
}
/// Get the hash of this header (sha3 of the RLP).
pub fn hash(&self) -> H256 {
self.hash
}
/// Recovers the public key of the sender.
pub fn recover_public(&self) -> Result<Public, Error> {
Ok(recover(&self.signature(), &self.unsigned.hash(self.network_id()))?)
}
/// Do basic validation, checking for valid signature and minimum gas,
// TODO: consider use in block validation.
#[cfg(test)]
#[cfg(feature = "json-tests")]
pub fn validate(self, schedule: &Schedule, require_low: bool, allow_network_id_of_one: bool) -> Result<UnverifiedTransaction, Error> {
if require_low && !self.signature().is_low_s() {
return Err(EthkeyError::InvalidSignature.into())
}
match self.network_id() {
None => {},
Some(1) if allow_network_id_of_one => {},
_ => return Err(TransactionError::InvalidNetworkId.into()),
}
self.recover_public()?;
if self.gas < U256::from(self.gas_required(&schedule)) {
Err(TransactionError::InvalidGasLimit(::util::OutOfBounds{min: Some(U256::from(self.gas_required(&schedule))), max: None, found: self.gas}).into())
} else {
Ok(self)
}
}
}
/// A `UnverifiedTransaction` with successfully recovered `sender`.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SignedTransaction {
transaction: UnverifiedTransaction,
sender: Address,
public: Public,
}
impl HeapSizeOf for SignedTransaction {
fn heap_size_of_children(&self) -> usize {
self.transaction.unsigned.heap_size_of_children()
}
}
impl Encodable for SignedTransaction {
fn rlp_append(&self, s: &mut RlpStream) { self.transaction.rlp_append_sealed_transaction(s) }
}
impl Deref for SignedTransaction {
type Target = UnverifiedTransaction;
fn deref(&self) -> &Self::Target {
&self.transaction
}
}
impl From<SignedTransaction> for UnverifiedTransaction {
fn from(tx: SignedTransaction) -> Self {
tx.transaction
}
}
impl SignedTransaction {
/// Try to verify transaction and recover sender.
pub fn new(transaction: UnverifiedTransaction) -> Result<Self, Error> {
let public = transaction.recover_public()?;
let sender = public_to_address(&public);
Ok(SignedTransaction {
transaction: transaction,
sender: sender,
public: public,
})
}
/// Returns transaction sender.
pub fn sender(&self) -> Address {
self.sender
}
/// Returns a public key of the sender.
pub fn public_key(&self) -> Public {
self.public
}
}
/// Signed Transaction that is a part of canon blockchain.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", binary)]
pub struct LocalizedTransaction {
/// Signed part.
pub signed: UnverifiedTransaction,
/// Block number.
pub block_number: BlockNumber,
/// Block hash.
pub block_hash: H256,
/// Transaction index within block.
pub transaction_index: usize,
/// Cached sender
pub cached_sender: Option<Address>,
}
impl LocalizedTransaction {
/// Returns transaction sender.
/// Panics if `LocalizedTransaction` is constructed using invalid `UnverifiedTransaction`.
pub fn sender(&mut self) -> Address {
if let Some(sender) = self.cached_sender {
return sender;
}
let sender = public_to_address(&self.recover_public()
.expect("LocalizedTransaction is always constructed from transaction from blockchain; Blockchain only stores verified transactions; qed"));
self.cached_sender = Some(sender);
sender
}
}
impl Deref for LocalizedTransaction {
type Target = UnverifiedTransaction;
fn deref(&self) -> &Self::Target {
&self.signed
}
}
/// Queued transaction with additional information.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", binary)]
pub struct PendingTransaction {
/// Signed transaction data.
pub transaction: SignedTransaction,
/// To be activated at this condition. `None` for immediately.
pub condition: Option<Condition>,
}
impl PendingTransaction {
/// Create a new pending transaction from signed transaction.
pub fn new(signed: SignedTransaction, condition: Option<Condition>) -> Self {
PendingTransaction {
transaction: signed,
condition: condition,
}
}
}
impl Deref for PendingTransaction {
type Target = SignedTransaction;
fn deref(&self) -> &SignedTransaction { &self.transaction }
}
impl From<SignedTransaction> for PendingTransaction {
fn from(t: SignedTransaction) -> Self {
PendingTransaction {
transaction: t,
condition: None,
}
}
}
#[test]
fn sender_test() {
let t: UnverifiedTransaction = decode(&::rustc_serialize::hex::FromHex::from_hex("f85f800182520894095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap());
assert_eq!(t.data, b"");
assert_eq!(t.gas, U256::from(0x5208u64));
assert_eq!(t.gas_price, U256::from(0x01u64));
assert_eq!(t.nonce, U256::from(0x00u64));
if let Action::Call(ref to) = t.action {
assert_eq!(*to, "095e7baea6a6c7c4c2dfeb977efac326af552d87".into());
} else { panic!(); }
assert_eq!(t.value, U256::from(0x0au64));
assert_eq!(public_to_address(&t.recover_public().unwrap()), "0f65fe9276bc9a24ae7083ae28e2660ef72df99e".into());
assert_eq!(t.network_id(), None);
}
#[test]
fn signing() {
use ethkey::{Random, Generator};
let key = Random.generate().unwrap();
let t = Transaction {
action: Action::Create,
nonce: U256::from(42),
gas_price: U256::from(3000),
gas: U256::from(50_000),
value: U256::from(1),
data: b"Hello!".to_vec()
}.sign(&key.secret(), None);
assert_eq!(Address::from(key.public().sha3()), t.sender());
assert_eq!(t.network_id(), None);
}
#[test]
fn fake_signing() {
let t = Transaction {
action: Action::Create,
nonce: U256::from(42),
gas_price: U256::from(3000),
gas: U256::from(50_000),
value: U256::from(1),
data: b"Hello!".to_vec()
}.fake_sign(Address::from(0x69));
assert_eq!(Address::from(0x69), t.sender());
assert_eq!(t.network_id(), None);
let t = t.clone();
assert_eq!(Address::from(0x69), t.sender());
assert_eq!(t.network_id(), None);
}
#[test]
fn should_recover_from_network_specific_signing() {
use ethkey::{Random, Generator};
let key = Random.generate().unwrap();
let t = Transaction {
action: Action::Create,
nonce: U256::from(42),
gas_price: U256::from(3000),
gas: U256::from(50_000),
value: U256::from(1),
data: b"Hello!".to_vec()
}.sign(&key.secret(), Some(69));
assert_eq!(Address::from(key.public().sha3()), t.sender());
assert_eq!(t.network_id(), Some(69));
}
#[test]
fn should_agree_with_vitalik() {
use rustc_serialize::hex::FromHex;
let test_vector = |tx_data: &str, address: &'static str| {
let signed = decode(&FromHex::from_hex(tx_data).unwrap());
let signed = SignedTransaction::new(signed).unwrap();
assert_eq!(signed.sender(), address.into());
flushln!("networkid: {:?}", signed.network_id());
};
test_vector("f864808504a817c800825208943535353535353535353535353535353535353535808025a0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116da0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116d", "0xf0f6f18bca1b28cd68e4357452947e021241e9ce");
test_vector("f864018504a817c80182a410943535353535353535353535353535353535353535018025a0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bcaa0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6", "0x23ef145a395ea3fa3deb533b8a9e1b4c6c25d112");
test_vector("f864028504a817c80282f618943535353535353535353535353535353535353535088025a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5", "0x2e485e0c23b4c3c542628a5f672eeab0ad4888be");
test_vector("f865038504a817c803830148209435353535353535353535353535353535353535351b8025a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4e0a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4de", "0x82a88539669a3fd524d669e858935de5e5410cf0");
test_vector("f865048504a817c80483019a28943535353535353535353535353535353535353535408025a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c063a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c060", "0xf9358f2538fd5ccfeb848b64a96b743fcc930554");
test_vector("f865058504a817c8058301ec309435353535353535353535353535353535353535357d8025a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", "0xa8f7aba377317440bc5b26198a363ad22af1f3a4");
test_vector("f866068504a817c80683023e3894353535353535353535353535353535353535353581d88025a06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2fa06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2d", "0xf1f571dc362a0e5b2696b8e775f8491d3e50de35");
test_vector("f867078504a817c807830290409435353535353535353535353535353535353535358201578025a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021", "0xd37922162ab7cea97c97a87551ed02c9a38b7332");
test_vector("f867088504a817c8088302e2489435353535353535353535353535353535353535358202008025a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", "0x9bddad43f934d313c2b79ca28a432dd2b7281029");
test_vector("f867098504a817c809830334509435353535353535353535353535353535353535358202d98025a052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afba052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", "0x3c24d7329e92f84f08556ceb6df1cdb0104ca49f");
}<|fim▁end|>
|
}
impl Encodable for UnverifiedTransaction {
fn rlp_append(&self, s: &mut RlpStream) { self.rlp_append_sealed_transaction(s) }
|
<|file_name|>tokens_test.go<|end_file_name|><|fim▁begin|>/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package util
import (
"testing"
kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
)
func TestTokenParseErrors(t *testing.T) {
invalidTokens := []string{
"1234567890123456789012",
"12345.1234567890123456",
".1234567890123456",
"123456.1234567890.123456",
}
for _, token := range invalidTokens {
if _, _, err := ParseToken(token); err == nil {
t.Errorf("generateTokenIfNeeded did not return an error for this invalid token: [%s]", token)
}
}
}
func TestGenerateToken(t *testing.T) {
var cfg kubeadmapi.TokenDiscovery
GenerateToken(&cfg)
if len(cfg.ID) != 6 {
t.Errorf("failed GenerateToken first part length:\n\texpected: 6\n\t actual: %d", len(cfg.ID))<|fim▁hole|> }
if len(cfg.Secret) != 16 {
t.Errorf("failed GenerateToken first part length:\n\texpected: 16\n\t actual: %d", len(cfg.Secret))
}
}
func TestRandBytes(t *testing.T) {
var randTest = []int{
0,
1,
2,
3,
100,
}
for _, rt := range randTest {
actual, err := RandBytes(rt)
if err != nil {
t.Errorf("failed RandBytes: %v", err)
}
if len(actual) != rt*2 {
t.Errorf("failed RandBytes:\n\texpected: %d\n\t actual: %d\n", rt*2, len(actual))
}
}
}<|fim▁end|>
| |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![feature(fn_traits, try_from)]
extern crate redis;
extern crate rand;
#[macro_use]<|fim▁hole|>extern crate log;
extern crate env_logger;
pub mod types;
pub mod pubsub;
pub mod storage;
pub mod feature;<|fim▁end|>
| |
<|file_name|>factory.py<|end_file_name|><|fim▁begin|>import sys
from apps.cowry.exceptions import PaymentMethodNotFound
from django.utils.importlib import import_module
def _load_from_module(path):
package, attr = path.rsplit('.', 1)
module = import_module(package)<|fim▁hole|> return getattr(module, attr)
# TODO read django settings to find out what adapters to load.
# TODO Ensure not duplicate payment method names.
# ADAPTERS = getattr(settings, 'COWRY_ADAPTERS')
ADAPTERS = ('apps.cowry_docdata.adapters.DocDataPaymentAdapter',)
_adapters = []
for adapter_str in ADAPTERS:
adapter_class = _load_from_module(adapter_str)
_adapters.append(adapter_class())
def _adapter_for_payment_method(payment_method_id):
for adapter in _adapters:
for pmi in adapter.get_payment_methods():
if payment_method_id == pmi:
return adapter
raise PaymentMethodNotFound('', payment_method_id)
def create_payment_object(order, payment_method_id, payment_submethod='', amount='', currency=''):
adapter = _adapter_for_payment_method(payment_method_id)
payment = adapter.create_payment_object(order, payment_method_id, payment_submethod, amount, currency)
payment.save()
return payment
def get_payment_methods(amount=None, currency='', country='', recurring=None, pm_ids=None):
payment_methods = []
for adapter in _adapters:
cur_payment_methods = adapter.get_payment_methods()
for pm_id in cur_payment_methods:
if pm_ids is None or pm_id in pm_ids:
# Extract values from the configuration.
pm_config = cur_payment_methods[pm_id]
max_amount = pm_config.get('max_amount', sys.maxint)
min_amount = pm_config.get('min_amount', 0)
restricted_currencies = pm_config.get('restricted_currencies', (currency,))
restricted_countries = pm_config.get('restricted_countries', (country,))
supports_recurring = pm_config.get('supports_recurring', True)
supports_single = pm_config.get('supports_single', True)
# See if we need to exclude the current payment_method (pm).
add_pm = True
if amount and (amount > max_amount or amount < min_amount):
add_pm = False
if country not in restricted_countries:
add_pm = False
if currency not in restricted_currencies:
add_pm = False
if recurring and not supports_recurring:
add_pm = False
if not recurring and not supports_single:
add_pm = False
# For now we only return a few params. Later on we might want to return the entire object.
if add_pm:
payment_methods.append({'id': pm_id, 'name': pm_config.get('name')})
return payment_methods
def get_payment_method_ids(amount=None, currency='', country='', recurring=None, pm_ids=None):
payment_method_ids = []
for pm in get_payment_methods(amount=amount, currency=currency, country=country, recurring=recurring, pm_ids=pm_ids):
payment_method_ids.append(pm['id'])
return payment_method_ids
def get_payment_submethods(payment_method_id):
adapter = _adapter_for_payment_method(payment_method_id)
for payment_methods in adapter.get_payment_method_config():
for pmi in payment_methods.keys():
config = payment_methods[pmi]
return config.get('submethods')<|fim▁end|>
| |
<|file_name|>search.js<|end_file_name|><|fim▁begin|>(function() {
var instance = openerp;
openerp.web.search = {};
var QWeb = instance.web.qweb,
_t = instance.web._t,
_lt = instance.web._lt;
_.mixin({
sum: function (obj) { return _.reduce(obj, function (a, b) { return a + b; }, 0); }
});
/** @namespace */
var my = instance.web.search = {};
var B = Backbone;
my.FacetValue = B.Model.extend({
});
my.FacetValues = B.Collection.extend({
model: my.FacetValue
});
my.Facet = B.Model.extend({
initialize: function (attrs) {
var values = attrs.values;
delete attrs.values;
B.Model.prototype.initialize.apply(this, arguments);
this.values = new my.FacetValues(values || []);
this.values.on('add remove change reset', function (_, options) {
this.trigger('change', this, options);
}, this);
},
get: function (key) {
if (key !== 'values') {
return B.Model.prototype.get.call(this, key);
}
return this.values.toJSON();
},
set: function (key, value) {
if (key !== 'values') {
return B.Model.prototype.set.call(this, key, value);
}
this.values.reset(value);
},
toJSON: function () {
var out = {};
var attrs = this.attributes;
for(var att in attrs) {
if (!attrs.hasOwnProperty(att) || att === 'field') {
continue;
}
out[att] = attrs[att];
}
out.values = this.values.toJSON();
return out;
}
});
my.SearchQuery = B.Collection.extend({
model: my.Facet,
initialize: function () {
B.Collection.prototype.initialize.apply(
this, arguments);
this.on('change', function (facet) {
if(!facet.values.isEmpty()) { return; }
this.remove(facet, {silent: true});
}, this);
},
add: function (values, options) {
options = options || {};
if (!values) {
values = [];
} else if (!(values instanceof Array)) {
values = [values];
}
_(values).each(function (value) {
var model = this._prepareModel(value, options);
var previous = this.detect(function (facet) {
return facet.get('category') === model.get('category')
&& facet.get('field') === model.get('field');
});
if (previous) {
previous.values.add(model.get('values'), _.omit(options, 'at', 'merge'));
return;
}
B.Collection.prototype.add.call(this, model, options);
}, this);
// warning: in backbone 1.0+ add is supposed to return the added models,
// but here toggle may delegate to add and return its value directly.
// return value of neither seems actually used but should be tested
// before change, probably
return this;
},
toggle: function (value, options) {
options = options || {};
var facet = this.detect(function (facet) {
return facet.get('category') === value.category
&& facet.get('field') === value.field;
});
if (!facet) {
return this.add(value, options);
}
var changed = false;
_(value.values).each(function (val) {
var already_value = facet.values.detect(function (v) {
return v.get('value') === val.value
&& v.get('label') === val.label;
});
// toggle value
if (already_value) {
facet.values.remove(already_value, {silent: true});
} else {
facet.values.add(val, {silent: true});
}
changed = true;
});
// "Commit" changes to values array as a single call, so observers of
// change event don't get misled by intermediate incomplete toggling
// states
facet.trigger('change', facet);
return this;
}
});
function assert(condition, message) {
if(!condition) {
throw new Error(message);
}
}
my.InputView = instance.web.Widget.extend({
template: 'SearchView.InputView',
events: {
focus: function () { this.trigger('focused', this); },
blur: function () { this.$el.text(''); this.trigger('blurred', this); },
keydown: 'onKeydown',
paste: 'onPaste',
},
getSelection: function () {
this.el.normalize();
// get Text node
var root = this.el.childNodes[0];
if (!root || !root.textContent) {
// if input does not have a child node, or the child node is an
// empty string, then the selection can only be (0, 0)
return {start: 0, end: 0};
}
var range = window.getSelection().getRangeAt(0);
// In Firefox, depending on the way text is selected (drag, double- or
// triple-click) the range may start or end on the parent of the
// selected text node‽ Check for this condition and fixup the range
// note: apparently with C-a this can go even higher?
if (range.startContainer === this.el && range.startOffset === 0) {
range.setStart(root, 0);
}
if (range.endContainer === this.el && range.endOffset === 1) {
range.setEnd(root, root.length);
}
assert(range.startContainer === root,
"selection should be in the input view");
assert(range.endContainer === root,
"selection should be in the input view");
return {
start: range.startOffset,
end: range.endOffset
};
},
onKeydown: function (e) {
this.el.normalize();
var sel;
switch (e.which) {
// Do not insert newline, but let it bubble so searchview can use it
case $.ui.keyCode.ENTER:
e.preventDefault();
break;
// FIXME: may forget content if non-empty but caret at index 0, ok?
case $.ui.keyCode.BACKSPACE:
sel = this.getSelection();
if (sel.start === 0 && sel.start === sel.end) {
e.preventDefault();
var preceding = this.getParent().siblingSubview(this, -1);
if (preceding && (preceding instanceof my.FacetView)) {
preceding.model.destroy();
}
}
break;
// let left/right events propagate to view if caret is at input border
// and not a selection
case $.ui.keyCode.LEFT:
sel = this.getSelection();
if (sel.start !== 0 || sel.start !== sel.end) {
e.stopPropagation();
}
break;
case $.ui.keyCode.RIGHT:
sel = this.getSelection();
var len = this.$el.text().length;
if (sel.start !== len || sel.start !== sel.end) {
e.stopPropagation();
}
break;
}
},
setCursorAtEnd: function () {
this.el.normalize();
var sel = window.getSelection();
sel.removeAllRanges();
var range = document.createRange();
// in theory, range.selectNodeContents should work here. In practice,
// MSIE9 has issues from time to time, instead of selecting the inner
// text node it would select the reference node instead (e.g. in demo
// data, company news, copy across the "Company News" link + the title,
// from about half the link to half the text, paste in search box then
// hit the left arrow key, getSelection would blow up).
//
// Explicitly selecting only the inner text node (only child node
// since we've normalized the parent) avoids the issue
range.selectNode(this.el.childNodes[0]);
range.collapse(false);
sel.addRange(range);
},
onPaste: function () {
this.el.normalize();
// In MSIE and Webkit, it is possible to get various representations of
// the clipboard data at this point e.g.
// window.clipboardData.getData('Text') and
// event.clipboardData.getData('text/plain') to ensure we have a plain
// text representation of the object (and probably ensure the object is
// pastable as well, so nobody puts an image in the search view)
// (nb: since it's not possible to alter the content of the clipboard
// — at least in Webkit — to ensure only textual content is available,
// using this would require 1. getting the text data; 2. manually
// inserting the text data into the content; and 3. cancelling the
// paste event)
//
// But Firefox doesn't support the clipboard API (as of FF18)
// although it correctly triggers the paste event (Opera does not even
// do that) => implement lowest-denominator system where onPaste
// triggers a followup "cleanup" pass after the data has been pasted
setTimeout(function () {
// Read text content (ignore pasted HTML)
var data = this.$el.text();
if (!data)
return;
// paste raw text back in
this.$el.empty().text(data);
this.el.normalize();
// Set the cursor at the end of the text, so the cursor is not lost
// in some kind of error-spawning limbo.
this.setCursorAtEnd();
}.bind(this), 0);
}
});
my.FacetView = instance.web.Widget.extend({
template: 'SearchView.FacetView',
events: {
'focus': function () { this.trigger('focused', this); },
'blur': function () { this.trigger('blurred', this); },
'click': function (e) {
if ($(e.target).is('.oe_facet_remove')) {
this.model.destroy();
return false;
}
this.$el.focus();
e.stopPropagation();
},
'keydown': function (e) {
var keys = $.ui.keyCode;
switch (e.which) {
case keys.BACKSPACE:
case keys.DELETE:
this.model.destroy();
return false;
}
}
},
init: function (parent, model) {
this._super(parent);
this.model = model;
this.model.on('change', this.model_changed, this);
},
destroy: function () {
this.model.off('change', this.model_changed, this);
this._super();
},
start: function () {
var self = this;
var $e = this.$('> span:last-child');
return $.when(this._super()).then(function () {
return $.when.apply(null, self.model.values.map(function (value) {
return new my.FacetValueView(self, value).appendTo($e);
}));
});
},
model_changed: function () {
this.$el.text(this.$el.text() + '*');
}
});
my.FacetValueView = instance.web.Widget.extend({
template: 'SearchView.FacetView.Value',
init: function (parent, model) {
this._super(parent);
this.model = model;
this.model.on('change', this.model_changed, this);
},
destroy: function () {
this.model.off('change', this.model_changed, this);
this._super();
},
model_changed: function () {
this.$el.text(this.$el.text() + '*');
}
});
instance.web.SearchView = instance.web.Widget.extend(/** @lends instance.web.SearchView# */{
template: "SearchView",
events: {
// focus last input if view itself is clicked
'click': function (e) {
if (e.target === this.$('.oe_searchview_facets')[0]) {
this.$('.oe_searchview_input:last').focus();
}
},
// search button
'click button.oe_searchview_search': function (e) {
e.stopImmediatePropagation();
this.do_search();
},
'click .oe_searchview_clear': function (e) {
e.stopImmediatePropagation();
this.query.reset();
},
'click .oe_searchview_unfold_drawer': function (e) {
e.stopImmediatePropagation();
if (this.drawer)
this.drawer.toggle();
},
'keydown .oe_searchview_input, .oe_searchview_facet': function (e) {
switch(e.which) {
case $.ui.keyCode.LEFT:
this.focusPreceding(e.target);
e.preventDefault();
break;
case $.ui.keyCode.RIGHT:
if (!this.autocomplete.is_expandable()) {
this.focusFollowing(e.target);
}
e.preventDefault();
break;
}
},
'autocompleteopen': function () {
this.$el.autocomplete('widget').css('z-index', 9999);
},
},
/**
* @constructs instance.web.SearchView
* @extends instance.web.Widget
*
* @param parent
* @param dataset
* @param view_id
* @param defaults
* @param {Object} [options]
* @param {Boolean} [options.hidden=false] hide the search view
* @param {Boolean} [options.disable_custom_filters=false] do not load custom filters from ir.filters
*/
init: function(parent, dataset, view_id, defaults, options) {
this.options = _.defaults(options || {}, {
hidden: false,
disable_custom_filters: false,
});
this._super(parent);
this.dataset = dataset;
this.model = dataset.model;
this.view_id = view_id;
this.defaults = defaults || {};
this.has_defaults = !_.isEmpty(this.defaults);
this.headless = this.options.hidden && !this.has_defaults;
this.input_subviews = [];
this.view_manager = null;
this.$view_manager_header = null;
this.ready = $.Deferred();
this.drawer_ready = $.Deferred();
this.fields_view_get = $.Deferred();
this.drawer = new instance.web.SearchViewDrawer(parent, this);
},
start: function() {
var self = this;
var p = this._super();
this.$view_manager_header = this.$el.parents(".oe_view_manager_header").first();
this.setup_global_completion();
this.query = new my.SearchQuery()
.on('add change reset remove', this.proxy('do_search'))
.on('change', this.proxy('renderChangedFacets'))
.on('add reset remove', this.proxy('renderFacets'));
if (this.options.hidden) {
this.$el.hide();
}
if (this.headless) {
this.ready.resolve();
} else {
var load_view = instance.web.fields_view_get({
model: this.dataset._model,
view_id: this.view_id,
view_type: 'search',
context: this.dataset.get_context(),
});
this.alive($.when(load_view)).then(function (r) {
self.fields_view_get.resolve(r);
return self.search_view_loaded(r);
}).fail(function () {
self.ready.reject.apply(null, arguments);
});
}
var view_manager = this.getParent();
while (!(view_manager instanceof instance.web.ViewManager) &&
view_manager && view_manager.getParent) {
view_manager = view_manager.getParent();
}
if (view_manager) {
this.view_manager = view_manager;
view_manager.on('switch_mode', this, function (e) {
self.drawer.toggle(e === 'graph');
});
}
return $.when(p, this.ready);
},
set_drawer: function (drawer) {
this.drawer = drawer;
},
show: function () {
this.$el.show();
},
hide: function () {
this.$el.hide();
},
subviewForRoot: function (subview_root) {
return _(this.input_subviews).detect(function (subview) {
return subview.$el[0] === subview_root;
});
},
siblingSubview: function (subview, direction, wrap_around) {
var index = _(this.input_subviews).indexOf(subview) + direction;
if (wrap_around && index < 0) {
index = this.input_subviews.length - 1;
} else if (wrap_around && index >= this.input_subviews.length) {
index = 0;
}
return this.input_subviews[index];
},
focusPreceding: function (subview_root) {
return this.siblingSubview(
this.subviewForRoot(subview_root), -1, true)
.$el.focus();
},
focusFollowing: function (subview_root) {
return this.siblingSubview(
this.subviewForRoot(subview_root), +1, true)
.$el.focus();
},
/**
* Sets up search view's view-wide auto-completion widget
*/
setup_global_completion: function () {
var self = this;
this.autocomplete = new instance.web.search.AutoComplete(this, {
source: this.proxy('complete_global_search'),
select: this.proxy('select_completion'),
delay: 0,
get_search_string: function () {
return self.$('div.oe_searchview_input').text();
},
width: this.$el.width(),
});
this.autocomplete.appendTo(this.$el);
},
/**
* Provide auto-completion result for req.term (an array to `resp`)
*
* @param {Object} req request to complete
* @param {String} req.term searched term to complete
* @param {Function} resp response callback
*/
complete_global_search: function (req, resp) {
$.when.apply(null, _(this.drawer.inputs).chain()
.filter(function (input) { return input.visible(); })
.invoke('complete', req.term)
.value()).then(function () {
resp(_(arguments).chain()
.compact()
.flatten(true)
.value());
});
},
/**
* Action to perform in case of selection: create a facet (model)
* and add it to the search collection
*
* @param {Object} e selection event, preventDefault to avoid setting value on object
* @param {Object} ui selection information
* @param {Object} ui.item selected completion item
*/
select_completion: function (e, ui) {
e.preventDefault();
var input_index = _(this.input_subviews).indexOf(
this.subviewForRoot(
this.$('div.oe_searchview_input:focus')[0]));
this.query.add(ui.item.facet, {at: input_index / 2});
},
childFocused: function () {
this.$el.addClass('oe_focused');
},
childBlurred: function () {
var val = this.$el.val();
this.$el.val('');
this.$el.removeClass('oe_focused')
.trigger('blur');
this.autocomplete.close();
},
/**
* Call the renderFacets method with the correct arguments.
* This is due to the fact that change events are called with two arguments
* (model, options) while add, reset and remove events are called with
* (collection, model, options) as arguments
*/
renderChangedFacets: function (model, options) {
this.renderFacets(undefined, model, options);
},
/**
* @param {openerp.web.search.SearchQuery | undefined} Undefined if event is change
* @param {openerp.web.search.Facet}
* @param {Object} [options]
*/
renderFacets: function (collection, model, options) {
var self = this;
var started = [];
var $e = this.$('div.oe_searchview_facets');
_.invoke(this.input_subviews, 'destroy');
this.input_subviews = [];
var i = new my.InputView(this);
started.push(i.appendTo($e));
this.input_subviews.push(i);
this.query.each(function (facet) {
var f = new my.FacetView(this, facet);
started.push(f.appendTo($e));
self.input_subviews.push(f);
var i = new my.InputView(this);
started.push(i.appendTo($e));
self.input_subviews.push(i);
}, this);
_.each(this.input_subviews, function (childView) {
childView.on('focused', self, self.proxy('childFocused'));
childView.on('blurred', self, self.proxy('childBlurred'));
});
$.when.apply(null, started).then(function () {
if (options && options.focus_input === false) return;
var input_to_focus;
// options.at: facet inserted at given index, focus next input
// otherwise just focus last input
if (!options || typeof options.at !== 'number') {
input_to_focus = _.last(self.input_subviews);
} else {
input_to_focus = self.input_subviews[(options.at + 1) * 2];
}
input_to_focus.$el.focus();
});
},
search_view_loaded: function(data) {
var self = this;
this.fields_view = data;
if (data.type !== 'search' ||
data.arch.tag !== 'search') {
throw new Error(_.str.sprintf(
"Got non-search view after asking for a search view: type %s, arch root %s",
data.type, data.arch.tag));
}
return this.drawer_ready
.then(this.proxy('setup_default_query'))
.then(function () {
self.trigger("search_view_loaded", data);
self.ready.resolve();
});
},
setup_default_query: function () {
// Hacky implementation of CustomFilters#facet_for_defaults ensure
// CustomFilters will be ready (and CustomFilters#filters will be
// correctly filled) by the time this method executes.
var custom_filters = this.drawer.custom_filters.filters;
if (!this.options.disable_custom_filters && !_(custom_filters).isEmpty()) {
// Check for any is_default custom filter
var personal_filter = _(custom_filters).find(function (filter) {
return filter.user_id && filter.is_default;
});
if (personal_filter) {
this.drawer.custom_filters.toggle_filter(personal_filter, true);
return;
}
var global_filter = _(custom_filters).find(function (filter) {
return !filter.user_id && filter.is_default;
});
if (global_filter) {
this.drawer.custom_filters.toggle_filter(global_filter, true);
return;
}
}
// No custom filter, or no is_default custom filter, apply view defaults
this.query.reset(_(arguments).compact(), {preventSearch: true});
},
/**
* Extract search data from the view's facets.
*
* Result is an object with 4 (own) properties:
*
* errors
* An array of any error generated during data validation and
* extraction, contains the validation error objects
* domains
* Array of domains
* contexts
* Array of contexts
* groupbys
* Array of domains, in groupby order rather than view order
*
* @return {Object}
*/
build_search_data: function () {
var domains = [], contexts = [], groupbys = [], errors = [];
this.query.each(function (facet) {
var field = facet.get('field');
try {
var domain = field.get_domain(facet);
if (domain) {
domains.push(domain);
}
var context = field.get_context(facet);
if (context) {
contexts.push(context);
}
var group_by = field.get_groupby(facet);
if (group_by) {
groupbys.push.apply(groupbys, group_by);
}
} catch (e) {
if (e instanceof instance.web.search.Invalid) {
errors.push(e);
} else {
throw e;
}
}
});
return {
domains: domains,
contexts: contexts,
groupbys: groupbys,
errors: errors
};
},
/**
* Performs the search view collection of widget data.
*
* If the collection went well (all fields are valid), then triggers
* :js:func:`instance.web.SearchView.on_search`.
*
* If at least one field failed its validation, triggers
* :js:func:`instance.web.SearchView.on_invalid` instead.
*
* @param [_query]
* @param {Object} [options]
*/
do_search: function (_query, options) {
if (options && options.preventSearch) {
return;
}
var search = this.build_search_data();
if (!_.isEmpty(search.errors)) {
this.on_invalid(search.errors);
return;
}
this.trigger('search_data', search.domains, search.contexts, search.groupbys);
},
/**
* Triggered after the SearchView has collected all relevant domains and
* contexts.
*
* It is provided with an Array of domains and an Array of contexts, which
* may or may not be evaluated (each item can be either a valid domain or
* context, or a string to evaluate in order in the sequence)
*
* It is also passed an array of contexts used for group_by (they are in
* the correct order for group_by evaluation, which contexts may not be)
*
* @event
* @param {Array} domains an array of literal domains or domain references
* @param {Array} contexts an array of literal contexts or context refs
* @param {Array} groupbys ordered contexts which may or may not have group_by keys
*/
/**
* Triggered after a validation error in the SearchView fields.
*
* Error objects have three keys:
* * ``field`` is the name of the invalid field
* * ``value`` is the invalid value
* * ``message`` is the (in)validation message provided by the field
*
* @event
* @param {Array} errors a never-empty array of error objects
*/
on_invalid: function (errors) {
this.do_notify(_t("Invalid Search"), _t("triggered from search view"));
this.trigger('invalid_search', errors);
},
// The method appendTo is overwrited to be able to insert the drawer anywhere
appendTo: function ($searchview_parent, $searchview_drawer_node) {
var $searchview_drawer_node = $searchview_drawer_node || $searchview_parent;
return $.when(
this._super($searchview_parent),
this.drawer.appendTo($searchview_drawer_node)
);
},
destroy: function () {
this.drawer.destroy();
this.getParent().destroy.call(this);
}
});
instance.web.SearchViewDrawer = instance.web.Widget.extend({
template: "SearchViewDrawer",
init: function(parent, searchview) {
this._super(parent);
this.searchview = searchview;
this.searchview.set_drawer(this);
this.ready = searchview.drawer_ready;
this.controls = [];
this.inputs = [];
},
toggle: function (visibility) {
this.$el.toggle(visibility);
var $view_manager_body = this.$el.closest('.oe_view_manager_body');
if ($view_manager_body.length) {
$view_manager_body.scrollTop(0);
}
},
start: function() {
var self = this;
if (this.searchview.headless) return $.when(this._super(), this.searchview.ready);
var filters_ready = this.searchview.fields_view_get
.then(this.proxy('prepare_filters'));
return $.when(this._super(), filters_ready).then(function () {
var defaults = arguments[1][0];
self.ready.resolve.apply(null, defaults);
});
},
prepare_filters: function (data) {
this.make_widgets(
data['arch'].children,
data.fields);
this.add_common_inputs();
// build drawer
var in_drawer = this.select_for_drawer();
var $first_col = this.$(".col-md-7"),
$snd_col = this.$(".col-md-5");
var add_custom_filters = in_drawer[0].appendTo($first_col),
add_filters = in_drawer[1].appendTo($first_col),
add_rest = $.when.apply(null, _(in_drawer.slice(2)).invoke('appendTo', $snd_col)),
defaults_fetched = $.when.apply(null, _(this.inputs).invoke(
'facet_for_defaults', this.searchview.defaults));
return $.when(defaults_fetched, add_custom_filters, add_filters, add_rest);
},
/**
* Sets up thingie where all the mess is put?
*/
select_for_drawer: function () {
return _(this.inputs).filter(function (input) {
return input.in_drawer();
});
},
/**
* Builds a list of widget rows (each row is an array of widgets)
*
* @param {Array} items a list of nodes to convert to widgets
* @param {Object} fields a mapping of field names to (ORM) field attributes
* @param {Object} [group] group to put the new controls in
*/
make_widgets: function (items, fields, group) {
if (!group) {
group = new instance.web.search.Group(
this, 'q', {attrs: {string: _t("Filters")}});
}
var self = this;
var filters = [];
_.each(items, function (item) {
if (filters.length && item.tag !== 'filter') {
group.push(new instance.web.search.FilterGroup(filters, group));
filters = [];
}
switch (item.tag) {
case 'separator': case 'newline':
break;
case 'filter':
filters.push(new instance.web.search.Filter(item, group));
break;
case 'group':
self.add_separator();
self.make_widgets(item.children, fields,
new instance.web.search.Group(group, 'w', item));
self.add_separator();
break;
case 'field':
var field = this.make_field(
item, fields[item['attrs'].name], group);
group.push(field);
// filters
self.make_widgets(item.children, fields, group);
break;
}
}, this);
if (filters.length) {
group.push(new instance.web.search.FilterGroup(filters, this));
}
},
add_separator: function () {
if (!(_.last(this.inputs) instanceof instance.web.search.Separator))
new instance.web.search.Separator(this);
},
/**
* Creates a field for the provided field descriptor item (which comes
* from fields_view_get)
*
* @param {Object} item fields_view_get node for the field
* @param {Object} field fields_get result for the field
* @param {Object} [parent]
* @returns instance.web.search.Field
*/
make_field: function (item, field, parent) {
// M2O combined with selection widget is pointless and broken in search views,
// but has been used in the past for unsupported hacks -> ignore it
if (field.type === "many2one" && item.attrs.widget === "selection"){
item.attrs.widget = undefined;
}
var obj = instance.web.search.fields.get_any( [item.attrs.widget, field.type]);
if(obj) {
return new (obj) (item, field, parent || this);
} else {
console.group('Unknown field type ' + field.type);
console.error('View node', item);
console.info('View field', field);
console.info('In view', this);
console.groupEnd();
return null;
}
},
add_common_inputs: function() {
// add custom filters to this.inputs
this.custom_filters = new instance.web.search.CustomFilters(this);
// add Filters to this.inputs, need view.controls filled
(new instance.web.search.Filters(this));
(new instance.web.search.SaveFilter(this, this.custom_filters));
// add Advanced to this.inputs
(new instance.web.search.Advanced(this));
},
});
/**
* Registry of search fields, called by :js:class:`instance.web.SearchView` to
* find and instantiate its field widgets.
*/
instance.web.search.fields = new instance.web.Registry({
'char': 'instance.web.search.CharField',
'text': 'instance.web.search.CharField',
'html': 'instance.web.search.CharField',
'boolean': 'instance.web.search.BooleanField',
'integer': 'instance.web.search.IntegerField',
'id': 'instance.web.search.IntegerField',
'float': 'instance.web.search.FloatField',
'selection': 'instance.web.search.SelectionField',
'datetime': 'instance.web.search.DateTimeField',
'date': 'instance.web.search.DateField',
'many2one': 'instance.web.search.ManyToOneField',
'many2many': 'instance.web.search.CharField',
'one2many': 'instance.web.search.CharField'
});
instance.web.search.Invalid = instance.web.Class.extend( /** @lends instance.web.search.Invalid# */{
/**
* Exception thrown by search widgets when they hold invalid values,
* which they can not return when asked.
*
* @constructs instance.web.search.Invalid
* @extends instance.web.Class
*
* @param field the name of the field holding an invalid value
* @param value the invalid value
* @param message validation failure message
*/
init: function (field, value, message) {
this.field = field;
this.value = value;
this.message = message;
},
toString: function () {
return _.str.sprintf(
_t("Incorrect value for field %(fieldname)s: [%(value)s] is %(message)s"),
{fieldname: this.field, value: this.value, message: this.message}
);
}
});
instance.web.search.Widget = instance.web.Widget.extend( /** @lends instance.web.search.Widget# */{
template: null,
/**
* Root class of all search widgets
*
* @constructs instance.web.search.Widget
* @extends instance.web.Widget
*
* @param parent parent of this widget
*/
init: function (parent) {
this._super(parent);
var ancestor = parent;
do {
this.drawer = ancestor;
} while (!(ancestor instanceof instance.web.SearchViewDrawer)
&& (ancestor = (ancestor.getParent && ancestor.getParent())));
this.view = this.drawer.searchview || this.drawer;
}
});
instance.web.search.add_expand_listener = function($root) {
$root.find('a.searchview_group_string').click(function (e) {
$root.toggleClass('folded expanded');
e.stopPropagation();
e.preventDefault();
});
};
instance.web.search.Group = instance.web.search.Widget.extend({
init: function (parent, icon, node) {
this._super(parent);
var attrs = node.attrs;
this.modifiers = attrs.modifiers =
attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
this.attrs = attrs;
this.icon = icon;
this.name = attrs.string;
this.children = [];
this.drawer.controls.push(this);
},
push: function (input) {
this.children.push(input);
},
visible: function () {
return !this.modifiers.invisible;
},
});
instance.web.search.Input = instance.web.search.Widget.extend( /** @lends instance.web.search.Input# */{
_in_drawer: false,
/**
* @constructs instance.web.search.Input
* @extends instance.web.search.Widget
*
* @param parent
*/
init: function (parent) {
this._super(parent);
this.load_attrs({});
this.drawer.inputs.push(this);
},
/**
* Fetch auto-completion values for the widget.
*
* The completion values should be an array of objects with keys category,
* label, value prefixed with an object with keys type=section and label
*
* @param {String} value value to complete
* @returns {jQuery.Deferred<null|Array>}
*/
complete: function (value) {
return $.when(null);
},
/**
* Returns a Facet instance for the provided defaults if they apply to
* this widget, or null if they don't.
*
* This default implementation will try calling
* :js:func:`instance.web.search.Input#facet_for` if the widget's name
* matches the input key
*
* @param {Object} defaults
* @returns {jQuery.Deferred<null|Object>}
*/
facet_for_defaults: function (defaults) {
if (!this.attrs ||
!(this.attrs.name in defaults && defaults[this.attrs.name])) {
return $.when(null);
}
return this.facet_for(defaults[this.attrs.name]);
},
in_drawer: function () {
return !!this._in_drawer;
},
get_context: function () {
throw new Error(
"get_context not implemented for widget " + this.attrs.type);
},
get_groupby: function () {
throw new Error(
"get_groupby not implemented for widget " + this.attrs.type);
},
get_domain: function () {
throw new Error(
"get_domain not implemented for widget " + this.attrs.type);
},
load_attrs: function (attrs) {
attrs.modifiers = attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
this.attrs = attrs;
},
/**
* Returns whether the input is "visible". The default behavior is to
* query the ``modifiers.invisible`` flag on the input's description or
* view node.
*
* @returns {Boolean}
*/
visible: function () {
if (this.attrs.modifiers.invisible) {
return false;
}
var parent = this;
while ((parent = parent.getParent()) &&
( (parent instanceof instance.web.search.Group)
|| (parent instanceof instance.web.search.Input))) {
if (!parent.visible()) {
return false;
}
}
return true;
},
});
instance.web.search.FilterGroup = instance.web.search.Input.extend(/** @lends instance.web.search.FilterGroup# */{
template: 'SearchView.filters',
icon: 'q',
completion_label: _lt("Filter on: %s"),
/**
* Inclusive group of filters, creates a continuous "button" with clickable
* sections (the normal display for filters is to be a self-contained button)
*
* @constructs instance.web.search.FilterGroup
* @extends instance.web.search.Input
*
* @param {Array<instance.web.search.Filter>} filters elements of the group
* @param {instance.web.SearchView} parent parent in which the filters are contained
*/
init: function (filters, parent) {
// If all filters are group_by and we're not initializing a GroupbyGroup,
// create a GroupbyGroup instead of the current FilterGroup
if (!(this instanceof instance.web.search.GroupbyGroup) &&
_(filters).all(function (f) {
if (!f.attrs.context) { return false; }
var c = instance.web.pyeval.eval('context', f.attrs.context);
return !_.isEmpty(c.group_by);})) {
return new instance.web.search.GroupbyGroup(filters, parent);
}
this._super(parent);
this.filters = filters;
this.view.query.on('add remove change reset', this.proxy('search_change'));
},
start: function () {
this.$el.on('click', 'li', this.proxy('toggle_filter'));
return $.when(null);
},
/**
* Handles change of the search query: any of the group's filter which is
* in the search query should be visually checked in the drawer
*/
search_change: function () {
var self = this;
var $filters = this.$('> li').removeClass('badge');
var facet = this.view.query.find(_.bind(this.match_facet, this));
if (!facet) { return; }
facet.values.each(function (v) {
var i = _(self.filters).indexOf(v.get('value'));
if (i === -1) { return; }
$filters.filter(function () {
return Number($(this).data('index')) === i;
}).addClass('badge');
});
},
/**
* Matches the group to a facet, in order to find if the group is
* represented in the current search query
*/
match_facet: function (facet) {
return facet.get('field') === this;
},
make_facet: function (values) {
return {
category: _t("Filter"),
icon: this.icon,
values: values,
field: this
};
},
make_value: function (filter) {
return {
label: filter.attrs.string || filter.attrs.help || filter.attrs.name,
value: filter
};
},
facet_for_defaults: function (defaults) {
var self = this;
var fs = _(this.filters).chain()
.filter(function (f) {
return f.attrs && f.attrs.name && !!defaults[f.attrs.name];
}).map(function (f) {
return self.make_value(f);
}).value();
if (_.isEmpty(fs)) { return $.when(null); }
return $.when(this.make_facet(fs));
},
/**
* Fetches contexts for all enabled filters in the group
*
* @param {openerp.web.search.Facet} facet
* @return {*} combined contexts of the enabled filters in this group
*/
get_context: function (facet) {
var contexts = facet.values.chain()
.map(function (f) { return f.get('value').attrs.context; })
.without('{}')
.reject(_.isEmpty)
.value();
if (!contexts.length) { return; }
if (contexts.length === 1) { return contexts[0]; }
return _.extend(new instance.web.CompoundContext(), {
__contexts: contexts
});
},
/**
* Fetches group_by sequence for all enabled filters in the group
*
* @param {VS.model.SearchFacet} facet
* @return {Array} enabled filters in this group
*/
get_groupby: function (facet) {
return facet.values.chain()
.map(function (f) { return f.get('value').attrs.context; })
.without('{}')
.reject(_.isEmpty)
.value();
},
/**
* Handles domains-fetching for all the filters within it: groups them.
*
* @param {VS.model.SearchFacet} facet
* @return {*} combined domains of the enabled filters in this group
*/
get_domain: function (facet) {
var domains = facet.values.chain()
.map(function (f) { return f.get('value').attrs.domain; })
.without('[]')
.reject(_.isEmpty)
.value();
if (!domains.length) { return; }
if (domains.length === 1) { return domains[0]; }
for (var i=domains.length; --i;) {
domains.unshift(['|']);
}
return _.extend(new instance.web.CompoundDomain(), {
__domains: domains
});
},
toggle_filter: function (e) {
this.toggle(this.filters[Number($(e.target).data('index'))]);
},
toggle: function (filter) {
this.view.query.toggle(this.make_facet([this.make_value(filter)]));
},
complete: function (item) {
var self = this;
item = item.toLowerCase();
var facet_values = _(this.filters).chain()
.filter(function (filter) { return filter.visible(); })
.filter(function (filter) {
var at = {
string: filter.attrs.string || '',
help: filter.attrs.help || '',
name: filter.attrs.name || ''
};
var include = _.str.include;
return include(at.string.toLowerCase(), item)
|| include(at.help.toLowerCase(), item)
|| include(at.name.toLowerCase(), item);
})
.map(this.make_value)
.value();
if (_(facet_values).isEmpty()) { return $.when(null); }
return $.when(_.map(facet_values, function (facet_value) {
return {
label: _.str.sprintf(self.completion_label.toString(),
_.escape(facet_value.label)),
facet: self.make_facet([facet_value])
};
}));
}
});
instance.web.search.GroupbyGroup = instance.web.search.FilterGroup.extend({
icon: 'w',
completion_label: _lt("Group by: %s"),
init: function (filters, parent) {
this._super(filters, parent);
// Not flanders: facet unicity is handled through the
// (category, field) pair of facet attributes. This is all well and
// good for regular filter groups where a group matches a facet, but for
// groupby we want a single facet. So cheat: add an attribute on the
// view which proxies to the first GroupbyGroup, so it can be used
// for every GroupbyGroup and still provides the various methods needed
// by the search view. Use weirdo name to avoid risks of conflicts
if (!this.view._s_groupby) {
this.view._s_groupby = {
help: "See GroupbyGroup#init",
get_context: this.proxy('get_context'),
get_domain: this.proxy('get_domain'),
get_groupby: this.proxy('get_groupby')
};
}
},
match_facet: function (facet) {
return facet.get('field') === this.view._s_groupby;
},
make_facet: function (values) {
return {
category: _t("GroupBy"),
icon: this.icon,
values: values,
field: this.view._s_groupby
};
}
});
instance.web.search.Filter = instance.web.search.Input.extend(/** @lends instance.web.search.Filter# */{
template: 'SearchView.filter',
/**
* Implementation of the OpenERP filters (button with a context and/or
* a domain sent as-is to the search view)
*
* Filters are only attributes holder, the actual work (compositing
* domains and contexts, converting between facets and filters) is
* performed by the filter group.
*
* @constructs instance.web.search.Filter
* @extends instance.web.search.Input
*
* @param node
* @param parent
*/
init: function (node, parent) {
this._super(parent);
this.load_attrs(node.attrs);
},
facet_for: function () { return $.when(null); },
get_context: function () { },
get_domain: function () { },
});
instance.web.search.Separator = instance.web.search.Input.extend({
_in_drawer: false,
complete: function () {
return {is_separator: true};
}
});
instance.web.search.Field = instance.web.search.Input.extend( /** @lends instance.web.search.Field# */ {
template: 'SearchView.field',
default_operator: '=',
/**
* @constructs instance.web.search.Field
* @extends instance.web.search.Input
*
* @param view_section
* @param field
* @param parent
*/
init: function (view_section, field, parent) {
this._super(parent);
this.load_attrs(_.extend({}, field, view_section.attrs));
},
facet_for: function (value) {
return $.when({
field: this,
category: this.attrs.string || this.attrs.name,
values: [{label: String(value), value: value}]
});
},
value_from: function (facetValue) {
return facetValue.get('value');
},
get_context: function (facet) {
var self = this;
// A field needs a context to send when active
var context = this.attrs.context;
if (_.isEmpty(context) || !facet.values.length) {
return;
}
var contexts = facet.values.map(function (facetValue) {
return new instance.web.CompoundContext(context)
.set_eval_context({self: self.value_from(facetValue)});
});
if (contexts.length === 1) { return contexts[0]; }
return _.extend(new instance.web.CompoundContext(), {
__contexts: contexts
});
},
get_groupby: function () { },
/**
* Function creating the returned domain for the field, override this
* methods in children if you only need to customize the field's domain
* without more complex alterations or tests (and without the need to
* change override the handling of filter_domain)
*
* @param {String} name the field's name
* @param {String} operator the field's operator (either attribute-specified or default operator for the field
* @param {Number|String} facet parsed value for the field
* @returns {Array<Array>} domain to include in the resulting search
*/
make_domain: function (name, operator, facet) {
return [[name, operator, this.value_from(facet)]];
},
get_domain: function (facet) {
if (!facet.values.length) { return; }
var value_to_domain;
var self = this;
var domain = this.attrs['filter_domain'];
if (domain) {
value_to_domain = function (facetValue) {
return new instance.web.CompoundDomain(domain)
.set_eval_context({self: self.value_from(facetValue)});
};
} else {
value_to_domain = function (facetValue) {
return self.make_domain(
self.attrs.name,
self.attrs.operator || self.default_operator,
facetValue);
};
}
var domains = facet.values.map(value_to_domain);
if (domains.length === 1) { return domains[0]; }
for (var i = domains.length; --i;) {
domains.unshift(['|']);
}
return _.extend(new instance.web.CompoundDomain(), {
__domains: domains
});
}
});
/**
* Implementation of the ``char`` OpenERP field type:
*
* * Default operator is ``ilike`` rather than ``=``
*
* * The Javascript and the HTML values are identical (strings)
*
* @class
* @extends instance.web.search.Field
*/
instance.web.search.CharField = instance.web.search.Field.extend( /** @lends instance.web.search.CharField# */ {
default_operator: 'ilike',
complete: function (value) {
if (_.isEmpty(value)) { return $.when(null); }
var label = _.str.sprintf(_.str.escapeHTML(
_t("Search %(field)s for: %(value)s")), {
field: '<em>' + _.escape(this.attrs.string) + '</em>',
value: '<strong>' + _.escape(value) + '</strong>'});
return $.when([{
label: label,
facet: {
category: this.attrs.string,
field: this,
values: [{label: value, value: value}]
}
}]);
}
});
instance.web.search.NumberField = instance.web.search.Field.extend(/** @lends instance.web.search.NumberField# */{
complete: function (value) {
var val = this.parse(value);
if (isNaN(val)) { return $.when(); }
var label = _.str.sprintf(
_t("Search %(field)s for: %(value)s"), {
field: '<em>' + _.escape(this.attrs.string) + '</em>',
value: '<strong>' + _.escape(value) + '</strong>'});
return $.when([{
label: label,
facet: {
category: this.attrs.string,
field: this,
values: [{label: value, value: val}]
}
}]);
},
});
/**
* @class
* @extends instance.web.search.NumberField
*/
instance.web.search.IntegerField = instance.web.search.NumberField.extend(/** @lends instance.web.search.IntegerField# */{
error_message: _t("not a valid integer"),
parse: function (value) {
try {
return instance.web.parse_value(value, {'widget': 'integer'});
} catch (e) {
return NaN;
}
}
});
/**
* @class
* @extends instance.web.search.NumberField
*/
instance.web.search.FloatField = instance.web.search.NumberField.extend(/** @lends instance.web.search.FloatField# */{
error_message: _t("not a valid number"),
parse: function (value) {
try {
return instance.web.parse_value(value, {'widget': 'float'});
} catch (e) {
return NaN;
}
}
});
/**
* Utility function for m2o & selection fields taking a selection/name_get pair
* (value, name) and converting it to a Facet descriptor
*
* @param {instance.web.search.Field} field holder field
* @param {Array} pair pair value to convert
*/
function facet_from(field, pair) {
return {
field: field,
category: field['attrs'].string,
values: [{label: pair[1], value: pair[0]}]
};
}
/**
* @class
* @extends instance.web.search.Field
*/
instance.web.search.SelectionField = instance.web.search.Field.extend(/** @lends instance.web.search.SelectionField# */{
// This implementation is a basic <select> field, but it may have to be
// altered to be more in line with the GTK client, which uses a combo box
// (~ jquery.autocomplete):
// * If an option was selected in the list, behave as currently
// * If something which is not in the list was entered (via the text input),
// the default domain should become (`ilike` string_value) but **any
// ``context`` or ``filter_domain`` becomes falsy, idem if ``@operator``
// is specified. So at least get_domain needs to be quite a bit
// overridden (if there's no @value and there is no filter_domain and
// there is no @operator, return [[name, 'ilike', str_val]]
template: 'SearchView.field.selection',
init: function () {
this._super.apply(this, arguments);
// prepend empty option if there is no empty option in the selection list
this.prepend_empty = !_(this.attrs.selection).detect(function (item) {
return !item[1];
});
},
complete: function (needle) {
var self = this;
var results = _(this.attrs.selection).chain()
.filter(function (sel) {
var value = sel[0], label = sel[1];
if (!value) { return false; }
return label.toLowerCase().indexOf(needle.toLowerCase()) !== -1;
})
.map(function (sel) {
return {
label: _.escape(sel[1]),
facet: facet_from(self, sel)
};
}).value();
if (_.isEmpty(results)) { return $.when(null); }
return $.when.call(null, [{
label: _.escape(this.attrs.string)
}].concat(results));
},
facet_for: function (value) {
var match = _(this.attrs.selection).detect(function (sel) {
return sel[0] === value;
});
if (!match) { return $.when(null); }
return $.when(facet_from(this, match));
}
});
instance.web.search.BooleanField = instance.web.search.SelectionField.extend(/** @lends instance.web.search.BooleanField# */{
/**
* @constructs instance.web.search.BooleanField
* @extends instance.web.search.BooleanField
*/
init: function () {
this._super.apply(this, arguments);
this.attrs.selection = [
[true, _t("Yes")],
[false, _t("No")]
];
}
});
/**
* @class
* @extends instance.web.search.DateField
*/
instance.web.search.DateField = instance.web.search.Field.extend(/** @lends instance.web.search.DateField# */{
value_from: function (facetValue) {
return instance.web.date_to_str(facetValue.get('value'));
},
complete: function (needle) {
var d = Date.parse(needle);
if (!d) { return $.when(null); }
var date_string = instance.web.format_value(d, this.attrs);
var label = _.str.sprintf(_.str.escapeHTML(
_t("Search %(field)s at: %(value)s")), {
field: '<em>' + _.escape(this.attrs.string) + '</em>',
value: '<strong>' + date_string + '</strong>'});
return $.when([{
label: label,
facet: {
category: this.attrs.string,
field: this,
values: [{label: date_string, value: d}]
}
}]);
}
});
/**
* Implementation of the ``datetime`` openerp field type:
*
* * Uses the same widget as the ``date`` field type (a simple date)
*
* * Builds a slighly more complex, it's a datetime range (includes time)
* spanning the whole day selected by the date widget
*
* @class
* @extends instance.web.DateField
*/
instance.web.search.DateTimeField = instance.web.search.DateField.extend(/** @lends instance.web.search.DateTimeField# */{
value_from: function (facetValue) {
return instance.web.datetime_to_str(facetValue.get('value'));
}
});
instance.web.search.ManyToOneField = instance.web.search.CharField.extend({
default_operator: {},
init: function (view_section, field, parent) {
this._super(view_section, field, parent);
this.model = new instance.web.Model(this.attrs.relation);
},
complete: function (value) {
if (_.isEmpty(value)) { return $.when(null); }
var label = _.str.sprintf(_.str.escapeHTML(
_t("Search %(field)s for: %(value)s")), {
field: '<em>' + _.escape(this.attrs.string) + '</em>',
value: '<strong>' + _.escape(value) + '</strong>'});
return $.when([{
label: label,
facet: {
category: this.attrs.string,
field: this,
values: [{label: value, value: value}]
},
expand: this.expand.bind(this),
}]);
},
expand: function (needle) {
var self = this;
// FIXME: "concurrent" searches (multiple requests, mis-ordered responses)
var context = instance.web.pyeval.eval(
'contexts', [this.view.dataset.get_context()]);
return this.model.call('name_search', [], {
name: needle,
args: instance.web.pyeval.eval(
'domains', this.attrs.domain ? [this.attrs.domain] : [], context),
limit: 8,
context: context
}).then(function (results) {
if (_.isEmpty(results)) { return null; }
return _(results).map(function (result) {
return {
label: _.escape(result[1]),
facet: facet_from(self, result)
};
});
});
},
facet_for: function (value) {
var self = this;
if (value instanceof Array) {
if (value.length === 2 && _.isString(value[1])) {
return $.when(facet_from(this, value));
}
assert(value.length <= 1,
_t("M2O search fields do not currently handle multiple default values"));
// there are many cases of {search_default_$m2ofield: [id]}, need
// to handle this as if it were a single value.
value = value[0];
}
return this.model.call('name_get', [value]).then(function (names) {
if (_(names).isEmpty()) { return null; }
return facet_from(self, names[0]);
});
},
value_from: function (facetValue) {
return facetValue.get('label');
},
make_domain: function (name, operator, facetValue) {
switch(operator){
case this.default_operator:
return [[name, '=', facetValue.get('value')]];
case 'child_of':
return [[name, 'child_of', facetValue.get('value')]];
}
return this._super(name, operator, facetValue);
},
get_context: function (facet) {
var values = facet.values;
if (_.isEmpty(this.attrs.context) && values.length === 1) {
var c = {};
c['default_' + this.attrs.name] = values.at(0).get('value');
return c;
}
return this._super(facet);
}
});
instance.web.search.CustomFilters = instance.web.search.Input.extend({
template: 'SearchView.Custom',
_in_drawer: true,
init: function () {
this.is_ready = $.Deferred();
this._super.apply(this,arguments);
},
start: function () {
var self = this;
this.model = new instance.web.Model('ir.filters');
this.filters = {};
this.$filters = {};
this.view.query
.on('remove', function (facet) {
if (!facet.get('is_custom_filter')) {
return;
}
self.clear_selection();
})
.on('reset', this.proxy('clear_selection'));
return this.model.call('get_filters', [this.view.model, this.get_action_id()])
.then(this.proxy('set_filters'))
.done(function () { self.is_ready.resolve(); })
.fail(function () { self.is_ready.reject.apply(self.is_ready, arguments); });
},
get_action_id: function(){
var action = instance.client.action_manager.inner_action;
if (action) return action.id;
},
/**
* Special implementation delaying defaults until CustomFilters is loaded
*/
facet_for_defaults: function () {
return this.is_ready;
},
/**
* Generates a mapping key (in the filters and $filter mappings) for the
* filter descriptor object provided (as returned by ``get_filters``).
*
* The mapping key is guaranteed to be unique for a given (user_id, name)
* pair.
*
* @param {Object} filter
* @param {String} filter.name
* @param {Number|Pair<Number, String>} [filter.user_id]
* @return {String} mapping key corresponding to the filter
*/
key_for: function (filter) {
var user_id = filter.user_id,
action_id = filter.action_id;
var uid = (user_id instanceof Array) ? user_id[0] : user_id;
var act_id = (action_id instanceof Array) ? action_id[0] : action_id;
return _.str.sprintf('(%s)(%s)%s', uid, act_id, filter.name);
},
/**
* Generates a :js:class:`~instance.web.search.Facet` descriptor from a
* filter descriptor
*
* @param {Object} filter
* @param {String} filter.name
* @param {Object} [filter.context]
* @param {Array} [filter.domain]
* @return {Object}
*/
facet_for: function (filter) {
return {
category: _t("Custom Filter"),
icon: 'M',
field: {
get_context: function () { return filter.context; },
get_groupby: function () { return [filter.context]; },
get_domain: function () { return filter.domain; }
},
_id: filter['id'],
is_custom_filter: true,
values: [{label: filter.name, value: null}]
};
},
clear_selection: function () {
this.$('span.badge').removeClass('badge');
},
append_filter: function (filter) {
var self = this;
var key = this.key_for(filter);
var warning = _t("This filter is global and will be removed for everybody if you continue.");
var $filter;
if (key in this.$filters) {
$filter = this.$filters[key];
} else {
var id = filter.id;
this.filters[key] = filter;
$filter = $('<li></li>')
.appendTo(this.$('.oe_searchview_custom_list'))
.toggleClass('oe_searchview_custom_default', filter.is_default)
.append(this.$filters[key] = $('<span>').text(filter.name));
this.$filters[key].addClass(filter.user_id ? 'oe_searchview_custom_private'
: 'oe_searchview_custom_public')
$('<a class="oe_searchview_custom_delete">x</a>')
.click(function (e) {
e.stopPropagation();
if (!(filter.user_id || confirm(warning))) {
return;
}
self.model.call('unlink', [id]).done(function () {
$filter.remove();
delete self.$filters[key];
delete self.filters[key];
if (_.isEmpty(self.filters)) {
self.hide();
}
});
})
.appendTo($filter);
}
this.$filters[key].unbind('click').click(function () {
self.toggle_filter(filter);
});
this.show();
},
toggle_filter: function (filter, preventSearch) {
var current = this.view.query.find(function (facet) {
return facet.get('_id') === filter.id;
});
if (current) {
this.view.query.remove(current);
this.$filters[this.key_for(filter)].removeClass('badge');
return;
}
this.view.query.reset([this.facet_for(filter)], {
preventSearch: preventSearch || false});
this.$filters[this.key_for(filter)].addClass('badge');
},
set_filters: function (filters) {
_(filters).map(_.bind(this.append_filter, this));
if (!filters.length) {
this.hide();
}
},
hide: function () {
this.$el.hide();
},
show: function () {
this.$el.show();
},
});
instance.web.search.SaveFilter = instance.web.search.Input.extend({
template: 'SearchView.SaveFilter',
_in_drawer: true,
init: function (parent, custom_filters) {
this._super(parent);
this.custom_filters = custom_filters;
},
start: function () {
var self = this;
this.model = new instance.web.Model('ir.filters');
this.$el.on('submit', 'form', this.proxy('save_current'));
this.$el.on('click', 'input[type=checkbox]', function() {
$(this).siblings('input[type=checkbox]').prop('checked', false);
});
this.$el.on('click', 'h4', function () {
self.$el.toggleClass('oe_opened');
});
},
save_current: function () {
var self = this;
var $name = this.$('input:first');
var private_filter = !this.$('#oe_searchview_custom_public').prop('checked');
var set_as_default = this.$('#oe_searchview_custom_default').prop('checked');
if (_.isEmpty($name.val())){
this.do_warn(_t("Error"), _t("Filter name is required."));
return false;
}
var search = this.view.build_search_data();
instance.web.pyeval.eval_domains_and_contexts({
domains: search.domains,
contexts: search.contexts,
group_by_seq: search.groupbys || []
}).done(function (results) {
if (!_.isEmpty(results.group_by)) {
results.context.group_by = results.group_by;
}
// Don't save user_context keys in the custom filter, otherwise end
// up with e.g. wrong uid or lang stored *and used in subsequent
// reqs*
var ctx = results.context;
_(_.keys(instance.session.user_context)).each(function (key) {
delete ctx[key];
});
var filter = {
name: $name.val(),
user_id: private_filter ? instance.session.uid : false,
model_id: self.view.model,
context: results.context,
domain: results.domain,
is_default: set_as_default,
action_id: self.custom_filters.get_action_id()
};
// FIXME: current context?
return self.model.call('create_or_replace', [filter]).done(function (id) {
filter.id = id;
if (self.custom_filters) {
self.custom_filters.append_filter(filter);
}
self.$el
.removeClass('oe_opened')
.find('form')[0].reset();
});
});
return false;
},
});
instance.web.search.Filters = instance.web.search.Input.extend({
template: 'SearchView.Filters',
_in_drawer: true,
start: function () {
var self = this;
var is_group = function (i) { return i instanceof instance.web.search.FilterGroup; };
var visible_filters = _(this.drawer.controls).chain().reject(function (group) {
return _(_(group.children).filter(is_group)).isEmpty()
|| group.modifiers.invisible;
});
var groups = visible_filters.map(function (group) {
var filters = _(group.children).filter(is_group);
return {
name: _.str.sprintf("<span class='oe_i'>%s</span> %s",
group.icon, group.name),
filters: filters,
length: _(filters).chain().map(function (i) {
return i.filters.length; }).sum().value()
};
}).value();
var $dl = $('<dl class="dl-horizontal">').appendTo(this.$el);
var rendered_lines = _.map(groups, function (group) {
$('<dt>').html(group.name).appendTo($dl);
var $dd = $('<dd>').appendTo($dl);
return $.when.apply(null, _(group.filters).invoke('appendTo', $dd));
});
return $.when.apply(this, rendered_lines);
},
});
instance.web.search.Advanced = instance.web.search.Input.extend({
template: 'SearchView.advanced',
_in_drawer: true,
start: function () {
var self = this;
this.$el
.on('keypress keydown keyup', function (e) { e.stopPropagation(); })
.on('click', 'h4', function () {
self.$el.toggleClass('oe_opened');
}).on('click', 'button.oe_add_condition', function () {
self.append_proposition();
}).on('submit', 'form', function (e) {
e.preventDefault();
self.commit_search();
});
return $.when(
this._super(),
new instance.web.Model(this.view.model).call('fields_get', {
context: this.view.dataset.context
}).done(function(data) {
self.fields = {
id: { string: 'ID', type: 'id' }
};
_.each(data, function(field_def, field_name) {
if (field_def.selectable !== false && field_name != 'id') {
self.fields[field_name] = field_def;
}
});
})).done(function () {
self.append_proposition();
});
},
append_proposition: function () {
var self = this;
return (new instance.web.search.ExtendedSearchProposition(this, this.fields))
.appendTo(this.$('ul')).done(function () {
self.$('button.oe_apply').prop('disabled', false);
});
},
remove_proposition: function (prop) {
// removing last proposition, disable apply button
if (this.getChildren().length <= 1) {
this.$('button.oe_apply').prop('disabled', true);
}
prop.destroy();
},
commit_search: function () {
// Get domain sections from all propositions
var children = this.getChildren();
var propositions = _.invoke(children, 'get_proposition');
var domain = _(propositions).pluck('value');
for (var i = domain.length; --i;) {
domain.unshift('|');
}
this.view.query.add({
category: _t("Advanced"),
values: propositions,
field: {
get_context: function () { },
get_domain: function () { return domain;},
get_groupby: function () { }
}
});
// remove all propositions
_.invoke(children, 'destroy');
// add new empty proposition
this.append_proposition();
// TODO: API on searchview
this.view.$el.removeClass('oe_searchview_open_drawer');
}
});
instance.web.search.ExtendedSearchProposition = instance.web.Widget.extend(/** @lends instance.web.search.ExtendedSearchProposition# */{
template: 'SearchView.extended_search.proposition',
events: {
'change .searchview_extended_prop_field': 'changed',
'change .searchview_extended_prop_op': 'operator_changed',
'click .searchview_extended_delete_prop': function (e) {
e.stopPropagation();
this.getParent().remove_proposition(this);
}
},
/**
* @constructs instance.web.search.ExtendedSearchProposition
* @extends instance.web.Widget
*
* @param parent
* @param fields
*/
init: function (parent, fields) {
this._super(parent);
this.fields = _(fields).chain()
.map(function(val, key) { return _.extend({}, val, {'name': key}); })
.filter(function (field) { return !field.deprecated && (field.store === void 0 || field.store || field.fnct_search); })
.sortBy(function(field) {return field.string;})
.value();
this.attrs = {_: _, fields: this.fields, selected: null};
this.value = null;
},
start: function () {
return this._super().done(this.proxy('changed'));
},
changed: function() {
var nval = this.$(".searchview_extended_prop_field").val();
if(this.attrs.selected === null || this.attrs.selected === undefined || nval != this.attrs.selected.name) {
this.select_field(_.detect(this.fields, function(x) {return x.name == nval;}));
}
},<|fim▁hole|> operator_changed: function (e) {
var $value = this.$('.searchview_extended_prop_value');
switch ($(e.target).val()) {
case '∃':
case '∄':
$value.hide();
break;
default:
$value.show();
}
},
/**
* Selects the provided field object
*
* @param field a field descriptor object (as returned by fields_get, augmented by the field name)
*/
select_field: function(field) {
var self = this;
if(this.attrs.selected !== null && this.attrs.selected !== undefined) {
this.value.destroy();
this.value = null;
this.$('.searchview_extended_prop_op').html('');
}
this.attrs.selected = field;
if(field === null || field === undefined) {
return;
}
var type = field.type;
var Field = instance.web.search.custom_filters.get_object(type);
if(!Field) {
Field = instance.web.search.custom_filters.get_object("char");
}
this.value = new Field(this, field);
_.each(this.value.operators, function(operator) {
$('<option>', {value: operator.value})
.text(String(operator.text))
.appendTo(self.$('.searchview_extended_prop_op'));
});
var $value_loc = this.$('.searchview_extended_prop_value').show().empty();
this.value.appendTo($value_loc);
},
get_proposition: function() {
if (this.attrs.selected === null || this.attrs.selected === undefined)
return null;
var field = this.attrs.selected;
var op_select = this.$('.searchview_extended_prop_op')[0];
var operator = op_select.options[op_select.selectedIndex];
return {
label: this.value.get_label(field, operator),
value: this.value.get_domain(field, operator),
};
}
});
instance.web.search.ExtendedSearchProposition.Field = instance.web.Widget.extend({
init: function (parent, field) {
this._super(parent);
this.field = field;
},
get_label: function (field, operator) {
var format;
switch (operator.value) {
case '∃': case '∄': format = _t('%(field)s %(operator)s'); break;
default: format = _t('%(field)s %(operator)s "%(value)s"'); break;
}
return this.format_label(format, field, operator);
},
format_label: function (format, field, operator) {
return _.str.sprintf(format, {
field: field.string,
// According to spec, HTMLOptionElement#label should return
// HTMLOptionElement#text when not defined/empty, but it does
// not in older Webkit (between Safari 5.1.5 and Chrome 17) and
// Gecko (pre Firefox 7) browsers, so we need a manual fallback
// for those
operator: operator.label || operator.text,
value: this
});
},
get_domain: function (field, operator) {
switch (operator.value) {
case '∃': return this.make_domain(field.name, '!=', false);
case '∄': return this.make_domain(field.name, '=', false);
default: return this.make_domain(
field.name, operator.value, this.get_value());
}
},
make_domain: function (field, operator, value) {
return [field, operator, value];
},
/**
* Returns a human-readable version of the value, in case the "logical"
* and the "semantic" values of a field differ (as for selection fields,
* for instance).
*
* The default implementation simply returns the value itself.
*
* @return {String} human-readable version of the value
*/
toString: function () {
return this.get_value();
}
});
instance.web.search.ExtendedSearchProposition.Char = instance.web.search.ExtendedSearchProposition.Field.extend({
template: 'SearchView.extended_search.proposition.char',
operators: [
{value: "ilike", text: _lt("contains")},
{value: "not ilike", text: _lt("doesn't contain")},
{value: "=", text: _lt("is equal to")},
{value: "!=", text: _lt("is not equal to")},
{value: "∃", text: _lt("is set")},
{value: "∄", text: _lt("is not set")}
],
get_value: function() {
return this.$el.val();
}
});
instance.web.search.ExtendedSearchProposition.DateTime = instance.web.search.ExtendedSearchProposition.Field.extend({
template: 'SearchView.extended_search.proposition.empty',
operators: [
{value: "=", text: _lt("is equal to")},
{value: "!=", text: _lt("is not equal to")},
{value: ">", text: _lt("greater than")},
{value: "<", text: _lt("less than")},
{value: ">=", text: _lt("greater or equal than")},
{value: "<=", text: _lt("less or equal than")},
{value: "∃", text: _lt("is set")},
{value: "∄", text: _lt("is not set")}
],
/**
* Date widgets live in view_form which is not yet loaded when this is
* initialized -_-
*/
widget: function () { return instance.web.DateTimeWidget; },
get_value: function() {
return this.datewidget.get_value();
},
toString: function () {
return instance.web.format_value(this.get_value(), { type:"datetime" });
},
start: function() {
var ready = this._super();
this.datewidget = new (this.widget())(this);
this.datewidget.appendTo(this.$el);
return ready;
}
});
instance.web.search.ExtendedSearchProposition.Date = instance.web.search.ExtendedSearchProposition.DateTime.extend({
widget: function () { return instance.web.DateWidget; },
toString: function () {
return instance.web.format_value(this.get_value(), { type:"date" });
}
});
instance.web.search.ExtendedSearchProposition.Integer = instance.web.search.ExtendedSearchProposition.Field.extend({
template: 'SearchView.extended_search.proposition.integer',
operators: [
{value: "=", text: _lt("is equal to")},
{value: "!=", text: _lt("is not equal to")},
{value: ">", text: _lt("greater than")},
{value: "<", text: _lt("less than")},
{value: ">=", text: _lt("greater or equal than")},
{value: "<=", text: _lt("less or equal than")},
{value: "∃", text: _lt("is set")},
{value: "∄", text: _lt("is not set")}
],
toString: function () {
return this.$el.val();
},
get_value: function() {
try {
var val =this.$el.val();
return instance.web.parse_value(val === "" ? 0 : val, {'widget': 'integer'});
} catch (e) {
return "";
}
}
});
instance.web.search.ExtendedSearchProposition.Id = instance.web.search.ExtendedSearchProposition.Integer.extend({
operators: [{value: "=", text: _lt("is")}]
});
instance.web.search.ExtendedSearchProposition.Float = instance.web.search.ExtendedSearchProposition.Field.extend({
template: 'SearchView.extended_search.proposition.float',
operators: [
{value: "=", text: _lt("is equal to")},
{value: "!=", text: _lt("is not equal to")},
{value: ">", text: _lt("greater than")},
{value: "<", text: _lt("less than")},
{value: ">=", text: _lt("greater or equal than")},
{value: "<=", text: _lt("less or equal than")},
{value: "∃", text: _lt("is set")},
{value: "∄", text: _lt("is not set")}
],
toString: function () {
return this.$el.val();
},
get_value: function() {
try {
var val =this.$el.val();
return instance.web.parse_value(val === "" ? 0.0 : val, {'widget': 'float'});
} catch (e) {
return "";
}
}
});
instance.web.search.ExtendedSearchProposition.Selection = instance.web.search.ExtendedSearchProposition.Field.extend({
template: 'SearchView.extended_search.proposition.selection',
operators: [
{value: "=", text: _lt("is")},
{value: "!=", text: _lt("is not")},
{value: "∃", text: _lt("is set")},
{value: "∄", text: _lt("is not set")}
],
toString: function () {
var select = this.$el[0];
var option = select.options[select.selectedIndex];
return option.label || option.text;
},
get_value: function() {
return this.$el.val();
}
});
instance.web.search.ExtendedSearchProposition.Boolean = instance.web.search.ExtendedSearchProposition.Field.extend({
template: 'SearchView.extended_search.proposition.empty',
operators: [
{value: "=", text: _lt("is true")},
{value: "!=", text: _lt("is false")}
],
get_label: function (field, operator) {
return this.format_label(
_t('%(field)s %(operator)s'), field, operator);
},
get_value: function() {
return true;
}
});
instance.web.search.custom_filters = new instance.web.Registry({
'char': 'instance.web.search.ExtendedSearchProposition.Char',
'text': 'instance.web.search.ExtendedSearchProposition.Char',
'one2many': 'instance.web.search.ExtendedSearchProposition.Char',
'many2one': 'instance.web.search.ExtendedSearchProposition.Char',
'many2many': 'instance.web.search.ExtendedSearchProposition.Char',
'datetime': 'instance.web.search.ExtendedSearchProposition.DateTime',
'date': 'instance.web.search.ExtendedSearchProposition.Date',
'integer': 'instance.web.search.ExtendedSearchProposition.Integer',
'float': 'instance.web.search.ExtendedSearchProposition.Float',
'boolean': 'instance.web.search.ExtendedSearchProposition.Boolean',
'selection': 'instance.web.search.ExtendedSearchProposition.Selection',
'id': 'instance.web.search.ExtendedSearchProposition.Id'
});
instance.web.search.AutoComplete = instance.web.Widget.extend({
template: "SearchView.autocomplete",
// Parameters for autocomplete constructor:
//
// parent: this is used to detect keyboard events
//
// options.source: function ({term:query}, callback). This function will be called to
// obtain the search results corresponding to the query string. It is assumed that
// options.source will call callback with the results.
// options.delay: delay in millisecond before calling source. Useful if you don't want
// to make too many rpc calls
// options.select: function (ev, {item: {facet:facet}}). Autocomplete widget will call
// that function when a selection is made by the user
// options.get_search_string: function (). This function will be called by autocomplete
// to obtain the current search string.
init: function (parent, options) {
this._super(parent);
this.$input = parent.$el;
this.source = options.source;
this.delay = options.delay;
this.select = options.select,
this.get_search_string = options.get_search_string;
this.width = options.width || 400;
this.current_result = null;
this.searching = true;
this.search_string = null;
this.current_search = null;
},
start: function () {
var self = this;
this.$el.width(this.width);
this.$input.on('keyup', function (ev) {
if (ev.which === $.ui.keyCode.RIGHT) {
self.searching = true;
ev.preventDefault();
return;
}
if (!self.searching) {
self.searching = true;
return;
}
self.search_string = self.get_search_string();
if (self.search_string.length) {
var search_string = self.search_string;
setTimeout(function () { self.initiate_search(search_string);}, self.delay);
} else {
self.close();
}
});
this.$input.on('keydown', function (ev) {
switch (ev.which) {
case $.ui.keyCode.TAB:
case $.ui.keyCode.ENTER:
if (self.get_search_string().length) {
self.select_item(ev);
}
break;
case $.ui.keyCode.DOWN:
self.move('down');
self.searching = false;
ev.preventDefault();
break;
case $.ui.keyCode.UP:
self.move('up');
self.searching = false;
ev.preventDefault();
break;
case $.ui.keyCode.RIGHT:
self.searching = false;
var current = self.current_result
if (current && current.expand && !current.expanded) {
self.expand();
self.searching = true;
}
ev.preventDefault();
break;
case $.ui.keyCode.ESCAPE:
self.close();
self.searching = false;
break;
}
});
},
initiate_search: function (query) {
if (query === this.search_string && query !== this.current_search) {
this.search(query);
}
},
search: function (query) {
var self = this;
this.current_search = query;
this.source({term:query}, function (results) {
if (results.length) {
self.render_search_results(results);
self.focus_element(self.$('li:first-child'));
} else {
self.close();
}
});
},
render_search_results: function (results) {
var self = this;
var $list = this.$('ul');
$list.empty();
var render_separator = false;
results.forEach(function (result) {
if (result.is_separator) {
if (render_separator)
$list.append($('<li>').addClass('oe-separator'));
render_separator = false;
} else {
var $item = self.make_list_item(result).appendTo($list);
result.$el = $item;
render_separator = true;
}
});
this.show();
},
make_list_item: function (result) {
var self = this;
var $li = $('<li>')
.hover(function (ev) {self.focus_element($li);})
.mousedown(function (ev) {
if (ev.button === 0) { // left button
self.select(ev, {item: {facet: result.facet}});
self.close();
} else {
ev.preventDefault();
}
})
.data('result', result);
if (result.expand) {
var $expand = $('<span class="oe-expand">').text('▶').appendTo($li);
$expand.mousedown(function (ev) {
ev.preventDefault();
ev.stopPropagation();
if (result.expanded)
self.fold();
else
self.expand();
});
result.expanded = false;
}
if (result.indent) $li.addClass('oe-indent');
$li.append($('<span>').html(result.label));
return $li;
},
expand: function () {
var self = this;
this.current_result.expand(this.get_search_string()).then(function (results) {
(results || [{label: '(no result)'}]).reverse().forEach(function (result) {
result.indent = true;
var $li = self.make_list_item(result);
self.current_result.$el.after($li);
});
self.current_result.expanded = true;
self.current_result.$el.find('span.oe-expand').html('▼');
});
},
fold: function () {
var $next = this.current_result.$el.next();
while ($next.hasClass('oe-indent')) {
$next.remove();
$next = this.current_result.$el.next();
}
this.current_result.expanded = false;
this.current_result.$el.find('span.oe-expand').html('▶');
},
focus_element: function ($li) {
this.$('li').removeClass('oe-selection-focus');
$li.addClass('oe-selection-focus');
this.current_result = $li.data('result');
},
select_item: function (ev) {
if (this.current_result.facet) {
this.select(ev, {item: {facet: this.current_result.facet}});
this.close();
}
},
show: function () {
this.$el.show();
},
close: function () {
this.current_search = null;
this.search_string = null;
this.searching = true;
this.$el.hide();
},
move: function (direction) {
var $next;
if (direction === 'down') {
$next = this.$('li.oe-selection-focus').nextAll(':not(.oe-separator)').first();
if (!$next.length) $next = this.$('li:first-child');
} else {
$next = this.$('li.oe-selection-focus').prevAll(':not(.oe-separator)').first();
if (!$next.length) $next = this.$('li:not(.oe-separator)').last();
}
this.focus_element($next);
},
is_expandable: function () {
return !!this.$('.oe-selection-focus .oe-expand').length;
},
});
})();
// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:<|fim▁end|>
| |
<|file_name|>widget.rs<|end_file_name|><|fim▁begin|>use std::io::{Result, Write};
use analysis;
use env::Env;
use super::{function, general};
use super::general::tabs;
pub fn generate<W: Write>(w: &mut W, env: &Env, analysis: &analysis::object::Info) -> Result<()>{
let type_ = analysis.type_(&env.library);
try!(general::start_comments(w, &env.config));
try!(general::uses(w, &analysis.imports, &env.config.library_name, env.config.min_cfg_version));
try!(general::objects_child_type(w, &analysis.name, &type_.c_type));
try!(general::impl_parents(w, &analysis.name, &analysis.parents));
try!(general::impl_interfaces(w, &analysis.name, &analysis.implements));
if generate_inherent(analysis) {
try!(writeln!(w, ""));
try!(writeln!(w, "impl {} {{", analysis.name));
for func_analysis in &analysis.constructors() {
try!(function::generate(w, env, func_analysis, false, false, 1));
}
if !generate_trait(analysis) {
for func_analysis in &analysis.methods() {
try!(function::generate(w, env, func_analysis, false, false, 1));
}
}
for func_analysis in &analysis.functions() {
try!(function::generate(w, env, func_analysis, false, false, 1));
}
try!(writeln!(w, "}}"));
}
try!(general::impl_static_type(w, &analysis.name, &type_.glib_get_type));
if generate_trait(analysis) {
try!(writeln!(w, ""));
try!(writeln!(w, "pub trait {}Ext {{", analysis.name));
for func_analysis in &analysis.methods() {
try!(function::generate(w, env, func_analysis, true, true, 1));
}
try!(writeln!(w, "}}"));
try!(writeln!(w, ""));
try!(writeln!(w, "impl<O: Upcast<{}>> {}Ext for O {{", analysis.name, analysis.name));
for func_analysis in &analysis.methods() {
try!(function::generate(w, env, func_analysis, true, false, 1));
}
try!(writeln!(w, "}}"));
}
Ok(())
}
fn generate_inherent(analysis: &analysis::object::Info) -> bool {
analysis.has_constructors || analysis.has_functions || !analysis.has_children
}
fn generate_trait(analysis: &analysis::object::Info) -> bool {
analysis.has_children
}
pub fn generate_reexports(env: &Env, analysis: &analysis::object::Info, module_name: &str,
contents: &mut Vec<String>, traits: &mut Vec<String>) {
let version_cfg = general::version_condition_string(&env.config.library_name,
env.config.min_cfg_version, analysis.version, false, 0);
let (cfg, cfg_1) = match version_cfg {
Some(s) => (format!("{}\n", s), format!("{}{}\n", tabs(1), s)),
None => ("".into(), "".into()),
};
contents.push(format!(""));
contents.push(format!("{}mod {};", cfg, module_name));
contents.push(format!("{}pub use self::{}::{};", cfg, module_name, analysis.name));<|fim▁hole|> if generate_trait(analysis) {
contents.push(format!("{}pub use self::{}::{}Ext;", cfg, module_name, analysis.name));
traits.push(format!("{}{}pub use super::{}Ext;", cfg_1, tabs(1), analysis.name));
}
}<|fim▁end|>
| |
<|file_name|>zuul.py<|end_file_name|><|fim▁begin|># Copyright 2012 Hewlett-Packard Development Company, L.P.
#
# 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.
"""
The Zuul module adds triggers that configure jobs for use with Zuul_.
To change the Zuul notification URL, set a global default::
- defaults:
name: global
zuul-url: http://127.0.0.1:8001/jenkins_endpoint
The above URL is the default.
.. _Zuul: http://ci.openstack.org/zuul/
"""
def zuul():
"""yaml: zuul
Configure this job to be triggered by Zuul.
Example::
triggers:
- zuul
"""
def zuul_post():
"""yaml: zuul-post
Configure this post-merge job to be triggered by Zuul.
Example::
triggers:
- zuul-post
"""
import jenkins_jobs.modules.base
ZUUL_PARAMETERS = [
{'string':
{'description': 'Zuul provided key to link builds with Gerrit events',
'name': 'ZUUL_UUID'}},
{'string':
{'description': 'Zuul provided key to link builds with Gerrit'
' events (deprecated use ZUUL_UUID instead)',
'name': 'UUID'}},
{'string':
{'description': 'Zuul pipeline triggering this job',
'name': 'ZUUL_PIPELINE'}},
{'string':
{'description': 'Zuul provided project name',
'name': 'GERRIT_PROJECT'}},
{'string':
{'description': 'Branch name of triggering project',
'name': 'ZUUL_PROJECT'}},
{'string':
{'description': 'Zuul provided branch name',
'name': 'GERRIT_BRANCH'}},
{'string':
{'description': 'Branch name of triggering change',
'name': 'ZUUL_BRANCH'}},
{'string':
{'description': 'Zuul provided list of dependent changes to merge',
'name': 'GERRIT_CHANGES'}},
{'string':
{'description': 'List of dependent changes to merge',
'name': 'ZUUL_CHANGES'}},
{'string':
{'description': 'Reference for the merged commit(s) to use',
'name': 'ZUUL_REF'}},
{'string':
{'description': 'The commit SHA1 at the head of ZUUL_REF',
'name': 'ZUUL_COMMIT'}},
{'string':
{'description': 'List of included changes',
'name': 'ZUUL_CHANGE_IDS'}},
{'string':
{'description': 'ID of triggering change',
'name': 'ZUUL_CHANGE'}},
{'string':
{'description': 'Patchset of triggering change',
'name': 'ZUUL_PATCHSET'}},
]
ZUUL_POST_PARAMETERS = [
{'string':
{'description': 'Zuul provided key to link builds with Gerrit events',
'name': 'ZUUL_UUID'}},
{'string':
{'description': 'Zuul provided key to link builds with Gerrit'
' events (deprecated use ZUUL_UUID instead)',
'name': 'UUID'}},
{'string':
{'description': 'Zuul pipeline triggering this job',
'name': 'ZUUL_PIPELINE'}},
{'string':
{'description': 'Zuul provided project name',
'name': 'GERRIT_PROJECT'}},
{'string':
{'description': 'Branch name of triggering project',
'name': 'ZUUL_PROJECT'}},
{'string':
{'description': 'Zuul provided ref name',
'name': 'GERRIT_REFNAME'}},
{'string':
{'description': 'Name of updated reference triggering this job',
'name': 'ZUUL_REF'}},
{'string':
{'description': 'Name of updated reference triggering this job',
'name': 'ZUUL_REFNAME'}},
{'string':
{'description': 'Zuul provided old reference for ref-updated',
'name': 'GERRIT_OLDREV'}},
{'string':
{'description': 'Old SHA at this reference',
'name': 'ZUUL_OLDREV'}},
{'string':
{'description': 'Zuul provided new reference for ref-updated',
'name': 'GERRIT_NEWREV'}},
{'string':
{'description': 'New SHA at this reference',
'name': 'ZUUL_NEWREV'}},
{'string':
{'description': 'Shortened new SHA at this reference',
'name': 'ZUUL_SHORT_NEWREV'}},
]<|fim▁hole|>
class Zuul(jenkins_jobs.modules.base.Base):
sequence = 0
def handle_data(self, parser):
changed = False
jobs = (parser.data.get('job', {}).values() +
parser.data.get('job-template', {}).values())
for job in jobs:
triggers = job.get('triggers')
if not triggers:
continue
if ('zuul' not in job.get('triggers', []) and
'zuul-post' not in job.get('triggers', [])):
continue
if 'parameters' not in job:
job['parameters'] = []
if 'notifications' not in job:
job['notifications'] = []
# This isn't a good pattern, and somewhat violates the
# spirit of the global defaults, but Zuul is working on
# a better design that should obviate the need for most
# of this module, so this gets it doen with minimal
# intrusion to the rest of JJB.
if parser.data.get('defaults', {}).get('global'):
url = parser.data['defaults']['global'].get(
'zuul-url', DEFAULT_URL)
notifications = [{'http': {'url': url}}]
job['notifications'].extend(notifications)
if 'zuul' in job.get('triggers', []):
job['parameters'].extend(ZUUL_PARAMETERS)
job['triggers'].remove('zuul')
if 'zuul-post' in job.get('triggers', []):
job['parameters'].extend(ZUUL_POST_PARAMETERS)
job['triggers'].remove('zuul-post')
changed = True
return changed<|fim▁end|>
|
DEFAULT_URL = 'http://127.0.0.1:8001/jenkins_endpoint'
|
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>fn main() {
let x = &5;
println!("Hello, world!");<|fim▁hole|>
match x {
&y => println!("1. {:?}", y),
}
match x {
ref y => println!("2. {:p} -> {:?}", y, y),
}
struct Point {
x : i32,
y : i32,
}
let origin = Point { x: 0, y: 10 };
match origin {
Point { x: a, y : b, .. } => println!("3. Point of {}, {}", a, b),
}
}<|fim▁end|>
| |
<|file_name|>Control.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Created on Tue Dec 08 13:25:40 2015
@author: J. Alejandro Cardona
"""
from Board import *
import pygame
UP, LEFT, DOWN, RIGHT = 1, 2, 3, 4
juego = Board()
_2 = pygame.image.load("2.jpg"); _2re = _2.get_rect()
_4 = pygame.image.load("4.jpg"); _4re = _4.get_rect()
_8 = pygame.image.load("8.jpg"); _8re = _8.get_rect()
_16 = pygame.image.load("16.jpg"); _16re = _16.get_rect()
_32 = pygame.image.load("32.jpg"); _32re = _32.get_rect()
_64 = pygame.image.load("64.jpg"); _64re = _64.get_rect()
_128 = pygame.image.load("128.jpg"); _128re = _128.get_rect()
_256 = pygame.image.load("256.jpg"); _256re = _256.get_rect()
_512 = pygame.image.load("512.jpg"); _512re = _512.get_rect()
<|fim▁hole|>_1024 = pygame.image.load("1024.jpg"); _1024re = _1024.get_rect()
_2048 = pygame.image.load("2048.jpg"); _2048re = _2048.get_rect()
figs = {2:(_2, _2re), 4:(_4,_4re), 8:(_8,_8re), 16:(_16,_16re),
32:(_32,_32re), 64:(_64,_64re), 128:(_128,_128re), 256:(_256,_256re),
512:(_512,_512re), 1024:(_1024,_1024re), 2048:(_2048,_2048re)}
def read_key(key):
# Este metodo se usa solo para jugar en modo consola
if key == 'w':
juego.move(UP)
elif key == 's':
juego.move(DOWN)
elif key == 'a':
juego.move(LEFT)
elif key == 'd':
juego.move(RIGHT)<|fim▁end|>
| |
<|file_name|>Wiltron360SS69.py<|end_file_name|><|fim▁begin|>from ..GenericInstrument import GenericInstrument
from .helper import SignalGenerator, amplitudelimiter
class Wiltron360SS69(GenericInstrument, SignalGenerator):
"""Wiltron 360SS69 10e6, 40e9.
.. figure:: images/SignalGenerator/Wiltron360SS69.jpg
"""
def __init__(self, instrument):
"""."""
super().__init__(instrument)
# self.log = logging.getLogger(__name__)
# self.log.info('Creating an instance of\t' + str(__class__))
self.amps = [-140, 17]
self.freqs = [10e6, 40e9]
# self.siggen.write("*CLS") # clear error status
# self.frequency = min(self.freqs)
@property
def frequency(self):
"""."""
return(self.query("OF0"))
@frequency.setter
def frequency(self, frequency):
self.write(f"F0{frequency:.2f}GH")
@property
def amplitude(self):
"""."""
return(self.query("OL0"))
<|fim▁hole|>
'''@property
def output(self):
if self.query("OUTPut:STATe?") == "1":
return(True)
else:
return(False)
@output.setter
def output(self, boolean=False):
self.write("OUTPut:STATe {:d}".format(boolean))
'''<|fim▁end|>
|
@amplitude.setter
@amplitudelimiter
def amplitude(self, amplitude):
self.write(f"L0{amplitude:.2f}DM")
|
<|file_name|>test_minion.py<|end_file_name|><|fim▁begin|>import copy
import logging
import os
import pytest
import salt.ext.tornado
import salt.ext.tornado.gen
import salt.ext.tornado.testing
import salt.minion
import salt.syspaths
import salt.utils.crypt
import salt.utils.event as event
import salt.utils.platform
import salt.utils.process
from salt._compat import ipaddress
from salt.exceptions import SaltClientError, SaltMasterUnresolvableError, SaltSystemExit
from tests.support.mock import MagicMock, patch
log = logging.getLogger(__name__)
def test_minion_load_grains_false():
"""
Minion does not generate grains when load_grains is False
"""
opts = {"random_startup_delay": 0, "grains": {"foo": "bar"}}
with patch("salt.loader.grains") as grainsfunc:
minion = salt.minion.Minion(opts, load_grains=False)
assert minion.opts["grains"] == opts["grains"]
grainsfunc.assert_not_called()
def test_minion_load_grains_true():
"""
Minion generates grains when load_grains is True
"""
opts = {"random_startup_delay": 0, "grains": {}}
with patch("salt.loader.grains") as grainsfunc:
minion = salt.minion.Minion(opts, load_grains=True)
assert minion.opts["grains"] != {}
grainsfunc.assert_called()
def test_minion_load_grains_default():
"""
Minion load_grains defaults to True
"""
opts = {"random_startup_delay": 0, "grains": {}}
with patch("salt.loader.grains") as grainsfunc:
minion = salt.minion.Minion(opts)
assert minion.opts["grains"] != {}
grainsfunc.assert_called()
@pytest.mark.parametrize(
"event",
[
(
"fire_event",
lambda data, tag, cb=None, timeout=60: True,
),
(
"fire_event_async",
lambda data, tag, cb=None, timeout=60: salt.ext.tornado.gen.maybe_future(
True
),
),
],
)
def test_send_req_fires_completion_event(event):
event_enter = MagicMock()
event_enter.send.side_effect = event[1]
event = MagicMock()
event.__enter__.return_value = event_enter
with patch("salt.utils.event.get_event", return_value=event):
opts = salt.config.DEFAULT_MINION_OPTS.copy()
opts["random_startup_delay"] = 0
opts["return_retry_tries"] = 30
opts["grains"] = {}
with patch("salt.loader.grains"):
minion = salt.minion.Minion(opts)
load = {"load": "value"}
timeout = 60
if "async" in event[0]:
rtn = minion._send_req_async(load, timeout).result()
else:
rtn = minion._send_req_sync(load, timeout)
# get the
for idx, call in enumerate(event.mock_calls, 1):
if "fire_event" in call[0]:
condition_event_tag = (
len(call.args) > 1
and call.args[1] == "__master_req_channel_payload"
)
condition_event_tag_error = "{} != {}; Call(number={}): {}".format(
idx, call, call.args[1], "__master_req_channel_payload"
)
condition_timeout = (
len(call.kwargs) == 1 and call.kwargs["timeout"] == timeout
)
condition_timeout_error = "{} != {}; Call(number={}): {}".format(
idx, call, call.kwargs["timeout"], timeout
)
fire_event_called = True
assert condition_event_tag, condition_event_tag_error
assert condition_timeout, condition_timeout_error
assert fire_event_called
assert rtn
@patch("salt.channel.client.ReqChannel.factory")
def test_mine_send_tries(req_channel_factory):
channel_enter = MagicMock()
channel_enter.send.side_effect = lambda load, timeout, tries: tries
channel = MagicMock()
channel.__enter__.return_value = channel_enter
req_channel_factory.return_value = channel
opts = {
"random_startup_delay": 0,
"grains": {},
"return_retry_tries": 20,
"minion_sign_messages": False,
}
with patch("salt.loader.grains"):
minion = salt.minion.Minion(opts)
minion.tok = "token"
data = {}
tag = "tag"
rtn = minion._mine_send(tag, data)
assert rtn == 20
def test_invalid_master_address():
opts = salt.config.DEFAULT_MINION_OPTS.copy()
with patch.dict(
opts,
{
"ipv6": False,
"master": float("127.0"),
"master_port": "4555",
"retry_dns": False,
},
):
pytest.raises(SaltSystemExit, salt.minion.resolve_dns, opts)
def test_source_int_name_local():
"""
test when file_client local and
source_interface_name is set
"""
interfaces = {
"bond0.1234": {
"hwaddr": "01:01:01:d0:d0:d0",
"up": True,
"inet": [
{
"broadcast": "111.1.111.255",
"netmask": "111.1.0.0",
"label": "bond0",
"address": "111.1.0.1",
}
],
}
}
opts = salt.config.DEFAULT_MINION_OPTS.copy()
with patch.dict(
opts,
{
"ipv6": False,
"master": "127.0.0.1",
"master_port": "4555",
"file_client": "local",
"source_interface_name": "bond0.1234",
"source_ret_port": 49017,
"source_publish_port": 49018,
},
), patch("salt.utils.network.interfaces", MagicMock(return_value=interfaces)):
assert salt.minion.resolve_dns(opts) == {
"master_ip": "127.0.0.1",
"source_ip": "111.1.0.1",
"source_ret_port": 49017,
"source_publish_port": 49018,
"master_uri": "tcp://127.0.0.1:4555",
}
@pytest.mark.slow_test
def test_source_int_name_remote():
"""
test when file_client remote and
source_interface_name is set and
interface is down
"""
interfaces = {
"bond0.1234": {
"hwaddr": "01:01:01:d0:d0:d0",
"up": False,
"inet": [
{
"broadcast": "111.1.111.255",
"netmask": "111.1.0.0",
"label": "bond0",
"address": "111.1.0.1",
}
],
}
}
opts = salt.config.DEFAULT_MINION_OPTS.copy()
with patch.dict(
opts,
{
"ipv6": False,
"master": "127.0.0.1",
"master_port": "4555",
"file_client": "remote",
"source_interface_name": "bond0.1234",
"source_ret_port": 49017,
"source_publish_port": 49018,
},
), patch("salt.utils.network.interfaces", MagicMock(return_value=interfaces)):
assert salt.minion.resolve_dns(opts) == {
"master_ip": "127.0.0.1",
"source_ret_port": 49017,
"source_publish_port": 49018,
"master_uri": "tcp://127.0.0.1:4555",
}
@pytest.mark.slow_test
def test_source_address():
"""
test when source_address is set
"""
interfaces = {
"bond0.1234": {
"hwaddr": "01:01:01:d0:d0:d0",
"up": False,
"inet": [
{
"broadcast": "111.1.111.255",
"netmask": "111.1.0.0",
"label": "bond0",
"address": "111.1.0.1",
}
],
}
}
opts = salt.config.DEFAULT_MINION_OPTS.copy()
with patch.dict(
opts,
{
"ipv6": False,
"master": "127.0.0.1",
"master_port": "4555",
"file_client": "local",
"source_interface_name": "",
"source_address": "111.1.0.1",
"source_ret_port": 49017,
"source_publish_port": 49018,
},
), patch("salt.utils.network.interfaces", MagicMock(return_value=interfaces)):
assert salt.minion.resolve_dns(opts) == {
"source_publish_port": 49018,
"source_ret_port": 49017,
"master_uri": "tcp://127.0.0.1:4555",
"source_ip": "111.1.0.1",
"master_ip": "127.0.0.1",
}
# Tests for _handle_decoded_payload in the salt.minion.Minion() class: 3
@pytest.mark.slow_test
def test_handle_decoded_payload_jid_match_in_jid_queue():
"""
Tests that the _handle_decoded_payload function returns when a jid is given that is already present
in the jid_queue.
<|fim▁hole|> """
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_data = {"fun": "foo.bar", "jid": 123}
mock_jid_queue = [123]
minion = salt.minion.Minion(
mock_opts,
jid_queue=copy.copy(mock_jid_queue),
io_loop=salt.ext.tornado.ioloop.IOLoop(),
)
try:
ret = minion._handle_decoded_payload(mock_data).result()
assert minion.jid_queue == mock_jid_queue
assert ret is None
finally:
minion.destroy()
@pytest.mark.slow_test
def test_handle_decoded_payload_jid_queue_addition():
"""
Tests that the _handle_decoded_payload function adds a jid to the minion's jid_queue when the new
jid isn't already present in the jid_queue.
"""
with patch("salt.minion.Minion.ctx", MagicMock(return_value={})), patch(
"salt.utils.process.SignalHandlingProcess.start",
MagicMock(return_value=True),
), patch(
"salt.utils.process.SignalHandlingProcess.join",
MagicMock(return_value=True),
):
mock_jid = 11111
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_data = {"fun": "foo.bar", "jid": mock_jid}
mock_jid_queue = [123, 456]
minion = salt.minion.Minion(
mock_opts,
jid_queue=copy.copy(mock_jid_queue),
io_loop=salt.ext.tornado.ioloop.IOLoop(),
)
try:
# Assert that the minion's jid_queue attribute matches the mock_jid_queue as a baseline
# This can help debug any test failures if the _handle_decoded_payload call fails.
assert minion.jid_queue == mock_jid_queue
# Call the _handle_decoded_payload function and update the mock_jid_queue to include the new
# mock_jid. The mock_jid should have been added to the jid_queue since the mock_jid wasn't
# previously included. The minion's jid_queue attribute and the mock_jid_queue should be equal.
minion._handle_decoded_payload(mock_data).result()
mock_jid_queue.append(mock_jid)
assert minion.jid_queue == mock_jid_queue
finally:
minion.destroy()
@pytest.mark.slow_test
def test_handle_decoded_payload_jid_queue_reduced_minion_jid_queue_hwm():
"""
Tests that the _handle_decoded_payload function removes a jid from the minion's jid_queue when the
minion's jid_queue high water mark (minion_jid_queue_hwm) is hit.
"""
with patch("salt.minion.Minion.ctx", MagicMock(return_value={})), patch(
"salt.utils.process.SignalHandlingProcess.start",
MagicMock(return_value=True),
), patch(
"salt.utils.process.SignalHandlingProcess.join",
MagicMock(return_value=True),
):
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_opts["minion_jid_queue_hwm"] = 2
mock_data = {"fun": "foo.bar", "jid": 789}
mock_jid_queue = [123, 456]
minion = salt.minion.Minion(
mock_opts,
jid_queue=copy.copy(mock_jid_queue),
io_loop=salt.ext.tornado.ioloop.IOLoop(),
)
try:
# Assert that the minion's jid_queue attribute matches the mock_jid_queue as a baseline
# This can help debug any test failures if the _handle_decoded_payload call fails.
assert minion.jid_queue == mock_jid_queue
# Call the _handle_decoded_payload function and check that the queue is smaller by one item
# and contains the new jid
minion._handle_decoded_payload(mock_data).result()
assert len(minion.jid_queue) == 2
assert minion.jid_queue == [456, 789]
finally:
minion.destroy()
@pytest.mark.slow_test
def test_process_count_max():
"""
Tests that the _handle_decoded_payload function does not spawn more than the configured amount of processes,
as per process_count_max.
"""
with patch("salt.minion.Minion.ctx", MagicMock(return_value={})), patch(
"salt.utils.process.SignalHandlingProcess.start",
MagicMock(return_value=True),
), patch(
"salt.utils.process.SignalHandlingProcess.join",
MagicMock(return_value=True),
), patch(
"salt.utils.minion.running", MagicMock(return_value=[])
), patch(
"salt.ext.tornado.gen.sleep",
MagicMock(return_value=salt.ext.tornado.concurrent.Future()),
):
process_count_max = 10
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_opts["__role"] = "minion"
mock_opts["minion_jid_queue_hwm"] = 100
mock_opts["process_count_max"] = process_count_max
io_loop = salt.ext.tornado.ioloop.IOLoop()
minion = salt.minion.Minion(mock_opts, jid_queue=[], io_loop=io_loop)
try:
# mock gen.sleep to throw a special Exception when called, so that we detect it
class SleepCalledException(Exception):
"""Thrown when sleep is called"""
salt.ext.tornado.gen.sleep.return_value.set_exception(
SleepCalledException()
)
# up until process_count_max: gen.sleep does not get called, processes are started normally
for i in range(process_count_max):
mock_data = {"fun": "foo.bar", "jid": i}
io_loop.run_sync(
lambda data=mock_data: minion._handle_decoded_payload(data)
)
assert (
salt.utils.process.SignalHandlingProcess.start.call_count == i + 1
)
assert len(minion.jid_queue) == i + 1
salt.utils.minion.running.return_value += [i]
# above process_count_max: gen.sleep does get called, JIDs are created but no new processes are started
mock_data = {"fun": "foo.bar", "jid": process_count_max + 1}
pytest.raises(
SleepCalledException,
lambda: io_loop.run_sync(
lambda: minion._handle_decoded_payload(mock_data)
),
)
assert (
salt.utils.process.SignalHandlingProcess.start.call_count
== process_count_max
)
assert len(minion.jid_queue) == process_count_max + 1
finally:
minion.destroy()
@pytest.mark.slow_test
def test_beacons_before_connect():
"""
Tests that the 'beacons_before_connect' option causes the beacons to be initialized before connect.
"""
with patch("salt.minion.Minion.ctx", MagicMock(return_value={})), patch(
"salt.minion.Minion.sync_connect_master",
MagicMock(side_effect=RuntimeError("stop execution")),
), patch(
"salt.utils.process.SignalHandlingProcess.start",
MagicMock(return_value=True),
), patch(
"salt.utils.process.SignalHandlingProcess.join",
MagicMock(return_value=True),
):
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_opts["beacons_before_connect"] = True
io_loop = salt.ext.tornado.ioloop.IOLoop()
io_loop.make_current()
minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
try:
try:
minion.tune_in(start=True)
except RuntimeError:
pass
# Make sure beacons are initialized but the sheduler is not
assert "beacons" in minion.periodic_callbacks
assert "schedule" not in minion.periodic_callbacks
finally:
minion.destroy()
@pytest.mark.slow_test
def test_scheduler_before_connect():
"""
Tests that the 'scheduler_before_connect' option causes the scheduler to be initialized before connect.
"""
with patch("salt.minion.Minion.ctx", MagicMock(return_value={})), patch(
"salt.minion.Minion.sync_connect_master",
MagicMock(side_effect=RuntimeError("stop execution")),
), patch(
"salt.utils.process.SignalHandlingProcess.start",
MagicMock(return_value=True),
), patch(
"salt.utils.process.SignalHandlingProcess.join",
MagicMock(return_value=True),
):
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_opts["scheduler_before_connect"] = True
io_loop = salt.ext.tornado.ioloop.IOLoop()
io_loop.make_current()
minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
try:
try:
minion.tune_in(start=True)
except RuntimeError:
pass
# Make sure the scheduler is initialized but the beacons are not
assert "schedule" in minion.periodic_callbacks
assert "beacons" not in minion.periodic_callbacks
finally:
minion.destroy()
def test_minion_module_refresh(tmp_path):
"""
Tests that the 'module_refresh' just return in case there is no 'schedule'
because destroy method was already called.
"""
with patch("salt.minion.Minion.ctx", MagicMock(return_value={})), patch(
"salt.utils.process.SignalHandlingProcess.start",
MagicMock(return_value=True),
), patch(
"salt.utils.process.SignalHandlingProcess.join",
MagicMock(return_value=True),
):
try:
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_opts["cachedir"] = str(tmp_path)
minion = salt.minion.Minion(
mock_opts,
io_loop=salt.ext.tornado.ioloop.IOLoop(),
)
minion.schedule = salt.utils.schedule.Schedule(mock_opts, {}, returners={})
assert hasattr(minion, "schedule")
minion.destroy()
assert not hasattr(minion, "schedule")
assert not minion.module_refresh()
finally:
minion.destroy()
def test_minion_module_refresh_beacons_refresh(tmp_path):
"""
Tests that 'module_refresh' calls beacons_refresh and that the
minion object has a beacons attribute with beacons.
"""
with patch("salt.minion.Minion.ctx", MagicMock(return_value={})), patch(
"salt.utils.process.SignalHandlingProcess.start",
MagicMock(return_value=True),
), patch(
"salt.utils.process.SignalHandlingProcess.join",
MagicMock(return_value=True),
):
try:
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_opts["cachedir"] = str(tmp_path)
minion = salt.minion.Minion(
mock_opts,
io_loop=salt.ext.tornado.ioloop.IOLoop(),
)
minion.schedule = salt.utils.schedule.Schedule(mock_opts, {}, returners={})
assert not hasattr(minion, "beacons")
minion.module_refresh()
assert hasattr(minion, "beacons")
assert hasattr(minion.beacons, "beacons")
assert "service.beacon" in minion.beacons.beacons
minion.destroy()
finally:
minion.destroy()
@pytest.mark.slow_test
def test_when_ping_interval_is_set_the_callback_should_be_added_to_periodic_callbacks():
with patch("salt.minion.Minion.ctx", MagicMock(return_value={})), patch(
"salt.minion.Minion.sync_connect_master",
MagicMock(side_effect=RuntimeError("stop execution")),
), patch(
"salt.utils.process.SignalHandlingProcess.start",
MagicMock(return_value=True),
), patch(
"salt.utils.process.SignalHandlingProcess.join",
MagicMock(return_value=True),
):
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_opts["ping_interval"] = 10
io_loop = salt.ext.tornado.ioloop.IOLoop()
io_loop.make_current()
minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
try:
try:
minion.connected = MagicMock(side_effect=(False, True))
minion._fire_master_minion_start = MagicMock()
minion.tune_in(start=False)
except RuntimeError:
pass
# Make sure the scheduler is initialized but the beacons are not
assert "ping" in minion.periodic_callbacks
finally:
minion.destroy()
@pytest.mark.slow_test
def test_when_passed_start_event_grains():
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
# provide mock opts an os grain since we'll look for it later.
mock_opts["grains"]["os"] = "linux"
mock_opts["start_event_grains"] = ["os"]
io_loop = salt.ext.tornado.ioloop.IOLoop()
io_loop.make_current()
minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
try:
minion.tok = MagicMock()
minion._send_req_sync = MagicMock()
minion._fire_master(
"Minion has started", "minion_start", include_startup_grains=True
)
load = minion._send_req_sync.call_args[0][0]
assert "grains" in load
assert "os" in load["grains"]
finally:
minion.destroy()
@pytest.mark.slow_test
def test_when_not_passed_start_event_grains():
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
io_loop = salt.ext.tornado.ioloop.IOLoop()
io_loop.make_current()
minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
try:
minion.tok = MagicMock()
minion._send_req_sync = MagicMock()
minion._fire_master("Minion has started", "minion_start")
load = minion._send_req_sync.call_args[0][0]
assert "grains" not in load
finally:
minion.destroy()
@pytest.mark.slow_test
def test_when_other_events_fired_and_start_event_grains_are_set():
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_opts["start_event_grains"] = ["os"]
io_loop = salt.ext.tornado.ioloop.IOLoop()
io_loop.make_current()
minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
try:
minion.tok = MagicMock()
minion._send_req_sync = MagicMock()
minion._fire_master("Custm_event_fired", "custom_event")
load = minion._send_req_sync.call_args[0][0]
assert "grains" not in load
finally:
minion.destroy()
@pytest.mark.slow_test
def test_minion_retry_dns_count():
"""
Tests that the resolve_dns will retry dns look ups for a maximum of
3 times before raising a SaltMasterUnresolvableError exception.
"""
opts = salt.config.DEFAULT_MINION_OPTS.copy()
with patch.dict(
opts,
{
"ipv6": False,
"master": "dummy",
"master_port": "4555",
"retry_dns": 1,
"retry_dns_count": 3,
},
):
pytest.raises(SaltMasterUnresolvableError, salt.minion.resolve_dns, opts)
@pytest.mark.slow_test
def test_gen_modules_executors():
"""
Ensure gen_modules is called with the correct arguments #54429
"""
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
io_loop = salt.ext.tornado.ioloop.IOLoop()
io_loop.make_current()
minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
class MockPillarCompiler:
def compile_pillar(self):
return {}
try:
with patch("salt.pillar.get_pillar", return_value=MockPillarCompiler()):
with patch("salt.loader.executors") as execmock:
minion.gen_modules()
assert execmock.called_with(minion.opts, minion.functions)
finally:
minion.destroy()
@patch("salt.utils.process.default_signals")
@pytest.mark.slow_test
def test_reinit_crypto_on_fork(def_mock):
"""
Ensure salt.utils.crypt.reinit_crypto() is executed when forking for new job
"""
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_opts["multiprocessing"] = True
io_loop = salt.ext.tornado.ioloop.IOLoop()
io_loop.make_current()
minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
job_data = {"jid": "test-jid", "fun": "test.ping"}
def mock_start(self):
# pylint: disable=comparison-with-callable
assert (
len(
[
x
for x in self._after_fork_methods
if x[0] == salt.utils.crypt.reinit_crypto
]
)
== 1
)
# pylint: enable=comparison-with-callable
with patch.object(salt.utils.process.SignalHandlingProcess, "start", mock_start):
io_loop.run_sync(lambda: minion._handle_decoded_payload(job_data))
def test_minion_manage_schedule():
"""
Tests that the manage_schedule will call the add function, adding
schedule data into opts.
"""
with patch("salt.minion.Minion.ctx", MagicMock(return_value={})), patch(
"salt.minion.Minion.sync_connect_master",
MagicMock(side_effect=RuntimeError("stop execution")),
), patch(
"salt.utils.process.SignalHandlingMultiprocessingProcess.start",
MagicMock(return_value=True),
), patch(
"salt.utils.process.SignalHandlingMultiprocessingProcess.join",
MagicMock(return_value=True),
):
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
io_loop = salt.ext.tornado.ioloop.IOLoop()
io_loop.make_current()
with patch("salt.utils.schedule.clean_proc_dir", MagicMock(return_value=None)):
try:
mock_functions = {"test.ping": None}
minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
minion.schedule = salt.utils.schedule.Schedule(
mock_opts,
mock_functions,
returners={},
new_instance=True,
)
minion.opts["foo"] = "bar"
schedule_data = {
"test_job": {
"function": "test.ping",
"return_job": False,
"jid_include": True,
"maxrunning": 2,
"seconds": 10,
}
}
data = {
"name": "test-item",
"schedule": schedule_data,
"func": "add",
"persist": False,
}
tag = "manage_schedule"
minion.manage_schedule(tag, data)
assert "test_job" in minion.opts["schedule"]
finally:
del minion.schedule
minion.destroy()
del minion
def test_minion_manage_beacons():
"""
Tests that the manage_beacons will call the add function, adding
beacon data into opts.
"""
with patch("salt.minion.Minion.ctx", MagicMock(return_value={})), patch(
"salt.minion.Minion.sync_connect_master",
MagicMock(side_effect=RuntimeError("stop execution")),
), patch(
"salt.utils.process.SignalHandlingMultiprocessingProcess.start",
MagicMock(return_value=True),
), patch(
"salt.utils.process.SignalHandlingMultiprocessingProcess.join",
MagicMock(return_value=True),
):
try:
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_opts["beacons"] = {}
io_loop = salt.ext.tornado.ioloop.IOLoop()
io_loop.make_current()
mock_functions = {"test.ping": None}
minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
minion.beacons = salt.beacons.Beacon(mock_opts, mock_functions)
bdata = [{"salt-master": "stopped"}, {"apache2": "stopped"}]
data = {"name": "ps", "beacon_data": bdata, "func": "add"}
tag = "manage_beacons"
log.debug("==== minion.opts %s ====", minion.opts)
minion.manage_beacons(tag, data)
assert "ps" in minion.opts["beacons"]
assert minion.opts["beacons"]["ps"] == bdata
finally:
minion.destroy()
def test_prep_ip_port():
_ip = ipaddress.ip_address
opts = {"master": "10.10.0.3", "master_uri_format": "ip_only"}
ret = salt.minion.prep_ip_port(opts)
assert ret == {"master": _ip("10.10.0.3")}
opts = {
"master": "10.10.0.3",
"master_port": 1234,
"master_uri_format": "default",
}
ret = salt.minion.prep_ip_port(opts)
assert ret == {"master": "10.10.0.3"}
opts = {"master": "10.10.0.3:1234", "master_uri_format": "default"}
ret = salt.minion.prep_ip_port(opts)
assert ret == {"master": "10.10.0.3", "master_port": 1234}
opts = {"master": "host name", "master_uri_format": "default"}
pytest.raises(SaltClientError, salt.minion.prep_ip_port, opts)
opts = {"master": "10.10.0.3:abcd", "master_uri_format": "default"}
pytest.raises(SaltClientError, salt.minion.prep_ip_port, opts)
opts = {"master": "10.10.0.3::1234", "master_uri_format": "default"}
pytest.raises(SaltClientError, salt.minion.prep_ip_port, opts)
@pytest.mark.skip_if_not_root
def test_sock_path_len():
"""
This tests whether or not a larger hash causes the sock path to exceed
the system's max sock path length. See the below link for more
information.
https://github.com/saltstack/salt/issues/12172#issuecomment-43903643
"""
opts = {
"id": "salt-testing",
"hash_type": "sha512",
"sock_dir": os.path.join(salt.syspaths.SOCK_DIR, "minion"),
"extension_modules": "",
}
opts = salt.config.DEFAULT_MINION_OPTS.copy()
with patch.dict(opts, opts):
try:
event_publisher = event.AsyncEventPublisher(opts)
result = True
except ValueError:
# There are rare cases where we operate a closed socket, especially in containers.
# In this case, don't fail the test because we'll catch it down the road.
result = True
except SaltSystemExit:
result = False
assert result
@pytest.mark.skip_on_windows(reason="Skippin, no Salt master running on Windows.")
def test_master_type_failover():
"""
Tests master_type "failover" to not fall back to 127.0.0.1 address when master does not resolve in DNS
"""
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_opts.update(
{
"master_type": "failover",
"master": ["master1", "master2"],
"__role": "",
"retry_dns": 0,
}
)
class MockPubChannel:
def connect(self):
raise SaltClientError("MockedChannel")
def close(self):
return
def mock_resolve_dns(opts, fallback=False):
assert not fallback
if opts["master"] == "master1":
raise SaltClientError("Cannot resolve {}".format(opts["master"]))
return {
"master_ip": "192.168.2.1",
"master_uri": "tcp://192.168.2.1:4505",
}
def mock_channel_factory(opts, **kwargs):
assert opts["master"] == "master2"
return MockPubChannel()
with patch("salt.minion.resolve_dns", mock_resolve_dns), patch(
"salt.channel.client.AsyncPubChannel.factory", mock_channel_factory
), patch("salt.loader.grains", MagicMock(return_value=[])):
with pytest.raises(SaltClientError):
minion = salt.minion.Minion(mock_opts)
yield minion.connect_master()
def test_master_type_failover_no_masters():
"""
Tests master_type "failover" to not fall back to 127.0.0.1 address when no master can be resolved
"""
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_opts.update(
{
"master_type": "failover",
"master": ["master1", "master2"],
"__role": "",
"retry_dns": 0,
}
)
def mock_resolve_dns(opts, fallback=False):
assert not fallback
raise SaltClientError("Cannot resolve {}".format(opts["master"]))
with patch("salt.minion.resolve_dns", mock_resolve_dns), patch(
"salt.loader.grains", MagicMock(return_value=[])
):
with pytest.raises(SaltClientError):
minion = salt.minion.Minion(mock_opts)
yield minion.connect_master()
def test_config_cache_path_overrides():
cachedir = os.path.abspath("/path/to/master/cache")
opts = {"cachedir": cachedir, "conf_file": None}
mminion = salt.minion.MasterMinion(opts)
assert mminion.opts["cachedir"] == cachedir
def test_minion_grains_refresh_pre_exec_false():
"""
Minion does not refresh grains when grains_refresh_pre_exec is False
"""
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_opts["multiprocessing"] = False
mock_opts["grains_refresh_pre_exec"] = False
mock_data = {"fun": "foo.bar", "jid": 123}
with patch("salt.loader.grains") as grainsfunc, patch(
"salt.minion.Minion._target", MagicMock(return_value=True)
):
minion = salt.minion.Minion(
mock_opts,
jid_queue=None,
io_loop=salt.ext.tornado.ioloop.IOLoop(),
load_grains=False,
)
try:
ret = minion._handle_decoded_payload(mock_data).result()
grainsfunc.assert_not_called()
finally:
minion.destroy()
def test_minion_grains_refresh_pre_exec_true():
"""
Minion refreshes grains when grains_refresh_pre_exec is True
"""
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_opts["multiprocessing"] = False
mock_opts["grains_refresh_pre_exec"] = True
mock_data = {"fun": "foo.bar", "jid": 123}
with patch("salt.loader.grains") as grainsfunc, patch(
"salt.minion.Minion._target", MagicMock(return_value=True)
):
minion = salt.minion.Minion(
mock_opts,
jid_queue=None,
io_loop=salt.ext.tornado.ioloop.IOLoop(),
load_grains=False,
)
try:
ret = minion._handle_decoded_payload(mock_data).result()
grainsfunc.assert_called()
finally:
minion.destroy()<|fim▁end|>
|
Note: This test doesn't contain all of the patch decorators above the function like the other tests
for _handle_decoded_payload below. This is essential to this test as the call to the function must
return None BEFORE any of the processes are spun up because we should be avoiding firing duplicate
jobs.
|
<|file_name|>1212.cpp<|end_file_name|><|fim▁begin|><|fim▁hole|> char c = getchar();
printf("%d", b[c-'0']);
while((c = getchar()) != '\n')
printf("%03d", b[c-'0']);
}<|fim▁end|>
|
#include <cstdio>
int b[8] = {0,1,10,11,100,101,110,111};
int main()
{
|
<|file_name|>Toggle_button.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ZetCode PyQt5 tutorial
In this example, we create three toggle buttons.
They will control the background colour of a
QFrame.
author: Jan Bodnar
website: zetcode.com
last edited: January 2015
"""
import sys
from PyQt5.QtWidgets import (QWidget, QPushButton,
QFrame, QApplication)
from PyQt5.QtGui import QColor
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.col = QColor(0, 0, 0)
redb = QPushButton('Red', self)
redb.setCheckable(True)
redb.move(10, 10)
redb.clicked[bool].connect(self.setColor)
redb = QPushButton('Green', self)
redb.setCheckable(True)
redb.move(10, 60)
redb.clicked[bool].connect(self.setColor)
blueb = QPushButton('Blue', self)
blueb.setCheckable(True)
blueb.move(10, 110)<|fim▁hole|> self.square = QFrame(self)
self.square.setGeometry(150, 20, 100, 100)
self.square.setStyleSheet("QWidget { background-color: %s }" %
self.col.name())
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('Toggle button')
self.show()
def setColor(self, pressed):
source = self.sender()
if pressed:
val = 255
else: val = 0
if source.text() == "Red":
self.col.setRed(val)
elif source.text() == "Green":
self.col.setGreen(val)
else:
self.col.setBlue(val)
self.square.setStyleSheet("QFrame { background-color: %s }" %
self.col.name())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())<|fim▁end|>
|
blueb.clicked[bool].connect(self.setColor)
|
<|file_name|>0141_auto__del_field_group_is_open.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Group.is_open'
db.delete_column('askbot_group', 'is_open')
def backwards(self, orm):
# Adding field 'Group.is_open'
db.add_column('askbot_group', 'is_open',
self.gf('django.db.models.fields.BooleanField')(default=False),
keep_default=False)
models = {
'askbot.activity': {
'Meta': {'object_name': 'Activity', 'db_table': "u'activity'"},
'active_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'activity_type': ('django.db.models.fields.SmallIntegerField', [], {}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_auditted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['askbot.Post']", 'null': 'True'}),
'receiving_users': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'received_activity'", 'symmetrical': 'False', 'to': "orm['auth.User']"}),
'recipients': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'incoming_activity'", 'symmetrical': 'False', 'through': "orm['askbot.ActivityAuditStatus']", 'to': "orm['auth.User']"}),
'summary': ('django.db.models.fields.TextField', [], {'default': "''"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'askbot.activityauditstatus': {
'Meta': {'unique_together': "(('user', 'activity'),)", 'object_name': 'ActivityAuditStatus'},
'activity': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['askbot.Activity']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'status': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'askbot.anonymousproblem': {
'Meta': {'object_name': 'AnonymousProblem'},
'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ip_addr': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'anonymous_problems'", 'to': "orm['askbot.Post']"}),
'session_key': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'summary': ('django.db.models.fields.CharField', [], {'max_length': '180'}),
'text': ('django.db.models.fields.TextField', [], {}),
'wiki': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
'askbot.anonymousexercise': {
'Meta': {'object_name': 'AnonymousExercise'},
'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ip_addr': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}),
'is_anonymous': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'session_key': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'summary': ('django.db.models.fields.CharField', [], {'max_length': '180'}),
'tagnames': ('django.db.models.fields.CharField', [], {'max_length': '125'}),
'text': ('django.db.models.fields.TextField', [], {}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '300'}),
'wiki': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
'askbot.askwidget': {
'Meta': {'object_name': 'AskWidget'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'include_text_field': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'inner_style': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'outer_style': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'tag': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['askbot.Tag']", 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'askbot.award': {
'Meta': {'object_name': 'Award', 'db_table': "u'award'"},
'awarded_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'badge': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'award_badge'", 'to': "orm['askbot.BadgeData']"}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'notified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'award_user'", 'to': "orm['auth.User']"})
},
'askbot.badgedata': {
'Meta': {'ordering': "('slug',)", 'object_name': 'BadgeData'},
'awarded_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'awarded_to': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'badges'", 'symmetrical': 'False', 'through': "orm['askbot.Award']", 'to': "orm['auth.User']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'})
},
'askbot.draftproblem': {
'Meta': {'object_name': 'DraftProblem'},
'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'draft_problems'", 'to': "orm['auth.User']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'text': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'thread': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'draft_problems'", 'to': "orm['askbot.Thread']"})
},
'askbot.draftexercise': {
'Meta': {'object_name': 'DraftExercise'},
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'tagnames': ('django.db.models.fields.CharField', [], {'max_length': '125', 'null': 'True'}),
'text': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True'})
},
'askbot.emailfeedsetting': {
'Meta': {'unique_together': "(('subscriber', 'feed_type'),)", 'object_name': 'EmailFeedSetting'},
'added_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'feed_type': ('django.db.models.fields.CharField', [], {'max_length': '16'}),
'frequency': ('django.db.models.fields.CharField', [], {'default': "'n'", 'max_length': '8'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'reported_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'subscriber': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'notification_subscriptions'", 'to': "orm['auth.User']"})
},
'askbot.favoriteexercise': {
'Meta': {'object_name': 'FavoriteExercise', 'db_table': "u'favorite_exercise'"},
'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'thread': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['askbot.Thread']"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_favorite_exercises'", 'to': "orm['auth.User']"})
},
'askbot.group': {
'Meta': {'object_name': 'Group', '_ormbases': ['auth.Group']},
'group_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.Group']", 'unique': 'True', 'primary_key': 'True'}),
'logo_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True'}),
'moderate_email': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'openness': ('django.db.models.fields.SmallIntegerField', [], {'default': '2'}),
'preapproved_email_domains': ('django.db.models.fields.TextField', [], {'default': "''", 'null': 'True', 'blank': 'True'}),
'preapproved_emails': ('django.db.models.fields.TextField', [], {'default': "''", 'null': 'True', 'blank': 'True'})
},
'askbot.markedtag': {
'Meta': {'object_name': 'MarkedTag'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'reason': ('django.db.models.fields.CharField', [], {'max_length': '16'}),
'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_selections'", 'to': "orm['askbot.Tag']"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'tag_selections'", 'to': "orm['auth.User']"})
},
'askbot.post': {
'Meta': {'object_name': 'Post'},
'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'approved': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'posts'", 'to': "orm['auth.User']"}),
'comment_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'deleted_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'deleted_posts'", 'null': 'True', 'to': "orm['auth.User']"}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'group_posts'", 'symmetrical': 'False', 'through': "orm['askbot.PostToGroup']", 'to': "orm['askbot.Group']"}),
'html': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_anonymous': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_edited_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'last_edited_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'last_edited_posts'", 'null': 'True', 'to': "orm['auth.User']"}),
'locked': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'locked_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'locked_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locked_posts'", 'null': 'True', 'to': "orm['auth.User']"}),
'offensive_flag_count': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'old_problem_id': ('django.db.models.fields.PositiveIntegerField', [], {'default': 'None', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'old_comment_id': ('django.db.models.fields.PositiveIntegerField', [], {'default': 'None', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'old_exercise_id': ('django.db.models.fields.PositiveIntegerField', [], {'default': 'None', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'comments'", 'null': 'True', 'to': "orm['askbot.Post']"}),
'post_type': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'summary': ('django.db.models.fields.CharField', [], {'max_length': '180'}),
'text': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'thread': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'posts'", 'null': 'True', 'blank': 'True', 'to': "orm['askbot.Thread']"}),
'vote_down_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'vote_up_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'wiki': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'wikified_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'})
},
'askbot.postflagreason': {
'Meta': {'object_name': 'PostFlagReason'},
'added_at': ('django.db.models.fields.DateTimeField', [], {}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'details': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'post_reject_reasons'", 'to': "orm['askbot.Post']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '128'})
},
'askbot.postrevision': {
'Meta': {'ordering': "('-revision',)", 'unique_together': "(('post', 'revision'),)", 'object_name': 'PostRevision'},
'approved': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'approved_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'approved_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'postrevisions'", 'to': "orm['auth.User']"}),
'by_email': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'email_address': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_anonymous': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'post': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'revisions'", 'null': 'True', 'to': "orm['askbot.Post']"}),
'revised_at': ('django.db.models.fields.DateTimeField', [], {}),
'revision': ('django.db.models.fields.PositiveIntegerField', [], {}),
'summary': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}),
'tagnames': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '125', 'blank': 'True'}),
'text': ('django.db.models.fields.TextField', [], {}),
'title': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '300', 'blank': 'True'})
},
'askbot.posttogroup': {
'Meta': {'unique_together': "(('post', 'group'),)", 'object_name': 'PostToGroup', 'db_table': "'askbot_post_groups'"},
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['askbot.Group']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'post': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['askbot.Post']"})
},
'askbot.exerciseview': {
'Meta': {'object_name': 'ExerciseView'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'viewed'", 'to': "orm['askbot.Post']"}),
'when': ('django.db.models.fields.DateTimeField', [], {}),
'who': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'exercise_views'", 'to': "orm['auth.User']"})
},
'askbot.exercisewidget': {
'Meta': {'object_name': 'ExerciseWidget'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'order_by': ('django.db.models.fields.CharField', [], {'default': "'-added_at'", 'max_length': '18'}),
'exercise_number': ('django.db.models.fields.PositiveIntegerField', [], {'default': '7'}),
'search_query': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '50', 'null': 'True', 'blank': 'True'}),
'style': ('django.db.models.fields.TextField', [], {'default': '"\\n@import url(\'http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:300,400,700\');\\nbody {\\n overflow: hidden;\\n}\\n\\n#container {\\n width: 200px;\\n height: 350px;\\n}\\nul {\\n list-style: none;\\n padding: 5px;\\n margin: 5px;\\n}\\nli {\\n border-bottom: #CCC 1px solid;\\n padding-bottom: 5px;\\n padding-top: 5px;\\n}\\nli:last-child {\\n border: none;\\n}\\na {\\n text-decoration: none;\\n color: #464646;\\n font-family: \'Yanone Kaffeesatz\', sans-serif;\\n font-size: 15px;\\n}\\n"', 'blank': 'True'}),
'tagnames': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'askbot.replyaddress': {
'Meta': {'object_name': 'ReplyAddress'},
'address': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '25'}),
'allowed_from_email': ('django.db.models.fields.EmailField', [], {'max_length': '150'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'post': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'reply_addresses'", 'null': 'True', 'to': "orm['askbot.Post']"}),
'reply_action': ('django.db.models.fields.CharField', [], {'default': "'auto_problem_or_comment'", 'max_length': '32'}),
'response_post': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'edit_addresses'", 'null': 'True', 'to': "orm['askbot.Post']"}),
'used_at': ('django.db.models.fields.DateTimeField', [], {'default': 'None', 'null': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'askbot.repute': {
'Meta': {'object_name': 'Repute', 'db_table': "u'repute'"},
'comment': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'negative': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'positive': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['askbot.Post']", 'null': 'True', 'blank': 'True'}),
'reputation': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
'reputation_type': ('django.db.models.fields.SmallIntegerField', [], {}),
'reputed_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'askbot.tag': {
'Meta': {'ordering': "('-used_count', 'name')", 'object_name': 'Tag', 'db_table': "u'tag'"},
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_tags'", 'to': "orm['auth.User']"}),
'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'deleted_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'deleted_tags'", 'null': 'True', 'to': "orm['auth.User']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'status': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}),
'suggested_by': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'suggested_tags'", 'symmetrical': 'False', 'to': "orm['auth.User']"}),
'tag_wiki': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'described_tag'", 'unique': 'True', 'null': 'True', 'to': "orm['askbot.Post']"}),
'used_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'})
},
'askbot.thread': {
'Meta': {'object_name': 'Thread'},
'accepted_problem': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'+'", 'null': 'True', 'to': "orm['askbot.Post']"}),
'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'problem_accepted_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'problem_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'approved': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}),
'close_reason': ('django.db.models.fields.SmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'closed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'closed_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'closed_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
'favorited_by': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'unused_favorite_threads'", 'symmetrical': 'False', 'through': "orm['askbot.FavoriteExercise']", 'to': "orm['auth.User']"}),
'favourite_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'followed_by': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'followed_threads'", 'symmetrical': 'False', 'to': "orm['auth.User']"}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'group_threads'", 'symmetrical': 'False', 'db_table': "'askbot_thread_groups'", 'to': "orm['askbot.Group']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_activity_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_activity_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'unused_last_active_in_threads'", 'to': "orm['auth.User']"}),
'score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'tagnames': ('django.db.models.fields.CharField', [], {'max_length': '125'}),
'tags': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'threads'", 'symmetrical': 'False', 'to': "orm['askbot.Tag']"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '300'}),
'view_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'})
},
'askbot.vote': {
'Meta': {'unique_together': "(('user', 'voted_post'),)", 'object_name': 'Vote', 'db_table': "u'vote'"},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'votes'", 'to': "orm['auth.User']"}),
'vote': ('django.db.models.fields.SmallIntegerField', [], {}),
'voted_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'voted_post': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'votes'", 'to': "orm['askbot.Post']"})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},<|fim▁hole|> 'Meta': {'object_name': 'User'},
'about': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'avatar_type': ('django.db.models.fields.CharField', [], {'default': "'n'", 'max_length': '1'}),
'bronze': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'consecutive_days_visit_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'country': ('django_countries.fields.CountryField', [], {'max_length': '2', 'blank': 'True'}),
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'date_of_birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'display_tag_filter_strategy': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'email_isvalid': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'email_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True'}),
'email_signature': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'email_tag_filter_strategy': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'gold': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'gravatar': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ignored_tags': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'interesting_tags': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_fake': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'location': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'new_response_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'exercises_per_page': ('django.db.models.fields.SmallIntegerField', [], {'default': '10'}),
'real_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'reputation': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}),
'seen_response_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'show_country': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'show_marked_tags': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'silver': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'status': ('django.db.models.fields.CharField', [], {'default': "'w'", 'max_length': '2'}),
'subscribed_tags': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['askbot']<|fim▁end|>
|
'auth.user': {
|
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from flask import render_template, redirect, request, url_for, flash
from flask_login import login_user, logout_user, login_required, current_user
from . import auth
from .. import db
from ..models import User
from ..email import send_email
from .forms import LoginForm, RegistrationForm, ChangePasswordForm,\
PasswordResetRequestForm, PasswordResetForm, ChangeEmailForm
@auth.before_app_request<|fim▁hole|> and request.endpoint[:5] != 'auth.' \
and request.endpoint != 'static':
return redirect(url_for('auth.unconfirmed'))
@auth.route('/unconfirmed')
def unconfirmed():
if current_user.is_anonymous or current_user.confirmed:
return redirect(url_for('main.index'))
return render_template('auth/unconfirmed.html')
@auth.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is not None and user.verify_password(form.password.data):
login_user(user, form.remember_me.data)
return redirect(request.args.get('next') or url_for('main.index'))
flash('Invalid username or password.')
return render_template('auth/login.html', form=form)
@auth.route('/logout')
@login_required
def logout():
logout_user()
flash('You have been logged out.')
return redirect(url_for('main.index'))
@auth.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
user = User(email=form.email.data,
username=form.username.data,
password=form.password.data)
db.session.add(user)
db.session.commit()
token = user.generate_confirmation_token()
send_email(user.email, 'Confirm Your Account',
'auth/email/confirm', user=user, token=token)
flash('A confirmation email has been sent to you by email.')
return redirect(url_for('auth.login'))
return render_template('auth/register.html', form=form)
@auth.route('/confirm/<token>')
@login_required
def confirm(token):
if current_user.confirmed:
return redirect(url_for('main.index'))
if current_user.confirm(token):
flash('You have confirmed your account. Thanks!')
else:
flash('The confirmation link is invalid or has expired.')
return redirect(url_for('main.index'))
@auth.route('/confirm')
@login_required
def resend_confirmation():
token = current_user.generate_confirmation_token()
send_email(current_user.email, 'Confirm Your Account',
'auth/email/confirm', user=current_user, token=token)
flash('A new confirmation email has been sent to you by email.')
return redirect(url_for('main.index'))
@auth.route('/change-password', methods=['GET', 'POST'])
@login_required
def change_password():
form = ChangePasswordForm()
if form.validate_on_submit():
if current_user.verify_password(form.old_password.data):
current_user.password = form.password.data
db.session.add(current_user)
flash('Your password has been updated.')
return redirect(url_for('main.index'))
else:
flash('Invalid password.')
return render_template('auth/change_password.html', form=form)
@auth.route('/reset', methods=['GET', 'POST'])
def password_reset_request():
if not current_user.is_anonymous:
return redirect(url_for('main.index'))
form = PasswordResetRequestForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user:
token = user.generate_reset_token()
send_email(user.email, 'Reset Your Password',
'auth/email/reset_password',
user=user, token=token,
next=request.args.get('next'))
flash('An email with instructions to reset your password has been '
'sent to you.')
return redirect(url_for('auth.login'))
return render_template('auth/reset_password.html', form=form)
@auth.route('/reset/<token>', methods=['GET', 'POST'])
def password_reset(token):
if not current_user.is_anonymous:
return redirect(url_for('main.index'))
form = PasswordResetForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is None:
return redirect(url_for('main.index'))
if user.reset_password(token, form.password.data):
flash('Your password has been updated.')
return redirect(url_for('auth.login'))
else:
return redirect(url_for('main.index'))
return render_template('auth/reset_password.html', form=form)
@auth.route('/change-email', methods=['GET', 'POST'])
@login_required
def change_email_request():
form = ChangeEmailForm()
if form.validate_on_submit():
if current_user.verify_password(form.password.data):
new_email = form.email.data
token = current_user.generate_email_change_token(new_email)
send_email(new_email, 'Confirm your email address',
'auth/email/change_email',
user=current_user, token=token)
flash('An email with instructions to confirm your new email '
'address has been sent to you.')
return redirect(url_for('main.index'))
else:
flash('Invalid email or password.')
return render_template('auth/change_email.html', form=form)
@auth.route('/change-email/<token>')
@login_required
def change_email(token):
if current_user.change_email(token):
flash('Your email address has been updated.')
else:
flash('Invalid request.')
return redirect(url_for('main.index'))<|fim▁end|>
|
def before_request():
if current_user.is_authenticated:
current_user.ping()
if not current_user.confirmed \
|
<|file_name|>xenia_and_ringroad.py<|end_file_name|><|fim▁begin|># coding: utf-8<|fim▁hole|># xenia_and_ringroad
n, m = map(int, raw_input().split())
atividades_casas = map(int, raw_input().split())
tempo = 0
posicao = 1
for i in range(len(atividades_casas)):
if posicao < atividades_casas[i]:
tempo += (atividades_casas[i] - posicao)
elif posicao > atividades_casas[i]:
tempo += (n - posicao + atividades_casas[i])
posicao = atividades_casas[i]
print tempo<|fim▁end|>
|
# Maria Clara Dantas, UFCG
|
<|file_name|>hungry_zombie_kittens.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 -u
#---- Includes ----#
from ..army_architect import Bot_blueprint, Army_blueprint
#---- General Settings ----#
army_name = "The Hungry Zombie Kittens"
army_description = "Previously these kittens ate cat food. But now they wan't to eat your freakin' soul! (And your body to of course, after they ripped it asunder ;,,,;)"
<|fim▁hole|> name = "Zombie Kitten"
skin = "HK-KittyZombie.png"
ai_diff = 0
ai_diff_dynamic = True
can_use_ninja = 0
can_use_ninja_dynamic = False
shield_factor = 0.6
shield_factor_dynamic = True
damage_factor = 1
damage_factor_dynamic = False
speed_factor = 0.6
speed_factor_dynamic = False
class Franken_kitten(Bot_blueprint):
name = "Franken Kitten"
skin = "HK-FrankenKitty.png"
ai_diff = 0
ai_diff_dynamic = True
can_use_ninja = 1
can_use_ninja_dynamic = True
shield_factor = 0.6
shield_factor_dynamic = False
damage_factor = 1
damage_factor_dynamic = False
speed_factor = 0.8
speed_factor_dynamic = True
class Ghoul_kitten(Bot_blueprint):
name = "Ghoul Kitten"
skin = "HK-KittyMime.png"
ai_diff = 2
ai_diff_dynamic = True
can_use_ninja = 1
can_use_ninja_dynamic = True
shield_factor = 0.5
shield_factor_dynamic = True
damage_factor = 1.0
damage_factor_dynamic = False
speed_factor = 1.6
speed_factor_dynamic = True
def generate_blueprint(challenge_amount, lives, team):
global army_name, army_description
#---- Generate a list of of bot blueprints ----#
blueprints = []
# How many of each bot per challenge amount:
blueprint_weights = {
Zombie_kitten: 2,
Franken_kitten: 1,
Ghoul_kitten: 0.5,
}
for blueprint, wieght in blueprint_weights.items():
num_bots = round(wieght * challenge_amount)
for x in range(num_bots):
blueprints.append(blueprint(lives, team))
#---- Scale the blueprints ----#
# Sum the current default_challenge_amount
default_challenge_amount_sum = 0
for blueprint in blueprints:
default_challenge_amount_sum += blueprint.default_challenge_amount
scale_factor = challenge_amount / default_challenge_amount_sum
for blueprint in blueprints:
blueprint.scale_challenge_amount_with(scale_factor)
#---- Return the army ----#
return Army_blueprint(army_name, army_description, blueprints)<|fim▁end|>
|
#---- Bot Patterns ----#
class Zombie_kitten(Bot_blueprint):
|
<|file_name|>tool.js<|end_file_name|><|fim▁begin|>// Arrays contendo os elementos editados
var editedElements = [];
var selectedElementIndex = null;
var unsavedChanges = false;
function updateIframeMinHeight() {
var iframe = $('#app-tool-iframe');
var container = $('#app-iframe-container');
if (container.height() > iframe.height())
iframe.css('min-height', container.height());
return;
}
// Atualiza o texto do elemento selecionado no editor
function updateSelectedElement(element) {
var target = $('#app-selected-element-text');
var containerID = 'app-selected-element-text';
var selectedID = 'app-tool-preview-card-li-selected';
if (!element)
element = 'nenhum';
target.replaceWith('<span id="' + containerID + '">' + element + '</span>');
$('[data-selector="' + target.text() + '"]').parent().removeClass(selectedID);
$('[data-selector="' + element + '"]').parent().addClass(selectedID);
if (!$('#app-editor-controls').is(":visible")) {
$('#app-editor-greeting').slideToggle(250);
$('#app-editor-controls').slideToggle(250);
}
if (selectedElementIndex) {
enableUnsavedChangesWarning();
saveEditedElement(selectedElementIndex);<|fim▁hole|>}
// Mostra/oculta overlay do elemento selecionado no iFrame
function showSelectionOverlay(element, visible) {
var iframe = $('#app-tool-iframe');
var overlay = 'app-tool-iframe-css-overlay';
// Injeta estilo do overlay dentro do iframe se ainda não existir
if (!iframe.contents().find('#' + overlay).length) {
iframe.contents().find('html').append('\
<style id="' + overlay + '"> .' + overlay + ' {\n\
background-color: rgba(255, 110, 64, 0.5) !important;\n\
} </style>');
}
if (visible)
iframe.contents().find(element).addClass(overlay);
else
iframe.contents().find(element).removeClass(overlay);
return;
}
// Adiciona elemento na lista de seletores e define os eventos do mouse
// Se o elemento já existe na lista de seletores, nada acontece
function addElementToTagList(element) {
if (!$('[data-selector="' + element + '"]').length) {
$('#app-tool-tag-container').append(
'<li class="app-tool-preview-card-li"><a href="#" data-selector="' +
element + '">' + element + '</a></li>');
var newElement = $('[data-selector="' + element + '"]');
newElement.click(function () {
updateSelectedElement(element);
});
newElement.mouseover(function () {
showSelectionOverlay(element, true);
});
newElement.mouseout(function () {
showSelectionOverlay(element, false);
});
}
return;
}
// Recebe uma string contendo um ou mais elementos (ex. várias classes ou IDs)
// e um prefixo e adiciona cada classe/ID individual na lista de elementos
function addMultipleElementToTagList(prefix, element) {
if (!prefix)
prefix = '';
if (element) {
if (String(element).indexOf(' ') !== -1) {
var tmp = String(element).split(' ');
for (var i = 0; i < tmp.length; i++) {
addElementToTagList(prefix + tmp[i]);
}
} else {
addElementToTagList(prefix + element);
}
}
return;
}
// Chama função ao redimensionar a janela
$(window).resize(updateIframeMinHeight);
// Escaneia e adiciona todos os elementos do iframe
// na lista de seletores ao carregar a página
$(document).ready(function () {
$('#app-tool-tag-container').css('max-height', $(window).height() * 0.65);
$('#app-tool-iframe').on('load', function () {
$('#app-tool-iframe').contents().find('*').each(function () {
addElementToTagList($(this).prop("nodeName").toLowerCase());
addMultipleElementToTagList('.', $(this).attr('class'));
addMultipleElementToTagList('#', $(this).attr('id'));
});
});
});
function enableUnsavedChangesWarning() {
if (!unsavedChanges) {
$(window).on('beforeunload', function () {
return 'Suas alterações serão perdidas!';
});
unsavedChanges = true;
}
return;
}
function loadElementIntoEditor(i) {
clearEditor();
updateMDLInput($('#margin'), editedElements[i].margin);
updateMDLInput($('#border'), editedElements[i].border);
updateMDLInput($('#padding'), editedElements[i].padding);
updateMDLInput($('#z-index'), editedElements[i].zindex);
updateMDLInput($('#left'), editedElements[i].left);
updateMDLInput($('#right'), editedElements[i].right);
updateMDLInput($('#top'), editedElements[i].top);
updateMDLInput($('#bottom'), editedElements[i].bottom);
updateMDLInput($('#width'), editedElements[i].width);
updateMDLInput($('#height'), editedElements[i].height);
updateMDLInput($('#min-width'), editedElements[i].minwidth);
updateMDLInput($('#min-height'), editedElements[i].minheight);
updateMDLInput($('#max-width'), editedElements[i].maxwidth);
updateMDLInput($('#max-height'), editedElements[i].maxheight);
updateMDLInput($('#background-image'), editedElements[i].backgroundimage);
updateMDLInput($('#background-color'), editedElements[i].backgroundcolor);
updateMDLInput($('#color'), editedElements[i].color);
updateMDLInput($('#font-family'), editedElements[i].fontfamily);
updateMDLInput($('#font-size'), editedElements[i].fontsize);
updateMDLInput($('#font-weight'), editedElements[i].fontweight);
updateMDLRadio('position', editedElements[i].position);
updateMDLRadio('overflow', editedElements[i].overflow);
updateMDLRadio('background-repeat', editedElements[i].backgroundrepeat);
updateMDLRadio('font-style', editedElements[i].fontstyle);
updateMDLRadio('text-align', editedElements[i].textalign);
updateMDLRadio('text-decoration', editedElements[i].textdecoration);
if (editedElements[i].fontvariant == 'small-caps') {
$('#small-caps').prop('checked', true);
$('#small-caps').parent().addClass('is-checked');
}
}
function saveEditedElement(i) {
editedElements[i].margin = $('#margin').val();
editedElements[i].border = $('#border').val();
editedElements[i].padding = $('#padding').val();
editedElements[i].zindex = $('#z-index').val();
editedElements[i].left = $('#left').val();
editedElements[i].right = $('#right').val();
editedElements[i].top = $('#top').val();
editedElements[i].bottom = $('#bottom').val();
editedElements[i].width = $('#width').val();
editedElements[i].height = $('#height').val();
editedElements[i].minwidth = $('#min-width').val();
editedElements[i].minheight = $('#min-height').val();
editedElements[i].maxwidth = $('#max-width').val();
editedElements[i].maxheight = $('#max-height').val();
editedElements[i].backgroundimage = $('#background-image').val();
editedElements[i].backgroundcolor = $('#background-color').val();
editedElements[i].color = $('#color').val();
editedElements[i].fontfamily = $('#font-family').val();
editedElements[i].fontsize = $('#font-size').val();
editedElements[i].fontweight = $('#font-weight').val();
editedElements[i].position = $('input[name=position]:checked').val();
editedElements[i].overflow = $('input[name=overflow]:checked').val();
editedElements[i].backgroundrepeat = $('input[name=background-repeat]:checked').val();
editedElements[i].fontstyle = $('input[name=font-style]:checked').val();
editedElements[i].textalign = $('input[name=text-align]:checked').val();
editedElements[i].textdecoration = $('input[name=text-decoration]:checked').val();
}
function checkEditedElements(selector) {
var index = null;
for (var i = 0; i < editedElements.length; i++)
{
if (editedElements[i].id == selector) {
selectedElementIndex = i;
loadElementIntoEditor(i);
return;
}
}
var newElement = {id: selector, margin: '', border: '', padding: '', zindex: '',
left: '', right: '', top: '', bottom: '', width: '', height: '', minwidth: '',
minheight: '', maxwidth: '', maxheight: '', backgroundcolor: '', backgroundimage: '',
color: '', fontfamilly: '', fontsize: '', fontweight: '', position: '', overflow: '',
backgroundrepeat: '', fontstyle: '', textalign: '', textdecoration: '', fontvariant: ''};
index = editedElements.push(newElement);
selectedElementIndex = index - 1;
loadElementIntoEditor(index - 1);
return;
}
// Atualiza o valor do campo informado
function updateMDLInput(element, value) {
if (value) {
element.val(String(value));
element.parent().addClass('is-dirty');
}
return;
}
// Seleciona botão no grupo de acordo com o valor informado
function updateMDLRadio(group, value) {
var target;
if (value) {
switch (group) {
case 'position':
if (value == 'initial')
target = $('#initial_p');
else
target = $('#' + value);
break;
case 'overflow':
if (value == 'initial')
target = $('#initial_d');
else
target = $('#' + value);
break;
case 'background-repeat':
if (value == 'initial')
target = $('#initial_b');
else
target = $('#' + value);
break;
case 'font-style':
if (value == 'initial')
target = $('#initial_f0');
else
target = $('#' + value);
break;
case 'text-align':
if (value == 'initial')
target = $('#initial_f1');
else if (value == 'left')
target = $('#left_f');
else if (value == 'right')
target = $('#right_f');
else
target = $('#' + value);
break;
case 'text-decoration':
// Em navegadores recentes, o campo text-decoration contém o valor combinado
// dos atributos text-decoration-line, text-decoration-color e text-decoration-style,
// então verificamos e dividimos a string antes de definir o target, se necessário
if (String(value).indexOf(' ') !== -1) {
var tmp = String(value).split(' ');
value = tmp[0];
}
if (value == 'initial')
target = $('#initial_f2');
else
target = $('#' + value);
break;
}
target.prop('checked', true);
target.parent().addClass('is-checked');
}
return;
}
function clearEditor() {
// Aba Posição
var inputElements = '#margin #border #padding #z-index #left #right #top #bottom ';
// Aba Dimensões
inputElements = inputElements.concat('#width #height #min-width #min-height #max-width #max-height ');
// Aba Preenchimento
inputElements = inputElements.concat('#background-image ');
// Aba Texto
inputElements = inputElements.concat('#font-family #font-size #font-weight ');
var tmp = String(inputElements).split(' ');
for (var i = 0; i < tmp.length; i++) {
$(tmp[i]).val('');
$(tmp[i]).parent().removeClass('is-dirty');
}
$('input:radio').parent().removeClass('is-checked');
$('input:checkbox').parent().removeClass('is-checked');
$('input:radio').removeAttr('checked');
$('input:checkbox').removeAttr('checked');
$('#background-color').val('#000000');
$('#app-button-background-color').prop('disabled', true);
$('#color').val('#000000');
$('#app-button-color').prop('disabled', true);
return;
}
/*
$('#color').on('input propertychange', function () {
$('#app-button-color').prop('disabled', false);
});
$('#background-color').change(function () {
$('#app-button-background-color').prop('disabled', false);
});
$('#app-button-color').click(function () {
alert('trigger');
$('#color').val('#000000');
$('#app-button-color').prop('disabled', true);
});
$('#app-button-background-color').click(function () {
$('#background-color').val('#000000');
$('#app-button-background-color').prop('disabled', true);
});
*/
function editorBackButton() {
window.location = '?url=index';
return;
}<|fim▁end|>
|
}
checkEditedElements(element);
return;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.