file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
config.py |
# Copyright 2017 Mycroft AI 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 re
import json
import inflection
from os.path import exists, isfile
from requests import RequestException
from mycroft.util.json_helper import load_commented_json, merge_dict
from mycroft.util.log import LOG
from .locations import (DEFAULT_CONFIG, SYSTEM_CONFIG, USER_CONFIG,
WEB_CONFIG_CACHE)
def is_remote_list(values):
''' check if this list corresponds to a backend formatted collection of
dictionaries '''
for v in values:
if not isinstance(v, dict):
return False
if "@type" not in v.keys():
return False
return True
def translate_remote(config, setting):
"""
Translate config names from server to equivalents usable
in mycroft-core.
Args:
config: base config to populate
settings: remote settings to be translated
"""
IGNORED_SETTINGS = ["uuid", "@type", "active", "user", "device"]
for k, v in setting.items():
if k not in IGNORED_SETTINGS:
# Translate the CamelCase values stored remotely into the
# Python-style names used within mycroft-core.
key = inflection.underscore(re.sub(r"Setting(s)?", "", k))
if isinstance(v, dict):
config[key] = config.get(key, {})
translate_remote(config[key], v)
elif isinstance(v, list):
if is_remote_list(v):
if key not in config:
config[key] = {}
translate_list(config[key], v)
else:
config[key] = v
else:
config[key] = v
def translate_list(config, values):
"""
Translate list formated by mycroft server.
Args:
config (dict): target config
values (list): list from mycroft server config
"""
for v in values:
module = v["@type"]
if v.get("active"):
config["module"] = module
config[module] = config.get(module, {})
translate_remote(config[module], v)
class LocalConf(dict):
"""
Config dict from file.
"""
def __init__(self, path):
super(LocalConf, self).__init__()
if path:
self.path = path
self.load_local(path)
def load_local(self, path):
"""
Load local json file into self.
Args:
path (str): file to load
"""
if exists(path) and isfile(path):
try:
config = load_commented_json(path)
for key in config:
self.__setitem__(key, config[key])
LOG.debug("Configuration {} loaded".format(path))
except Exception as e:
LOG.error("Error loading configuration '{}'".format(path))
LOG.error(repr(e))
else:
LOG.debug("Configuration '{}' not defined, skipping".format(path))
def store(self, path=None):
"""
Cache the received settings locally. The cache will be used if
the remote is unreachable to load settings that are as close
to the user's as possible
"""
path = path or self.path
with open(path, 'w') as f:
json.dump(self, f, indent=2)
def merge(self, conf):
merge_dict(self, conf)
class RemoteConf(LocalConf):
"""
Config dict fetched from mycroft.ai
"""
def __init__(self, cache=None):
super(RemoteConf, self).__init__(None)
cache = cache or WEB_CONFIG_CACHE
from mycroft.api import is_paired
if not is_paired():
self.load_local(cache)
return
try:
# Here to avoid cyclic import
from mycroft.api import DeviceApi
api = DeviceApi()
setting = api.get_settings()
try:
location = api.get_location()
except RequestException as e:
LOG.error("RequestException fetching remote location: {}"
.format(str(e)))
if exists(cache) and isfile(cache):
location = load_commented_json(cache).get('location')
if location:
setting["location"] = location
# Remove server specific entries
config = {}
translate_remote(config, setting)
for key in config:
self.__setitem__(key, config[key])
self.store(cache)
except RequestException as e:
LOG.error("RequestException fetching remote configuration: {}"
.format(str(e)))
self.load_local(cache)
except Exception as e:
LOG.error("Failed to fetch remote configuration: %s" % repr(e),
exc_info=True)
self.load_local(cache)
class Configuration:
__config = {} # Cached config
__patch = {} # Patch config that skills can update to override config
@staticmethod
def get(configs=None, cache=True):
"""
Get configuration, returns cached instance if available otherwise
builds a new configuration dict.
Args:
configs (list): List of configuration dicts
cache (boolean): True if the result should be cached
"""
if Configuration.__config:
return Configuration.__config
else:
return Configuration.load_config_stack(configs, cache)
@staticmethod
def | (configs=None, cache=False):
"""
load a stack of config dicts into a single dict
Args:
configs (list): list of dicts to load
cache (boolean): True if result should be cached
Returns: merged dict of all configuration files
"""
if not configs:
configs = [LocalConf(DEFAULT_CONFIG), RemoteConf(),
LocalConf(SYSTEM_CONFIG), LocalConf(USER_CONFIG),
Configuration.__patch]
else:
# Handle strings in stack
for index, item in enumerate(configs):
if isinstance(item, str):
configs[index] = LocalConf(item)
# Merge all configs into one
base = {}
for c in configs:
merge_dict(base, c)
# copy into cache
if cache:
Configuration.__config.clear()
for key in base:
Configuration.__config[key] = base[key]
return Configuration.__config
else:
return base
@staticmethod
def set_config_update_handlers(bus):
"""Setup websocket handlers to update config.
Args:
bus: Message bus client instance
"""
bus.on("configuration.updated", Configuration.updated)
bus.on("configuration.patch", Configuration.patch)
@staticmethod
def updated(message):
"""
handler for configuration.updated, triggers an update
of cached config.
"""
Configuration.load_config_stack(cache=True)
@staticmethod
def patch(message):
"""
patch the volatile dict usable by skills
Args:
message: Messagebus message should contain a config
in the data payload.
"""
config = message.data.get("config", {})
merge_dict(Configuration.__patch, config)
Configuration.load_config_stack(cache=True)
| load_config_stack | identifier_name |
fig08_10.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# fig08_10.py
#
# Author: Billy Wilson Arante
# Created: 2016/10/10
from rational import Rational
def main():
"""Main"""
# Objects of class Rational
rational1 = Rational() # 1/1
rational2 = Rational(10, 30) # 10/30 reduces to 1/3
rational3 = Rational(-7, 14) # -7/14 reduces to -1/2
# Printing objects of class Rational
print "Rational 1:", rational1
print "Rational 2:", rational2
print "Rational 3:", rational3
print
# Testing mathematical operators
print rational1, "/", rational2, "=", rational1 / rational2
print rational3, "-", rational2, "=", rational3 - rational2
print rational2, "*", rational3, "-", rational1, "=", \
rational2 * rational3 - rational1
# Overloading + implicitly overloads +=
rational1 += rational2 * rational3
print "\nrational1 after adding rational2 * rational3:", rational1
print
# Test comparison operators
print rational1, "<=", rational2, ":", rational1 <= rational2
print rational1, ">", rational3, ":", rational1 > rational3
print
# Test built-in function abs
print "The absolute value of", rational3, "is:", abs(rational3)
print
# Test coercion
print rational2, "as an integer is:", int(rational2)
print rational2, "as a float is:", float(rational2)
print rational2, "+ 1 =", rational2 + 1
if __name__ == "__main__":
| main() | conditional_block | |
fig08_10.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# fig08_10.py
#
# Author: Billy Wilson Arante
# Created: 2016/10/10
from rational import Rational
| rational1 = Rational() # 1/1
rational2 = Rational(10, 30) # 10/30 reduces to 1/3
rational3 = Rational(-7, 14) # -7/14 reduces to -1/2
# Printing objects of class Rational
print "Rational 1:", rational1
print "Rational 2:", rational2
print "Rational 3:", rational3
print
# Testing mathematical operators
print rational1, "/", rational2, "=", rational1 / rational2
print rational3, "-", rational2, "=", rational3 - rational2
print rational2, "*", rational3, "-", rational1, "=", \
rational2 * rational3 - rational1
# Overloading + implicitly overloads +=
rational1 += rational2 * rational3
print "\nrational1 after adding rational2 * rational3:", rational1
print
# Test comparison operators
print rational1, "<=", rational2, ":", rational1 <= rational2
print rational1, ">", rational3, ":", rational1 > rational3
print
# Test built-in function abs
print "The absolute value of", rational3, "is:", abs(rational3)
print
# Test coercion
print rational2, "as an integer is:", int(rational2)
print rational2, "as a float is:", float(rational2)
print rational2, "+ 1 =", rational2 + 1
if __name__ == "__main__":
main() | def main():
"""Main"""
# Objects of class Rational | random_line_split |
fig08_10.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# fig08_10.py
#
# Author: Billy Wilson Arante
# Created: 2016/10/10
from rational import Rational
def main():
|
if __name__ == "__main__":
main()
| """Main"""
# Objects of class Rational
rational1 = Rational() # 1/1
rational2 = Rational(10, 30) # 10/30 reduces to 1/3
rational3 = Rational(-7, 14) # -7/14 reduces to -1/2
# Printing objects of class Rational
print "Rational 1:", rational1
print "Rational 2:", rational2
print "Rational 3:", rational3
print
# Testing mathematical operators
print rational1, "/", rational2, "=", rational1 / rational2
print rational3, "-", rational2, "=", rational3 - rational2
print rational2, "*", rational3, "-", rational1, "=", \
rational2 * rational3 - rational1
# Overloading + implicitly overloads +=
rational1 += rational2 * rational3
print "\nrational1 after adding rational2 * rational3:", rational1
print
# Test comparison operators
print rational1, "<=", rational2, ":", rational1 <= rational2
print rational1, ">", rational3, ":", rational1 > rational3
print
# Test built-in function abs
print "The absolute value of", rational3, "is:", abs(rational3)
print
# Test coercion
print rational2, "as an integer is:", int(rational2)
print rational2, "as a float is:", float(rational2)
print rational2, "+ 1 =", rational2 + 1 | identifier_body |
fig08_10.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# fig08_10.py
#
# Author: Billy Wilson Arante
# Created: 2016/10/10
from rational import Rational
def | ():
"""Main"""
# Objects of class Rational
rational1 = Rational() # 1/1
rational2 = Rational(10, 30) # 10/30 reduces to 1/3
rational3 = Rational(-7, 14) # -7/14 reduces to -1/2
# Printing objects of class Rational
print "Rational 1:", rational1
print "Rational 2:", rational2
print "Rational 3:", rational3
print
# Testing mathematical operators
print rational1, "/", rational2, "=", rational1 / rational2
print rational3, "-", rational2, "=", rational3 - rational2
print rational2, "*", rational3, "-", rational1, "=", \
rational2 * rational3 - rational1
# Overloading + implicitly overloads +=
rational1 += rational2 * rational3
print "\nrational1 after adding rational2 * rational3:", rational1
print
# Test comparison operators
print rational1, "<=", rational2, ":", rational1 <= rational2
print rational1, ">", rational3, ":", rational1 > rational3
print
# Test built-in function abs
print "The absolute value of", rational3, "is:", abs(rational3)
print
# Test coercion
print rational2, "as an integer is:", int(rational2)
print rational2, "as a float is:", float(rational2)
print rational2, "+ 1 =", rational2 + 1
if __name__ == "__main__":
main()
| main | identifier_name |
user.py | # coding: utf-8
from libs.redis_storage import db1
class User(object):
def __init__(self, **kwargs):
pk = kwargs.get('pk') or db1.incr('new_user_id')
kwargs['pk'] = pk
db1.hmset('user::{}'.format(pk), kwargs)
super(User, self).__setattr__('pk', pk)
super(User, self).__setattr__(
'__info__',
db1.hgetall(self.db_key) or {}
)
for k, v in self.__info__.iteritems():
self.__info__[k] = v.decode('utf-8')
@property
def short_info(self):
return {field: getattr(self, field) for field in [
'fio',
'sex',
'avatar',
'battles',
'wins',
'defeats',
'last_update'
]}
@property
def db_key(self):
return 'user::{}'.format(self.pk)
@property
def fio(self):
return u'{} {}'.format(self.last_name or u'', self.first_name or u'')
@property
def battles(self):
return int(self.__info__.get('battles', 0))
@property
def wins(self):
return int(self.__info__.get('wins', 0))
@property
def defeats(self):
return int(self.__info__.get('defeats', 0))
@property
def last_update(self):
return int(self.__info__.get('last_update', 0))
def __setattr__(self, attr, value):
self.__info__[attr] = value
db1.hset(self.db_key, attr, value)
def __getattr__(self, attr):
return self.__info__.get(attr)
def incr(self, attr, by=1):
|
def get_user_by_service(service, service_user_id):
user_pk = db1.get('{}_user_id::{}'.format(service, service_user_id))
if user_pk:
return User(pk=user_pk)
def add_service_to_user(service, service_user_id, user_pk):
db1.set('{}_user_id::{}'.format(service, service_user_id), user_pk)
user = User(pk=user_pk)
setattr(user, '{}_user_id'.format(service), service_user_id)
| db1.hincrby(self.db_key, attr, by) | identifier_body |
user.py | # coding: utf-8
from libs.redis_storage import db1
class User(object):
def __init__(self, **kwargs):
pk = kwargs.get('pk') or db1.incr('new_user_id')
kwargs['pk'] = pk
db1.hmset('user::{}'.format(pk), kwargs)
super(User, self).__setattr__('pk', pk)
super(User, self).__setattr__(
'__info__',
db1.hgetall(self.db_key) or {}
)
for k, v in self.__info__.iteritems():
self.__info__[k] = v.decode('utf-8')
@property
def short_info(self):
return {field: getattr(self, field) for field in [
'fio',
'sex',
'avatar',
'battles',
'wins',
'defeats',
'last_update'
]}
@property
def db_key(self):
return 'user::{}'.format(self.pk)
@property
def fio(self):
return u'{} {}'.format(self.last_name or u'', self.first_name or u'')
@property
def battles(self):
return int(self.__info__.get('battles', 0))
@property
def wins(self): | return int(self.__info__.get('defeats', 0))
@property
def last_update(self):
return int(self.__info__.get('last_update', 0))
def __setattr__(self, attr, value):
self.__info__[attr] = value
db1.hset(self.db_key, attr, value)
def __getattr__(self, attr):
return self.__info__.get(attr)
def incr(self, attr, by=1):
db1.hincrby(self.db_key, attr, by)
def get_user_by_service(service, service_user_id):
user_pk = db1.get('{}_user_id::{}'.format(service, service_user_id))
if user_pk:
return User(pk=user_pk)
def add_service_to_user(service, service_user_id, user_pk):
db1.set('{}_user_id::{}'.format(service, service_user_id), user_pk)
user = User(pk=user_pk)
setattr(user, '{}_user_id'.format(service), service_user_id) | return int(self.__info__.get('wins', 0))
@property
def defeats(self): | random_line_split |
user.py | # coding: utf-8
from libs.redis_storage import db1
class User(object):
def __init__(self, **kwargs):
pk = kwargs.get('pk') or db1.incr('new_user_id')
kwargs['pk'] = pk
db1.hmset('user::{}'.format(pk), kwargs)
super(User, self).__setattr__('pk', pk)
super(User, self).__setattr__(
'__info__',
db1.hgetall(self.db_key) or {}
)
for k, v in self.__info__.iteritems():
self.__info__[k] = v.decode('utf-8')
@property
def short_info(self):
return {field: getattr(self, field) for field in [
'fio',
'sex',
'avatar',
'battles',
'wins',
'defeats',
'last_update'
]}
@property
def db_key(self):
return 'user::{}'.format(self.pk)
@property
def fio(self):
return u'{} {}'.format(self.last_name or u'', self.first_name or u'')
@property
def battles(self):
return int(self.__info__.get('battles', 0))
@property
def wins(self):
return int(self.__info__.get('wins', 0))
@property
def defeats(self):
return int(self.__info__.get('defeats', 0))
@property
def last_update(self):
return int(self.__info__.get('last_update', 0))
def __setattr__(self, attr, value):
self.__info__[attr] = value
db1.hset(self.db_key, attr, value)
def __getattr__(self, attr):
return self.__info__.get(attr)
def incr(self, attr, by=1):
db1.hincrby(self.db_key, attr, by)
def | (service, service_user_id):
user_pk = db1.get('{}_user_id::{}'.format(service, service_user_id))
if user_pk:
return User(pk=user_pk)
def add_service_to_user(service, service_user_id, user_pk):
db1.set('{}_user_id::{}'.format(service, service_user_id), user_pk)
user = User(pk=user_pk)
setattr(user, '{}_user_id'.format(service), service_user_id)
| get_user_by_service | identifier_name |
user.py | # coding: utf-8
from libs.redis_storage import db1
class User(object):
def __init__(self, **kwargs):
pk = kwargs.get('pk') or db1.incr('new_user_id')
kwargs['pk'] = pk
db1.hmset('user::{}'.format(pk), kwargs)
super(User, self).__setattr__('pk', pk)
super(User, self).__setattr__(
'__info__',
db1.hgetall(self.db_key) or {}
)
for k, v in self.__info__.iteritems():
|
@property
def short_info(self):
return {field: getattr(self, field) for field in [
'fio',
'sex',
'avatar',
'battles',
'wins',
'defeats',
'last_update'
]}
@property
def db_key(self):
return 'user::{}'.format(self.pk)
@property
def fio(self):
return u'{} {}'.format(self.last_name or u'', self.first_name or u'')
@property
def battles(self):
return int(self.__info__.get('battles', 0))
@property
def wins(self):
return int(self.__info__.get('wins', 0))
@property
def defeats(self):
return int(self.__info__.get('defeats', 0))
@property
def last_update(self):
return int(self.__info__.get('last_update', 0))
def __setattr__(self, attr, value):
self.__info__[attr] = value
db1.hset(self.db_key, attr, value)
def __getattr__(self, attr):
return self.__info__.get(attr)
def incr(self, attr, by=1):
db1.hincrby(self.db_key, attr, by)
def get_user_by_service(service, service_user_id):
user_pk = db1.get('{}_user_id::{}'.format(service, service_user_id))
if user_pk:
return User(pk=user_pk)
def add_service_to_user(service, service_user_id, user_pk):
db1.set('{}_user_id::{}'.format(service, service_user_id), user_pk)
user = User(pk=user_pk)
setattr(user, '{}_user_id'.format(service), service_user_id)
| self.__info__[k] = v.decode('utf-8') | conditional_block |
window.rs | //! The kiss3d window.
/*
* FIXME: this file is too big. Some heavy refactoring need to be done here.
*/
use std::mem;
use std::thread;
use std::time::Duration;
use glfw;
use glfw::{Context, Key, Action, WindowMode, WindowEvent};
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::mpsc::Receiver;
use std::path::Path;
use std::iter::repeat;
use time;
use gl;
use gl::types::*;
use image::{ImageBuffer,Rgb};
use image::imageops;
use na::{Pnt2, Vec2, Vec3, Pnt3};
use na;
use ncollide_procedural::TriMesh3;
use camera::Camera;
use scene::SceneNode;
use line_renderer::LineRenderer;
use point_renderer::PointRenderer;
use post_processing::PostProcessingEffect;
use resource::{FramebufferManager, RenderTarget, Texture, TextureManager, Mesh, Material};
use light::Light;
use text::{TextRenderer, Font};
use window::EventManager;
use camera::ArcBall;
static DEFAULT_WIDTH: u32 = 800u32;
static DEFAULT_HEIGHT: u32 = 600u32;
/// Structure representing a window and a 3D scene.
///
/// This is the main interface with the 3d engine.
pub struct Window {
events: Rc<Receiver<(f64, WindowEvent)>>,
unhandled_events: Rc<RefCell<Vec<WindowEvent>>>,
glfw: glfw::Glfw,
window: glfw::Window,
max_ms_per_frame: Option<u64>,
scene: SceneNode,
light_mode: Light, // FIXME: move that to the scene graph
background: Vec3<GLfloat>,
line_renderer: LineRenderer,
point_renderer: PointRenderer,
text_renderer: TextRenderer,
framebuffer_manager: FramebufferManager,
post_process_render_target: RenderTarget,
curr_time: u64,
camera: Rc<RefCell<ArcBall>>
}
impl Window {
/// Indicates whether this window should be closed.
#[inline]
pub fn should_close(&self) -> bool {
self.window.should_close()
}
/// Access the glfw context.
#[inline]
pub fn context<'r>(&'r self) -> &'r glfw::Glfw {
&self.glfw
}
/// Access the glfw window.
#[inline]
pub fn glfw_window(&self) -> &glfw::Window {
&self.window
}
/// Mutably access the glfw window.
#[inline]
pub fn glfw_window_mut(&mut self) -> &mut glfw::Window {
&mut self.window
}
/// The window width.
#[inline]
pub fn width(&self) -> f32 {
let (w, _) = self.window.get_size();
w as f32
}
/// The window height.
#[inline]
pub fn height(&self) -> f32 {
let (_, h) = self.window.get_size();
h as f32
}
/// The size of the window.
#[inline]
pub fn size(&self) -> Vec2<f32> {
let (w, h) = self.window.get_size();
Vec2::new(w as f32, h as f32)
}
/// Sets the maximum number of frames per second. Cannot be 0. `None` means there is no limit.
#[inline]
pub fn set_framerate_limit(&mut self, fps: Option<u64>) {
self.max_ms_per_frame = fps.map(|f| { assert!(f != 0); 1000 / f })
}
/// Set window title
pub fn set_title(&mut self, title: &str) {
self.window.set_title(title)
}
/// Closes the window.
#[inline]
pub fn close(&mut self) {
self.window.set_should_close(true)
}
/// Hides the window, without closing it. Use `show` to make it visible again.
#[inline]
pub fn hide(&mut self) {
self.window.hide()
}
/// Makes the window visible. Use `hide` to hide it.
#[inline]
pub fn show(&mut self) {
self.window.show()
}
/// Sets the background color.
#[inline]
pub fn set_background_color(&mut self, r: f32, g: GLfloat, b: f32) {
self.background.x = r;
self.background.y = g;
self.background.z = b;
}
// XXX: remove this (moved to the render_frame).
/// Adds a line to be drawn during the next frame.
#[inline]
pub fn draw_line(&mut self, a: &Pnt3<f32>, b: &Pnt3<f32>, color: &Pnt3<f32>) {
self.line_renderer.draw_line(a.clone(), b.clone(), color.clone());
}
// XXX: remove this (moved to the render_frame).
/// Adds a point to be drawn during the next frame.
#[inline]
pub fn draw_point(&mut self, pt: &Pnt3<f32>, color: &Pnt3<f32>) {
self.point_renderer.draw_point(pt.clone(), color.clone());
}
// XXX: remove this (moved to the render_frame).
/// Adds a string to be drawn during the next frame.
#[inline]
pub fn draw_text(&mut self, text: &str, pos: &Pnt2<f32>, font: &Rc<Font>, color: &Pnt3<f32>) {
self.text_renderer.draw_text(text, pos, font, color);
}
/// Removes an object from the scene.
pub fn remove(&mut self, sn: &mut SceneNode) {
sn.unlink()
}
/// Adds a group to the scene.
///
/// A group is a node not containing any object.
pub fn add_group(&mut self) -> SceneNode {
self.scene.add_group()
}
/// Adds an obj model to the scene.
///
/// # Arguments
/// * `path` - relative path to the obj file.
/// * `scale` - scale to apply to the model.
pub fn add_obj(&mut self, path: &Path, mtl_dir: &Path, scale: Vec3<f32>) -> SceneNode {
self.scene.add_obj(path, mtl_dir, scale)
}
/// Adds an unnamed mesh to the scene.
pub fn add_mesh(&mut self, mesh: Rc<RefCell<Mesh>>, scale: Vec3<f32>) -> SceneNode {
self.scene.add_mesh(mesh, scale)
}
/// Creates and adds a new object using the geometry generated by a given procedural generator.
/// Creates and adds a new object using a mesh descriptor.
pub fn add_trimesh(&mut self, descr: TriMesh3<f32>, scale: Vec3<f32>) -> SceneNode {
self.scene.add_trimesh(descr, scale)
}
/// Creates and adds a new object using the geometry registered as `geometry_name`.
pub fn add_geom_with_name(&mut self, geometry_name: &str, scale: Vec3<f32>) -> Option<SceneNode> {
self.scene.add_geom_with_name(geometry_name, scale)
}
/// Adds a cube to the scene. The cube is initially axis-aligned and centered at (0, 0, 0).
///
/// # Arguments
/// * `wx` - the cube extent along the z axis
/// * `wy` - the cube extent along the y axis
/// * `wz` - the cube extent along the z axis
pub fn add_cube(&mut self, wx: GLfloat, wy: GLfloat, wz: GLfloat) -> SceneNode {
self.scene.add_cube(wx, wy, wz)
}
/// Adds a sphere to the scene. The sphere is initially centered at (0, 0, 0).
///
/// # Arguments
/// * `r` - the sphere radius
pub fn add_sphere(&mut self, r: GLfloat) -> SceneNode {
self.scene.add_sphere(r)
}
/// Adds a cone to the scene. The cone is initially centered at (0, 0, 0) and points toward the
/// positive `y` axis.
///
/// # Arguments
/// * `h` - the cone height
/// * `r` - the cone base radius
pub fn add_cone(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_cone(r, h)
}
/// Adds a cylinder to the scene. The cylinder is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the cylinder height
/// * `r` - the cylinder base radius
pub fn add_cylinder(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_cylinder(r, h)
}
/// Adds a capsule to the scene. The capsule is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the capsule height
/// * `r` - the capsule caps radius
pub fn add_capsule(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_capsule(r, h)
}
/// Adds a double-sided quad to the scene. The quad is initially centered at (0, 0, 0). The
/// quad itself is composed of a user-defined number of triangles regularly spaced on a grid.
/// This is the main way to draw height maps.
///
/// # Arguments
/// * `w` - the quad width.
/// * `h` - the quad height.
/// * `wsubdivs` - number of horizontal subdivisions. This correspond to the number of squares
/// which will be placed horizontally on each line. Must not be `0`.
/// * `hsubdivs` - number of vertical subdivisions. This correspond to the number of squares
/// which will be placed vertically on each line. Must not be `0`.
/// update.
pub fn add_quad(&mut self, w: f32, h: f32, usubdivs: usize, vsubdivs: usize) -> SceneNode {
self.scene.add_quad(w, h, usubdivs, vsubdivs)
}
/// Adds a double-sided quad with the specified vertices.
pub fn add_quad_with_vertices(&mut self,
vertices: &[Pnt3<f32>],
nhpoints: usize,
nvpoints: usize)
-> SceneNode {
self.scene.add_quad_with_vertices(vertices, nhpoints, nvpoints)
}
#[doc(hidden)]
pub fn add_texture(&mut self, path: &Path, name: &str) -> Rc<Texture> {
TextureManager::get_global_manager(|tm| tm.add(path, name))
}
/// Returns whether this window is closed or not.
pub fn is_closed(&self) -> bool {
false // FIXME
}
/// Sets the light mode. Only one light is supported.
pub fn set_light(&mut self, pos: Light) {
self.light_mode = pos;
}
/// Opens a window, hide it then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
pub fn new_hidden(title: &str) -> Window {
Window::do_new(title, true, DEFAULT_WIDTH, DEFAULT_HEIGHT)
}
/// Opens a window then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
pub fn new(title: &str) -> Window {
Window::do_new(title, false, DEFAULT_WIDTH, DEFAULT_HEIGHT)
}
/// Opens a window with a custom size then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title.
/// * `width` - the window width.
/// * `height` - the window height.
pub fn new_with_size(title: &str, width: u32, height: u32) -> Window {
Window::do_new(title, false, width, height)
}
// FIXME: make this pub?
fn do_new(title: &str, hide: bool, width: u32, height: u32) -> Window {
// FIXME: glfw::set_error_callback(~ErrorCallback);
let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
let (mut window, events) = glfw.create_window(width, height, title, WindowMode::Windowed).expect("Unable to open a glfw window.");
window.make_current();
verify!(gl::load_with(|name| window.get_proc_address(name) as *const _));
init_gl();
let mut usr_window = Window {
max_ms_per_frame: None,
glfw: glfw,
window: window,
events: Rc::new(events),
unhandled_events: Rc::new(RefCell::new(Vec::new())),
scene: SceneNode::new_empty(),
light_mode: Light::Absolute(Pnt3::new(0.0, 10.0, 0.0)),
background: Vec3::new(0.0, 0.0, 0.0),
line_renderer: LineRenderer::new(),
point_renderer: PointRenderer::new(),
text_renderer: TextRenderer::new(),
post_process_render_target: FramebufferManager::new_render_target(width as usize, height as usize),
framebuffer_manager: FramebufferManager::new(),
curr_time: time::precise_time_ns(),
camera: Rc::new(RefCell::new(ArcBall::new(Pnt3::new(0.0f32, 0.0, -1.0), na::orig())))
};
// setup callbacks
usr_window.window.set_framebuffer_size_polling(true);
usr_window.window.set_key_polling(true);
usr_window.window.set_mouse_button_polling(true);
usr_window.window.set_cursor_pos_polling(true);
usr_window.window.set_scroll_polling(true);
if hide {
usr_window.window.hide()
}
// usr_window.framebuffer_size_callback(DEFAULT_WIDTH, DEFAULT_HEIGHT);
let light = usr_window.light_mode.clone();
usr_window.set_light(light);
usr_window
}
/// Reference to the scene associated with this window.
#[inline]
pub fn scene<'a>(&'a self) -> &'a SceneNode {
&self.scene
}
/// Mutable reference to the scene associated with this window.
#[inline]
pub fn scene_mut<'a>(&'a mut self) -> &'a mut SceneNode {
&mut self.scene
}
// FIXME: give more options for the snap size and offset.
/// Read the pixels currently displayed to the screen.
///
/// # Arguments:
/// * `out` - the output buffer. It is automatically resized.
pub fn snap(&self, out: &mut Vec<u8>) {
let (width, height) = self.window.get_size();
self.snap_rect(out, 0, 0, width as usize, height as usize)
}
/// Read a section of pixels from the screen
///
/// # Arguments:
/// * `out` - the output buffer. It is automatically resized
/// * `x, y, width, height` - the rectangle to capture
pub fn snap_rect(&self, out: &mut Vec<u8>, x: usize, y: usize, width: usize, height: usize) {
let size = (width * height * 3) as usize;
if out.len() < size {
let diff = size - out.len();
out.extend(repeat(0).take(diff));
}
else {
out.truncate(size)
}
// FIXME: this is _not_ the fastest way of doing this.
unsafe {
gl::PixelStorei(gl::PACK_ALIGNMENT, 1);
gl::ReadPixels(x as i32, y as i32,
width as i32, height as i32,
gl::RGB,
gl::UNSIGNED_BYTE,
mem::transmute(&mut out[0]));
}
}
/// Get the current screen as an image
pub fn snap_image(&self) -> ImageBuffer<Rgb<u8>, Vec<u8>> {
let (width, height) = self.window.get_size();
let mut buf = Vec::new();
self.snap(&mut buf);
let img_opt = ImageBuffer::from_vec(width as u32, height as u32, buf);
let img = img_opt.expect("Buffer created from window was not big enough for image.");
imageops::flip_vertical(&img)
}
/// Gets the events manager that gives access to an event iterator.
pub fn events(&self) -> EventManager {
EventManager::new(self.events.clone(), self.unhandled_events.clone())
}
/// Poll events and pass them to a user-defined function. If the function returns `true`, the
/// default engine event handler (camera, framebuffer size, etc.) is executed, if it returns
/// `false`, the default engine event handler is not executed. Return `false` if you want to
/// override the default engine behaviour.
#[inline]
fn handle_events(&mut self, camera: &mut Option<&mut Camera>) {
let unhandled_events = self.unhandled_events.clone(); // FIXME: this is very ugly.
let events = self.events.clone(); // FIXME: this is very ugly
for event in unhandled_events.borrow().iter() {
self.handle_event(camera, event)
}
for event in glfw::flush_messages(&*events) {
self.handle_event(camera, &event.1)
}
unhandled_events.borrow_mut().clear();
self.glfw.poll_events();
}
fn handle_event(&mut self, camera: &mut Option<&mut Camera>, event: &WindowEvent) {
match *event {
WindowEvent::Key(Key::Escape, _, Action::Release, _) => {
self.close();
},
WindowEvent::FramebufferSize(w, h) => {
self.update_viewport(w as f32, h as f32);
},
_ => { }
}
match *camera {
Some(ref mut cam) => cam.handle_event(&self.window, event),
None => self.camera.borrow_mut().handle_event(&self.window, event)
}
}
/// Renders the scene using the default camera.
///
/// Returns `false` if the window should be closed.
pub fn render(&mut self) -> bool {
self.render_with(None, None)
}
/// Render using a specific post processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with_effect(&mut self, effect: &mut PostProcessingEffect) -> bool {
self.render_with(None, Some(effect))
}
/// Render using a specific camera.
///
/// Returns `false` if the window should be closed.
pub fn render_with_camera(&mut self, camera: &mut Camera) -> bool {
self.render_with(Some(camera), None)
}
/// Render using a specific camera and post processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with_camera_and_effect(&mut self, camera: &mut Camera, effect: &mut PostProcessingEffect) -> bool {
self.render_with(Some(camera), Some(effect))
}
/// Draws the scene with the given camera and post-processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with(&mut self,
camera: Option<&mut Camera>,
post_processing: Option<&mut PostProcessingEffect>)
-> bool {
let mut camera = camera;
self.handle_events(&mut camera);
match camera {
Some(cam) => self.do_render_with(cam, post_processing),
None => {
let self_cam = self.camera.clone(); // FIXME: this is ugly.
let mut bself_cam = self_cam.borrow_mut();
self.do_render_with(&mut *bself_cam, post_processing)
}
}
}
fn do_render_with(&mut self,
camera: &mut Camera,
post_processing: Option<&mut PostProcessingEffect>)
-> bool {
// XXX: too bad we have to do this at each frame…
let w = self.width();
let h = self.height();
camera.handle_event(&self.window, &WindowEvent::FramebufferSize(w as i32, h as i32));
camera.update(&self.window);
match self.light_mode {
Light::StickToCamera => self.set_light(Light::StickToCamera),
_ => { }
}
let mut post_processing = post_processing;
if post_processing.is_some() {
// if we need post-processing, render to our own frame buffer
self.framebuffer_manager.select(&self.post_process_render_target);
}
else {
self.framebuffer_manager.select(&FramebufferManager::screen());
}
for pass in 0usize .. camera.num_passes() {
camera.start_pass(pass, &self.window);
self.render_scene(camera, pass);
}
camera.render_complete(&self.window);
let (znear, zfar) = camera.clip_planes();
// FIXME: remove this completely?
// swatch off the wireframe mode for post processing and text rendering.
// if self.wireframe_mode {
// verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL));
// }
match post_processing {
Some(ref mut p) => {
// switch back to the screen framebuffer …
self.framebuffer_manager.select(&FramebufferManager::screen());
// … and execute the post-process
// FIXME: use the real time value instead of 0.016!
p.update(0.016, w, h, znear, zfar);
p.draw(&self.post_process_render_target);
},
None => { }
}
self.text_renderer.render(w, h);
// We are done: swap buffers
self.window.swap_buffers();
// Limit the fps if needed.
match self.max_ms_per_frame {
None => { },
Some(ms) => {
let elapsed = (time::precise_time_ns() - self.curr_time) / 1000000;
if elapsed < ms {
thread::sleep(Duration::from_millis(ms - elapsed));
}
}
}
self.curr_time = time::precise_time_ns();
// self.transparent_objects.clear();
// self.opaque_objects.clear();
!self.should_close()
}
fn render_scene(&mut self, camera: &mut Camera, pass: usize) {
// Activate the default texture
verify!(gl::ActiveTexture(gl::TEXTURE0));
// Clear the screen to black
verify!(gl::ClearColor(self.background.x, self.background.y, self.background.z, 1.0));
verify!(gl::Clear(gl::COLOR_BUFFER_BIT));
verify!(gl::Clear(gl::DEPTH_BUFFER_BIT));
if self.line_renderer.needs_rendering() {
self.line_renderer.render(pass, camera);
}
if self.point_renderer.needs_rendering() {
self.point_renderer.render(pass, camera);
}
self.scene.data_mut().render(pass, camera, &self.light_mode);
}
fn update_viewport(&mut self, w: f32, h: f32) {
// Update the viewport
verify!(gl::Scissor(0, 0, w as i32, h as i32));
FramebufferManager::screen().resize(w, h);
self.post_process_render_target.resize(w, h);
}
}
fn init_gl() {
/*
* Misc configurations
*/ | verify!(gl::Enable(gl::SCISSOR_TEST));
verify!(gl::DepthFunc(gl::LEQUAL));
verify!(gl::FrontFace(gl::CCW));
verify!(gl::Enable(gl::CULL_FACE));
verify!(gl::CullFace(gl::BACK));
} | verify!(gl::FrontFace(gl::CCW));
verify!(gl::Enable(gl::DEPTH_TEST)); | random_line_split |
window.rs | //! The kiss3d window.
/*
* FIXME: this file is too big. Some heavy refactoring need to be done here.
*/
use std::mem;
use std::thread;
use std::time::Duration;
use glfw;
use glfw::{Context, Key, Action, WindowMode, WindowEvent};
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::mpsc::Receiver;
use std::path::Path;
use std::iter::repeat;
use time;
use gl;
use gl::types::*;
use image::{ImageBuffer,Rgb};
use image::imageops;
use na::{Pnt2, Vec2, Vec3, Pnt3};
use na;
use ncollide_procedural::TriMesh3;
use camera::Camera;
use scene::SceneNode;
use line_renderer::LineRenderer;
use point_renderer::PointRenderer;
use post_processing::PostProcessingEffect;
use resource::{FramebufferManager, RenderTarget, Texture, TextureManager, Mesh, Material};
use light::Light;
use text::{TextRenderer, Font};
use window::EventManager;
use camera::ArcBall;
static DEFAULT_WIDTH: u32 = 800u32;
static DEFAULT_HEIGHT: u32 = 600u32;
/// Structure representing a window and a 3D scene.
///
/// This is the main interface with the 3d engine.
pub struct Window {
events: Rc<Receiver<(f64, WindowEvent)>>,
unhandled_events: Rc<RefCell<Vec<WindowEvent>>>,
glfw: glfw::Glfw,
window: glfw::Window,
max_ms_per_frame: Option<u64>,
scene: SceneNode,
light_mode: Light, // FIXME: move that to the scene graph
background: Vec3<GLfloat>,
line_renderer: LineRenderer,
point_renderer: PointRenderer,
text_renderer: TextRenderer,
framebuffer_manager: FramebufferManager,
post_process_render_target: RenderTarget,
curr_time: u64,
camera: Rc<RefCell<ArcBall>>
}
impl Window {
/// Indicates whether this window should be closed.
#[inline]
pub fn should_close(&self) -> bool {
self.window.should_close()
}
/// Access the glfw context.
#[inline]
pub fn context<'r>(&'r self) -> &'r glfw::Glfw {
&self.glfw
}
/// Access the glfw window.
#[inline]
pub fn glfw_window(&self) -> &glfw::Window {
&self.window
}
/// Mutably access the glfw window.
#[inline]
pub fn glfw_window_mut(&mut self) -> &mut glfw::Window {
&mut self.window
}
/// The window width.
#[inline]
pub fn width(&self) -> f32 {
let (w, _) = self.window.get_size();
w as f32
}
/// The window height.
#[inline]
pub fn height(&self) -> f32 {
let (_, h) = self.window.get_size();
h as f32
}
/// The size of the window.
#[inline]
pub fn size(&self) -> Vec2<f32> {
let (w, h) = self.window.get_size();
Vec2::new(w as f32, h as f32)
}
/// Sets the maximum number of frames per second. Cannot be 0. `None` means there is no limit.
#[inline]
pub fn set_framerate_limit(&mut self, fps: Option<u64>) {
self.max_ms_per_frame = fps.map(|f| { assert!(f != 0); 1000 / f })
}
/// Set window title
pub fn set_title(&mut self, title: &str) {
self.window.set_title(title)
}
/// Closes the window.
#[inline]
pub fn close(&mut self) {
self.window.set_should_close(true)
}
/// Hides the window, without closing it. Use `show` to make it visible again.
#[inline]
pub fn hide(&mut self) {
self.window.hide()
}
/// Makes the window visible. Use `hide` to hide it.
#[inline]
pub fn show(&mut self) {
self.window.show()
}
/// Sets the background color.
#[inline]
pub fn set_background_color(&mut self, r: f32, g: GLfloat, b: f32) {
self.background.x = r;
self.background.y = g;
self.background.z = b;
}
// XXX: remove this (moved to the render_frame).
/// Adds a line to be drawn during the next frame.
#[inline]
pub fn draw_line(&mut self, a: &Pnt3<f32>, b: &Pnt3<f32>, color: &Pnt3<f32>) {
self.line_renderer.draw_line(a.clone(), b.clone(), color.clone());
}
// XXX: remove this (moved to the render_frame).
/// Adds a point to be drawn during the next frame.
#[inline]
pub fn draw_point(&mut self, pt: &Pnt3<f32>, color: &Pnt3<f32>) {
self.point_renderer.draw_point(pt.clone(), color.clone());
}
// XXX: remove this (moved to the render_frame).
/// Adds a string to be drawn during the next frame.
#[inline]
pub fn draw_text(&mut self, text: &str, pos: &Pnt2<f32>, font: &Rc<Font>, color: &Pnt3<f32>) {
self.text_renderer.draw_text(text, pos, font, color);
}
/// Removes an object from the scene.
pub fn remove(&mut self, sn: &mut SceneNode) {
sn.unlink()
}
/// Adds a group to the scene.
///
/// A group is a node not containing any object.
pub fn add_group(&mut self) -> SceneNode {
self.scene.add_group()
}
/// Adds an obj model to the scene.
///
/// # Arguments
/// * `path` - relative path to the obj file.
/// * `scale` - scale to apply to the model.
pub fn add_obj(&mut self, path: &Path, mtl_dir: &Path, scale: Vec3<f32>) -> SceneNode {
self.scene.add_obj(path, mtl_dir, scale)
}
/// Adds an unnamed mesh to the scene.
pub fn add_mesh(&mut self, mesh: Rc<RefCell<Mesh>>, scale: Vec3<f32>) -> SceneNode {
self.scene.add_mesh(mesh, scale)
}
/// Creates and adds a new object using the geometry generated by a given procedural generator.
/// Creates and adds a new object using a mesh descriptor.
pub fn add_trimesh(&mut self, descr: TriMesh3<f32>, scale: Vec3<f32>) -> SceneNode |
/// Creates and adds a new object using the geometry registered as `geometry_name`.
pub fn add_geom_with_name(&mut self, geometry_name: &str, scale: Vec3<f32>) -> Option<SceneNode> {
self.scene.add_geom_with_name(geometry_name, scale)
}
/// Adds a cube to the scene. The cube is initially axis-aligned and centered at (0, 0, 0).
///
/// # Arguments
/// * `wx` - the cube extent along the z axis
/// * `wy` - the cube extent along the y axis
/// * `wz` - the cube extent along the z axis
pub fn add_cube(&mut self, wx: GLfloat, wy: GLfloat, wz: GLfloat) -> SceneNode {
self.scene.add_cube(wx, wy, wz)
}
/// Adds a sphere to the scene. The sphere is initially centered at (0, 0, 0).
///
/// # Arguments
/// * `r` - the sphere radius
pub fn add_sphere(&mut self, r: GLfloat) -> SceneNode {
self.scene.add_sphere(r)
}
/// Adds a cone to the scene. The cone is initially centered at (0, 0, 0) and points toward the
/// positive `y` axis.
///
/// # Arguments
/// * `h` - the cone height
/// * `r` - the cone base radius
pub fn add_cone(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_cone(r, h)
}
/// Adds a cylinder to the scene. The cylinder is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the cylinder height
/// * `r` - the cylinder base radius
pub fn add_cylinder(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_cylinder(r, h)
}
/// Adds a capsule to the scene. The capsule is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the capsule height
/// * `r` - the capsule caps radius
pub fn add_capsule(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_capsule(r, h)
}
/// Adds a double-sided quad to the scene. The quad is initially centered at (0, 0, 0). The
/// quad itself is composed of a user-defined number of triangles regularly spaced on a grid.
/// This is the main way to draw height maps.
///
/// # Arguments
/// * `w` - the quad width.
/// * `h` - the quad height.
/// * `wsubdivs` - number of horizontal subdivisions. This correspond to the number of squares
/// which will be placed horizontally on each line. Must not be `0`.
/// * `hsubdivs` - number of vertical subdivisions. This correspond to the number of squares
/// which will be placed vertically on each line. Must not be `0`.
/// update.
pub fn add_quad(&mut self, w: f32, h: f32, usubdivs: usize, vsubdivs: usize) -> SceneNode {
self.scene.add_quad(w, h, usubdivs, vsubdivs)
}
/// Adds a double-sided quad with the specified vertices.
pub fn add_quad_with_vertices(&mut self,
vertices: &[Pnt3<f32>],
nhpoints: usize,
nvpoints: usize)
-> SceneNode {
self.scene.add_quad_with_vertices(vertices, nhpoints, nvpoints)
}
#[doc(hidden)]
pub fn add_texture(&mut self, path: &Path, name: &str) -> Rc<Texture> {
TextureManager::get_global_manager(|tm| tm.add(path, name))
}
/// Returns whether this window is closed or not.
pub fn is_closed(&self) -> bool {
false // FIXME
}
/// Sets the light mode. Only one light is supported.
pub fn set_light(&mut self, pos: Light) {
self.light_mode = pos;
}
/// Opens a window, hide it then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
pub fn new_hidden(title: &str) -> Window {
Window::do_new(title, true, DEFAULT_WIDTH, DEFAULT_HEIGHT)
}
/// Opens a window then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
pub fn new(title: &str) -> Window {
Window::do_new(title, false, DEFAULT_WIDTH, DEFAULT_HEIGHT)
}
/// Opens a window with a custom size then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title.
/// * `width` - the window width.
/// * `height` - the window height.
pub fn new_with_size(title: &str, width: u32, height: u32) -> Window {
Window::do_new(title, false, width, height)
}
// FIXME: make this pub?
fn do_new(title: &str, hide: bool, width: u32, height: u32) -> Window {
// FIXME: glfw::set_error_callback(~ErrorCallback);
let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
let (mut window, events) = glfw.create_window(width, height, title, WindowMode::Windowed).expect("Unable to open a glfw window.");
window.make_current();
verify!(gl::load_with(|name| window.get_proc_address(name) as *const _));
init_gl();
let mut usr_window = Window {
max_ms_per_frame: None,
glfw: glfw,
window: window,
events: Rc::new(events),
unhandled_events: Rc::new(RefCell::new(Vec::new())),
scene: SceneNode::new_empty(),
light_mode: Light::Absolute(Pnt3::new(0.0, 10.0, 0.0)),
background: Vec3::new(0.0, 0.0, 0.0),
line_renderer: LineRenderer::new(),
point_renderer: PointRenderer::new(),
text_renderer: TextRenderer::new(),
post_process_render_target: FramebufferManager::new_render_target(width as usize, height as usize),
framebuffer_manager: FramebufferManager::new(),
curr_time: time::precise_time_ns(),
camera: Rc::new(RefCell::new(ArcBall::new(Pnt3::new(0.0f32, 0.0, -1.0), na::orig())))
};
// setup callbacks
usr_window.window.set_framebuffer_size_polling(true);
usr_window.window.set_key_polling(true);
usr_window.window.set_mouse_button_polling(true);
usr_window.window.set_cursor_pos_polling(true);
usr_window.window.set_scroll_polling(true);
if hide {
usr_window.window.hide()
}
// usr_window.framebuffer_size_callback(DEFAULT_WIDTH, DEFAULT_HEIGHT);
let light = usr_window.light_mode.clone();
usr_window.set_light(light);
usr_window
}
/// Reference to the scene associated with this window.
#[inline]
pub fn scene<'a>(&'a self) -> &'a SceneNode {
&self.scene
}
/// Mutable reference to the scene associated with this window.
#[inline]
pub fn scene_mut<'a>(&'a mut self) -> &'a mut SceneNode {
&mut self.scene
}
// FIXME: give more options for the snap size and offset.
/// Read the pixels currently displayed to the screen.
///
/// # Arguments:
/// * `out` - the output buffer. It is automatically resized.
pub fn snap(&self, out: &mut Vec<u8>) {
let (width, height) = self.window.get_size();
self.snap_rect(out, 0, 0, width as usize, height as usize)
}
/// Read a section of pixels from the screen
///
/// # Arguments:
/// * `out` - the output buffer. It is automatically resized
/// * `x, y, width, height` - the rectangle to capture
pub fn snap_rect(&self, out: &mut Vec<u8>, x: usize, y: usize, width: usize, height: usize) {
let size = (width * height * 3) as usize;
if out.len() < size {
let diff = size - out.len();
out.extend(repeat(0).take(diff));
}
else {
out.truncate(size)
}
// FIXME: this is _not_ the fastest way of doing this.
unsafe {
gl::PixelStorei(gl::PACK_ALIGNMENT, 1);
gl::ReadPixels(x as i32, y as i32,
width as i32, height as i32,
gl::RGB,
gl::UNSIGNED_BYTE,
mem::transmute(&mut out[0]));
}
}
/// Get the current screen as an image
pub fn snap_image(&self) -> ImageBuffer<Rgb<u8>, Vec<u8>> {
let (width, height) = self.window.get_size();
let mut buf = Vec::new();
self.snap(&mut buf);
let img_opt = ImageBuffer::from_vec(width as u32, height as u32, buf);
let img = img_opt.expect("Buffer created from window was not big enough for image.");
imageops::flip_vertical(&img)
}
/// Gets the events manager that gives access to an event iterator.
pub fn events(&self) -> EventManager {
EventManager::new(self.events.clone(), self.unhandled_events.clone())
}
/// Poll events and pass them to a user-defined function. If the function returns `true`, the
/// default engine event handler (camera, framebuffer size, etc.) is executed, if it returns
/// `false`, the default engine event handler is not executed. Return `false` if you want to
/// override the default engine behaviour.
#[inline]
fn handle_events(&mut self, camera: &mut Option<&mut Camera>) {
let unhandled_events = self.unhandled_events.clone(); // FIXME: this is very ugly.
let events = self.events.clone(); // FIXME: this is very ugly
for event in unhandled_events.borrow().iter() {
self.handle_event(camera, event)
}
for event in glfw::flush_messages(&*events) {
self.handle_event(camera, &event.1)
}
unhandled_events.borrow_mut().clear();
self.glfw.poll_events();
}
fn handle_event(&mut self, camera: &mut Option<&mut Camera>, event: &WindowEvent) {
match *event {
WindowEvent::Key(Key::Escape, _, Action::Release, _) => {
self.close();
},
WindowEvent::FramebufferSize(w, h) => {
self.update_viewport(w as f32, h as f32);
},
_ => { }
}
match *camera {
Some(ref mut cam) => cam.handle_event(&self.window, event),
None => self.camera.borrow_mut().handle_event(&self.window, event)
}
}
/// Renders the scene using the default camera.
///
/// Returns `false` if the window should be closed.
pub fn render(&mut self) -> bool {
self.render_with(None, None)
}
/// Render using a specific post processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with_effect(&mut self, effect: &mut PostProcessingEffect) -> bool {
self.render_with(None, Some(effect))
}
/// Render using a specific camera.
///
/// Returns `false` if the window should be closed.
pub fn render_with_camera(&mut self, camera: &mut Camera) -> bool {
self.render_with(Some(camera), None)
}
/// Render using a specific camera and post processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with_camera_and_effect(&mut self, camera: &mut Camera, effect: &mut PostProcessingEffect) -> bool {
self.render_with(Some(camera), Some(effect))
}
/// Draws the scene with the given camera and post-processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with(&mut self,
camera: Option<&mut Camera>,
post_processing: Option<&mut PostProcessingEffect>)
-> bool {
let mut camera = camera;
self.handle_events(&mut camera);
match camera {
Some(cam) => self.do_render_with(cam, post_processing),
None => {
let self_cam = self.camera.clone(); // FIXME: this is ugly.
let mut bself_cam = self_cam.borrow_mut();
self.do_render_with(&mut *bself_cam, post_processing)
}
}
}
fn do_render_with(&mut self,
camera: &mut Camera,
post_processing: Option<&mut PostProcessingEffect>)
-> bool {
// XXX: too bad we have to do this at each frame…
let w = self.width();
let h = self.height();
camera.handle_event(&self.window, &WindowEvent::FramebufferSize(w as i32, h as i32));
camera.update(&self.window);
match self.light_mode {
Light::StickToCamera => self.set_light(Light::StickToCamera),
_ => { }
}
let mut post_processing = post_processing;
if post_processing.is_some() {
// if we need post-processing, render to our own frame buffer
self.framebuffer_manager.select(&self.post_process_render_target);
}
else {
self.framebuffer_manager.select(&FramebufferManager::screen());
}
for pass in 0usize .. camera.num_passes() {
camera.start_pass(pass, &self.window);
self.render_scene(camera, pass);
}
camera.render_complete(&self.window);
let (znear, zfar) = camera.clip_planes();
// FIXME: remove this completely?
// swatch off the wireframe mode for post processing and text rendering.
// if self.wireframe_mode {
// verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL));
// }
match post_processing {
Some(ref mut p) => {
// switch back to the screen framebuffer …
self.framebuffer_manager.select(&FramebufferManager::screen());
// … and execute the post-process
// FIXME: use the real time value instead of 0.016!
p.update(0.016, w, h, znear, zfar);
p.draw(&self.post_process_render_target);
},
None => { }
}
self.text_renderer.render(w, h);
// We are done: swap buffers
self.window.swap_buffers();
// Limit the fps if needed.
match self.max_ms_per_frame {
None => { },
Some(ms) => {
let elapsed = (time::precise_time_ns() - self.curr_time) / 1000000;
if elapsed < ms {
thread::sleep(Duration::from_millis(ms - elapsed));
}
}
}
self.curr_time = time::precise_time_ns();
// self.transparent_objects.clear();
// self.opaque_objects.clear();
!self.should_close()
}
fn render_scene(&mut self, camera: &mut Camera, pass: usize) {
// Activate the default texture
verify!(gl::ActiveTexture(gl::TEXTURE0));
// Clear the screen to black
verify!(gl::ClearColor(self.background.x, self.background.y, self.background.z, 1.0));
verify!(gl::Clear(gl::COLOR_BUFFER_BIT));
verify!(gl::Clear(gl::DEPTH_BUFFER_BIT));
if self.line_renderer.needs_rendering() {
self.line_renderer.render(pass, camera);
}
if self.point_renderer.needs_rendering() {
self.point_renderer.render(pass, camera);
}
self.scene.data_mut().render(pass, camera, &self.light_mode);
}
fn update_viewport(&mut self, w: f32, h: f32) {
// Update the viewport
verify!(gl::Scissor(0, 0, w as i32, h as i32));
FramebufferManager::screen().resize(w, h);
self.post_process_render_target.resize(w, h);
}
}
fn init_gl() {
/*
* Misc configurations
*/
verify!(gl::FrontFace(gl::CCW));
verify!(gl::Enable(gl::DEPTH_TEST));
verify!(gl::Enable(gl::SCISSOR_TEST));
verify!(gl::DepthFunc(gl::LEQUAL));
verify!(gl::FrontFace(gl::CCW));
verify!(gl::Enable(gl::CULL_FACE));
verify!(gl::CullFace(gl::BACK));
}
| {
self.scene.add_trimesh(descr, scale)
} | identifier_body |
window.rs | //! The kiss3d window.
/*
* FIXME: this file is too big. Some heavy refactoring need to be done here.
*/
use std::mem;
use std::thread;
use std::time::Duration;
use glfw;
use glfw::{Context, Key, Action, WindowMode, WindowEvent};
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::mpsc::Receiver;
use std::path::Path;
use std::iter::repeat;
use time;
use gl;
use gl::types::*;
use image::{ImageBuffer,Rgb};
use image::imageops;
use na::{Pnt2, Vec2, Vec3, Pnt3};
use na;
use ncollide_procedural::TriMesh3;
use camera::Camera;
use scene::SceneNode;
use line_renderer::LineRenderer;
use point_renderer::PointRenderer;
use post_processing::PostProcessingEffect;
use resource::{FramebufferManager, RenderTarget, Texture, TextureManager, Mesh, Material};
use light::Light;
use text::{TextRenderer, Font};
use window::EventManager;
use camera::ArcBall;
static DEFAULT_WIDTH: u32 = 800u32;
static DEFAULT_HEIGHT: u32 = 600u32;
/// Structure representing a window and a 3D scene.
///
/// This is the main interface with the 3d engine.
pub struct Window {
events: Rc<Receiver<(f64, WindowEvent)>>,
unhandled_events: Rc<RefCell<Vec<WindowEvent>>>,
glfw: glfw::Glfw,
window: glfw::Window,
max_ms_per_frame: Option<u64>,
scene: SceneNode,
light_mode: Light, // FIXME: move that to the scene graph
background: Vec3<GLfloat>,
line_renderer: LineRenderer,
point_renderer: PointRenderer,
text_renderer: TextRenderer,
framebuffer_manager: FramebufferManager,
post_process_render_target: RenderTarget,
curr_time: u64,
camera: Rc<RefCell<ArcBall>>
}
impl Window {
/// Indicates whether this window should be closed.
#[inline]
pub fn should_close(&self) -> bool {
self.window.should_close()
}
/// Access the glfw context.
#[inline]
pub fn context<'r>(&'r self) -> &'r glfw::Glfw {
&self.glfw
}
/// Access the glfw window.
#[inline]
pub fn glfw_window(&self) -> &glfw::Window {
&self.window
}
/// Mutably access the glfw window.
#[inline]
pub fn glfw_window_mut(&mut self) -> &mut glfw::Window {
&mut self.window
}
/// The window width.
#[inline]
pub fn width(&self) -> f32 {
let (w, _) = self.window.get_size();
w as f32
}
/// The window height.
#[inline]
pub fn height(&self) -> f32 {
let (_, h) = self.window.get_size();
h as f32
}
/// The size of the window.
#[inline]
pub fn size(&self) -> Vec2<f32> {
let (w, h) = self.window.get_size();
Vec2::new(w as f32, h as f32)
}
/// Sets the maximum number of frames per second. Cannot be 0. `None` means there is no limit.
#[inline]
pub fn set_framerate_limit(&mut self, fps: Option<u64>) {
self.max_ms_per_frame = fps.map(|f| { assert!(f != 0); 1000 / f })
}
/// Set window title
pub fn set_title(&mut self, title: &str) {
self.window.set_title(title)
}
/// Closes the window.
#[inline]
pub fn close(&mut self) {
self.window.set_should_close(true)
}
/// Hides the window, without closing it. Use `show` to make it visible again.
#[inline]
pub fn hide(&mut self) {
self.window.hide()
}
/// Makes the window visible. Use `hide` to hide it.
#[inline]
pub fn show(&mut self) {
self.window.show()
}
/// Sets the background color.
#[inline]
pub fn set_background_color(&mut self, r: f32, g: GLfloat, b: f32) {
self.background.x = r;
self.background.y = g;
self.background.z = b;
}
// XXX: remove this (moved to the render_frame).
/// Adds a line to be drawn during the next frame.
#[inline]
pub fn draw_line(&mut self, a: &Pnt3<f32>, b: &Pnt3<f32>, color: &Pnt3<f32>) {
self.line_renderer.draw_line(a.clone(), b.clone(), color.clone());
}
// XXX: remove this (moved to the render_frame).
/// Adds a point to be drawn during the next frame.
#[inline]
pub fn draw_point(&mut self, pt: &Pnt3<f32>, color: &Pnt3<f32>) {
self.point_renderer.draw_point(pt.clone(), color.clone());
}
// XXX: remove this (moved to the render_frame).
/// Adds a string to be drawn during the next frame.
#[inline]
pub fn draw_text(&mut self, text: &str, pos: &Pnt2<f32>, font: &Rc<Font>, color: &Pnt3<f32>) {
self.text_renderer.draw_text(text, pos, font, color);
}
/// Removes an object from the scene.
pub fn remove(&mut self, sn: &mut SceneNode) {
sn.unlink()
}
/// Adds a group to the scene.
///
/// A group is a node not containing any object.
pub fn add_group(&mut self) -> SceneNode {
self.scene.add_group()
}
/// Adds an obj model to the scene.
///
/// # Arguments
/// * `path` - relative path to the obj file.
/// * `scale` - scale to apply to the model.
pub fn add_obj(&mut self, path: &Path, mtl_dir: &Path, scale: Vec3<f32>) -> SceneNode {
self.scene.add_obj(path, mtl_dir, scale)
}
/// Adds an unnamed mesh to the scene.
pub fn add_mesh(&mut self, mesh: Rc<RefCell<Mesh>>, scale: Vec3<f32>) -> SceneNode {
self.scene.add_mesh(mesh, scale)
}
/// Creates and adds a new object using the geometry generated by a given procedural generator.
/// Creates and adds a new object using a mesh descriptor.
pub fn add_trimesh(&mut self, descr: TriMesh3<f32>, scale: Vec3<f32>) -> SceneNode {
self.scene.add_trimesh(descr, scale)
}
/// Creates and adds a new object using the geometry registered as `geometry_name`.
pub fn add_geom_with_name(&mut self, geometry_name: &str, scale: Vec3<f32>) -> Option<SceneNode> {
self.scene.add_geom_with_name(geometry_name, scale)
}
/// Adds a cube to the scene. The cube is initially axis-aligned and centered at (0, 0, 0).
///
/// # Arguments
/// * `wx` - the cube extent along the z axis
/// * `wy` - the cube extent along the y axis
/// * `wz` - the cube extent along the z axis
pub fn add_cube(&mut self, wx: GLfloat, wy: GLfloat, wz: GLfloat) -> SceneNode {
self.scene.add_cube(wx, wy, wz)
}
/// Adds a sphere to the scene. The sphere is initially centered at (0, 0, 0).
///
/// # Arguments
/// * `r` - the sphere radius
pub fn | (&mut self, r: GLfloat) -> SceneNode {
self.scene.add_sphere(r)
}
/// Adds a cone to the scene. The cone is initially centered at (0, 0, 0) and points toward the
/// positive `y` axis.
///
/// # Arguments
/// * `h` - the cone height
/// * `r` - the cone base radius
pub fn add_cone(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_cone(r, h)
}
/// Adds a cylinder to the scene. The cylinder is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the cylinder height
/// * `r` - the cylinder base radius
pub fn add_cylinder(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_cylinder(r, h)
}
/// Adds a capsule to the scene. The capsule is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the capsule height
/// * `r` - the capsule caps radius
pub fn add_capsule(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_capsule(r, h)
}
/// Adds a double-sided quad to the scene. The quad is initially centered at (0, 0, 0). The
/// quad itself is composed of a user-defined number of triangles regularly spaced on a grid.
/// This is the main way to draw height maps.
///
/// # Arguments
/// * `w` - the quad width.
/// * `h` - the quad height.
/// * `wsubdivs` - number of horizontal subdivisions. This correspond to the number of squares
/// which will be placed horizontally on each line. Must not be `0`.
/// * `hsubdivs` - number of vertical subdivisions. This correspond to the number of squares
/// which will be placed vertically on each line. Must not be `0`.
/// update.
pub fn add_quad(&mut self, w: f32, h: f32, usubdivs: usize, vsubdivs: usize) -> SceneNode {
self.scene.add_quad(w, h, usubdivs, vsubdivs)
}
/// Adds a double-sided quad with the specified vertices.
pub fn add_quad_with_vertices(&mut self,
vertices: &[Pnt3<f32>],
nhpoints: usize,
nvpoints: usize)
-> SceneNode {
self.scene.add_quad_with_vertices(vertices, nhpoints, nvpoints)
}
#[doc(hidden)]
pub fn add_texture(&mut self, path: &Path, name: &str) -> Rc<Texture> {
TextureManager::get_global_manager(|tm| tm.add(path, name))
}
/// Returns whether this window is closed or not.
pub fn is_closed(&self) -> bool {
false // FIXME
}
/// Sets the light mode. Only one light is supported.
pub fn set_light(&mut self, pos: Light) {
self.light_mode = pos;
}
/// Opens a window, hide it then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
pub fn new_hidden(title: &str) -> Window {
Window::do_new(title, true, DEFAULT_WIDTH, DEFAULT_HEIGHT)
}
/// Opens a window then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
pub fn new(title: &str) -> Window {
Window::do_new(title, false, DEFAULT_WIDTH, DEFAULT_HEIGHT)
}
/// Opens a window with a custom size then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title.
/// * `width` - the window width.
/// * `height` - the window height.
pub fn new_with_size(title: &str, width: u32, height: u32) -> Window {
Window::do_new(title, false, width, height)
}
// FIXME: make this pub?
fn do_new(title: &str, hide: bool, width: u32, height: u32) -> Window {
// FIXME: glfw::set_error_callback(~ErrorCallback);
let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
let (mut window, events) = glfw.create_window(width, height, title, WindowMode::Windowed).expect("Unable to open a glfw window.");
window.make_current();
verify!(gl::load_with(|name| window.get_proc_address(name) as *const _));
init_gl();
let mut usr_window = Window {
max_ms_per_frame: None,
glfw: glfw,
window: window,
events: Rc::new(events),
unhandled_events: Rc::new(RefCell::new(Vec::new())),
scene: SceneNode::new_empty(),
light_mode: Light::Absolute(Pnt3::new(0.0, 10.0, 0.0)),
background: Vec3::new(0.0, 0.0, 0.0),
line_renderer: LineRenderer::new(),
point_renderer: PointRenderer::new(),
text_renderer: TextRenderer::new(),
post_process_render_target: FramebufferManager::new_render_target(width as usize, height as usize),
framebuffer_manager: FramebufferManager::new(),
curr_time: time::precise_time_ns(),
camera: Rc::new(RefCell::new(ArcBall::new(Pnt3::new(0.0f32, 0.0, -1.0), na::orig())))
};
// setup callbacks
usr_window.window.set_framebuffer_size_polling(true);
usr_window.window.set_key_polling(true);
usr_window.window.set_mouse_button_polling(true);
usr_window.window.set_cursor_pos_polling(true);
usr_window.window.set_scroll_polling(true);
if hide {
usr_window.window.hide()
}
// usr_window.framebuffer_size_callback(DEFAULT_WIDTH, DEFAULT_HEIGHT);
let light = usr_window.light_mode.clone();
usr_window.set_light(light);
usr_window
}
/// Reference to the scene associated with this window.
#[inline]
pub fn scene<'a>(&'a self) -> &'a SceneNode {
&self.scene
}
/// Mutable reference to the scene associated with this window.
#[inline]
pub fn scene_mut<'a>(&'a mut self) -> &'a mut SceneNode {
&mut self.scene
}
// FIXME: give more options for the snap size and offset.
/// Read the pixels currently displayed to the screen.
///
/// # Arguments:
/// * `out` - the output buffer. It is automatically resized.
pub fn snap(&self, out: &mut Vec<u8>) {
let (width, height) = self.window.get_size();
self.snap_rect(out, 0, 0, width as usize, height as usize)
}
/// Read a section of pixels from the screen
///
/// # Arguments:
/// * `out` - the output buffer. It is automatically resized
/// * `x, y, width, height` - the rectangle to capture
pub fn snap_rect(&self, out: &mut Vec<u8>, x: usize, y: usize, width: usize, height: usize) {
let size = (width * height * 3) as usize;
if out.len() < size {
let diff = size - out.len();
out.extend(repeat(0).take(diff));
}
else {
out.truncate(size)
}
// FIXME: this is _not_ the fastest way of doing this.
unsafe {
gl::PixelStorei(gl::PACK_ALIGNMENT, 1);
gl::ReadPixels(x as i32, y as i32,
width as i32, height as i32,
gl::RGB,
gl::UNSIGNED_BYTE,
mem::transmute(&mut out[0]));
}
}
/// Get the current screen as an image
pub fn snap_image(&self) -> ImageBuffer<Rgb<u8>, Vec<u8>> {
let (width, height) = self.window.get_size();
let mut buf = Vec::new();
self.snap(&mut buf);
let img_opt = ImageBuffer::from_vec(width as u32, height as u32, buf);
let img = img_opt.expect("Buffer created from window was not big enough for image.");
imageops::flip_vertical(&img)
}
/// Gets the events manager that gives access to an event iterator.
pub fn events(&self) -> EventManager {
EventManager::new(self.events.clone(), self.unhandled_events.clone())
}
/// Poll events and pass them to a user-defined function. If the function returns `true`, the
/// default engine event handler (camera, framebuffer size, etc.) is executed, if it returns
/// `false`, the default engine event handler is not executed. Return `false` if you want to
/// override the default engine behaviour.
#[inline]
fn handle_events(&mut self, camera: &mut Option<&mut Camera>) {
let unhandled_events = self.unhandled_events.clone(); // FIXME: this is very ugly.
let events = self.events.clone(); // FIXME: this is very ugly
for event in unhandled_events.borrow().iter() {
self.handle_event(camera, event)
}
for event in glfw::flush_messages(&*events) {
self.handle_event(camera, &event.1)
}
unhandled_events.borrow_mut().clear();
self.glfw.poll_events();
}
fn handle_event(&mut self, camera: &mut Option<&mut Camera>, event: &WindowEvent) {
match *event {
WindowEvent::Key(Key::Escape, _, Action::Release, _) => {
self.close();
},
WindowEvent::FramebufferSize(w, h) => {
self.update_viewport(w as f32, h as f32);
},
_ => { }
}
match *camera {
Some(ref mut cam) => cam.handle_event(&self.window, event),
None => self.camera.borrow_mut().handle_event(&self.window, event)
}
}
/// Renders the scene using the default camera.
///
/// Returns `false` if the window should be closed.
pub fn render(&mut self) -> bool {
self.render_with(None, None)
}
/// Render using a specific post processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with_effect(&mut self, effect: &mut PostProcessingEffect) -> bool {
self.render_with(None, Some(effect))
}
/// Render using a specific camera.
///
/// Returns `false` if the window should be closed.
pub fn render_with_camera(&mut self, camera: &mut Camera) -> bool {
self.render_with(Some(camera), None)
}
/// Render using a specific camera and post processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with_camera_and_effect(&mut self, camera: &mut Camera, effect: &mut PostProcessingEffect) -> bool {
self.render_with(Some(camera), Some(effect))
}
/// Draws the scene with the given camera and post-processing effect.
///
/// Returns `false` if the window should be closed.
pub fn render_with(&mut self,
camera: Option<&mut Camera>,
post_processing: Option<&mut PostProcessingEffect>)
-> bool {
let mut camera = camera;
self.handle_events(&mut camera);
match camera {
Some(cam) => self.do_render_with(cam, post_processing),
None => {
let self_cam = self.camera.clone(); // FIXME: this is ugly.
let mut bself_cam = self_cam.borrow_mut();
self.do_render_with(&mut *bself_cam, post_processing)
}
}
}
fn do_render_with(&mut self,
camera: &mut Camera,
post_processing: Option<&mut PostProcessingEffect>)
-> bool {
// XXX: too bad we have to do this at each frame…
let w = self.width();
let h = self.height();
camera.handle_event(&self.window, &WindowEvent::FramebufferSize(w as i32, h as i32));
camera.update(&self.window);
match self.light_mode {
Light::StickToCamera => self.set_light(Light::StickToCamera),
_ => { }
}
let mut post_processing = post_processing;
if post_processing.is_some() {
// if we need post-processing, render to our own frame buffer
self.framebuffer_manager.select(&self.post_process_render_target);
}
else {
self.framebuffer_manager.select(&FramebufferManager::screen());
}
for pass in 0usize .. camera.num_passes() {
camera.start_pass(pass, &self.window);
self.render_scene(camera, pass);
}
camera.render_complete(&self.window);
let (znear, zfar) = camera.clip_planes();
// FIXME: remove this completely?
// swatch off the wireframe mode for post processing and text rendering.
// if self.wireframe_mode {
// verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL));
// }
match post_processing {
Some(ref mut p) => {
// switch back to the screen framebuffer …
self.framebuffer_manager.select(&FramebufferManager::screen());
// … and execute the post-process
// FIXME: use the real time value instead of 0.016!
p.update(0.016, w, h, znear, zfar);
p.draw(&self.post_process_render_target);
},
None => { }
}
self.text_renderer.render(w, h);
// We are done: swap buffers
self.window.swap_buffers();
// Limit the fps if needed.
match self.max_ms_per_frame {
None => { },
Some(ms) => {
let elapsed = (time::precise_time_ns() - self.curr_time) / 1000000;
if elapsed < ms {
thread::sleep(Duration::from_millis(ms - elapsed));
}
}
}
self.curr_time = time::precise_time_ns();
// self.transparent_objects.clear();
// self.opaque_objects.clear();
!self.should_close()
}
fn render_scene(&mut self, camera: &mut Camera, pass: usize) {
// Activate the default texture
verify!(gl::ActiveTexture(gl::TEXTURE0));
// Clear the screen to black
verify!(gl::ClearColor(self.background.x, self.background.y, self.background.z, 1.0));
verify!(gl::Clear(gl::COLOR_BUFFER_BIT));
verify!(gl::Clear(gl::DEPTH_BUFFER_BIT));
if self.line_renderer.needs_rendering() {
self.line_renderer.render(pass, camera);
}
if self.point_renderer.needs_rendering() {
self.point_renderer.render(pass, camera);
}
self.scene.data_mut().render(pass, camera, &self.light_mode);
}
fn update_viewport(&mut self, w: f32, h: f32) {
// Update the viewport
verify!(gl::Scissor(0, 0, w as i32, h as i32));
FramebufferManager::screen().resize(w, h);
self.post_process_render_target.resize(w, h);
}
}
fn init_gl() {
/*
* Misc configurations
*/
verify!(gl::FrontFace(gl::CCW));
verify!(gl::Enable(gl::DEPTH_TEST));
verify!(gl::Enable(gl::SCISSOR_TEST));
verify!(gl::DepthFunc(gl::LEQUAL));
verify!(gl::FrontFace(gl::CCW));
verify!(gl::Enable(gl::CULL_FACE));
verify!(gl::CullFace(gl::BACK));
}
| add_sphere | identifier_name |
sb-1.3.0.js | /**
*
* Spacebrew Library for Javascript
* --------------------------------
*
* This library was designed to work on front-end (browser) envrionments, and back-end (server)
* environments. Please refer to the readme file, the documentation and examples to learn how to
* use this library.
*
* Spacebrew is an open, dynamically re-routable software toolkit for choreographing interactive
* spaces. Or, in other words, a simple way to connect interactive things to one another. Learn
* more about Spacebrew here: http://docs.spacebrew.cc/
*
* To import into your web apps, we recommend using the minimized version of this library.
*
* Latest Updates:
* - added blank "options" attribute to config message - for future use
* - caps number of messages sent to 60 per second
* - reconnect to spacebrew if connection lost
* - enable client apps to extend libs with admin functionality.
* - added close method to close Spacebrew connection.
*
* @author Brett Renfer and Julio Terra from LAB @ Rockwell Group
* @filename sb-1.3.0.js
* @version 1.3.0
* @date May 7, 2013
*
*/
/**
* Check if Bind method exists in current enviroment. If not, it creates an implementation of
* this useful method.
*/
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
/**
* @namespace for Spacebrew library
*/
var Spacebrew = Spacebrew || {};
/**
* create placeholder var for WebSocket object, if it does not already exist
*/
var WebSocket = WebSocket || {};
/**
* Check if Running in Browser or Server (Node) Environment *
*/
// check if window object already exists to determine if running browswer
var window = window || undefined;
// check if module object already exists to determine if this is a node application
var module = module || undefined;
// if app is running in a browser, then define the getQueryString method
if (window) {
if (!window['getQueryString']){
/**
* Get parameters from a query string
* @param {String} name Name of query string to parse (w/o '?' or '&')
* @return {String} value of parameter (or empty string if not found)
*/
window.getQueryString = function( name ) {
if (!window.location) return;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null ) return "";
else return results[1];
}
}
}
// if app is running in a node server environment then package Spacebrew library as a module.
// WebSocket module (ws) needs to be saved in a node_modules so that it can be imported.
if (!window && module) {
WebSocket = require("ws");
module.exports = {
Spacebrew: Spacebrew
}
}
/**
* Define the Spacebrew Library *
*/
/**
* Spacebrew client!
* @constructor
* @param {String} server (Optional) Base address of Spacebrew server. This server address is overwritten if server defined in query string; defaults to localhost.
* @param {String} name (Optional) Base name of app. Base name is overwritten if "name" is defined in query string; defaults to window.location.href.
* @param {String} description (Optional) Base description of app. Description name is overwritten if "description" is defined in query string;
* @param {Object} options (Optional) An object that holds the optional parameters described below
* port (Optional) Port number for the Spacebrew server
* admin (Optional) Flag that identifies when app should register for admin privileges with server
* debug (Optional) Debug flag that turns on info and debug messaging (limited use)
*/
Spacebrew.Client = function( server, name, description, options ){
var options = options || {};
// check if the server variable is an object that holds all config values
if (server != undefined) {
if (toString.call(server) !== '[object String]') {
options.port = server.port || undefined;
options.debug = server.debug || false;
options.reconnect = server.reconnect || false;
description = server.description || undefined;
name = server.name || undefined;
server = server.server || undefined;
}
}
this.debug = (window.getQueryString('debug') === "true" ? true : (options.debug || false));
this.reconnect = options.reconnect || true;
this.reconnect_timer = undefined;
this.send_interval = 16;
this.send_blocked = false;
this.msg = {};
/**
* Name of app
* @type {String}
*/
this._name = name || "javascript client #";
if (window) {
this._name = (window.getQueryString('name') !== "" ? unescape(window.getQueryString('name')) : this._name);
}
/**
* Description of your app
* @type {String}
*/
this._description = description || "spacebrew javascript client";
if (window) {
this._description = (window.getQueryString('description') !== "" ? unescape(window.getQueryString('description')) : this._description);
}
/**
* Spacebrew server to which the app will connect
* @type {String}
*/
this.server = server || "sandbox.spacebrew.cc";
if (window) {
this.server = (window.getQueryString('server') !== "" ? unescape(window.getQueryString('server')) : this.server);
}
/**
* Port number on which Spacebrew server is running
* @type {Integer}
*/
this.port = options.port || 9000;
if (window) {
port = window.getQueryString('port');
if (port !== "" && !isNaN(port)) {
this.port = port;
}
}
/**
* Reference to WebSocket
* @type {WebSocket}
*/
this.socket = null;
/**
* Configuration file for Spacebrew
* @type {Object}
*/
this.client_config = {
name: this._name,
description: this._description,
publish:{
messages:[]
},
subscribe:{
messages:[]
},
options:{}
};
this.admin = {}
/**
* Are we connected to a Spacebrew server?
* @type {Boolean}
*/
this._isConnected = false;
}
/**
* Connect to Spacebrew
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype.connect = function(){
try {
this.socket = new WebSocket("ws://" + this.server + ":" + this.port);
this.socket.onopen = this._onOpen.bind(this);
this.socket.onmessage = this._onMessage.bind(this);
this.socket.onclose = this._onClose.bind(this);
} catch(e){
this._isConnected = false;
console.log("[connect:Spacebrew] connection attempt failed")
}
}
/**
* Close Spacebrew connection
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype.close = function(){
try {
if (this._isConnected) {
this.socket.close();
this._isConnected = false;
console.log("[close:Spacebrew] closing websocket connection")
}
} catch (e) {
this._isConnected = false;
}
}
/**
* Override in your app to receive on open event for connection
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onOpen = function( name, value ){}
/**
* Override in your app to receive on close event for connection
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onClose = function( name, value ){}
/**
* Override in your app to receive "range" messages, e.g. sb.onRangeMessage = yourRangeFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onRangeMessage = function( name, value ){}
/**
* Override in your app to receive "boolean" messages, e.g. sb.onBooleanMessage = yourBoolFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onBooleanMessage = function( name, value ){}
/**
* Override in your app to receive "string" messages, e.g. sb.onStringMessage = yourStringFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onStringMessage = function( name, value ){}
/**
* Override in your app to receive "custom" messages, e.g. sb.onCustomMessage = yourStringFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onCustomMessage = function( name, value, type ){}
/**
* Add a route you are publishing on
* @param {String} name Name of incoming route
* @param {String} type "boolean", "range", or "string"
* @param {String} def default value
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.addPublish = function( name, type, def ){
this.client_config.publish.messages.push({"name":name, "type":type, "default":def});
this.updatePubSub();
}
/**
* [addSubscriber description]
* @param {String} name Name of outgoing route
* @param {String} type "boolean", "range", or "string"
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.addSubscribe = function( name, type ){
this.client_config.subscribe.messages.push({"name":name, "type":type });
this.updatePubSub();
}
/**
* Update publishers and subscribers
* @memberOf Spacebrew.Client
* @private
*/
Spacebrew.Client.prototype.updatePubSub = function(){
if (this._isConnected) {
this.socket.send(JSON.stringify({"config": this.client_config}));
}
}
/**
* Send a route to Spacebrew
* @param {String} name Name of outgoing route (must match something in addPublish)
* @param {String} type "boolean", "range", or "string"
* @param {String} value Value to send
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.send = function( name, type, value ){
var self = this;
this.msg = {
"message": {
"clientName":this._name,
"name": name,
"type": type,
"value": value
}
}
// if send block is not active then send message
if (!this.send_blocked) {
this.socket.send(JSON.stringify(this.msg));
this.send_blocked = true;
this.msg = undefined;
// set the timer to unblock message sending
setTimeout(function() {
self.send_blocked = false; // remove send block
if (self.msg != undefined) { // if message exists then sent it
self.send(self.msg.message.name, self.msg.message.type, self.msg.message.value);
}
}, self.send_interval);
}
}
/**
* Called on WebSocket open
* @private
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype._onOpen = function() {
console.log("[_onOpen:Spacebrew] Spacebrew connection opened, client name is: " + this._name);
this._isConnected = true;
if (this.admin.active) this.connectAdmin();
// if reconnect functionality is activated then clear interval timer when connection succeeds
if (this.reconnect_timer) {
console.log("[_onOpen:Spacebrew] tearing down reconnect timer")
this.reconnect_timer = clearInterval(this.reconnect_timer);
this.reconnect_timer = undefined;
}
// send my config
this.updatePubSub();
this.onOpen();
}
/**
* Called on WebSocket message
* @private
* @param {Object} e
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype._onMessage = function( e ){
var data = JSON.parse(e.data)
, name
, type
, value
;
// handle client messages
if (data["message"]) {
// check to make sure that this is not an admin message
if (!data.message["clientName"]) {
name = data.message.name;
type = data.message.type;
value = data.message.value;
switch( type ){
case "boolean":
this.onBooleanMessage( name, value == "true" );
break;
case "string":
this.onStringMessage( name, value );
break;
case "range":
this.onRangeMessage( name, Number(value) );
break;
default:
this.onCustomMessage( name, value, type );
}
}
}
// handle admin messages
else {
if (this.admin.active) {
this._handleAdminMessages( data );
}
}
}
/**
* Called on WebSocket close
* @private
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype._onClose = function() {
var self = this;
console.log("[_onClose:Spacebrew] Spacebrew connection closed");
this._isConnected = false;
if (this.admin.active) this.admin.remoteAddress = undefined;
// if reconnect functionality is activated set interval timer if connection dies
if (this.reconnect && !this.reconnect_timer) {
console.log("[_onClose:Spacebrew] setting up reconnect timer");
this.reconnect_timer = setInterval(function () {
if (self.isConnected != false) |
}, 5000);
}
this.onClose();
};
/**
* name Method that sets or gets the spacebrew app name. If parameter is provided then it sets the name, otherwise
* it just returns the current app name.
* @param {String} newName New name of the spacebrew app
* @return {String} Returns the name of the spacebrew app if called as a getter function. If called as a
* setter function it will return false if the method is called after connecting to spacebrew,
* because the name must be configured before connection is made.
*/
Spacebrew.Client.prototype.name = function (newName){
if (newName) { // if a name has been passed in then update it
if (this._isConnected) return false; // if already connected we can't update name
this._name = newName;
if (window) {
this._name = (window.getQueryString('name') !== "" ? unescape(window.getQueryString('name')) : this._name);
}
this.client_config.name = this._name; // update spacebrew config file
}
return this._name;
};
/**
* name Method that sets or gets the spacebrew app description. If parameter is provided then it sets the description,
* otherwise it just returns the current app description.
* @param {String} newDesc New description of the spacebrew app
* @return {String} Returns the description of the spacebrew app if called as a getter function. If called as a
* setter function it will return false if the method is called after connecting to spacebrew,
* because the description must be configured before connection is made.
*/
Spacebrew.Client.prototype.description = function (newDesc){
if (newDesc) { // if a description has been passed in then update it
if (this._isConnected) return false; // if already connected we can't update description
this._description = newDesc || "spacebrew javascript client";
if (window) {
this._description = (window.getQueryString('description') !== "" ? unescape(window.getQueryString('description')) : this._description);
}
this.client_config.description = this._description; // update spacebrew config file
}
return this._description;
};
/**
* isConnected Method that returns current connection state of the spacebrew client.
* @return {Boolean} Returns true if currently connected to Spacebrew
*/
Spacebrew.Client.prototype.isConnected = function (){
return this._isConnected;
};
Spacebrew.Client.prototype.extend = function ( mixin ) {
for (var prop in mixin) {
if (mixin.hasOwnProperty(prop)) {
this[prop] = mixin[prop];
}
}
};
| {
self.connect();
console.log("[reconnect:Spacebrew] attempting to reconnect to spacebrew");
} | conditional_block |
sb-1.3.0.js | /**
*
* Spacebrew Library for Javascript
* --------------------------------
*
* This library was designed to work on front-end (browser) envrionments, and back-end (server)
* environments. Please refer to the readme file, the documentation and examples to learn how to
* use this library.
*
* Spacebrew is an open, dynamically re-routable software toolkit for choreographing interactive
* spaces. Or, in other words, a simple way to connect interactive things to one another. Learn
* more about Spacebrew here: http://docs.spacebrew.cc/
*
* To import into your web apps, we recommend using the minimized version of this library.
*
* Latest Updates:
* - added blank "options" attribute to config message - for future use
* - caps number of messages sent to 60 per second
* - reconnect to spacebrew if connection lost
* - enable client apps to extend libs with admin functionality.
* - added close method to close Spacebrew connection.
*
* @author Brett Renfer and Julio Terra from LAB @ Rockwell Group
* @filename sb-1.3.0.js
* @version 1.3.0
* @date May 7, 2013
*
*/
/**
* Check if Bind method exists in current enviroment. If not, it creates an implementation of
* this useful method.
*/
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
/**
* @namespace for Spacebrew library
*/
var Spacebrew = Spacebrew || {};
/**
* create placeholder var for WebSocket object, if it does not already exist
*/
var WebSocket = WebSocket || {};
/**
* Check if Running in Browser or Server (Node) Environment *
*/
// check if window object already exists to determine if running browswer
var window = window || undefined;
// check if module object already exists to determine if this is a node application
var module = module || undefined;
// if app is running in a browser, then define the getQueryString method
if (window) {
if (!window['getQueryString']){
/**
* Get parameters from a query string
* @param {String} name Name of query string to parse (w/o '?' or '&')
* @return {String} value of parameter (or empty string if not found)
*/
window.getQueryString = function( name ) {
if (!window.location) return;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null ) return "";
else return results[1];
}
}
}
// if app is running in a node server environment then package Spacebrew library as a module.
// WebSocket module (ws) needs to be saved in a node_modules so that it can be imported.
if (!window && module) {
WebSocket = require("ws");
module.exports = {
Spacebrew: Spacebrew
}
}
/**
* Define the Spacebrew Library *
*/
/**
* Spacebrew client!
* @constructor
* @param {String} server (Optional) Base address of Spacebrew server. This server address is overwritten if server defined in query string; defaults to localhost.
* @param {String} name (Optional) Base name of app. Base name is overwritten if "name" is defined in query string; defaults to window.location.href.
* @param {String} description (Optional) Base description of app. Description name is overwritten if "description" is defined in query string;
* @param {Object} options (Optional) An object that holds the optional parameters described below
* port (Optional) Port number for the Spacebrew server
* admin (Optional) Flag that identifies when app should register for admin privileges with server
* debug (Optional) Debug flag that turns on info and debug messaging (limited use)
*/
Spacebrew.Client = function( server, name, description, options ){
var options = options || {};
// check if the server variable is an object that holds all config values
if (server != undefined) {
if (toString.call(server) !== '[object String]') {
options.port = server.port || undefined;
options.debug = server.debug || false;
options.reconnect = server.reconnect || false;
description = server.description || undefined;
name = server.name || undefined;
server = server.server || undefined;
}
}
this.debug = (window.getQueryString('debug') === "true" ? true : (options.debug || false));
this.reconnect = options.reconnect || true;
this.reconnect_timer = undefined;
this.send_interval = 16;
this.send_blocked = false;
this.msg = {};
/**
* Name of app
* @type {String}
*/
this._name = name || "javascript client #";
if (window) {
this._name = (window.getQueryString('name') !== "" ? unescape(window.getQueryString('name')) : this._name);
}
/**
* Description of your app
* @type {String}
*/
this._description = description || "spacebrew javascript client";
if (window) {
this._description = (window.getQueryString('description') !== "" ? unescape(window.getQueryString('description')) : this._description);
}
/**
* Spacebrew server to which the app will connect
* @type {String}
*/
this.server = server || "sandbox.spacebrew.cc";
if (window) {
this.server = (window.getQueryString('server') !== "" ? unescape(window.getQueryString('server')) : this.server);
}
/**
* Port number on which Spacebrew server is running
* @type {Integer}
*/
this.port = options.port || 9000;
if (window) {
port = window.getQueryString('port');
if (port !== "" && !isNaN(port)) {
this.port = port;
}
}
/**
* Reference to WebSocket
* @type {WebSocket}
*/
this.socket = null;
/**
* Configuration file for Spacebrew
* @type {Object}
*/
this.client_config = {
name: this._name,
description: this._description,
publish:{
messages:[]
},
subscribe:{
messages:[]
},
options:{}
};
this.admin = {}
/**
* Are we connected to a Spacebrew server?
* @type {Boolean}
*/
this._isConnected = false;
}
/**
* Connect to Spacebrew
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype.connect = function(){
try {
this.socket = new WebSocket("ws://" + this.server + ":" + this.port);
this.socket.onopen = this._onOpen.bind(this);
this.socket.onmessage = this._onMessage.bind(this);
this.socket.onclose = this._onClose.bind(this);
} catch(e){
this._isConnected = false;
console.log("[connect:Spacebrew] connection attempt failed")
}
}
/**
* Close Spacebrew connection
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype.close = function(){
try {
if (this._isConnected) {
this.socket.close();
this._isConnected = false;
console.log("[close:Spacebrew] closing websocket connection")
}
} catch (e) {
this._isConnected = false;
}
}
/**
* Override in your app to receive on open event for connection
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onOpen = function( name, value ){}
/**
* Override in your app to receive on close event for connection
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onClose = function( name, value ){}
/**
* Override in your app to receive "range" messages, e.g. sb.onRangeMessage = yourRangeFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onRangeMessage = function( name, value ){}
/**
* Override in your app to receive "boolean" messages, e.g. sb.onBooleanMessage = yourBoolFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onBooleanMessage = function( name, value ){}
/**
* Override in your app to receive "string" messages, e.g. sb.onStringMessage = yourStringFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onStringMessage = function( name, value ){}
/**
* Override in your app to receive "custom" messages, e.g. sb.onCustomMessage = yourStringFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onCustomMessage = function( name, value, type ){}
/**
* Add a route you are publishing on
* @param {String} name Name of incoming route
* @param {String} type "boolean", "range", or "string"
* @param {String} def default value
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.addPublish = function( name, type, def ){
this.client_config.publish.messages.push({"name":name, "type":type, "default":def});
this.updatePubSub();
}
/**
* [addSubscriber description]
* @param {String} name Name of outgoing route
* @param {String} type "boolean", "range", or "string"
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.addSubscribe = function( name, type ){
this.client_config.subscribe.messages.push({"name":name, "type":type });
this.updatePubSub();
}
/**
* Update publishers and subscribers
* @memberOf Spacebrew.Client
* @private
*/
Spacebrew.Client.prototype.updatePubSub = function(){
if (this._isConnected) {
this.socket.send(JSON.stringify({"config": this.client_config}));
}
}
/**
* Send a route to Spacebrew
* @param {String} name Name of outgoing route (must match something in addPublish)
* @param {String} type "boolean", "range", or "string"
* @param {String} value Value to send
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.send = function( name, type, value ){
var self = this;
this.msg = {
"message": {
"clientName":this._name,
"name": name,
"type": type,
"value": value
}
}
// if send block is not active then send message
if (!this.send_blocked) {
this.socket.send(JSON.stringify(this.msg));
this.send_blocked = true;
this.msg = undefined;
// set the timer to unblock message sending
setTimeout(function() {
self.send_blocked = false; // remove send block
if (self.msg != undefined) { // if message exists then sent it
self.send(self.msg.message.name, self.msg.message.type, self.msg.message.value);
}
}, self.send_interval);
}
}
/**
* Called on WebSocket open
* @private
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype._onOpen = function() {
console.log("[_onOpen:Spacebrew] Spacebrew connection opened, client name is: " + this._name);
this._isConnected = true;
if (this.admin.active) this.connectAdmin();
// if reconnect functionality is activated then clear interval timer when connection succeeds
if (this.reconnect_timer) {
console.log("[_onOpen:Spacebrew] tearing down reconnect timer")
this.reconnect_timer = clearInterval(this.reconnect_timer);
this.reconnect_timer = undefined;
}
// send my config
this.updatePubSub();
this.onOpen();
}
/**
* Called on WebSocket message
* @private
* @param {Object} e
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype._onMessage = function( e ){
var data = JSON.parse(e.data)
, name
, type
, value
;
// handle client messages
if (data["message"]) {
// check to make sure that this is not an admin message
if (!data.message["clientName"]) {
name = data.message.name;
type = data.message.type;
value = data.message.value;
switch( type ){
case "boolean":
this.onBooleanMessage( name, value == "true" );
break;
case "string":
this.onStringMessage( name, value );
break;
case "range":
this.onRangeMessage( name, Number(value) );
break;
default:
this.onCustomMessage( name, value, type );
}
}
}
// handle admin messages
else {
if (this.admin.active) {
this._handleAdminMessages( data );
}
}
}
/**
* Called on WebSocket close
* @private
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype._onClose = function() {
var self = this;
console.log("[_onClose:Spacebrew] Spacebrew connection closed");
this._isConnected = false;
if (this.admin.active) this.admin.remoteAddress = undefined;
// if reconnect functionality is activated set interval timer if connection dies
if (this.reconnect && !this.reconnect_timer) {
console.log("[_onClose:Spacebrew] setting up reconnect timer");
this.reconnect_timer = setInterval(function () {
if (self.isConnected != false) {
self.connect();
console.log("[reconnect:Spacebrew] attempting to reconnect to spacebrew");
}
}, 5000);
}
| };
/**
* name Method that sets or gets the spacebrew app name. If parameter is provided then it sets the name, otherwise
* it just returns the current app name.
* @param {String} newName New name of the spacebrew app
* @return {String} Returns the name of the spacebrew app if called as a getter function. If called as a
* setter function it will return false if the method is called after connecting to spacebrew,
* because the name must be configured before connection is made.
*/
Spacebrew.Client.prototype.name = function (newName){
if (newName) { // if a name has been passed in then update it
if (this._isConnected) return false; // if already connected we can't update name
this._name = newName;
if (window) {
this._name = (window.getQueryString('name') !== "" ? unescape(window.getQueryString('name')) : this._name);
}
this.client_config.name = this._name; // update spacebrew config file
}
return this._name;
};
/**
* name Method that sets or gets the spacebrew app description. If parameter is provided then it sets the description,
* otherwise it just returns the current app description.
* @param {String} newDesc New description of the spacebrew app
* @return {String} Returns the description of the spacebrew app if called as a getter function. If called as a
* setter function it will return false if the method is called after connecting to spacebrew,
* because the description must be configured before connection is made.
*/
Spacebrew.Client.prototype.description = function (newDesc){
if (newDesc) { // if a description has been passed in then update it
if (this._isConnected) return false; // if already connected we can't update description
this._description = newDesc || "spacebrew javascript client";
if (window) {
this._description = (window.getQueryString('description') !== "" ? unescape(window.getQueryString('description')) : this._description);
}
this.client_config.description = this._description; // update spacebrew config file
}
return this._description;
};
/**
* isConnected Method that returns current connection state of the spacebrew client.
* @return {Boolean} Returns true if currently connected to Spacebrew
*/
Spacebrew.Client.prototype.isConnected = function (){
return this._isConnected;
};
Spacebrew.Client.prototype.extend = function ( mixin ) {
for (var prop in mixin) {
if (mixin.hasOwnProperty(prop)) {
this[prop] = mixin[prop];
}
}
}; | this.onClose(); | random_line_split |
relative_paths.py | # All of the other examples directly embed the Javascript and CSS code for
# Bokeh's client-side runtime into the HTML. This leads to the HTML files
# being rather large. An alternative is to ask Bokeh to produce HTML that
# has a relative link to the Bokeh Javascript and CSS. This is easy to
# do; you just pass in a few extra arguments to the output_file() command.
import numpy as np | N = 100
x = np.linspace(0, 4*np.pi, N)
y = np.sin(x)
output_file("relative_paths.html", title="Relative path example", mode="relative")
scatter(x,y, color="#FF00FF", tools="pan,wheel_zoom,box_zoom,reset,previewsave")
show()
# By default, the URLs for the Javascript and CSS will be relative to
# the current directory, i.e. the directory in which the HTML file is
# generated. You can provide a different "root" directory from which
# the relative paths will be computed:
#
# output_file("scatter.html", title="scatter.py example",
# resources="relative", rootdir="some/other/path") | from bokeh.plotting import *
| random_line_split |
b-dummy.ts | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
/**
* [[include:dummies/b-dummy/README.md]]
* @packageDocumentation
*/
import 'models/demo/pagination';
import { derive } from 'core/functools/trait';
import * as cookie from 'core/cookies';
import * as htmlHelpers from 'core/html';
import * as browserHelpers from 'core/browser';
import * as session from 'core/session';
import { inViewFactory } from 'core/dom/in-view';
import { ImageLoader, imageLoaderFactory } from 'core/dom/image';
import { ResizeWatcher } from 'core/dom/resize-observer';
import updateOn from 'core/component/directives/update-on/engines';
import iLockPageScroll from 'traits/i-lock-page-scroll/i-lock-page-scroll';
import iObserveDOM from 'traits/i-observe-dom/i-observe-dom';
import inMemoryRouterEngine from 'core/router/engines/in-memory';
import historyApiRouterEngine from 'core/router/engines/browser-history';
import iData, {
component,
field,
hook,
wait,
ModsNTable
} from 'super/i-data/i-data';
import bBottomSlide from 'base/b-bottom-slide/b-bottom-slide';
import daemons from 'dummies/b-dummy/daemons';
import type { Directives, Modules, Engines } from 'dummies/b-dummy/interface';
const
inViewMutation = inViewFactory('mutation'),
inViewObserver = inViewFactory('observer');
export * from 'super/i-data/i-data';
export * from 'dummies/b-dummy/interface';
interface bDummy extends Trait<typeof iLockPageScroll>, Trait<typeof iObserveDOM> {}
@component({
functional: {
functional: true,
dataProvider: undefined
}
})
@derive(iLockPageScroll, iObserveDOM)
class bDummy extends iData implements iLockPageScroll, iObserveDOM {
@field()
testField: unknown = undefined;
get directives(): Directives {
return {
imageFactory: imageLoaderFactory,
image: ImageLoader,
inViewMutation,
inViewObserver,
updateOn
};
}
get engines(): Engines {
return {
router: {
historyApiRouterEngine,
inMemoryRouterEngine
}
}; | }
get modules(): Modules {
return {
resizeWatcher: ResizeWatcher,
iObserveDOM,
htmlHelpers,
session,
browserHelpers,
cookie
};
}
get componentInstances(): Dictionary {
return {
bDummy,
bBottomSlide
};
}
override get baseMods(): CanUndef<Readonly<ModsNTable>> {
return {foo: 'bar'};
}
static override readonly daemons: typeof daemons = daemons;
setStage(value: string): void {
this.stage = value;
}
/** @see [[iObserveDOM.initDOMObservers]] */
@hook('mounted')
@wait('ready')
initDOMObservers(): void {
iObserveDOM.observe(this, {
node: this.$el!,
childList: true,
subtree: true
});
}
}
export default bDummy; | random_line_split | |
b-dummy.ts | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
/**
* [[include:dummies/b-dummy/README.md]]
* @packageDocumentation
*/
import 'models/demo/pagination';
import { derive } from 'core/functools/trait';
import * as cookie from 'core/cookies';
import * as htmlHelpers from 'core/html';
import * as browserHelpers from 'core/browser';
import * as session from 'core/session';
import { inViewFactory } from 'core/dom/in-view';
import { ImageLoader, imageLoaderFactory } from 'core/dom/image';
import { ResizeWatcher } from 'core/dom/resize-observer';
import updateOn from 'core/component/directives/update-on/engines';
import iLockPageScroll from 'traits/i-lock-page-scroll/i-lock-page-scroll';
import iObserveDOM from 'traits/i-observe-dom/i-observe-dom';
import inMemoryRouterEngine from 'core/router/engines/in-memory';
import historyApiRouterEngine from 'core/router/engines/browser-history';
import iData, {
component,
field,
hook,
wait,
ModsNTable
} from 'super/i-data/i-data';
import bBottomSlide from 'base/b-bottom-slide/b-bottom-slide';
import daemons from 'dummies/b-dummy/daemons';
import type { Directives, Modules, Engines } from 'dummies/b-dummy/interface';
const
inViewMutation = inViewFactory('mutation'),
inViewObserver = inViewFactory('observer');
export * from 'super/i-data/i-data';
export * from 'dummies/b-dummy/interface';
interface bDummy extends Trait<typeof iLockPageScroll>, Trait<typeof iObserveDOM> {}
@component({
functional: {
functional: true,
dataProvider: undefined
}
})
@derive(iLockPageScroll, iObserveDOM)
class bDummy extends iData implements iLockPageScroll, iObserveDOM {
@field()
testField: unknown = undefined;
get directives(): Directives |
get engines(): Engines {
return {
router: {
historyApiRouterEngine,
inMemoryRouterEngine
}
};
}
get modules(): Modules {
return {
resizeWatcher: ResizeWatcher,
iObserveDOM,
htmlHelpers,
session,
browserHelpers,
cookie
};
}
get componentInstances(): Dictionary {
return {
bDummy,
bBottomSlide
};
}
override get baseMods(): CanUndef<Readonly<ModsNTable>> {
return {foo: 'bar'};
}
static override readonly daemons: typeof daemons = daemons;
setStage(value: string): void {
this.stage = value;
}
/** @see [[iObserveDOM.initDOMObservers]] */
@hook('mounted')
@wait('ready')
initDOMObservers(): void {
iObserveDOM.observe(this, {
node: this.$el!,
childList: true,
subtree: true
});
}
}
export default bDummy;
| {
return {
imageFactory: imageLoaderFactory,
image: ImageLoader,
inViewMutation,
inViewObserver,
updateOn
};
} | identifier_body |
b-dummy.ts | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
/**
* [[include:dummies/b-dummy/README.md]]
* @packageDocumentation
*/
import 'models/demo/pagination';
import { derive } from 'core/functools/trait';
import * as cookie from 'core/cookies';
import * as htmlHelpers from 'core/html';
import * as browserHelpers from 'core/browser';
import * as session from 'core/session';
import { inViewFactory } from 'core/dom/in-view';
import { ImageLoader, imageLoaderFactory } from 'core/dom/image';
import { ResizeWatcher } from 'core/dom/resize-observer';
import updateOn from 'core/component/directives/update-on/engines';
import iLockPageScroll from 'traits/i-lock-page-scroll/i-lock-page-scroll';
import iObserveDOM from 'traits/i-observe-dom/i-observe-dom';
import inMemoryRouterEngine from 'core/router/engines/in-memory';
import historyApiRouterEngine from 'core/router/engines/browser-history';
import iData, {
component,
field,
hook,
wait,
ModsNTable
} from 'super/i-data/i-data';
import bBottomSlide from 'base/b-bottom-slide/b-bottom-slide';
import daemons from 'dummies/b-dummy/daemons';
import type { Directives, Modules, Engines } from 'dummies/b-dummy/interface';
const
inViewMutation = inViewFactory('mutation'),
inViewObserver = inViewFactory('observer');
export * from 'super/i-data/i-data';
export * from 'dummies/b-dummy/interface';
interface bDummy extends Trait<typeof iLockPageScroll>, Trait<typeof iObserveDOM> {}
@component({
functional: {
functional: true,
dataProvider: undefined
}
})
@derive(iLockPageScroll, iObserveDOM)
class bDummy extends iData implements iLockPageScroll, iObserveDOM {
@field()
testField: unknown = undefined;
get directives(): Directives {
return {
imageFactory: imageLoaderFactory,
image: ImageLoader,
inViewMutation,
inViewObserver,
updateOn
};
}
get engines(): Engines {
return {
router: {
historyApiRouterEngine,
inMemoryRouterEngine
}
};
}
get modules(): Modules {
return {
resizeWatcher: ResizeWatcher,
iObserveDOM,
htmlHelpers,
session,
browserHelpers,
cookie
};
}
get componentInstances(): Dictionary {
return {
bDummy,
bBottomSlide
};
}
override get | (): CanUndef<Readonly<ModsNTable>> {
return {foo: 'bar'};
}
static override readonly daemons: typeof daemons = daemons;
setStage(value: string): void {
this.stage = value;
}
/** @see [[iObserveDOM.initDOMObservers]] */
@hook('mounted')
@wait('ready')
initDOMObservers(): void {
iObserveDOM.observe(this, {
node: this.$el!,
childList: true,
subtree: true
});
}
}
export default bDummy;
| baseMods | identifier_name |
response.tools.ts | import { ContentfulCommon } from 'ng2-contentful';
import { ContentfulNodePagesResponse } from './aliases.structures';
// this will be the part of ng2-contentful tools
/**
* Transforms response to usable form by resolving all includes objects
* @param response
* @param depth
* @returns {T[]}
*/
export function transformResponse<T extends ContentfulCommon<any>>(response: ContentfulNodePagesResponse, depth: number = 1): T[] {
let currentDepth = 0;
// collect all includes
let includes: any = {};
for (let key in response.includes) {
if (response.includes.hasOwnProperty(key)) |
}
for (let item of response.items) {
includes[item.sys.id] = item;
}
/**
* Replace `sys` reference with full contentful's object for one item
* @param item
* @returns {ContentfulCommon<any>}
*/
function extendObjectWithFields(item: ContentfulCommon<any>): ContentfulCommon<any> {
if (item.hasOwnProperty('sys') && includes.hasOwnProperty(item.sys.id)) {
item.fields = includes[item.sys.id].fields;
item.sys = includes[item.sys.id].sys;
}
return item;
}
/**
* Replace `sys` references with full contentful's objects for item's array
* @param items
* @returns {Array<ContentfulCommon<any>>}
*/
function extendArrayWithFields(items: Array<ContentfulCommon<any>>): Array<ContentfulCommon<any>> {
let replacedItems: Array<ContentfulCommon<any>> = [];
for (let item of items) {
replacedItems.push(extendObjectWithFields(item));
}
return replacedItems;
}
/**
* Analyze the contentful object for relations with other objects and tries to resolve it
* @param item
* @returns {Array<ContentfulCommon<any>>}
*/
function replaceInItem(item: ContentfulCommon<any>): Array<ContentfulCommon<any>> {
let replacedItems: Array<ContentfulCommon<any>> = [];
for (let key in item.fields) {
if (item.fields.hasOwnProperty(key)) {
let value = item.fields[key];
if (value instanceof Array) {
replacedItems.push(...extendArrayWithFields(value));
}
if (value instanceof Object && value.hasOwnProperty('sys')) {
replacedItems.push(extendObjectWithFields(value));
}
}
}
return replacedItems;
}
function replaceInItems(items: Array<ContentfulCommon<any>>): void {
currentDepth++;
let replacedItems: Array<any> = [];
for (let item of items) {
replacedItems.push(...replaceInItem(item));
}
if (currentDepth < depth) {
replaceInItems(replacedItems);
}
}
replaceInItems(response.items);
return response.items as T[];
}
| {
for (let item of response.includes[key]) {
includes[item.sys.id] = item;
}
} | conditional_block |
response.tools.ts | import { ContentfulCommon } from 'ng2-contentful';
import { ContentfulNodePagesResponse } from './aliases.structures';
// this will be the part of ng2-contentful tools
/**
* Transforms response to usable form by resolving all includes objects
* @param response
* @param depth | */
export function transformResponse<T extends ContentfulCommon<any>>(response: ContentfulNodePagesResponse, depth: number = 1): T[] {
let currentDepth = 0;
// collect all includes
let includes: any = {};
for (let key in response.includes) {
if (response.includes.hasOwnProperty(key)) {
for (let item of response.includes[key]) {
includes[item.sys.id] = item;
}
}
}
for (let item of response.items) {
includes[item.sys.id] = item;
}
/**
* Replace `sys` reference with full contentful's object for one item
* @param item
* @returns {ContentfulCommon<any>}
*/
function extendObjectWithFields(item: ContentfulCommon<any>): ContentfulCommon<any> {
if (item.hasOwnProperty('sys') && includes.hasOwnProperty(item.sys.id)) {
item.fields = includes[item.sys.id].fields;
item.sys = includes[item.sys.id].sys;
}
return item;
}
/**
* Replace `sys` references with full contentful's objects for item's array
* @param items
* @returns {Array<ContentfulCommon<any>>}
*/
function extendArrayWithFields(items: Array<ContentfulCommon<any>>): Array<ContentfulCommon<any>> {
let replacedItems: Array<ContentfulCommon<any>> = [];
for (let item of items) {
replacedItems.push(extendObjectWithFields(item));
}
return replacedItems;
}
/**
* Analyze the contentful object for relations with other objects and tries to resolve it
* @param item
* @returns {Array<ContentfulCommon<any>>}
*/
function replaceInItem(item: ContentfulCommon<any>): Array<ContentfulCommon<any>> {
let replacedItems: Array<ContentfulCommon<any>> = [];
for (let key in item.fields) {
if (item.fields.hasOwnProperty(key)) {
let value = item.fields[key];
if (value instanceof Array) {
replacedItems.push(...extendArrayWithFields(value));
}
if (value instanceof Object && value.hasOwnProperty('sys')) {
replacedItems.push(extendObjectWithFields(value));
}
}
}
return replacedItems;
}
function replaceInItems(items: Array<ContentfulCommon<any>>): void {
currentDepth++;
let replacedItems: Array<any> = [];
for (let item of items) {
replacedItems.push(...replaceInItem(item));
}
if (currentDepth < depth) {
replaceInItems(replacedItems);
}
}
replaceInItems(response.items);
return response.items as T[];
} | * @returns {T[]} | random_line_split |
response.tools.ts | import { ContentfulCommon } from 'ng2-contentful';
import { ContentfulNodePagesResponse } from './aliases.structures';
// this will be the part of ng2-contentful tools
/**
* Transforms response to usable form by resolving all includes objects
* @param response
* @param depth
* @returns {T[]}
*/
export function transformResponse<T extends ContentfulCommon<any>>(response: ContentfulNodePagesResponse, depth: number = 1): T[] | {
let currentDepth = 0;
// collect all includes
let includes: any = {};
for (let key in response.includes) {
if (response.includes.hasOwnProperty(key)) {
for (let item of response.includes[key]) {
includes[item.sys.id] = item;
}
}
}
for (let item of response.items) {
includes[item.sys.id] = item;
}
/**
* Replace `sys` reference with full contentful's object for one item
* @param item
* @returns {ContentfulCommon<any>}
*/
function extendObjectWithFields(item: ContentfulCommon<any>): ContentfulCommon<any> {
if (item.hasOwnProperty('sys') && includes.hasOwnProperty(item.sys.id)) {
item.fields = includes[item.sys.id].fields;
item.sys = includes[item.sys.id].sys;
}
return item;
}
/**
* Replace `sys` references with full contentful's objects for item's array
* @param items
* @returns {Array<ContentfulCommon<any>>}
*/
function extendArrayWithFields(items: Array<ContentfulCommon<any>>): Array<ContentfulCommon<any>> {
let replacedItems: Array<ContentfulCommon<any>> = [];
for (let item of items) {
replacedItems.push(extendObjectWithFields(item));
}
return replacedItems;
}
/**
* Analyze the contentful object for relations with other objects and tries to resolve it
* @param item
* @returns {Array<ContentfulCommon<any>>}
*/
function replaceInItem(item: ContentfulCommon<any>): Array<ContentfulCommon<any>> {
let replacedItems: Array<ContentfulCommon<any>> = [];
for (let key in item.fields) {
if (item.fields.hasOwnProperty(key)) {
let value = item.fields[key];
if (value instanceof Array) {
replacedItems.push(...extendArrayWithFields(value));
}
if (value instanceof Object && value.hasOwnProperty('sys')) {
replacedItems.push(extendObjectWithFields(value));
}
}
}
return replacedItems;
}
function replaceInItems(items: Array<ContentfulCommon<any>>): void {
currentDepth++;
let replacedItems: Array<any> = [];
for (let item of items) {
replacedItems.push(...replaceInItem(item));
}
if (currentDepth < depth) {
replaceInItems(replacedItems);
}
}
replaceInItems(response.items);
return response.items as T[];
} | identifier_body | |
response.tools.ts | import { ContentfulCommon } from 'ng2-contentful';
import { ContentfulNodePagesResponse } from './aliases.structures';
// this will be the part of ng2-contentful tools
/**
* Transforms response to usable form by resolving all includes objects
* @param response
* @param depth
* @returns {T[]}
*/
export function transformResponse<T extends ContentfulCommon<any>>(response: ContentfulNodePagesResponse, depth: number = 1): T[] {
let currentDepth = 0;
// collect all includes
let includes: any = {};
for (let key in response.includes) {
if (response.includes.hasOwnProperty(key)) {
for (let item of response.includes[key]) {
includes[item.sys.id] = item;
}
}
}
for (let item of response.items) {
includes[item.sys.id] = item;
}
/**
* Replace `sys` reference with full contentful's object for one item
* @param item
* @returns {ContentfulCommon<any>}
*/
function | (item: ContentfulCommon<any>): ContentfulCommon<any> {
if (item.hasOwnProperty('sys') && includes.hasOwnProperty(item.sys.id)) {
item.fields = includes[item.sys.id].fields;
item.sys = includes[item.sys.id].sys;
}
return item;
}
/**
* Replace `sys` references with full contentful's objects for item's array
* @param items
* @returns {Array<ContentfulCommon<any>>}
*/
function extendArrayWithFields(items: Array<ContentfulCommon<any>>): Array<ContentfulCommon<any>> {
let replacedItems: Array<ContentfulCommon<any>> = [];
for (let item of items) {
replacedItems.push(extendObjectWithFields(item));
}
return replacedItems;
}
/**
* Analyze the contentful object for relations with other objects and tries to resolve it
* @param item
* @returns {Array<ContentfulCommon<any>>}
*/
function replaceInItem(item: ContentfulCommon<any>): Array<ContentfulCommon<any>> {
let replacedItems: Array<ContentfulCommon<any>> = [];
for (let key in item.fields) {
if (item.fields.hasOwnProperty(key)) {
let value = item.fields[key];
if (value instanceof Array) {
replacedItems.push(...extendArrayWithFields(value));
}
if (value instanceof Object && value.hasOwnProperty('sys')) {
replacedItems.push(extendObjectWithFields(value));
}
}
}
return replacedItems;
}
function replaceInItems(items: Array<ContentfulCommon<any>>): void {
currentDepth++;
let replacedItems: Array<any> = [];
for (let item of items) {
replacedItems.push(...replaceInItem(item));
}
if (currentDepth < depth) {
replaceInItems(replacedItems);
}
}
replaceInItems(response.items);
return response.items as T[];
}
| extendObjectWithFields | identifier_name |
post.js | import React, { PureComponent } from "react";
import { graphql } from 'gatsby'
import Link from "gatsby-link";
import path from "ramda/src/path";
import ScrollReveal from "scrollreveal";
import Layout from "../components/Layout";
import "prismjs/themes/prism.css";
import styles from "./post.module.scss";
const getPost = path(["data", "markdownRemark"]);
const getContext = path(["pageContext"]);
const PostNav = ({ prev, next }) => (
<div className={styles.postNav}>
{prev && (
<Link to={`/${prev.fields.slug}`}>
上一篇:
{prev.frontmatter.title}
</Link>
)}
{next && (
<Link to={`/${next.fields.slug}`}>
下一篇:
{next.frontmatter.title}
</Link>
)}
</div>
);
export default class Post extends PureComponent {
componentDidMount() {
ScrollReveal().reveal(".article-header>h1", {
delay: 500,
useDelay: "onload",
reset: true,
origin: "top",
distance: "120px"
});
ScrollReveal().reveal(".article-content", {
delay: 500,
useDelay: "onload",
reset: true,
origin: "bottom",
distance: "120px"
});
}
componentWillUnmount() {
ScrollReveal().destroy();
}
render() {
c | ost = getPost(this.props);
const { next, prev } = getContext(this.props); // Not to be confused with react context...
return (
<Layout>
<header className="article-header">
<h1>{post.frontmatter.title}</h1>
</header>
<div
className="article-content"
dangerouslySetInnerHTML={{ __html: post.html }}
/>
<PostNav prev={prev} next={next} />
</Layout>
);
}
}
export const query = graphql`
query BlogPostQuery($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
}
}
}
`;
| onst p | identifier_name |
post.js | import path from "ramda/src/path";
import ScrollReveal from "scrollreveal";
import Layout from "../components/Layout";
import "prismjs/themes/prism.css";
import styles from "./post.module.scss";
const getPost = path(["data", "markdownRemark"]);
const getContext = path(["pageContext"]);
const PostNav = ({ prev, next }) => (
<div className={styles.postNav}>
{prev && (
<Link to={`/${prev.fields.slug}`}>
上一篇:
{prev.frontmatter.title}
</Link>
)}
{next && (
<Link to={`/${next.fields.slug}`}>
下一篇:
{next.frontmatter.title}
</Link>
)}
</div>
);
export default class Post extends PureComponent {
componentDidMount() {
ScrollReveal().reveal(".article-header>h1", {
delay: 500,
useDelay: "onload",
reset: true,
origin: "top",
distance: "120px"
});
ScrollReveal().reveal(".article-content", {
delay: 500,
useDelay: "onload",
reset: true,
origin: "bottom",
distance: "120px"
});
}
componentWillUnmount() {
ScrollReveal().destroy();
}
render() {
const post = getPost(this.props);
const { next, prev } = getContext(this.props); // Not to be confused with react context...
return (
<Layout>
<header className="article-header">
<h1>{post.frontmatter.title}</h1>
</header>
<div
className="article-content"
dangerouslySetInnerHTML={{ __html: post.html }}
/>
<PostNav prev={prev} next={next} />
</Layout>
);
}
}
export const query = graphql`
query BlogPostQuery($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
}
}
}
`; | import React, { PureComponent } from "react";
import { graphql } from 'gatsby'
import Link from "gatsby-link"; | random_line_split | |
unordered_input.rs | //! Create new `Streams` connected to external inputs.
use std::rc::Rc;
use std::cell::RefCell;
use std::default::Default;
use progress::frontier::Antichain;
use progress::{Operate, Timestamp};
use progress::nested::subgraph::Source;
use progress::count_map::CountMap;
use timely_communication::Allocate;
use Data;
use dataflow::channels::pushers::{Tee, Counter as PushCounter};
use dataflow::channels::pushers::buffer::{Buffer as PushBuffer, AutoflushSession};
use dataflow::operators::Capability;
use dataflow::operators::capability::mint as mint_capability;
use dataflow::{Stream, Scope};
/// Create a new `Stream` and `Handle` through which to supply input.
pub trait UnorderedInput<G: Scope> {
/// Create a new capability-based `Stream` and `Handle` through which to supply input. This
/// input supports multiple open epochs (timestamps) at the same time.
///
/// The `new_unordered_input` method returns `((Handle, Capability), Stream)` where the `Stream` can be used
/// immediately for timely dataflow construction, `Handle` and `Capability` are later used to introduce
/// data into the timely dataflow computation.
///
/// The `Capability` returned is for the default value of the timestamp type in use. The
/// capability can be dropped to inform the system that the input has advanced beyond the
/// capability's timestamp. To retain the ability to send, a new capability at a later timestamp
/// should be obtained first, via the `delayed` function for `Capability`.
///
/// To communicate the end-of-input drop all available capabilities.
///
/// #Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
///
/// use timely::*;
/// use timely::dataflow::operators::*;
/// use timely::dataflow::operators::capture::Extract;
/// use timely::dataflow::{Stream, Scope};
/// use timely::progress::timestamp::RootTimestamp;
///
/// // get send and recv endpoints, wrap send to share
/// let (send, recv) = ::std::sync::mpsc::channel();
/// let send = Arc::new(Mutex::new(send));
///
/// timely::execute(Configuration::Thread, move |root| {
///
/// // this is only to validate the output.
/// let send = send.lock().unwrap().clone();
///
/// // create and capture the unordered input.
/// let (mut input, mut cap) = root.scoped(|scope| {
/// let (input, stream) = scope.new_unordered_input();
/// stream.capture_into(send);
/// input
/// });
///
/// // feed values 0..10 at times 0..10.
/// for round in 0..10 {
/// input.session(cap.clone()).give(round);
/// cap = cap.delayed(&RootTimestamp::new(round + 1));
/// root.step();
/// }
/// }).unwrap();
///
/// let extract = recv.extract();
/// for i in 0..10 {
/// assert_eq!(extract[i], (RootTimestamp::new(i), vec![i]));
/// }
/// ```
fn new_unordered_input<D:Data>(&mut self) -> ((UnorderedHandle<G::Timestamp, D>, Capability<G::Timestamp>), Stream<G, D>);
}
impl<G: Scope> UnorderedInput<G> for G {
fn new_unordered_input<D:Data>(&mut self) -> ((UnorderedHandle<G::Timestamp, D>, Capability<G::Timestamp>), Stream<G, D>) {
let (output, registrar) = Tee::<G::Timestamp, D>::new();
let internal = Rc::new(RefCell::new(CountMap::new()));
let produced = Rc::new(RefCell::new(CountMap::new()));
let cap = mint_capability(Default::default(), internal.clone());
let helper = UnorderedHandle::new(PushCounter::new(output, produced.clone()));
let peers = self.peers();
let index = self.add_operator(UnorderedOperator {
internal: internal.clone(),
produced: produced.clone(),
peers: peers,
});
return ((helper, cap), Stream::new(Source { index: index, port: 0 }, registrar, self.clone()));
}
}
struct UnorderedOperator<T:Timestamp> {
internal: Rc<RefCell<CountMap<T>>>,
produced: Rc<RefCell<CountMap<T>>>,
peers: usize,
}
impl<T:Timestamp> Operate<T> for UnorderedOperator<T> {
fn name(&self) -> String { "Input".to_owned() }
fn inputs(&self) -> usize { 0 }
fn outputs(&self) -> usize { 1 }
fn get_internal_summary(&mut self) -> (Vec<Vec<Antichain<<T as Timestamp>::Summary>>>,
Vec<CountMap<T>>) {
let mut internal = CountMap::new();
// augment the counts for each reserved capability.
for &(ref time, count) in self.internal.borrow().iter() {
internal.update(time, count * (self.peers as i64 - 1));
}
// drain the changes to empty out, and complete the counts for internal.
self.internal.borrow_mut().drain_into(&mut internal);
(Vec::new(), vec![internal])
}
fn pull_internal_progress(&mut self,_consumed: &mut [CountMap<T>],
internal: &mut [CountMap<T>],
produced: &mut [CountMap<T>]) -> bool
{
self.produced.borrow_mut().drain_into(&mut produced[0]);
self.internal.borrow_mut().drain_into(&mut internal[0]);
return false;
}
fn notify_me(&self) -> bool { false }
}
/// A handle to an input `Stream`, used to introduce data to a timely dataflow computation.
pub struct | <T: Timestamp, D: Data> {
buffer: PushBuffer<T, D, PushCounter<T, D, Tee<T, D>>>,
}
impl<T: Timestamp, D: Data> UnorderedHandle<T, D> {
fn new(pusher: PushCounter<T, D, Tee<T, D>>) -> UnorderedHandle<T, D> {
UnorderedHandle {
buffer: PushBuffer::new(pusher),
}
}
/// Allocates a new automatically flushing session based on the supplied capability.
pub fn session<'b>(&'b mut self, cap: Capability<T>) -> AutoflushSession<'b, T, D, PushCounter<T, D, Tee<T, D>>> {
self.buffer.autoflush_session(cap)
}
}
impl<T: Timestamp, D: Data> Drop for UnorderedHandle<T, D> {
fn drop(&mut self) {
// TODO: explode if not all capabilities were given up?
}
}
| UnorderedHandle | identifier_name |
unordered_input.rs | //! Create new `Streams` connected to external inputs.
use std::rc::Rc;
use std::cell::RefCell;
use std::default::Default;
use progress::frontier::Antichain;
use progress::{Operate, Timestamp};
use progress::nested::subgraph::Source;
use progress::count_map::CountMap;
use timely_communication::Allocate;
use Data;
use dataflow::channels::pushers::{Tee, Counter as PushCounter};
use dataflow::channels::pushers::buffer::{Buffer as PushBuffer, AutoflushSession};
use dataflow::operators::Capability;
use dataflow::operators::capability::mint as mint_capability;
use dataflow::{Stream, Scope};
/// Create a new `Stream` and `Handle` through which to supply input.
pub trait UnorderedInput<G: Scope> {
/// Create a new capability-based `Stream` and `Handle` through which to supply input. This
/// input supports multiple open epochs (timestamps) at the same time.
///
/// The `new_unordered_input` method returns `((Handle, Capability), Stream)` where the `Stream` can be used
/// immediately for timely dataflow construction, `Handle` and `Capability` are later used to introduce
/// data into the timely dataflow computation.
///
/// The `Capability` returned is for the default value of the timestamp type in use. The
/// capability can be dropped to inform the system that the input has advanced beyond the
/// capability's timestamp. To retain the ability to send, a new capability at a later timestamp
/// should be obtained first, via the `delayed` function for `Capability`.
///
/// To communicate the end-of-input drop all available capabilities.
///
/// #Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
///
/// use timely::*;
/// use timely::dataflow::operators::*;
/// use timely::dataflow::operators::capture::Extract;
/// use timely::dataflow::{Stream, Scope};
/// use timely::progress::timestamp::RootTimestamp;
///
/// // get send and recv endpoints, wrap send to share
/// let (send, recv) = ::std::sync::mpsc::channel();
/// let send = Arc::new(Mutex::new(send));
///
/// timely::execute(Configuration::Thread, move |root| {
///
/// // this is only to validate the output.
/// let send = send.lock().unwrap().clone();
///
/// // create and capture the unordered input.
/// let (mut input, mut cap) = root.scoped(|scope| {
/// let (input, stream) = scope.new_unordered_input();
/// stream.capture_into(send);
/// input
/// });
///
/// // feed values 0..10 at times 0..10.
/// for round in 0..10 {
/// input.session(cap.clone()).give(round);
/// cap = cap.delayed(&RootTimestamp::new(round + 1));
/// root.step();
/// }
/// }).unwrap();
///
/// let extract = recv.extract();
/// for i in 0..10 {
/// assert_eq!(extract[i], (RootTimestamp::new(i), vec![i]));
/// }
/// ```
fn new_unordered_input<D:Data>(&mut self) -> ((UnorderedHandle<G::Timestamp, D>, Capability<G::Timestamp>), Stream<G, D>);
}
impl<G: Scope> UnorderedInput<G> for G {
fn new_unordered_input<D:Data>(&mut self) -> ((UnorderedHandle<G::Timestamp, D>, Capability<G::Timestamp>), Stream<G, D>) {
let (output, registrar) = Tee::<G::Timestamp, D>::new();
let internal = Rc::new(RefCell::new(CountMap::new()));
let produced = Rc::new(RefCell::new(CountMap::new()));
let cap = mint_capability(Default::default(), internal.clone());
let helper = UnorderedHandle::new(PushCounter::new(output, produced.clone()));
let peers = self.peers();
let index = self.add_operator(UnorderedOperator {
internal: internal.clone(),
produced: produced.clone(),
peers: peers,
});
return ((helper, cap), Stream::new(Source { index: index, port: 0 }, registrar, self.clone()));
}
}
struct UnorderedOperator<T:Timestamp> {
internal: Rc<RefCell<CountMap<T>>>,
produced: Rc<RefCell<CountMap<T>>>,
peers: usize,
}
impl<T:Timestamp> Operate<T> for UnorderedOperator<T> {
fn name(&self) -> String { "Input".to_owned() }
fn inputs(&self) -> usize { 0 }
fn outputs(&self) -> usize |
fn get_internal_summary(&mut self) -> (Vec<Vec<Antichain<<T as Timestamp>::Summary>>>,
Vec<CountMap<T>>) {
let mut internal = CountMap::new();
// augment the counts for each reserved capability.
for &(ref time, count) in self.internal.borrow().iter() {
internal.update(time, count * (self.peers as i64 - 1));
}
// drain the changes to empty out, and complete the counts for internal.
self.internal.borrow_mut().drain_into(&mut internal);
(Vec::new(), vec![internal])
}
fn pull_internal_progress(&mut self,_consumed: &mut [CountMap<T>],
internal: &mut [CountMap<T>],
produced: &mut [CountMap<T>]) -> bool
{
self.produced.borrow_mut().drain_into(&mut produced[0]);
self.internal.borrow_mut().drain_into(&mut internal[0]);
return false;
}
fn notify_me(&self) -> bool { false }
}
/// A handle to an input `Stream`, used to introduce data to a timely dataflow computation.
pub struct UnorderedHandle<T: Timestamp, D: Data> {
buffer: PushBuffer<T, D, PushCounter<T, D, Tee<T, D>>>,
}
impl<T: Timestamp, D: Data> UnorderedHandle<T, D> {
fn new(pusher: PushCounter<T, D, Tee<T, D>>) -> UnorderedHandle<T, D> {
UnorderedHandle {
buffer: PushBuffer::new(pusher),
}
}
/// Allocates a new automatically flushing session based on the supplied capability.
pub fn session<'b>(&'b mut self, cap: Capability<T>) -> AutoflushSession<'b, T, D, PushCounter<T, D, Tee<T, D>>> {
self.buffer.autoflush_session(cap)
}
}
impl<T: Timestamp, D: Data> Drop for UnorderedHandle<T, D> {
fn drop(&mut self) {
// TODO: explode if not all capabilities were given up?
}
}
| { 1 } | identifier_body |
unordered_input.rs | //! Create new `Streams` connected to external inputs.
use std::rc::Rc;
use std::cell::RefCell;
use std::default::Default;
use progress::frontier::Antichain;
use progress::{Operate, Timestamp};
use progress::nested::subgraph::Source;
use progress::count_map::CountMap;
use timely_communication::Allocate;
use Data;
use dataflow::channels::pushers::{Tee, Counter as PushCounter};
use dataflow::channels::pushers::buffer::{Buffer as PushBuffer, AutoflushSession};
use dataflow::operators::Capability;
use dataflow::operators::capability::mint as mint_capability;
use dataflow::{Stream, Scope};
/// Create a new `Stream` and `Handle` through which to supply input.
pub trait UnorderedInput<G: Scope> {
/// Create a new capability-based `Stream` and `Handle` through which to supply input. This
/// input supports multiple open epochs (timestamps) at the same time.
///
/// The `new_unordered_input` method returns `((Handle, Capability), Stream)` where the `Stream` can be used
/// immediately for timely dataflow construction, `Handle` and `Capability` are later used to introduce
/// data into the timely dataflow computation.
///
/// The `Capability` returned is for the default value of the timestamp type in use. The
/// capability can be dropped to inform the system that the input has advanced beyond the
/// capability's timestamp. To retain the ability to send, a new capability at a later timestamp
/// should be obtained first, via the `delayed` function for `Capability`.
///
/// To communicate the end-of-input drop all available capabilities.
///
/// #Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
///
/// use timely::*;
/// use timely::dataflow::operators::*;
/// use timely::dataflow::operators::capture::Extract;
/// use timely::dataflow::{Stream, Scope};
/// use timely::progress::timestamp::RootTimestamp;
///
/// // get send and recv endpoints, wrap send to share
/// let (send, recv) = ::std::sync::mpsc::channel();
/// let send = Arc::new(Mutex::new(send));
///
/// timely::execute(Configuration::Thread, move |root| {
///
/// // this is only to validate the output.
/// let send = send.lock().unwrap().clone();
///
/// // create and capture the unordered input.
/// let (mut input, mut cap) = root.scoped(|scope| {
/// let (input, stream) = scope.new_unordered_input();
/// stream.capture_into(send);
/// input
/// });
///
/// // feed values 0..10 at times 0..10.
/// for round in 0..10 {
/// input.session(cap.clone()).give(round);
/// cap = cap.delayed(&RootTimestamp::new(round + 1));
/// root.step();
/// }
/// }).unwrap();
///
/// let extract = recv.extract();
/// for i in 0..10 {
/// assert_eq!(extract[i], (RootTimestamp::new(i), vec![i]));
/// }
/// ```
fn new_unordered_input<D:Data>(&mut self) -> ((UnorderedHandle<G::Timestamp, D>, Capability<G::Timestamp>), Stream<G, D>);
}
impl<G: Scope> UnorderedInput<G> for G {
fn new_unordered_input<D:Data>(&mut self) -> ((UnorderedHandle<G::Timestamp, D>, Capability<G::Timestamp>), Stream<G, D>) {
let (output, registrar) = Tee::<G::Timestamp, D>::new();
let internal = Rc::new(RefCell::new(CountMap::new()));
let produced = Rc::new(RefCell::new(CountMap::new()));
let cap = mint_capability(Default::default(), internal.clone());
let helper = UnorderedHandle::new(PushCounter::new(output, produced.clone()));
let peers = self.peers();
let index = self.add_operator(UnorderedOperator {
internal: internal.clone(),
produced: produced.clone(),
peers: peers,
});
return ((helper, cap), Stream::new(Source { index: index, port: 0 }, registrar, self.clone()));
}
}
struct UnorderedOperator<T:Timestamp> {
internal: Rc<RefCell<CountMap<T>>>,
produced: Rc<RefCell<CountMap<T>>>,
peers: usize,
}
impl<T:Timestamp> Operate<T> for UnorderedOperator<T> {
fn name(&self) -> String { "Input".to_owned() }
fn inputs(&self) -> usize { 0 }
fn outputs(&self) -> usize { 1 }
fn get_internal_summary(&mut self) -> (Vec<Vec<Antichain<<T as Timestamp>::Summary>>>,
Vec<CountMap<T>>) {
let mut internal = CountMap::new();
// augment the counts for each reserved capability.
for &(ref time, count) in self.internal.borrow().iter() {
internal.update(time, count * (self.peers as i64 - 1));
}
// drain the changes to empty out, and complete the counts for internal.
self.internal.borrow_mut().drain_into(&mut internal);
(Vec::new(), vec![internal])
}
fn pull_internal_progress(&mut self,_consumed: &mut [CountMap<T>],
internal: &mut [CountMap<T>],
produced: &mut [CountMap<T>]) -> bool
{
self.produced.borrow_mut().drain_into(&mut produced[0]);
self.internal.borrow_mut().drain_into(&mut internal[0]);
return false;
}
fn notify_me(&self) -> bool { false }
}
/// A handle to an input `Stream`, used to introduce data to a timely dataflow computation.
pub struct UnorderedHandle<T: Timestamp, D: Data> {
buffer: PushBuffer<T, D, PushCounter<T, D, Tee<T, D>>>,
}
impl<T: Timestamp, D: Data> UnorderedHandle<T, D> {
fn new(pusher: PushCounter<T, D, Tee<T, D>>) -> UnorderedHandle<T, D> {
UnorderedHandle {
buffer: PushBuffer::new(pusher),
}
}
| }
impl<T: Timestamp, D: Data> Drop for UnorderedHandle<T, D> {
fn drop(&mut self) {
// TODO: explode if not all capabilities were given up?
}
} | /// Allocates a new automatically flushing session based on the supplied capability.
pub fn session<'b>(&'b mut self, cap: Capability<T>) -> AutoflushSession<'b, T, D, PushCounter<T, D, Tee<T, D>>> {
self.buffer.autoflush_session(cap)
} | random_line_split |
availability_set.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .resource import Resource
class AvailabilitySet(Resource):
"""Create or update availability set parameters.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id
:vartype id: str
:ivar name: Resource name
:vartype name: str
:ivar type: Resource type
:vartype type: str
:param location: Resource location
:type location: str
:param tags: Resource tags
:type tags: dict
:param platform_update_domain_count: Update Domain count.
:type platform_update_domain_count: int
:param platform_fault_domain_count: Fault Domain count.
:type platform_fault_domain_count: int
:param virtual_machines: A list of references to all virtual machines in
the availability set.
:type virtual_machines: list of :class:`SubResource
<azure.mgmt.compute.models.SubResource>`
:ivar statuses: The resource status information. | :type sku: :class:`Sku <azure.mgmt.compute.models.Sku>`
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'location': {'required': True},
'statuses': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'platform_update_domain_count': {'key': 'properties.platformUpdateDomainCount', 'type': 'int'},
'platform_fault_domain_count': {'key': 'properties.platformFaultDomainCount', 'type': 'int'},
'virtual_machines': {'key': 'properties.virtualMachines', 'type': '[SubResource]'},
'statuses': {'key': 'properties.statuses', 'type': '[InstanceViewStatus]'},
'managed': {'key': 'properties.managed', 'type': 'bool'},
'sku': {'key': 'sku', 'type': 'Sku'},
}
def __init__(self, location, tags=None, platform_update_domain_count=None, platform_fault_domain_count=None, virtual_machines=None, managed=None, sku=None):
super(AvailabilitySet, self).__init__(location=location, tags=tags)
self.platform_update_domain_count = platform_update_domain_count
self.platform_fault_domain_count = platform_fault_domain_count
self.virtual_machines = virtual_machines
self.statuses = None
self.managed = managed
self.sku = sku | :vartype statuses: list of :class:`InstanceViewStatus
<azure.mgmt.compute.models.InstanceViewStatus>`
:param managed: If the availability set supports managed disks.
:type managed: bool
:param sku: Sku of the availability set | random_line_split |
availability_set.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .resource import Resource
class AvailabilitySet(Resource):
"""Create or update availability set parameters.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id
:vartype id: str
:ivar name: Resource name
:vartype name: str
:ivar type: Resource type
:vartype type: str
:param location: Resource location
:type location: str
:param tags: Resource tags
:type tags: dict
:param platform_update_domain_count: Update Domain count.
:type platform_update_domain_count: int
:param platform_fault_domain_count: Fault Domain count.
:type platform_fault_domain_count: int
:param virtual_machines: A list of references to all virtual machines in
the availability set.
:type virtual_machines: list of :class:`SubResource
<azure.mgmt.compute.models.SubResource>`
:ivar statuses: The resource status information.
:vartype statuses: list of :class:`InstanceViewStatus
<azure.mgmt.compute.models.InstanceViewStatus>`
:param managed: If the availability set supports managed disks.
:type managed: bool
:param sku: Sku of the availability set
:type sku: :class:`Sku <azure.mgmt.compute.models.Sku>`
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'location': {'required': True},
'statuses': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'platform_update_domain_count': {'key': 'properties.platformUpdateDomainCount', 'type': 'int'},
'platform_fault_domain_count': {'key': 'properties.platformFaultDomainCount', 'type': 'int'},
'virtual_machines': {'key': 'properties.virtualMachines', 'type': '[SubResource]'},
'statuses': {'key': 'properties.statuses', 'type': '[InstanceViewStatus]'},
'managed': {'key': 'properties.managed', 'type': 'bool'},
'sku': {'key': 'sku', 'type': 'Sku'},
}
def | (self, location, tags=None, platform_update_domain_count=None, platform_fault_domain_count=None, virtual_machines=None, managed=None, sku=None):
super(AvailabilitySet, self).__init__(location=location, tags=tags)
self.platform_update_domain_count = platform_update_domain_count
self.platform_fault_domain_count = platform_fault_domain_count
self.virtual_machines = virtual_machines
self.statuses = None
self.managed = managed
self.sku = sku
| __init__ | identifier_name |
availability_set.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .resource import Resource
class AvailabilitySet(Resource):
"""Create or update availability set parameters.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id
:vartype id: str
:ivar name: Resource name
:vartype name: str
:ivar type: Resource type
:vartype type: str
:param location: Resource location
:type location: str
:param tags: Resource tags
:type tags: dict
:param platform_update_domain_count: Update Domain count.
:type platform_update_domain_count: int
:param platform_fault_domain_count: Fault Domain count.
:type platform_fault_domain_count: int
:param virtual_machines: A list of references to all virtual machines in
the availability set.
:type virtual_machines: list of :class:`SubResource
<azure.mgmt.compute.models.SubResource>`
:ivar statuses: The resource status information.
:vartype statuses: list of :class:`InstanceViewStatus
<azure.mgmt.compute.models.InstanceViewStatus>`
:param managed: If the availability set supports managed disks.
:type managed: bool
:param sku: Sku of the availability set
:type sku: :class:`Sku <azure.mgmt.compute.models.Sku>`
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'location': {'required': True},
'statuses': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'platform_update_domain_count': {'key': 'properties.platformUpdateDomainCount', 'type': 'int'},
'platform_fault_domain_count': {'key': 'properties.platformFaultDomainCount', 'type': 'int'},
'virtual_machines': {'key': 'properties.virtualMachines', 'type': '[SubResource]'},
'statuses': {'key': 'properties.statuses', 'type': '[InstanceViewStatus]'},
'managed': {'key': 'properties.managed', 'type': 'bool'},
'sku': {'key': 'sku', 'type': 'Sku'},
}
def __init__(self, location, tags=None, platform_update_domain_count=None, platform_fault_domain_count=None, virtual_machines=None, managed=None, sku=None):
| super(AvailabilitySet, self).__init__(location=location, tags=tags)
self.platform_update_domain_count = platform_update_domain_count
self.platform_fault_domain_count = platform_fault_domain_count
self.virtual_machines = virtual_machines
self.statuses = None
self.managed = managed
self.sku = sku | identifier_body | |
homepage.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Mathieu Jourdan
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob 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 weboob. If not, see <http://www.gnu.org/licenses/>.
from datetime import date
from weboob.deprecated.browser import Page
from weboob.capabilities.bill import Subscription
class LoginPage(Page):
def login(self, login, password):
self.browser.select_form('symConnexionForm')
self.browser["portlet_login_plein_page_3{pageFlow.mForm.login}"] = unicode(login)
self.browser["portlet_login_plein_page_3{pageFlow.mForm.password}"] = unicode(password)
self.browser.submit()
class HomePage(Page):
def on_loaded(self):
pass
class AccountPage(Page):
def get_subscription_list(self):
table = self.document.xpath('//table[@id="ensemble_contrat_N0"]')[0]
if len(table) > 0:
# some clients may have subscriptions to gas and electricity,
# but they receive a single bill
# to avoid "boobill details" and "boobill bills" returning the same
# table twice, we could return only one subscription for both.
# We do not, and "boobill details" will take care of parsing only the
# relevant section in the bill files.
for line in table[0].xpath('//tbody/tr'):
|
class TimeoutPage(Page):
def on_loaded(self):
pass
| cells = line.xpath('td')
snumber = cells[2].attrib['id'].replace('Contrat_', '')
slabel = cells[0].xpath('a')[0].text.replace('offre', '').strip()
d = unicode(cells[3].xpath('strong')[0].text.strip())
sdate = date(*reversed([int(x) for x in d.split("/")]))
sub = Subscription(snumber)
sub._id = snumber
sub.label = slabel
sub.subscriber = unicode(cells[1])
sub.renewdate = sdate
yield sub | conditional_block |
homepage.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Mathieu Jourdan
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob 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 weboob. If not, see <http://www.gnu.org/licenses/>.
from datetime import date
from weboob.deprecated.browser import Page
from weboob.capabilities.bill import Subscription
class | (Page):
def login(self, login, password):
self.browser.select_form('symConnexionForm')
self.browser["portlet_login_plein_page_3{pageFlow.mForm.login}"] = unicode(login)
self.browser["portlet_login_plein_page_3{pageFlow.mForm.password}"] = unicode(password)
self.browser.submit()
class HomePage(Page):
def on_loaded(self):
pass
class AccountPage(Page):
def get_subscription_list(self):
table = self.document.xpath('//table[@id="ensemble_contrat_N0"]')[0]
if len(table) > 0:
# some clients may have subscriptions to gas and electricity,
# but they receive a single bill
# to avoid "boobill details" and "boobill bills" returning the same
# table twice, we could return only one subscription for both.
# We do not, and "boobill details" will take care of parsing only the
# relevant section in the bill files.
for line in table[0].xpath('//tbody/tr'):
cells = line.xpath('td')
snumber = cells[2].attrib['id'].replace('Contrat_', '')
slabel = cells[0].xpath('a')[0].text.replace('offre', '').strip()
d = unicode(cells[3].xpath('strong')[0].text.strip())
sdate = date(*reversed([int(x) for x in d.split("/")]))
sub = Subscription(snumber)
sub._id = snumber
sub.label = slabel
sub.subscriber = unicode(cells[1])
sub.renewdate = sdate
yield sub
class TimeoutPage(Page):
def on_loaded(self):
pass
| LoginPage | identifier_name |
homepage.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Mathieu Jourdan
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob 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 weboob. If not, see <http://www.gnu.org/licenses/>.
from datetime import date
from weboob.deprecated.browser import Page
from weboob.capabilities.bill import Subscription
class LoginPage(Page):
|
class HomePage(Page):
def on_loaded(self):
pass
class AccountPage(Page):
def get_subscription_list(self):
table = self.document.xpath('//table[@id="ensemble_contrat_N0"]')[0]
if len(table) > 0:
# some clients may have subscriptions to gas and electricity,
# but they receive a single bill
# to avoid "boobill details" and "boobill bills" returning the same
# table twice, we could return only one subscription for both.
# We do not, and "boobill details" will take care of parsing only the
# relevant section in the bill files.
for line in table[0].xpath('//tbody/tr'):
cells = line.xpath('td')
snumber = cells[2].attrib['id'].replace('Contrat_', '')
slabel = cells[0].xpath('a')[0].text.replace('offre', '').strip()
d = unicode(cells[3].xpath('strong')[0].text.strip())
sdate = date(*reversed([int(x) for x in d.split("/")]))
sub = Subscription(snumber)
sub._id = snumber
sub.label = slabel
sub.subscriber = unicode(cells[1])
sub.renewdate = sdate
yield sub
class TimeoutPage(Page):
def on_loaded(self):
pass
| def login(self, login, password):
self.browser.select_form('symConnexionForm')
self.browser["portlet_login_plein_page_3{pageFlow.mForm.login}"] = unicode(login)
self.browser["portlet_login_plein_page_3{pageFlow.mForm.password}"] = unicode(password)
self.browser.submit() | identifier_body |
homepage.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Mathieu Jourdan
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob 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 weboob. If not, see <http://www.gnu.org/licenses/>.
from datetime import date
from weboob.deprecated.browser import Page
from weboob.capabilities.bill import Subscription
class LoginPage(Page):
def login(self, login, password):
self.browser.select_form('symConnexionForm')
self.browser["portlet_login_plein_page_3{pageFlow.mForm.login}"] = unicode(login)
self.browser["portlet_login_plein_page_3{pageFlow.mForm.password}"] = unicode(password)
self.browser.submit()
class HomePage(Page):
def on_loaded(self):
pass
class AccountPage(Page):
def get_subscription_list(self):
table = self.document.xpath('//table[@id="ensemble_contrat_N0"]')[0]
if len(table) > 0:
# some clients may have subscriptions to gas and electricity,
# but they receive a single bill
# to avoid "boobill details" and "boobill bills" returning the same
# table twice, we could return only one subscription for both.
# We do not, and "boobill details" will take care of parsing only the
# relevant section in the bill files.
for line in table[0].xpath('//tbody/tr'):
cells = line.xpath('td')
snumber = cells[2].attrib['id'].replace('Contrat_', '')
slabel = cells[0].xpath('a')[0].text.replace('offre', '').strip()
d = unicode(cells[3].xpath('strong')[0].text.strip())
sdate = date(*reversed([int(x) for x in d.split("/")]))
sub = Subscription(snumber)
sub._id = snumber
sub.label = slabel
sub.subscriber = unicode(cells[1])
sub.renewdate = sdate
yield sub
|
class TimeoutPage(Page):
def on_loaded(self):
pass | random_line_split | |
forms.py | # -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _
from taggit.forms import TagField
from places_core.forms import BootstrapBaseForm
from .models import Category, News
class NewsForm(forms.ModelForm, BootstrapBaseForm):
""" Edit/update/create blog entry. """
title = forms.CharField(
label=_(u"Da tytuł"),
max_length=64,
widget=forms.TextInput(attrs={
'class': 'form-control',
'maxlength': '64',}))
tags = TagField(required=False, label= _(u"Tags"))
def clean_title(self):
title = self.cleaned_data['title']
return title
class M |
model = News
exclude = ('edited', 'slug', 'creator',)
widgets = {
'content': forms.Textarea(attrs={'class': 'form-control custom-wysiwyg'}),
'category': forms.Select(attrs={'class': 'form-control'}),
'location': forms.HiddenInput(),
'image': forms.ClearableFileInput(attrs={'class': 'civ-img-input', }),
}
| eta: | identifier_name |
forms.py | # -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _
from taggit.forms import TagField
from places_core.forms import BootstrapBaseForm
from .models import Category, News
class NewsForm(forms.ModelForm, BootstrapBaseForm):
""" Edit/update/create blog entry. """
title = forms.CharField(
label=_(u"Da tytuł"),
max_length=64,
widget=forms.TextInput(attrs={
'class': 'form-control',
'maxlength': '64',}))
tags = TagField(required=False, label= _(u"Tags"))
def clean_title(self):
title = self.cleaned_data['title']
return title
class Meta:
m | odel = News
exclude = ('edited', 'slug', 'creator',)
widgets = {
'content': forms.Textarea(attrs={'class': 'form-control custom-wysiwyg'}),
'category': forms.Select(attrs={'class': 'form-control'}),
'location': forms.HiddenInput(),
'image': forms.ClearableFileInput(attrs={'class': 'civ-img-input', }),
}
| identifier_body | |
forms.py | # -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _
from taggit.forms import TagField
from places_core.forms import BootstrapBaseForm
from .models import Category, News
class NewsForm(forms.ModelForm, BootstrapBaseForm):
""" Edit/update/create blog entry. """
title = forms.CharField(
label=_(u"Da tytuł"),
max_length=64,
widget=forms.TextInput(attrs={
'class': 'form-control',
'maxlength': '64',}))
tags = TagField(required=False, label= _(u"Tags"))
def clean_title(self):
title = self.cleaned_data['title']
return title
class Meta:
model = News | 'category': forms.Select(attrs={'class': 'form-control'}),
'location': forms.HiddenInput(),
'image': forms.ClearableFileInput(attrs={'class': 'civ-img-input', }),
} | exclude = ('edited', 'slug', 'creator',)
widgets = {
'content': forms.Textarea(attrs={'class': 'form-control custom-wysiwyg'}), | random_line_split |
main.js | // The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import { sync } from 'vuex-router-sync'
import App from './views/App'
import router from './router'
import store from './store'
import Buefy from 'buefy'
import 'buefy/dist/buefy.css'
import 'bulma-divider'
import Moment from 'vue-moment'
import i18next from 'i18next'
import i18nOption from './settings/i18next'
import VueI18Next from '@panter/vue-i18next'
import VeeValidate, { Validator } from 'vee-validate'
import ko from 'vee-validate/dist/locale/ko'
import $ from 'jquery'
Vue.use({
install: function(Vue){
Vue.prototype.$jQuery = $; // you'll have this.$jQuery anywhere in your vue project
}
})
Vue.use(Buefy)
Vue.use(Moment)
Vue.use(VueI18Next)
sync(store, router)
var lang = $('html').attr('lang')
lang !== undefined
? i18nOption.lng = lang
: i18nOption.lng = 'en'
i18next.init(i18nOption)
const i18n = new VueI18Next(i18next)
Vue.config.productionTip = false
Vue.use(VeeValidate, {
locale: 'ko'
})
Validator.localize('ko', ko)
/* eslint-disable no-new */
new Vue({
el: '#app',
router: router,
store: store,
i18n: i18n,
render: h => h(App)
})
// Check local storage to handle refreshes | store.commit('SET_USER', localUser)
store.commit('SET_IS_AUTHENTICATED', window.localStorage.getItem('isAuthenticated'))
}
} | if (window.localStorage) {
var localUserString = window.localStorage.getItem('user') || 'null'
var localUser = JSON.parse(localUserString)
if (localUser && store.state.user !== localUser) { | random_line_split |
main.js | // The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import { sync } from 'vuex-router-sync'
import App from './views/App'
import router from './router'
import store from './store'
import Buefy from 'buefy'
import 'buefy/dist/buefy.css'
import 'bulma-divider'
import Moment from 'vue-moment'
import i18next from 'i18next'
import i18nOption from './settings/i18next'
import VueI18Next from '@panter/vue-i18next'
import VeeValidate, { Validator } from 'vee-validate'
import ko from 'vee-validate/dist/locale/ko'
import $ from 'jquery'
Vue.use({
install: function(Vue){
Vue.prototype.$jQuery = $; // you'll have this.$jQuery anywhere in your vue project
}
})
Vue.use(Buefy)
Vue.use(Moment)
Vue.use(VueI18Next)
sync(store, router)
var lang = $('html').attr('lang')
lang !== undefined
? i18nOption.lng = lang
: i18nOption.lng = 'en'
i18next.init(i18nOption)
const i18n = new VueI18Next(i18next)
Vue.config.productionTip = false
Vue.use(VeeValidate, {
locale: 'ko'
})
Validator.localize('ko', ko)
/* eslint-disable no-new */
new Vue({
el: '#app',
router: router,
store: store,
i18n: i18n,
render: h => h(App)
})
// Check local storage to handle refreshes
if (window.localStorage) {
var localUserString = window.localStorage.getItem('user') || 'null'
var localUser = JSON.parse(localUserString)
if (localUser && store.state.user !== localUser) |
}
| {
store.commit('SET_USER', localUser)
store.commit('SET_IS_AUTHENTICATED', window.localStorage.getItem('isAuthenticated'))
} | conditional_block |
saveMember.ts | import { FormValidationResult } from 'lc-form-validation';
import * as toastr from 'toastr';
import { actionTypes } from '../../../common/constants/actionTypes';
import { MemberEntity } from '../../../model';
import { memberAPI } from '../../../api/member';
import { memberFormValidation } from '../memberFormValidation';
import {trackPromise} from 'react-promise-tracker';
export const saveMemberAction = (member: MemberEntity) => (dispatch) => {
trackPromise(
memberFormValidation.validateForm(member)
.then((formValidationResult) => {
if (formValidationResult.succeeded) |
dispatch(saveMemberActionCompleted(formValidationResult));
})
);
};
const saveMember = (member: MemberEntity) => {
trackPromise(
memberAPI.saveMember(member)
.then(() => {
toastr.success('Member saved.');
history.back();
})
.catch(toastr.error)
);
};
const saveMemberActionCompleted = (formValidationResult: FormValidationResult) => ({
type: actionTypes.SAVE_MEMBER,
payload: formValidationResult,
});
| {
saveMember(member);
} | conditional_block |
saveMember.ts | import { FormValidationResult } from 'lc-form-validation';
import * as toastr from 'toastr';
import { actionTypes } from '../../../common/constants/actionTypes';
import { MemberEntity } from '../../../model';
import { memberAPI } from '../../../api/member';
import { memberFormValidation } from '../memberFormValidation';
import {trackPromise} from 'react-promise-tracker';
export const saveMemberAction = (member: MemberEntity) => (dispatch) => {
trackPromise(
memberFormValidation.validateForm(member)
.then((formValidationResult) => {
if (formValidationResult.succeeded) {
saveMember(member);
}
dispatch(saveMemberActionCompleted(formValidationResult));
})
);
};
const saveMember = (member: MemberEntity) => {
trackPromise(
memberAPI.saveMember(member)
.then(() => {
toastr.success('Member saved.');
history.back(); | );
};
const saveMemberActionCompleted = (formValidationResult: FormValidationResult) => ({
type: actionTypes.SAVE_MEMBER,
payload: formValidationResult,
}); | })
.catch(toastr.error) | random_line_split |
cols_dimensionality.py | 'output dimensionalities for each column'
import csv
import sys
import re
import math
from collections import defaultdict
def get_words( text ):
text = text.replace( "'", "" )
text = re.sub( r'\W+', ' ', text )
text = text.lower()
text = text.split()
words = []
for w in text:
if w in words:
continue
words.append( w )
return words
###
csv.field_size_limit( 1000000 )
input_file = sys.argv[1]
target_col = 'SalaryNormalized'
cols2tokenize = [ 'Title', 'FullDescription' ]
cols2binarize = [ 'Loc1', 'Loc2', 'Loc3', 'Loc4', 'ContractType', 'ContractTime', 'Company', 'Category', 'SourceName' ]
cols2drop = [ 'SalaryRaw' ]
###
i_f = open( input_file )
reader = csv.reader( i_f )
headers = reader.next()
target_index = headers.index( target_col )
indexes2tokenize = map( lambda x: headers.index( x ), cols2tokenize )
indexes2binarize = map( lambda x: headers.index( x ), cols2binarize )
indexes2drop = map( lambda x: headers.index( x ), cols2drop )
n = 0
unique_values = defaultdict( set )
for line in reader:
|
# print counts
for i in sorted( unique_values ):
l = len( unique_values[i] )
print "index: %s, count: %s" % ( i, l )
if l < 100:
pass
# print unique_values[i]
| for i in indexes2binarize:
value = line[i]
unique_values[i].add( value )
for i in indexes2tokenize:
words = get_words( line[i] )
unique_values[i].update( words )
n += 1
if n % 10000 == 0:
print n | conditional_block |
cols_dimensionality.py | 'output dimensionalities for each column'
import csv
import sys
import re
import math
from collections import defaultdict
def get_words( text ):
|
###
csv.field_size_limit( 1000000 )
input_file = sys.argv[1]
target_col = 'SalaryNormalized'
cols2tokenize = [ 'Title', 'FullDescription' ]
cols2binarize = [ 'Loc1', 'Loc2', 'Loc3', 'Loc4', 'ContractType', 'ContractTime', 'Company', 'Category', 'SourceName' ]
cols2drop = [ 'SalaryRaw' ]
###
i_f = open( input_file )
reader = csv.reader( i_f )
headers = reader.next()
target_index = headers.index( target_col )
indexes2tokenize = map( lambda x: headers.index( x ), cols2tokenize )
indexes2binarize = map( lambda x: headers.index( x ), cols2binarize )
indexes2drop = map( lambda x: headers.index( x ), cols2drop )
n = 0
unique_values = defaultdict( set )
for line in reader:
for i in indexes2binarize:
value = line[i]
unique_values[i].add( value )
for i in indexes2tokenize:
words = get_words( line[i] )
unique_values[i].update( words )
n += 1
if n % 10000 == 0:
print n
# print counts
for i in sorted( unique_values ):
l = len( unique_values[i] )
print "index: %s, count: %s" % ( i, l )
if l < 100:
pass
# print unique_values[i]
| text = text.replace( "'", "" )
text = re.sub( r'\W+', ' ', text )
text = text.lower()
text = text.split()
words = []
for w in text:
if w in words:
continue
words.append( w )
return words | identifier_body |
cols_dimensionality.py | 'output dimensionalities for each column'
import csv
import sys
import re
import math
from collections import defaultdict
def get_words( text ):
text = text.replace( "'", "" )
text = re.sub( r'\W+', ' ', text )
text = text.lower()
text = text.split()
words = []
for w in text:
if w in words:
continue
words.append( w )
return words
###
csv.field_size_limit( 1000000 )
input_file = sys.argv[1]
target_col = 'SalaryNormalized'
cols2tokenize = [ 'Title', 'FullDescription' ] |
i_f = open( input_file )
reader = csv.reader( i_f )
headers = reader.next()
target_index = headers.index( target_col )
indexes2tokenize = map( lambda x: headers.index( x ), cols2tokenize )
indexes2binarize = map( lambda x: headers.index( x ), cols2binarize )
indexes2drop = map( lambda x: headers.index( x ), cols2drop )
n = 0
unique_values = defaultdict( set )
for line in reader:
for i in indexes2binarize:
value = line[i]
unique_values[i].add( value )
for i in indexes2tokenize:
words = get_words( line[i] )
unique_values[i].update( words )
n += 1
if n % 10000 == 0:
print n
# print counts
for i in sorted( unique_values ):
l = len( unique_values[i] )
print "index: %s, count: %s" % ( i, l )
if l < 100:
pass
# print unique_values[i] | cols2binarize = [ 'Loc1', 'Loc2', 'Loc3', 'Loc4', 'ContractType', 'ContractTime', 'Company', 'Category', 'SourceName' ]
cols2drop = [ 'SalaryRaw' ]
### | random_line_split |
cols_dimensionality.py | 'output dimensionalities for each column'
import csv
import sys
import re
import math
from collections import defaultdict
def | ( text ):
text = text.replace( "'", "" )
text = re.sub( r'\W+', ' ', text )
text = text.lower()
text = text.split()
words = []
for w in text:
if w in words:
continue
words.append( w )
return words
###
csv.field_size_limit( 1000000 )
input_file = sys.argv[1]
target_col = 'SalaryNormalized'
cols2tokenize = [ 'Title', 'FullDescription' ]
cols2binarize = [ 'Loc1', 'Loc2', 'Loc3', 'Loc4', 'ContractType', 'ContractTime', 'Company', 'Category', 'SourceName' ]
cols2drop = [ 'SalaryRaw' ]
###
i_f = open( input_file )
reader = csv.reader( i_f )
headers = reader.next()
target_index = headers.index( target_col )
indexes2tokenize = map( lambda x: headers.index( x ), cols2tokenize )
indexes2binarize = map( lambda x: headers.index( x ), cols2binarize )
indexes2drop = map( lambda x: headers.index( x ), cols2drop )
n = 0
unique_values = defaultdict( set )
for line in reader:
for i in indexes2binarize:
value = line[i]
unique_values[i].add( value )
for i in indexes2tokenize:
words = get_words( line[i] )
unique_values[i].update( words )
n += 1
if n % 10000 == 0:
print n
# print counts
for i in sorted( unique_values ):
l = len( unique_values[i] )
print "index: %s, count: %s" % ( i, l )
if l < 100:
pass
# print unique_values[i]
| get_words | identifier_name |
search_indexes.py | from __future__ import unicode_literals
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from haystack import indexes
from reviewboard.reviews.models import ReviewRequest
from reviewboard.search.indexes import BaseSearchIndex
class ReviewRequestIndex(BaseSearchIndex, indexes.Indexable):
"""A Haystack search index for Review Requests."""
model = ReviewRequest
local_site_attr = 'local_site_id'
# We shouldn't use 'id' as a field name because it's by default reserved
# for Haystack. Hiding it will cause duplicates when updating the index.
review_request_id = indexes.IntegerField(model_attr='display_id')
summary = indexes.CharField(model_attr='summary')
description = indexes.CharField(model_attr='description')
testing_done = indexes.CharField(model_attr='testing_done')
commit_id = indexes.EdgeNgramField(model_attr='commit', null=True)
bug = indexes.CharField(model_attr='bugs_closed')
username = indexes.CharField(model_attr='submitter__username')
author = indexes.CharField()
last_updated = indexes.DateTimeField(model_attr='last_updated')
url = indexes.CharField(model_attr='get_absolute_url')
file = indexes.CharField()
# These fields all contain information needed to perform queries about
# whether a review request is accessible by a given user.
private = indexes.BooleanField()
private_repository_id = indexes.IntegerField()
private_target_groups = indexes.MultiValueField()
target_users = indexes.MultiValueField()
def get_model(self):
"""Returns the Django model for this index."""
return ReviewRequest
def get_updated_field(self):
return 'last_updated'
def index_queryset(self, using=None):
"""Index only public pending and submitted review requests."""
return (
self.get_model().objects
.public(status=None,
show_all_local_sites=True,
show_inactive=True,
filter_private=False)
.select_related('diffset_history',
'local_site',
'repository',
'submitter',
'submitter__profile')
.prefetch_related('diffset_history__diffsets__files',
'target_groups',
'target_people')
)
def prepare_file(self, obj):
return set([
(filediff.source_file, filediff.dest_file)
for diffset in obj.diffset_history.diffsets.all()
for filediff in diffset.files.all()
])
def prepare_private(self, review_request):
"""Prepare the private flag for the index.
This will be set to true if the review request isn't generally
accessible to users.
"""
return not review_request.is_accessible_by(AnonymousUser(),
silent=True)
def prepare_private_repository_id(self, review_request):
"""Prepare the private repository ID, if any, for the index.
If there's no repository, or it's public, 0 will be returned instead.
"""
if review_request.repository and not review_request.repository.public:
return review_request.repository_id
else:
return 0
def prepare_private_target_groups(self, review_request):
"""Prepare the list of invite-only target groups for the index.
If there aren't any invite-only groups associated, ``[0]`` will be
returned. This allows queries to be performed that check that none
of the groups are private, since we can't query against empty lists.
"""
return [
group.pk
for group in review_request.target_groups.all()
if group.invite_only
] or [0]
def | (self, review_request):
"""Prepare the list of target users for the index.
If there aren't any target users, ``[0]`` will be returned. This
allows queries to be performed that check that there aren't any
users in the list, since we can't query against empty lists.
"""
return [
user.pk
for user in review_request.target_people.all()
] or [0]
def prepare_author(self, review_request):
"""Prepare the author field.
Args:
review_request (reviewboard.reviews.models.review_request.
ReviewRequest):
The review request being indexed.
Returns:
unicode:
Either the author's full name (if their profile is public) or an
empty string.
"""
user = review_request.submitter
profile = user.get_profile(cached_only=True)
if profile is None or profile.is_private:
return ''
return user.get_full_name()
| prepare_target_users | identifier_name |
search_indexes.py | from __future__ import unicode_literals
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from haystack import indexes
from reviewboard.reviews.models import ReviewRequest
from reviewboard.search.indexes import BaseSearchIndex
class ReviewRequestIndex(BaseSearchIndex, indexes.Indexable):
"""A Haystack search index for Review Requests."""
model = ReviewRequest
local_site_attr = 'local_site_id'
# We shouldn't use 'id' as a field name because it's by default reserved
# for Haystack. Hiding it will cause duplicates when updating the index.
review_request_id = indexes.IntegerField(model_attr='display_id')
summary = indexes.CharField(model_attr='summary')
description = indexes.CharField(model_attr='description')
testing_done = indexes.CharField(model_attr='testing_done')
commit_id = indexes.EdgeNgramField(model_attr='commit', null=True)
bug = indexes.CharField(model_attr='bugs_closed')
username = indexes.CharField(model_attr='submitter__username')
author = indexes.CharField()
last_updated = indexes.DateTimeField(model_attr='last_updated')
url = indexes.CharField(model_attr='get_absolute_url')
file = indexes.CharField()
# These fields all contain information needed to perform queries about
# whether a review request is accessible by a given user.
private = indexes.BooleanField()
private_repository_id = indexes.IntegerField()
private_target_groups = indexes.MultiValueField()
target_users = indexes.MultiValueField()
def get_model(self):
"""Returns the Django model for this index."""
return ReviewRequest
def get_updated_field(self):
return 'last_updated'
def index_queryset(self, using=None):
"""Index only public pending and submitted review requests."""
return (
self.get_model().objects
.public(status=None,
show_all_local_sites=True,
show_inactive=True,
filter_private=False)
.select_related('diffset_history',
'local_site',
'repository',
'submitter',
'submitter__profile')
.prefetch_related('diffset_history__diffsets__files',
'target_groups',
'target_people')
)
def prepare_file(self, obj):
return set([
(filediff.source_file, filediff.dest_file)
for diffset in obj.diffset_history.diffsets.all()
for filediff in diffset.files.all()
])
def prepare_private(self, review_request):
"""Prepare the private flag for the index.
This will be set to true if the review request isn't generally
accessible to users.
"""
return not review_request.is_accessible_by(AnonymousUser(),
silent=True)
def prepare_private_repository_id(self, review_request):
"""Prepare the private repository ID, if any, for the index.
If there's no repository, or it's public, 0 will be returned instead.
"""
if review_request.repository and not review_request.repository.public:
|
else:
return 0
def prepare_private_target_groups(self, review_request):
"""Prepare the list of invite-only target groups for the index.
If there aren't any invite-only groups associated, ``[0]`` will be
returned. This allows queries to be performed that check that none
of the groups are private, since we can't query against empty lists.
"""
return [
group.pk
for group in review_request.target_groups.all()
if group.invite_only
] or [0]
def prepare_target_users(self, review_request):
"""Prepare the list of target users for the index.
If there aren't any target users, ``[0]`` will be returned. This
allows queries to be performed that check that there aren't any
users in the list, since we can't query against empty lists.
"""
return [
user.pk
for user in review_request.target_people.all()
] or [0]
def prepare_author(self, review_request):
"""Prepare the author field.
Args:
review_request (reviewboard.reviews.models.review_request.
ReviewRequest):
The review request being indexed.
Returns:
unicode:
Either the author's full name (if their profile is public) or an
empty string.
"""
user = review_request.submitter
profile = user.get_profile(cached_only=True)
if profile is None or profile.is_private:
return ''
return user.get_full_name()
| return review_request.repository_id | conditional_block |
search_indexes.py | from __future__ import unicode_literals
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from haystack import indexes
from reviewboard.reviews.models import ReviewRequest
from reviewboard.search.indexes import BaseSearchIndex
class ReviewRequestIndex(BaseSearchIndex, indexes.Indexable):
"""A Haystack search index for Review Requests."""
model = ReviewRequest
local_site_attr = 'local_site_id'
# We shouldn't use 'id' as a field name because it's by default reserved
# for Haystack. Hiding it will cause duplicates when updating the index.
review_request_id = indexes.IntegerField(model_attr='display_id')
summary = indexes.CharField(model_attr='summary')
description = indexes.CharField(model_attr='description')
testing_done = indexes.CharField(model_attr='testing_done')
commit_id = indexes.EdgeNgramField(model_attr='commit', null=True)
bug = indexes.CharField(model_attr='bugs_closed')
username = indexes.CharField(model_attr='submitter__username')
author = indexes.CharField()
last_updated = indexes.DateTimeField(model_attr='last_updated')
url = indexes.CharField(model_attr='get_absolute_url')
file = indexes.CharField()
# These fields all contain information needed to perform queries about
# whether a review request is accessible by a given user.
private = indexes.BooleanField()
private_repository_id = indexes.IntegerField()
private_target_groups = indexes.MultiValueField()
target_users = indexes.MultiValueField()
def get_model(self):
"""Returns the Django model for this index."""
return ReviewRequest
def get_updated_field(self):
return 'last_updated'
def index_queryset(self, using=None):
"""Index only public pending and submitted review requests."""
return (
self.get_model().objects
.public(status=None,
show_all_local_sites=True,
show_inactive=True,
filter_private=False)
.select_related('diffset_history',
'local_site',
'repository',
'submitter',
'submitter__profile') | 'target_people')
)
def prepare_file(self, obj):
return set([
(filediff.source_file, filediff.dest_file)
for diffset in obj.diffset_history.diffsets.all()
for filediff in diffset.files.all()
])
def prepare_private(self, review_request):
"""Prepare the private flag for the index.
This will be set to true if the review request isn't generally
accessible to users.
"""
return not review_request.is_accessible_by(AnonymousUser(),
silent=True)
def prepare_private_repository_id(self, review_request):
"""Prepare the private repository ID, if any, for the index.
If there's no repository, or it's public, 0 will be returned instead.
"""
if review_request.repository and not review_request.repository.public:
return review_request.repository_id
else:
return 0
def prepare_private_target_groups(self, review_request):
"""Prepare the list of invite-only target groups for the index.
If there aren't any invite-only groups associated, ``[0]`` will be
returned. This allows queries to be performed that check that none
of the groups are private, since we can't query against empty lists.
"""
return [
group.pk
for group in review_request.target_groups.all()
if group.invite_only
] or [0]
def prepare_target_users(self, review_request):
"""Prepare the list of target users for the index.
If there aren't any target users, ``[0]`` will be returned. This
allows queries to be performed that check that there aren't any
users in the list, since we can't query against empty lists.
"""
return [
user.pk
for user in review_request.target_people.all()
] or [0]
def prepare_author(self, review_request):
"""Prepare the author field.
Args:
review_request (reviewboard.reviews.models.review_request.
ReviewRequest):
The review request being indexed.
Returns:
unicode:
Either the author's full name (if their profile is public) or an
empty string.
"""
user = review_request.submitter
profile = user.get_profile(cached_only=True)
if profile is None or profile.is_private:
return ''
return user.get_full_name() | .prefetch_related('diffset_history__diffsets__files',
'target_groups', | random_line_split |
search_indexes.py | from __future__ import unicode_literals
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from haystack import indexes
from reviewboard.reviews.models import ReviewRequest
from reviewboard.search.indexes import BaseSearchIndex
class ReviewRequestIndex(BaseSearchIndex, indexes.Indexable):
| """A Haystack search index for Review Requests."""
model = ReviewRequest
local_site_attr = 'local_site_id'
# We shouldn't use 'id' as a field name because it's by default reserved
# for Haystack. Hiding it will cause duplicates when updating the index.
review_request_id = indexes.IntegerField(model_attr='display_id')
summary = indexes.CharField(model_attr='summary')
description = indexes.CharField(model_attr='description')
testing_done = indexes.CharField(model_attr='testing_done')
commit_id = indexes.EdgeNgramField(model_attr='commit', null=True)
bug = indexes.CharField(model_attr='bugs_closed')
username = indexes.CharField(model_attr='submitter__username')
author = indexes.CharField()
last_updated = indexes.DateTimeField(model_attr='last_updated')
url = indexes.CharField(model_attr='get_absolute_url')
file = indexes.CharField()
# These fields all contain information needed to perform queries about
# whether a review request is accessible by a given user.
private = indexes.BooleanField()
private_repository_id = indexes.IntegerField()
private_target_groups = indexes.MultiValueField()
target_users = indexes.MultiValueField()
def get_model(self):
"""Returns the Django model for this index."""
return ReviewRequest
def get_updated_field(self):
return 'last_updated'
def index_queryset(self, using=None):
"""Index only public pending and submitted review requests."""
return (
self.get_model().objects
.public(status=None,
show_all_local_sites=True,
show_inactive=True,
filter_private=False)
.select_related('diffset_history',
'local_site',
'repository',
'submitter',
'submitter__profile')
.prefetch_related('diffset_history__diffsets__files',
'target_groups',
'target_people')
)
def prepare_file(self, obj):
return set([
(filediff.source_file, filediff.dest_file)
for diffset in obj.diffset_history.diffsets.all()
for filediff in diffset.files.all()
])
def prepare_private(self, review_request):
"""Prepare the private flag for the index.
This will be set to true if the review request isn't generally
accessible to users.
"""
return not review_request.is_accessible_by(AnonymousUser(),
silent=True)
def prepare_private_repository_id(self, review_request):
"""Prepare the private repository ID, if any, for the index.
If there's no repository, or it's public, 0 will be returned instead.
"""
if review_request.repository and not review_request.repository.public:
return review_request.repository_id
else:
return 0
def prepare_private_target_groups(self, review_request):
"""Prepare the list of invite-only target groups for the index.
If there aren't any invite-only groups associated, ``[0]`` will be
returned. This allows queries to be performed that check that none
of the groups are private, since we can't query against empty lists.
"""
return [
group.pk
for group in review_request.target_groups.all()
if group.invite_only
] or [0]
def prepare_target_users(self, review_request):
"""Prepare the list of target users for the index.
If there aren't any target users, ``[0]`` will be returned. This
allows queries to be performed that check that there aren't any
users in the list, since we can't query against empty lists.
"""
return [
user.pk
for user in review_request.target_people.all()
] or [0]
def prepare_author(self, review_request):
"""Prepare the author field.
Args:
review_request (reviewboard.reviews.models.review_request.
ReviewRequest):
The review request being indexed.
Returns:
unicode:
Either the author's full name (if their profile is public) or an
empty string.
"""
user = review_request.submitter
profile = user.get_profile(cached_only=True)
if profile is None or profile.is_private:
return ''
return user.get_full_name() | identifier_body | |
package.rs | use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::hash;
use std::path::{Path, PathBuf};
use semver::Version;
use core::{Dependency, Manifest, PackageId, SourceId, Target, TargetKind};
use core::{Summary, Metadata, SourceMap};
use ops;
use util::{CargoResult, Config, LazyCell, ChainError, internal, human, lev_distance};
use rustc_serialize::{Encoder,Encodable};
/// Information about a package that is available somewhere in the file system.
///
/// A package is a `Cargo.toml` file plus all the files that are part of it.
// TODO: Is manifest_path a relic?
#[derive(Clone, Debug)]
pub struct Package {
// The package's manifest
manifest: Manifest,
// The root of the package
manifest_path: PathBuf,
}
#[derive(RustcEncodable)]
struct SerializedPackage<'a> {
name: &'a str,
version: &'a str,
id: &'a PackageId,
source: &'a SourceId,
dependencies: &'a [Dependency],
targets: &'a [Target],
features: &'a HashMap<String, Vec<String>>,
manifest_path: &'a str,
}
impl Encodable for Package {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
let summary = self.manifest.summary();
let package_id = summary.package_id();
SerializedPackage {
name: &package_id.name(),
version: &package_id.version().to_string(),
id: package_id,
source: summary.source_id(),
dependencies: summary.dependencies(),
targets: &self.manifest.targets(),
features: summary.features(),
manifest_path: &self.manifest_path.display().to_string(),
}.encode(s)
}
}
impl Package {
pub fn new(manifest: Manifest,
manifest_path: &Path) -> Package {
Package {
manifest: manifest,
manifest_path: manifest_path.to_path_buf(),
}
}
pub fn for_path(manifest_path: &Path, config: &Config) -> CargoResult<Package> |
pub fn dependencies(&self) -> &[Dependency] { self.manifest.dependencies() }
pub fn manifest(&self) -> &Manifest { &self.manifest }
pub fn manifest_path(&self) -> &Path { &self.manifest_path }
pub fn name(&self) -> &str { self.package_id().name() }
pub fn package_id(&self) -> &PackageId { self.manifest.package_id() }
pub fn root(&self) -> &Path { self.manifest_path.parent().unwrap() }
pub fn summary(&self) -> &Summary { self.manifest.summary() }
pub fn targets(&self) -> &[Target] { self.manifest().targets() }
pub fn version(&self) -> &Version { self.package_id().version() }
pub fn authors(&self) -> &Vec<String> { &self.manifest.metadata().authors }
pub fn publish(&self) -> bool { self.manifest.publish() }
pub fn has_custom_build(&self) -> bool {
self.targets().iter().any(|t| t.is_custom_build())
}
pub fn generate_metadata(&self) -> Metadata {
self.package_id().generate_metadata()
}
pub fn find_closest_target(&self, target: &str, kind: TargetKind) -> Option<&Target> {
let targets = self.targets();
let matches = targets.iter().filter(|t| *t.kind() == kind)
.map(|t| (lev_distance(target, t.name()), t))
.filter(|&(d, _)| d < 4);
matches.min_by_key(|t| t.0).map(|t| t.1)
}
}
impl fmt::Display for Package {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.summary().package_id())
}
}
impl PartialEq for Package {
fn eq(&self, other: &Package) -> bool {
self.package_id() == other.package_id()
}
}
impl Eq for Package {}
impl hash::Hash for Package {
fn hash<H: hash::Hasher>(&self, into: &mut H) {
self.package_id().hash(into)
}
}
pub struct PackageSet<'cfg> {
packages: Vec<(PackageId, LazyCell<Package>)>,
sources: RefCell<SourceMap<'cfg>>,
}
impl<'cfg> PackageSet<'cfg> {
pub fn new(package_ids: &[PackageId],
sources: SourceMap<'cfg>) -> PackageSet<'cfg> {
PackageSet {
packages: package_ids.iter().map(|id| {
(id.clone(), LazyCell::new(None))
}).collect(),
sources: RefCell::new(sources),
}
}
pub fn package_ids<'a>(&'a self) -> Box<Iterator<Item=&'a PackageId> + 'a> {
Box::new(self.packages.iter().map(|&(ref p, _)| p))
}
pub fn get(&self, id: &PackageId) -> CargoResult<&Package> {
let slot = try!(self.packages.iter().find(|p| p.0 == *id).chain_error(|| {
internal(format!("couldn't find `{}` in package set", id))
}));
let slot = &slot.1;
if let Some(pkg) = slot.borrow() {
return Ok(pkg)
}
let mut sources = self.sources.borrow_mut();
let source = try!(sources.get_mut(id.source_id()).chain_error(|| {
internal(format!("couldn't find source for `{}`", id))
}));
let pkg = try!(source.download(id).chain_error(|| {
human("unable to get packages from source")
}));
assert!(slot.fill(pkg).is_ok());
Ok(slot.borrow().unwrap())
}
pub fn sources(&self) -> Ref<SourceMap<'cfg>> {
self.sources.borrow()
}
}
| {
let path = manifest_path.parent().unwrap();
let source_id = try!(SourceId::for_path(path));
let (pkg, _) = try!(ops::read_package(&manifest_path, &source_id,
config));
Ok(pkg)
} | identifier_body |
package.rs | use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::hash;
use std::path::{Path, PathBuf};
use semver::Version;
use core::{Dependency, Manifest, PackageId, SourceId, Target, TargetKind};
use core::{Summary, Metadata, SourceMap};
use ops;
use util::{CargoResult, Config, LazyCell, ChainError, internal, human, lev_distance};
use rustc_serialize::{Encoder,Encodable};
/// Information about a package that is available somewhere in the file system.
///
/// A package is a `Cargo.toml` file plus all the files that are part of it.
// TODO: Is manifest_path a relic?
#[derive(Clone, Debug)]
pub struct Package {
// The package's manifest
manifest: Manifest,
// The root of the package
manifest_path: PathBuf,
}
#[derive(RustcEncodable)]
struct SerializedPackage<'a> {
name: &'a str,
version: &'a str,
id: &'a PackageId,
source: &'a SourceId,
dependencies: &'a [Dependency],
targets: &'a [Target],
features: &'a HashMap<String, Vec<String>>,
manifest_path: &'a str,
}
impl Encodable for Package {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
let summary = self.manifest.summary();
let package_id = summary.package_id();
SerializedPackage {
name: &package_id.name(),
version: &package_id.version().to_string(),
id: package_id,
source: summary.source_id(),
dependencies: summary.dependencies(),
targets: &self.manifest.targets(),
features: summary.features(),
manifest_path: &self.manifest_path.display().to_string(),
}.encode(s)
}
}
impl Package {
pub fn new(manifest: Manifest,
manifest_path: &Path) -> Package {
Package {
manifest: manifest,
manifest_path: manifest_path.to_path_buf(),
}
}
pub fn for_path(manifest_path: &Path, config: &Config) -> CargoResult<Package> {
let path = manifest_path.parent().unwrap();
let source_id = try!(SourceId::for_path(path));
let (pkg, _) = try!(ops::read_package(&manifest_path, &source_id,
config));
Ok(pkg)
}
pub fn dependencies(&self) -> &[Dependency] { self.manifest.dependencies() }
pub fn manifest(&self) -> &Manifest { &self.manifest }
pub fn manifest_path(&self) -> &Path { &self.manifest_path }
pub fn name(&self) -> &str { self.package_id().name() }
pub fn package_id(&self) -> &PackageId { self.manifest.package_id() }
pub fn root(&self) -> &Path { self.manifest_path.parent().unwrap() }
pub fn summary(&self) -> &Summary { self.manifest.summary() }
pub fn targets(&self) -> &[Target] { self.manifest().targets() }
pub fn version(&self) -> &Version { self.package_id().version() }
pub fn authors(&self) -> &Vec<String> { &self.manifest.metadata().authors }
pub fn publish(&self) -> bool { self.manifest.publish() }
pub fn has_custom_build(&self) -> bool {
self.targets().iter().any(|t| t.is_custom_build())
}
pub fn generate_metadata(&self) -> Metadata {
self.package_id().generate_metadata()
}
pub fn find_closest_target(&self, target: &str, kind: TargetKind) -> Option<&Target> {
let targets = self.targets();
let matches = targets.iter().filter(|t| *t.kind() == kind)
.map(|t| (lev_distance(target, t.name()), t))
.filter(|&(d, _)| d < 4);
matches.min_by_key(|t| t.0).map(|t| t.1)
}
}
impl fmt::Display for Package {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.summary().package_id())
}
}
impl PartialEq for Package {
fn eq(&self, other: &Package) -> bool {
self.package_id() == other.package_id()
}
}
impl Eq for Package {}
impl hash::Hash for Package {
fn hash<H: hash::Hasher>(&self, into: &mut H) {
self.package_id().hash(into)
}
}
pub struct PackageSet<'cfg> {
packages: Vec<(PackageId, LazyCell<Package>)>, | }
impl<'cfg> PackageSet<'cfg> {
pub fn new(package_ids: &[PackageId],
sources: SourceMap<'cfg>) -> PackageSet<'cfg> {
PackageSet {
packages: package_ids.iter().map(|id| {
(id.clone(), LazyCell::new(None))
}).collect(),
sources: RefCell::new(sources),
}
}
pub fn package_ids<'a>(&'a self) -> Box<Iterator<Item=&'a PackageId> + 'a> {
Box::new(self.packages.iter().map(|&(ref p, _)| p))
}
pub fn get(&self, id: &PackageId) -> CargoResult<&Package> {
let slot = try!(self.packages.iter().find(|p| p.0 == *id).chain_error(|| {
internal(format!("couldn't find `{}` in package set", id))
}));
let slot = &slot.1;
if let Some(pkg) = slot.borrow() {
return Ok(pkg)
}
let mut sources = self.sources.borrow_mut();
let source = try!(sources.get_mut(id.source_id()).chain_error(|| {
internal(format!("couldn't find source for `{}`", id))
}));
let pkg = try!(source.download(id).chain_error(|| {
human("unable to get packages from source")
}));
assert!(slot.fill(pkg).is_ok());
Ok(slot.borrow().unwrap())
}
pub fn sources(&self) -> Ref<SourceMap<'cfg>> {
self.sources.borrow()
}
} | sources: RefCell<SourceMap<'cfg>>, | random_line_split |
package.rs | use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::hash;
use std::path::{Path, PathBuf};
use semver::Version;
use core::{Dependency, Manifest, PackageId, SourceId, Target, TargetKind};
use core::{Summary, Metadata, SourceMap};
use ops;
use util::{CargoResult, Config, LazyCell, ChainError, internal, human, lev_distance};
use rustc_serialize::{Encoder,Encodable};
/// Information about a package that is available somewhere in the file system.
///
/// A package is a `Cargo.toml` file plus all the files that are part of it.
// TODO: Is manifest_path a relic?
#[derive(Clone, Debug)]
pub struct | {
// The package's manifest
manifest: Manifest,
// The root of the package
manifest_path: PathBuf,
}
#[derive(RustcEncodable)]
struct SerializedPackage<'a> {
name: &'a str,
version: &'a str,
id: &'a PackageId,
source: &'a SourceId,
dependencies: &'a [Dependency],
targets: &'a [Target],
features: &'a HashMap<String, Vec<String>>,
manifest_path: &'a str,
}
impl Encodable for Package {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
let summary = self.manifest.summary();
let package_id = summary.package_id();
SerializedPackage {
name: &package_id.name(),
version: &package_id.version().to_string(),
id: package_id,
source: summary.source_id(),
dependencies: summary.dependencies(),
targets: &self.manifest.targets(),
features: summary.features(),
manifest_path: &self.manifest_path.display().to_string(),
}.encode(s)
}
}
impl Package {
pub fn new(manifest: Manifest,
manifest_path: &Path) -> Package {
Package {
manifest: manifest,
manifest_path: manifest_path.to_path_buf(),
}
}
pub fn for_path(manifest_path: &Path, config: &Config) -> CargoResult<Package> {
let path = manifest_path.parent().unwrap();
let source_id = try!(SourceId::for_path(path));
let (pkg, _) = try!(ops::read_package(&manifest_path, &source_id,
config));
Ok(pkg)
}
pub fn dependencies(&self) -> &[Dependency] { self.manifest.dependencies() }
pub fn manifest(&self) -> &Manifest { &self.manifest }
pub fn manifest_path(&self) -> &Path { &self.manifest_path }
pub fn name(&self) -> &str { self.package_id().name() }
pub fn package_id(&self) -> &PackageId { self.manifest.package_id() }
pub fn root(&self) -> &Path { self.manifest_path.parent().unwrap() }
pub fn summary(&self) -> &Summary { self.manifest.summary() }
pub fn targets(&self) -> &[Target] { self.manifest().targets() }
pub fn version(&self) -> &Version { self.package_id().version() }
pub fn authors(&self) -> &Vec<String> { &self.manifest.metadata().authors }
pub fn publish(&self) -> bool { self.manifest.publish() }
pub fn has_custom_build(&self) -> bool {
self.targets().iter().any(|t| t.is_custom_build())
}
pub fn generate_metadata(&self) -> Metadata {
self.package_id().generate_metadata()
}
pub fn find_closest_target(&self, target: &str, kind: TargetKind) -> Option<&Target> {
let targets = self.targets();
let matches = targets.iter().filter(|t| *t.kind() == kind)
.map(|t| (lev_distance(target, t.name()), t))
.filter(|&(d, _)| d < 4);
matches.min_by_key(|t| t.0).map(|t| t.1)
}
}
impl fmt::Display for Package {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.summary().package_id())
}
}
impl PartialEq for Package {
fn eq(&self, other: &Package) -> bool {
self.package_id() == other.package_id()
}
}
impl Eq for Package {}
impl hash::Hash for Package {
fn hash<H: hash::Hasher>(&self, into: &mut H) {
self.package_id().hash(into)
}
}
pub struct PackageSet<'cfg> {
packages: Vec<(PackageId, LazyCell<Package>)>,
sources: RefCell<SourceMap<'cfg>>,
}
impl<'cfg> PackageSet<'cfg> {
pub fn new(package_ids: &[PackageId],
sources: SourceMap<'cfg>) -> PackageSet<'cfg> {
PackageSet {
packages: package_ids.iter().map(|id| {
(id.clone(), LazyCell::new(None))
}).collect(),
sources: RefCell::new(sources),
}
}
pub fn package_ids<'a>(&'a self) -> Box<Iterator<Item=&'a PackageId> + 'a> {
Box::new(self.packages.iter().map(|&(ref p, _)| p))
}
pub fn get(&self, id: &PackageId) -> CargoResult<&Package> {
let slot = try!(self.packages.iter().find(|p| p.0 == *id).chain_error(|| {
internal(format!("couldn't find `{}` in package set", id))
}));
let slot = &slot.1;
if let Some(pkg) = slot.borrow() {
return Ok(pkg)
}
let mut sources = self.sources.borrow_mut();
let source = try!(sources.get_mut(id.source_id()).chain_error(|| {
internal(format!("couldn't find source for `{}`", id))
}));
let pkg = try!(source.download(id).chain_error(|| {
human("unable to get packages from source")
}));
assert!(slot.fill(pkg).is_ok());
Ok(slot.borrow().unwrap())
}
pub fn sources(&self) -> Ref<SourceMap<'cfg>> {
self.sources.borrow()
}
}
| Package | identifier_name |
package.rs | use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::hash;
use std::path::{Path, PathBuf};
use semver::Version;
use core::{Dependency, Manifest, PackageId, SourceId, Target, TargetKind};
use core::{Summary, Metadata, SourceMap};
use ops;
use util::{CargoResult, Config, LazyCell, ChainError, internal, human, lev_distance};
use rustc_serialize::{Encoder,Encodable};
/// Information about a package that is available somewhere in the file system.
///
/// A package is a `Cargo.toml` file plus all the files that are part of it.
// TODO: Is manifest_path a relic?
#[derive(Clone, Debug)]
pub struct Package {
// The package's manifest
manifest: Manifest,
// The root of the package
manifest_path: PathBuf,
}
#[derive(RustcEncodable)]
struct SerializedPackage<'a> {
name: &'a str,
version: &'a str,
id: &'a PackageId,
source: &'a SourceId,
dependencies: &'a [Dependency],
targets: &'a [Target],
features: &'a HashMap<String, Vec<String>>,
manifest_path: &'a str,
}
impl Encodable for Package {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
let summary = self.manifest.summary();
let package_id = summary.package_id();
SerializedPackage {
name: &package_id.name(),
version: &package_id.version().to_string(),
id: package_id,
source: summary.source_id(),
dependencies: summary.dependencies(),
targets: &self.manifest.targets(),
features: summary.features(),
manifest_path: &self.manifest_path.display().to_string(),
}.encode(s)
}
}
impl Package {
pub fn new(manifest: Manifest,
manifest_path: &Path) -> Package {
Package {
manifest: manifest,
manifest_path: manifest_path.to_path_buf(),
}
}
pub fn for_path(manifest_path: &Path, config: &Config) -> CargoResult<Package> {
let path = manifest_path.parent().unwrap();
let source_id = try!(SourceId::for_path(path));
let (pkg, _) = try!(ops::read_package(&manifest_path, &source_id,
config));
Ok(pkg)
}
pub fn dependencies(&self) -> &[Dependency] { self.manifest.dependencies() }
pub fn manifest(&self) -> &Manifest { &self.manifest }
pub fn manifest_path(&self) -> &Path { &self.manifest_path }
pub fn name(&self) -> &str { self.package_id().name() }
pub fn package_id(&self) -> &PackageId { self.manifest.package_id() }
pub fn root(&self) -> &Path { self.manifest_path.parent().unwrap() }
pub fn summary(&self) -> &Summary { self.manifest.summary() }
pub fn targets(&self) -> &[Target] { self.manifest().targets() }
pub fn version(&self) -> &Version { self.package_id().version() }
pub fn authors(&self) -> &Vec<String> { &self.manifest.metadata().authors }
pub fn publish(&self) -> bool { self.manifest.publish() }
pub fn has_custom_build(&self) -> bool {
self.targets().iter().any(|t| t.is_custom_build())
}
pub fn generate_metadata(&self) -> Metadata {
self.package_id().generate_metadata()
}
pub fn find_closest_target(&self, target: &str, kind: TargetKind) -> Option<&Target> {
let targets = self.targets();
let matches = targets.iter().filter(|t| *t.kind() == kind)
.map(|t| (lev_distance(target, t.name()), t))
.filter(|&(d, _)| d < 4);
matches.min_by_key(|t| t.0).map(|t| t.1)
}
}
impl fmt::Display for Package {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.summary().package_id())
}
}
impl PartialEq for Package {
fn eq(&self, other: &Package) -> bool {
self.package_id() == other.package_id()
}
}
impl Eq for Package {}
impl hash::Hash for Package {
fn hash<H: hash::Hasher>(&self, into: &mut H) {
self.package_id().hash(into)
}
}
pub struct PackageSet<'cfg> {
packages: Vec<(PackageId, LazyCell<Package>)>,
sources: RefCell<SourceMap<'cfg>>,
}
impl<'cfg> PackageSet<'cfg> {
pub fn new(package_ids: &[PackageId],
sources: SourceMap<'cfg>) -> PackageSet<'cfg> {
PackageSet {
packages: package_ids.iter().map(|id| {
(id.clone(), LazyCell::new(None))
}).collect(),
sources: RefCell::new(sources),
}
}
pub fn package_ids<'a>(&'a self) -> Box<Iterator<Item=&'a PackageId> + 'a> {
Box::new(self.packages.iter().map(|&(ref p, _)| p))
}
pub fn get(&self, id: &PackageId) -> CargoResult<&Package> {
let slot = try!(self.packages.iter().find(|p| p.0 == *id).chain_error(|| {
internal(format!("couldn't find `{}` in package set", id))
}));
let slot = &slot.1;
if let Some(pkg) = slot.borrow() |
let mut sources = self.sources.borrow_mut();
let source = try!(sources.get_mut(id.source_id()).chain_error(|| {
internal(format!("couldn't find source for `{}`", id))
}));
let pkg = try!(source.download(id).chain_error(|| {
human("unable to get packages from source")
}));
assert!(slot.fill(pkg).is_ok());
Ok(slot.borrow().unwrap())
}
pub fn sources(&self) -> Ref<SourceMap<'cfg>> {
self.sources.borrow()
}
}
| {
return Ok(pkg)
} | conditional_block |
publisher.js | // Copyright (c) 2013, salesforce.com, inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided
// that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
// the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
(function ($$){
var sr, mobile, postType, thumbnailUrl;
myPublisher = {
init : function(signedRequest, isMobile) {
sr = signedRequest;
mobile = isMobile;
},
// Auto resize the iframe to fit the current content.
resize : function() {
$$.client.resize(sr.client);
},
// Simply display incoming events in order
logEvent : function(name) {
var elem = $$.byId("events");
var sep = ($$.isNil(elem.value)) ? "" : ",";
elem.value += sep + name
},
selectPostType : function(e) {
console.log("got click", e);
postType = e;
// Enable the share button
$$.client.publish(sr.client, {name : "publisher.setValidForSubmit", payload : true});
},
clearPostTypes : function() {
var i, elements = $$.byClass('postType');
for (i = 0; i < elements.length; i+=1) {
elements[i].checked=false;
}
},
| elem.style.color = (bool) ? "green" : "red";
},
updateContent : function() {
if (!mobile) {
$$.byId('name').innerHTML = sr.context.user.firstName + " " + sr.context.user.lastName;
$$.byId('location').innerHTML = sr.context.environment.displayLocation;
myPublisher.canvasOptions($$.byId('header-enabled'), "HideHeader");
myPublisher.canvasOptions($$.byId('share-enabled'), "HideShare");
}
},
selectThumbnail: function(e) {
thumbnailUrl = (e === "none") ? null : window.location.origin + e;
console.log("Thumbnail URL " + thumbnailUrl);
},
handlers : function() {
var handlers = {
onSetupPanel : function (payload) {
myPublisher.resize(); // Do I want to do this on iphone?
myPublisher.logEvent("setupPanel");
},
onShowPanel : function(payload) {
myPublisher.logEvent("showPanel");
},
onClearPanelState : function(payload) {
myPublisher.logEvent("clearPanelState");
myPublisher.clearPostTypes();
// Clear all the text fields and reset radio buttons
},
onSuccess : function() {
myPublisher.logEvent("success");
},
onFailure : function (payload) {
myPublisher.logEvent("failure");
myPublisher.clearPostTypes();
if (payload && payload.errors && payload.errors.message) {
alert("Error: " + payload.errors.message);
}
},
onGetPayload : function() {
myPublisher.logEvent("getPayload");
var p = {};
if (postType === 'Text') {
// Example of a Text Post
p.feedItemType = "TextPost";
p.auxText = $$.byId('auxText').value;
}
else if (postType === 'Link') {
// Example of a Link Post
p.feedItemType = "LinkPost";
p.auxText = $$.byId('auxText').value;
p.url = "http://www.salesforce.com";
p.urlName = $$.byId('title').value;
}
else if (postType === 'Canvas') {
// Example of a Canvas Post
p.feedItemType = "CanvasPost";
p.auxText = $$.byId('auxText').value;
p.namespace = sr.context.application.namespace;
p.developerName = sr.context.application.developerName;
p.height = $$.byId('height').value;
p.title = $$.byId('title').value;
p.description = $$.byId('description').value;
p.parameters = $$.byId('parameters').value;
p.thumbnailUrl = thumbnailUrl;
}
$$.client.publish(sr.client, {name : 'publisher.setPayload', payload : p});
}
};
return {
subscriptions : [
{name : 'publisher.setupPanel', onData : handlers.onSetupPanel},
{name : 'publisher.showPanel', onData : handlers.onShowPanel},
{name : 'publisher.clearPanelState', onData : handlers.onClearPanelState},
{name : 'publisher.failure', onData : handlers.onFailure},
{name : 'publisher.success', onData : handlers.onSuccess},
{name : 'publisher.getPayload', onData : handlers.onGetPayload}
]
};
}
};
}(Sfdc.canvas)); | canvasOptions : function(elem, option) {
var bool = Sfdc.canvas.indexOf(sr.context.application.options, option) == -1;
elem.innerHTML = (bool) ? "✓" : "✗"; | random_line_split |
publisher.js | // Copyright (c) 2013, salesforce.com, inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided
// that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
// the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
(function ($$){
var sr, mobile, postType, thumbnailUrl;
myPublisher = {
init : function(signedRequest, isMobile) {
sr = signedRequest;
mobile = isMobile;
},
// Auto resize the iframe to fit the current content.
resize : function() {
$$.client.resize(sr.client);
},
// Simply display incoming events in order
logEvent : function(name) {
var elem = $$.byId("events");
var sep = ($$.isNil(elem.value)) ? "" : ",";
elem.value += sep + name
},
selectPostType : function(e) {
console.log("got click", e);
postType = e;
// Enable the share button
$$.client.publish(sr.client, {name : "publisher.setValidForSubmit", payload : true});
},
clearPostTypes : function() {
var i, elements = $$.byClass('postType');
for (i = 0; i < elements.length; i+=1) {
elements[i].checked=false;
}
},
canvasOptions : function(elem, option) {
var bool = Sfdc.canvas.indexOf(sr.context.application.options, option) == -1;
elem.innerHTML = (bool) ? "✓" : "✗";
elem.style.color = (bool) ? "green" : "red";
},
updateContent : function() {
if (!mobile) {
$$.byId('name').innerHTML = sr.context.user.firstName + " " + sr.context.user.lastName;
$$.byId('location').innerHTML = sr.context.environment.displayLocation;
myPublisher.canvasOptions($$.byId('header-enabled'), "HideHeader");
myPublisher.canvasOptions($$.byId('share-enabled'), "HideShare");
}
},
selectThumbnail: function(e) {
thumbnailUrl = (e === "none") ? null : window.location.origin + e;
console.log("Thumbnail URL " + thumbnailUrl);
},
handlers : function() {
var handlers = {
onSetupPanel : function (payload) {
myPublisher.resize(); // Do I want to do this on iphone?
myPublisher.logEvent("setupPanel");
},
onShowPanel : function(payload) {
myPublisher.logEvent("showPanel");
},
onClearPanelState : function(payload) {
myPublisher.logEvent("clearPanelState");
myPublisher.clearPostTypes();
// Clear all the text fields and reset radio buttons
},
onSuccess : function() {
myPublisher.logEvent("success");
},
onFailure : function (payload) {
myPublisher.logEvent("failure");
myPublisher.clearPostTypes();
if (payload && payload.errors && payload.errors.message) |
},
onGetPayload : function() {
myPublisher.logEvent("getPayload");
var p = {};
if (postType === 'Text') {
// Example of a Text Post
p.feedItemType = "TextPost";
p.auxText = $$.byId('auxText').value;
}
else if (postType === 'Link') {
// Example of a Link Post
p.feedItemType = "LinkPost";
p.auxText = $$.byId('auxText').value;
p.url = "http://www.salesforce.com";
p.urlName = $$.byId('title').value;
}
else if (postType === 'Canvas') {
// Example of a Canvas Post
p.feedItemType = "CanvasPost";
p.auxText = $$.byId('auxText').value;
p.namespace = sr.context.application.namespace;
p.developerName = sr.context.application.developerName;
p.height = $$.byId('height').value;
p.title = $$.byId('title').value;
p.description = $$.byId('description').value;
p.parameters = $$.byId('parameters').value;
p.thumbnailUrl = thumbnailUrl;
}
$$.client.publish(sr.client, {name : 'publisher.setPayload', payload : p});
}
};
return {
subscriptions : [
{name : 'publisher.setupPanel', onData : handlers.onSetupPanel},
{name : 'publisher.showPanel', onData : handlers.onShowPanel},
{name : 'publisher.clearPanelState', onData : handlers.onClearPanelState},
{name : 'publisher.failure', onData : handlers.onFailure},
{name : 'publisher.success', onData : handlers.onSuccess},
{name : 'publisher.getPayload', onData : handlers.onGetPayload}
]
};
}
};
}(Sfdc.canvas));
| {
alert("Error: " + payload.errors.message);
} | conditional_block |
MathMenu.js | /*************************************************************
*
* MathJax/localization/pl/MathMenu.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* 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.
*
*/
MathJax.Localization.addTranslation("pl","MathMenu",{
version: "2.7.5",
isLoaded: true,
strings: {
Show: "Poka\u017C wzory jako",
MathMLcode: "Kod MathML",
OriginalMathML: "Oryginalny MathML",
TeXCommands: "Polecenia TeX",
AsciiMathInput: "Wej\u015Bcie AsciiMathML",
Original: "Oryginalny formularz",
ErrorMessage: "Komunikat o b\u0142\u0119dzie",
Annotation: "Adnotacja",
TeX: "TeX",
StarMath: "StarMath",
Maple: "Maple",
ContentMathML: "Zawarto\u015B\u0107 MathML",
OpenMath: "OpenMath",
texHints: "Poka\u017C wskaz\u00F3wki TeX w MathML",
Settings: "Ustawienia wzor\u00F3w",
ZoomTrigger: "Zwi\u0119kszanie zoomu",
Hover: "poprzez najechanie mysz\u0105",
Click: "poprzez klikni\u0119cie",
DoubleClick: "poprzez dwukrotnie klikni\u0119cie",
NoZoom: "Bez zoomu",
TriggerRequires: "Aktywacja wymaga:",
Option: "Option",
Alt: "Alt",
Command: "Command",
Control: "Ctrl",
Shift: "Shift",
ZoomFactor: "Wsp\u00F3\u0142czynnik powi\u0119kszenia",
Renderer: "Renderowanie wzor\u00F3w",
MPHandles: "Obs\u0142u\u017C MathPlayer",
MenuEvents: "Zdarzenia menu",
MouseEvents: "Zdarzenia myszy",
MenuAndMouse: "Zdarzenia myszy i menu",
FontPrefs: "Ustawienia czcionek",
ForHTMLCSS: "Dla HTML-CSS:",
Auto: "Automatycznie",
TeXLocal: "TeX (lokalny)",
TeXWeb: "TeX (www)",
TeXImage: "TeX (obraz)",
STIXLocal: "STIX (lokalny)",
ContextMenu: "Menu kontekstowe",
Browser: "Przegl\u0105darka",
Scale: "Skalowanie wszystkich wzor\u00F3w...",
Discoverable: "Podkre\u015Bl po najechaniu kursora",
Locale: "J\u0119zyk",
LoadLocale: "Pobierz z URL...",
About: "O MathJax",
Help: "Pomoc MathJax",
localTeXfonts: "U\u017Cyj lokalnej czcionki TeX",
webTeXfonts: "U\u017Cyj internetowej czcionki TeX",
imagefonts: "U\u017Cyj czcionki obrazkowej",
localSTIXfonts: "U\u017Cyj lokalnej czcionki STIX",
webSVGfonts: "U\u017Cyj internetowej czcionki SVG",
genericfonts: "U\u017Cyj generowanej czcionki unicode",
wofforotffonts: "czcionki WOFF lub OTF",
eotffonts: "czcionki EOT",
svgfonts: "czcionki SVG",
WebkitNativeMMLWarning: "Twoja przegl\u0105darka nie obs\u0142uguje MathML, wi\u0119c zmiana wyj\u015Bcia do MathML mo\u017Ce spowodowa\u0107, \u017Ce strona stanie si\u0119 niemo\u017Cliwa do odczytania.",
MSIENativeMMLWarning: "Program Internet Explorer wymaga wtyczki MathPlayer do procesu wy\u015Bwietlania MathML.",
OperaNativeMMLWarning: "Wsparcie dla MathML w Operze jest ograniczone. W zwi\u0105zku z tym zmiana wyj\u015Bcia na MathML mo\u017Ce spowodowa\u0107, \u017Ce niekt\u00F3re strony b\u0119d\u0105 niemo\u017Cliwe do odczytania.",
SafariNativeMMLWarning: "MathML zaimplementowany w twojej przegl\u0105darce nie obs\u0142uguje wszystkich mo\u017Cliwo\u015Bci MathJax, wi\u0119c cz\u0119\u015B\u0107 wyra\u017Cen mo\u017Ce nie renderowa\u0107 si\u0119 poprawnie.",
FirefoxNativeMMLWarning: "MathML zaimplementowany w twojej przegl\u0105darce nie obs\u0142uguje wszystkich mo\u017Cliwo\u015Bci MathJax, wi\u0119c cz\u0119\u015B\u0107 wyra\u017Ce\u0144 mo\u017Ce nie renderowa\u0107 si\u0119 poprawnie.",
MSIESVGWarning: "SVG nie jest zaimplementowane w Internet Explorerze do wersji 9 lub podczas emulowania IE8 lub poni\u017Cej, wi\u0119c zmiana wyj\u015Bcia do SVG mo\u017Ce spowodowa\u0107, \u017Ce strona stanie si\u0119 niemo\u017Cliwa do odczytania.",
LoadURL: "Za\u0142aduj t\u0142umaczenie z tego URL:",
BadURL: "Adres URL powinien by\u0107 dla pliku JavaScript, kt\u00F3ry definiuje dane t\u0142umaczenie MathJax. Pliki JavaScript powinny ko\u0144czy\u0107 si\u0119 \".js\"",
BadData: "Nie mo\u017Cna za\u0142adowa\u0107 danych t\u0142umacze\u0144 z %1",
SwitchAnyway: "Na pewno zmieni\u0107 renderer ?\n\n(Naci\u015Bnij OK a\u017Ceby zmieni\u0107, lub CANCEL aby kontynuowa\u0107 z aktualnym rendererem)",
ScaleMath: "Skaluj wszystkie wzory matematyczne (por\u00F3wnane do otaczaj\u0105cego tekstu) przez",
NonZeroScale: "Warto\u015B\u0107 nie powinna by\u0107 zerowa",
PercentScale: "Warto\u015B\u0107 powinna by\u0107 w procentach (na przyk\u0142ad 120%%)",
IE8warning: "Ta opcja wy\u0142\u0105czy obs\u0142ug\u0119 menu i powi\u0119kszania w MathJax, ale mo\u017Cesz klikn\u0105\u0107 z Altem na wz\u00F3r, aby otworzy\u0107 menu MathJax.\n\nCzy na pewno chcesz zmieni\u0107 ustawienia MathPlayer?",
IE9warning: "Menu kontekstowe MathJax zostanie wy\u0142\u0105czone, ale mo\u017Cesz klikn\u0105\u0107 z Altem na wz\u00F3r, aby otworzy\u0107 menu.",
NoOriginalForm: "Brak wzor\u00F3w w oryginalnej postaci",
Close: "Zamknij",
EqSource: "\u0179r\u00F3d\u0142o wzoru MathJax",
STIXWeb: "STIX (www)",
AsanaMathWeb: "Asana Math (www)",
GyrePagellaWeb: "Gyre Pagella (www)",
GyreTermesWeb: "Gyre Termes (www)", | AssistiveMML: "Asystuj\u0105cy MathML",
InTabOrder: "Zawarty w kolejno\u015Bci stron"
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/pl/MathMenu.js"); | LatinModernWeb: "Latin Modern (www)",
NeoEulerWeb: "Neo Euler (www)",
CloseAboutDialog: "Zamknij okno o MathJax",
FastPreview: "Szybki podgl\u0105d strony", | random_line_split |
master.py | #!/usr/bin/env python
"""
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.
"""
from resource_management import *
class ElasticSearchMaster(Script):
def hdfs_path_exists(self, hdfs_path):
import params
try:
Execute(format('hadoop fs -test -e {hdfs_path}'), user=params.es_user, logoutput=True, timeout=300)
return True
except:
return False
def es_user_exists(self, user):
import pwd
try:
pwd.getpwnam(user)
return True
except KeyError:
return False
def create_es_user(self):
import crypt
import params
Group(params.es_group)
User(params.es_user, gid=params.es_group, password=crypt.crypt(params.es_password, 'salt'), groups=[params.es_group], ignore_failures=True)
def create_es_hdfs_user(self):
import params
ExecuteHadoop(format('fs -mkdir -p /user/{es_user}'), user='hdfs', conf_dir=params.hadoop_conf_dir, ignore_failures=True)
ExecuteHadoop(format('fs -chown {es_user} /user/{es_user}'), user='hdfs', conf_dir=params.hadoop_conf_dir)
ExecuteHadoop(format('fs -chgrp {es_user} /user/{es_user}'), user='hdfs', conf_dir=params.hadoop_conf_dir)
def create_es_hdfs_upload_dir(self):
import params
ExecuteHadoop(format('fs -mkdir -p {es_hdfs_upload_dir}'), user='hdfs', conf_dir=params.hadoop_conf_dir, ignore_failures=True)
ExecuteHadoop(format('fs -chown {es_user} {es_hdfs_upload_dir}'), user='hdfs', conf_dir=params.hadoop_conf_dir)
ExecuteHadoop(format('fs -chgrp {es_user} {es_hdfs_upload_dir}'), user='hdfs', conf_dir=params.hadoop_conf_dir)
def store_status_properties(self):
import params
File(format("{es_user_file}"), owner=params.es_user, group=params.es_group, content=params.es_user)
File(format("{es_jar_path_file}"), owner=params.es_user, group=params.es_group, content=params.es_jar_path)
File(format("{es_hdfs_upload_dir_file}"), owner=params.es_user, group=params.es_group, content=params.es_hdfs_upload_dir)
def install(self, env):
import params
env.set_params(params)
def configure(self, env):
import os
import params
import urllib
env.set_params(params)
if not self.es_user_exists(params.es_user):
self.create_es_user()
if not (os.path.exists(params.es_jar_path) and os.path.isfile(params.es_jar_path)) :
es_jar_dir = os.path.dirname(os.path.abspath(params.es_jar_path))
Directory(es_jar_dir, owner=params.es_user, group=params.es_group, recursive=True)
print "Downloading ES YARN jar from: %s to: %s" % (params.es_jar_download_url, params.es_jar_path)
geodeTarball = urllib.URLopener() | File(format("/home/{es_user}/elasticsearch.properties"), owner=params.es_user, group=params.es_group, content=params.es_load_config_file)
if not self.hdfs_path_exists("/user/" + params.es_user) :
self.create_es_hdfs_user()
if not self.hdfs_path_exists(params.es_hdfs_upload_dir) :
self.create_es_hdfs_upload_dir()
Execute(format('hadoop jar {es_jar_path} -download-es hdfs.upload.dir={es_hdfs_upload_dir} download.local.dir={es_download_local_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
Execute(format('hadoop jar {es_jar_path} -install-es hdfs.upload.dir={es_hdfs_upload_dir} download.local.dir={es_download_local_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
Execute(format('hadoop jar {es_jar_path} -install hdfs.upload.dir={es_hdfs_upload_dir} download.local.dir={es_download_local_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
# Store the properties required by STATUS phase. Note that the STATUS phase has no access to the Script.get_config()
self.store_status_properties()
# Called by Ambari on ES service start
def start(self, env):
import params
env.set_params(params)
# Call the configure method on start to make sure any re-configurations would be applied.
self.configure(env)
Execute(format('hadoop jar {es_jar_path} -start containers={es_yarn_container_count} container.mem={es_yarn_container_mem} container.vcores={es_yarn_container_vcores} container.priority={es_yarn_container_priority} hdfs.upload.dir={es_hdfs_upload_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'),
user=params.es_user, logoutput=True, timeout=300)
# Called by Ambari on ES service stop
def stop(self, env):
import params
env.set_params(params)
Execute(format('hadoop jar {es_jar_path} -stop hdfs.upload.dir={es_hdfs_upload_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
# Warning: Ambari doesn't share the configuration parameters (e.g. elasticsearch-site.xml) in the status phase. To access some of those properties one has store them during the 'START' phase in shared store with the 'STATUS' phase
def status(self, env):
import status_params
env.set_params(status_params)
Execute(format('hadoop jar {es_jar_path} -status hdfs.upload.dir={es_hdfs_upload_dir} loadConfig=/home/{es_user}/elasticsearch.properties| grep RUNNING'), user=status_params.es_user, logoutput=True, timeout=300)
if __name__ == '__main__':
ElasticSearchMaster().execute() | geodeTarball.retrieve(params.es_jar_download_url, params.es_jar_path)
| random_line_split |
master.py | #!/usr/bin/env python
"""
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.
"""
from resource_management import *
class ElasticSearchMaster(Script):
def hdfs_path_exists(self, hdfs_path):
import params
try:
Execute(format('hadoop fs -test -e {hdfs_path}'), user=params.es_user, logoutput=True, timeout=300)
return True
except:
return False
def | (self, user):
import pwd
try:
pwd.getpwnam(user)
return True
except KeyError:
return False
def create_es_user(self):
import crypt
import params
Group(params.es_group)
User(params.es_user, gid=params.es_group, password=crypt.crypt(params.es_password, 'salt'), groups=[params.es_group], ignore_failures=True)
def create_es_hdfs_user(self):
import params
ExecuteHadoop(format('fs -mkdir -p /user/{es_user}'), user='hdfs', conf_dir=params.hadoop_conf_dir, ignore_failures=True)
ExecuteHadoop(format('fs -chown {es_user} /user/{es_user}'), user='hdfs', conf_dir=params.hadoop_conf_dir)
ExecuteHadoop(format('fs -chgrp {es_user} /user/{es_user}'), user='hdfs', conf_dir=params.hadoop_conf_dir)
def create_es_hdfs_upload_dir(self):
import params
ExecuteHadoop(format('fs -mkdir -p {es_hdfs_upload_dir}'), user='hdfs', conf_dir=params.hadoop_conf_dir, ignore_failures=True)
ExecuteHadoop(format('fs -chown {es_user} {es_hdfs_upload_dir}'), user='hdfs', conf_dir=params.hadoop_conf_dir)
ExecuteHadoop(format('fs -chgrp {es_user} {es_hdfs_upload_dir}'), user='hdfs', conf_dir=params.hadoop_conf_dir)
def store_status_properties(self):
import params
File(format("{es_user_file}"), owner=params.es_user, group=params.es_group, content=params.es_user)
File(format("{es_jar_path_file}"), owner=params.es_user, group=params.es_group, content=params.es_jar_path)
File(format("{es_hdfs_upload_dir_file}"), owner=params.es_user, group=params.es_group, content=params.es_hdfs_upload_dir)
def install(self, env):
import params
env.set_params(params)
def configure(self, env):
import os
import params
import urllib
env.set_params(params)
if not self.es_user_exists(params.es_user):
self.create_es_user()
if not (os.path.exists(params.es_jar_path) and os.path.isfile(params.es_jar_path)) :
es_jar_dir = os.path.dirname(os.path.abspath(params.es_jar_path))
Directory(es_jar_dir, owner=params.es_user, group=params.es_group, recursive=True)
print "Downloading ES YARN jar from: %s to: %s" % (params.es_jar_download_url, params.es_jar_path)
geodeTarball = urllib.URLopener()
geodeTarball.retrieve(params.es_jar_download_url, params.es_jar_path)
File(format("/home/{es_user}/elasticsearch.properties"), owner=params.es_user, group=params.es_group, content=params.es_load_config_file)
if not self.hdfs_path_exists("/user/" + params.es_user) :
self.create_es_hdfs_user()
if not self.hdfs_path_exists(params.es_hdfs_upload_dir) :
self.create_es_hdfs_upload_dir()
Execute(format('hadoop jar {es_jar_path} -download-es hdfs.upload.dir={es_hdfs_upload_dir} download.local.dir={es_download_local_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
Execute(format('hadoop jar {es_jar_path} -install-es hdfs.upload.dir={es_hdfs_upload_dir} download.local.dir={es_download_local_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
Execute(format('hadoop jar {es_jar_path} -install hdfs.upload.dir={es_hdfs_upload_dir} download.local.dir={es_download_local_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
# Store the properties required by STATUS phase. Note that the STATUS phase has no access to the Script.get_config()
self.store_status_properties()
# Called by Ambari on ES service start
def start(self, env):
import params
env.set_params(params)
# Call the configure method on start to make sure any re-configurations would be applied.
self.configure(env)
Execute(format('hadoop jar {es_jar_path} -start containers={es_yarn_container_count} container.mem={es_yarn_container_mem} container.vcores={es_yarn_container_vcores} container.priority={es_yarn_container_priority} hdfs.upload.dir={es_hdfs_upload_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'),
user=params.es_user, logoutput=True, timeout=300)
# Called by Ambari on ES service stop
def stop(self, env):
import params
env.set_params(params)
Execute(format('hadoop jar {es_jar_path} -stop hdfs.upload.dir={es_hdfs_upload_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
# Warning: Ambari doesn't share the configuration parameters (e.g. elasticsearch-site.xml) in the status phase. To access some of those properties one has store them during the 'START' phase in shared store with the 'STATUS' phase
def status(self, env):
import status_params
env.set_params(status_params)
Execute(format('hadoop jar {es_jar_path} -status hdfs.upload.dir={es_hdfs_upload_dir} loadConfig=/home/{es_user}/elasticsearch.properties| grep RUNNING'), user=status_params.es_user, logoutput=True, timeout=300)
if __name__ == '__main__':
ElasticSearchMaster().execute()
| es_user_exists | identifier_name |
master.py | #!/usr/bin/env python
"""
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.
"""
from resource_management import *
class ElasticSearchMaster(Script):
def hdfs_path_exists(self, hdfs_path):
import params
try:
Execute(format('hadoop fs -test -e {hdfs_path}'), user=params.es_user, logoutput=True, timeout=300)
return True
except:
return False
def es_user_exists(self, user):
import pwd
try:
pwd.getpwnam(user)
return True
except KeyError:
return False
def create_es_user(self):
import crypt
import params
Group(params.es_group)
User(params.es_user, gid=params.es_group, password=crypt.crypt(params.es_password, 'salt'), groups=[params.es_group], ignore_failures=True)
def create_es_hdfs_user(self):
import params
ExecuteHadoop(format('fs -mkdir -p /user/{es_user}'), user='hdfs', conf_dir=params.hadoop_conf_dir, ignore_failures=True)
ExecuteHadoop(format('fs -chown {es_user} /user/{es_user}'), user='hdfs', conf_dir=params.hadoop_conf_dir)
ExecuteHadoop(format('fs -chgrp {es_user} /user/{es_user}'), user='hdfs', conf_dir=params.hadoop_conf_dir)
def create_es_hdfs_upload_dir(self):
import params
ExecuteHadoop(format('fs -mkdir -p {es_hdfs_upload_dir}'), user='hdfs', conf_dir=params.hadoop_conf_dir, ignore_failures=True)
ExecuteHadoop(format('fs -chown {es_user} {es_hdfs_upload_dir}'), user='hdfs', conf_dir=params.hadoop_conf_dir)
ExecuteHadoop(format('fs -chgrp {es_user} {es_hdfs_upload_dir}'), user='hdfs', conf_dir=params.hadoop_conf_dir)
def store_status_properties(self):
|
def install(self, env):
import params
env.set_params(params)
def configure(self, env):
import os
import params
import urllib
env.set_params(params)
if not self.es_user_exists(params.es_user):
self.create_es_user()
if not (os.path.exists(params.es_jar_path) and os.path.isfile(params.es_jar_path)) :
es_jar_dir = os.path.dirname(os.path.abspath(params.es_jar_path))
Directory(es_jar_dir, owner=params.es_user, group=params.es_group, recursive=True)
print "Downloading ES YARN jar from: %s to: %s" % (params.es_jar_download_url, params.es_jar_path)
geodeTarball = urllib.URLopener()
geodeTarball.retrieve(params.es_jar_download_url, params.es_jar_path)
File(format("/home/{es_user}/elasticsearch.properties"), owner=params.es_user, group=params.es_group, content=params.es_load_config_file)
if not self.hdfs_path_exists("/user/" + params.es_user) :
self.create_es_hdfs_user()
if not self.hdfs_path_exists(params.es_hdfs_upload_dir) :
self.create_es_hdfs_upload_dir()
Execute(format('hadoop jar {es_jar_path} -download-es hdfs.upload.dir={es_hdfs_upload_dir} download.local.dir={es_download_local_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
Execute(format('hadoop jar {es_jar_path} -install-es hdfs.upload.dir={es_hdfs_upload_dir} download.local.dir={es_download_local_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
Execute(format('hadoop jar {es_jar_path} -install hdfs.upload.dir={es_hdfs_upload_dir} download.local.dir={es_download_local_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
# Store the properties required by STATUS phase. Note that the STATUS phase has no access to the Script.get_config()
self.store_status_properties()
# Called by Ambari on ES service start
def start(self, env):
import params
env.set_params(params)
# Call the configure method on start to make sure any re-configurations would be applied.
self.configure(env)
Execute(format('hadoop jar {es_jar_path} -start containers={es_yarn_container_count} container.mem={es_yarn_container_mem} container.vcores={es_yarn_container_vcores} container.priority={es_yarn_container_priority} hdfs.upload.dir={es_hdfs_upload_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'),
user=params.es_user, logoutput=True, timeout=300)
# Called by Ambari on ES service stop
def stop(self, env):
import params
env.set_params(params)
Execute(format('hadoop jar {es_jar_path} -stop hdfs.upload.dir={es_hdfs_upload_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
# Warning: Ambari doesn't share the configuration parameters (e.g. elasticsearch-site.xml) in the status phase. To access some of those properties one has store them during the 'START' phase in shared store with the 'STATUS' phase
def status(self, env):
import status_params
env.set_params(status_params)
Execute(format('hadoop jar {es_jar_path} -status hdfs.upload.dir={es_hdfs_upload_dir} loadConfig=/home/{es_user}/elasticsearch.properties| grep RUNNING'), user=status_params.es_user, logoutput=True, timeout=300)
if __name__ == '__main__':
ElasticSearchMaster().execute()
| import params
File(format("{es_user_file}"), owner=params.es_user, group=params.es_group, content=params.es_user)
File(format("{es_jar_path_file}"), owner=params.es_user, group=params.es_group, content=params.es_jar_path)
File(format("{es_hdfs_upload_dir_file}"), owner=params.es_user, group=params.es_group, content=params.es_hdfs_upload_dir) | identifier_body |
master.py | #!/usr/bin/env python
"""
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.
"""
from resource_management import *
class ElasticSearchMaster(Script):
def hdfs_path_exists(self, hdfs_path):
import params
try:
Execute(format('hadoop fs -test -e {hdfs_path}'), user=params.es_user, logoutput=True, timeout=300)
return True
except:
return False
def es_user_exists(self, user):
import pwd
try:
pwd.getpwnam(user)
return True
except KeyError:
return False
def create_es_user(self):
import crypt
import params
Group(params.es_group)
User(params.es_user, gid=params.es_group, password=crypt.crypt(params.es_password, 'salt'), groups=[params.es_group], ignore_failures=True)
def create_es_hdfs_user(self):
import params
ExecuteHadoop(format('fs -mkdir -p /user/{es_user}'), user='hdfs', conf_dir=params.hadoop_conf_dir, ignore_failures=True)
ExecuteHadoop(format('fs -chown {es_user} /user/{es_user}'), user='hdfs', conf_dir=params.hadoop_conf_dir)
ExecuteHadoop(format('fs -chgrp {es_user} /user/{es_user}'), user='hdfs', conf_dir=params.hadoop_conf_dir)
def create_es_hdfs_upload_dir(self):
import params
ExecuteHadoop(format('fs -mkdir -p {es_hdfs_upload_dir}'), user='hdfs', conf_dir=params.hadoop_conf_dir, ignore_failures=True)
ExecuteHadoop(format('fs -chown {es_user} {es_hdfs_upload_dir}'), user='hdfs', conf_dir=params.hadoop_conf_dir)
ExecuteHadoop(format('fs -chgrp {es_user} {es_hdfs_upload_dir}'), user='hdfs', conf_dir=params.hadoop_conf_dir)
def store_status_properties(self):
import params
File(format("{es_user_file}"), owner=params.es_user, group=params.es_group, content=params.es_user)
File(format("{es_jar_path_file}"), owner=params.es_user, group=params.es_group, content=params.es_jar_path)
File(format("{es_hdfs_upload_dir_file}"), owner=params.es_user, group=params.es_group, content=params.es_hdfs_upload_dir)
def install(self, env):
import params
env.set_params(params)
def configure(self, env):
import os
import params
import urllib
env.set_params(params)
if not self.es_user_exists(params.es_user):
self.create_es_user()
if not (os.path.exists(params.es_jar_path) and os.path.isfile(params.es_jar_path)) :
es_jar_dir = os.path.dirname(os.path.abspath(params.es_jar_path))
Directory(es_jar_dir, owner=params.es_user, group=params.es_group, recursive=True)
print "Downloading ES YARN jar from: %s to: %s" % (params.es_jar_download_url, params.es_jar_path)
geodeTarball = urllib.URLopener()
geodeTarball.retrieve(params.es_jar_download_url, params.es_jar_path)
File(format("/home/{es_user}/elasticsearch.properties"), owner=params.es_user, group=params.es_group, content=params.es_load_config_file)
if not self.hdfs_path_exists("/user/" + params.es_user) :
|
if not self.hdfs_path_exists(params.es_hdfs_upload_dir) :
self.create_es_hdfs_upload_dir()
Execute(format('hadoop jar {es_jar_path} -download-es hdfs.upload.dir={es_hdfs_upload_dir} download.local.dir={es_download_local_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
Execute(format('hadoop jar {es_jar_path} -install-es hdfs.upload.dir={es_hdfs_upload_dir} download.local.dir={es_download_local_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
Execute(format('hadoop jar {es_jar_path} -install hdfs.upload.dir={es_hdfs_upload_dir} download.local.dir={es_download_local_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
# Store the properties required by STATUS phase. Note that the STATUS phase has no access to the Script.get_config()
self.store_status_properties()
# Called by Ambari on ES service start
def start(self, env):
import params
env.set_params(params)
# Call the configure method on start to make sure any re-configurations would be applied.
self.configure(env)
Execute(format('hadoop jar {es_jar_path} -start containers={es_yarn_container_count} container.mem={es_yarn_container_mem} container.vcores={es_yarn_container_vcores} container.priority={es_yarn_container_priority} hdfs.upload.dir={es_hdfs_upload_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'),
user=params.es_user, logoutput=True, timeout=300)
# Called by Ambari on ES service stop
def stop(self, env):
import params
env.set_params(params)
Execute(format('hadoop jar {es_jar_path} -stop hdfs.upload.dir={es_hdfs_upload_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
# Warning: Ambari doesn't share the configuration parameters (e.g. elasticsearch-site.xml) in the status phase. To access some of those properties one has store them during the 'START' phase in shared store with the 'STATUS' phase
def status(self, env):
import status_params
env.set_params(status_params)
Execute(format('hadoop jar {es_jar_path} -status hdfs.upload.dir={es_hdfs_upload_dir} loadConfig=/home/{es_user}/elasticsearch.properties| grep RUNNING'), user=status_params.es_user, logoutput=True, timeout=300)
if __name__ == '__main__':
ElasticSearchMaster().execute()
| self.create_es_hdfs_user() | conditional_block |
bdist_egg.py | """setuptools.command.bdist_egg
Build .egg distributions"""
# This module should be kept compatible with Python 2.3
import sys
import os
import marshal
import textwrap
from setuptools import Command
from distutils.dir_util import remove_tree, mkpath
try:
# Python 2.7 or >=3.2
from sysconfig import get_path, get_python_version
def _get_purelib():
return get_path("purelib")
except ImportError:
from distutils.sysconfig import get_python_lib, get_python_version
def _get_purelib():
return get_python_lib(False)
from distutils import log
from distutils.errors import DistutilsSetupError
from pkg_resources import get_build_platform, Distribution, ensure_directory
from pkg_resources import EntryPoint
from types import CodeType
from setuptools.compat import basestring, next
from setuptools.extension import Library
def strip_module(filename):
if '.' in filename:
filename = os.path.splitext(filename)[0]
if filename.endswith('module'):
filename = filename[:-6]
return filename
def write_stub(resource, pyfile):
_stub_template = textwrap.dedent("""
def __bootstrap__():
global __bootstrap__, __loader__, __file__
import sys, pkg_resources, imp
__file__ = pkg_resources.resource_filename(__name__, %r)
__loader__ = None; del __bootstrap__, __loader__
imp.load_dynamic(__name__,__file__)
__bootstrap__()
""").lstrip()
with open(pyfile, 'w') as f:
f.write(_stub_template % resource)
class bdist_egg(Command):
description = "create an \"egg\" distribution"
user_options = [
('bdist-dir=', 'b',
"temporary directory for creating the distribution"),
('plat-name=', 'p', "platform name to embed in generated filenames "
"(default: %s)" % get_build_platform()),
('exclude-source-files', None,
"remove all .py files from the generated egg"),
('keep-temp', 'k',
"keep the pseudo-installation tree around after " +
"creating the distribution archive"),
('dist-dir=', 'd',
"directory to put final built distributions in"),
('skip-build', None,
"skip rebuilding everything (for testing/debugging)"),
]
boolean_options = [
'keep-temp', 'skip-build', 'exclude-source-files'
]
def initialize_options(self):
self.bdist_dir = None
self.plat_name = None
self.keep_temp = 0
self.dist_dir = None
self.skip_build = 0
self.egg_output = None
self.exclude_source_files = None
def finalize_options(self):
ei_cmd = self.ei_cmd = self.get_finalized_command("egg_info")
self.egg_info = ei_cmd.egg_info
if self.bdist_dir is None:
bdist_base = self.get_finalized_command('bdist').bdist_base
self.bdist_dir = os.path.join(bdist_base, 'egg')
if self.plat_name is None:
self.plat_name = get_build_platform()
self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
if self.egg_output is None:
# Compute filename of the output egg
basename = Distribution(
None, None, ei_cmd.egg_name, ei_cmd.egg_version,
get_python_version(),
self.distribution.has_ext_modules() and self.plat_name
).egg_name()
self.egg_output = os.path.join(self.dist_dir, basename + '.egg')
def do_install_data(self):
# Hack for packages that install data to install's --install-lib
self.get_finalized_command('install').install_lib = self.bdist_dir
site_packages = os.path.normcase(os.path.realpath(_get_purelib()))
old, self.distribution.data_files = self.distribution.data_files, []
for item in old:
if isinstance(item, tuple) and len(item) == 2:
if os.path.isabs(item[0]):
realpath = os.path.realpath(item[0])
normalized = os.path.normcase(realpath)
if normalized == site_packages or normalized.startswith(
site_packages + os.sep
):
item = realpath[len(site_packages) + 1:], item[1]
# XXX else: raise ???
self.distribution.data_files.append(item)
try:
log.info("installing package data to %s" % self.bdist_dir)
self.call_command('install_data', force=0, root=None)
finally:
self.distribution.data_files = old
def get_outputs(self):
return [self.egg_output]
def call_command(self, cmdname, **kw):
"""Invoke reinitialized command `cmdname` with keyword args"""
for dirname in INSTALL_DIRECTORY_ATTRS:
kw.setdefault(dirname, self.bdist_dir)
kw.setdefault('skip_build', self.skip_build)
kw.setdefault('dry_run', self.dry_run)
cmd = self.reinitialize_command(cmdname, **kw)
self.run_command(cmdname)
return cmd
def run(self):
# Generate metadata first
self.run_command("egg_info")
# We run install_lib before install_data, because some data hacks
# pull their data path from the install_lib command.
log.info("installing library code to %s" % self.bdist_dir)
instcmd = self.get_finalized_command('install')
old_root = instcmd.root
instcmd.root = None
if self.distribution.has_c_libraries() and not self.skip_build:
self.run_command('build_clib')
cmd = self.call_command('install_lib', warn_dir=0)
instcmd.root = old_root
all_outputs, ext_outputs = self.get_ext_outputs()
self.stubs = []
to_compile = []
for (p, ext_name) in enumerate(ext_outputs):
filename, ext = os.path.splitext(ext_name)
pyfile = os.path.join(self.bdist_dir, strip_module(filename) + '.py')
self.stubs.append(pyfile)
log.info("creating stub loader for %s" % ext_name)
if not self.dry_run:
write_stub(os.path.basename(ext_name), pyfile)
to_compile.append(pyfile)
ext_outputs[p] = ext_name.replace(os.sep, '/')
if to_compile:
cmd.byte_compile(to_compile)
if self.distribution.data_files:
self.do_install_data()
# Make the EGG-INFO directory
archive_root = self.bdist_dir
egg_info = os.path.join(archive_root, 'EGG-INFO')
self.mkpath(egg_info)
if self.distribution.scripts:
script_dir = os.path.join(egg_info, 'scripts')
log.info("installing scripts to %s" % script_dir)
self.call_command('install_scripts', install_dir=script_dir, no_ep=1)
self.copy_metadata_to(egg_info)
native_libs = os.path.join(egg_info, "native_libs.txt")
if all_outputs:
log.info("writing %s" % native_libs)
if not self.dry_run:
ensure_directory(native_libs)
libs_file = open(native_libs, 'wt')
libs_file.write('\n'.join(all_outputs))
libs_file.write('\n')
libs_file.close()
elif os.path.isfile(native_libs):
log.info("removing %s" % native_libs)
if not self.dry_run:
os.unlink(native_libs)
write_safety_flag(
os.path.join(archive_root, 'EGG-INFO'), self.zip_safe()
)
if os.path.exists(os.path.join(self.egg_info, 'depends.txt')):
log.warn(
"WARNING: 'depends.txt' will not be used by setuptools 0.6!\n"
"Use the install_requires/extras_require setup() args instead."
)
if self.exclude_source_files:
self.zap_pyfiles()
# Make the archive
make_zipfile(self.egg_output, archive_root, verbose=self.verbose,
dry_run=self.dry_run, mode=self.gen_header())
if not self.keep_temp:
remove_tree(self.bdist_dir, dry_run=self.dry_run)
# Add to 'Distribution.dist_files' so that the "upload" command works
getattr(self.distribution, 'dist_files', []).append(
('bdist_egg', get_python_version(), self.egg_output))
def zap_pyfiles(self):
log.info("Removing .py files from temporary directory")
for base, dirs, files in walk_egg(self.bdist_dir):
for name in files:
if name.endswith('.py'):
path = os.path.join(base, name)
log.debug("Deleting %s", path)
os.unlink(path)
def zip_safe(self):
safe = getattr(self.distribution, 'zip_safe', None)
if safe is not None:
return safe
log.warn("zip_safe flag not set; analyzing archive contents...")
return analyze_egg(self.bdist_dir, self.stubs)
def gen_header(self):
epm = EntryPoint.parse_map(self.distribution.entry_points or '')
ep = epm.get('setuptools.installation', {}).get('eggsecutable')
if ep is None:
return 'w' # not an eggsecutable, do it the usual way.
if not ep.attrs or ep.extras:
raise DistutilsSetupError(
"eggsecutable entry point (%r) cannot have 'extras' "
"or refer to a module" % (ep,)
)
pyver = sys.version[:3]
pkg = ep.module_name
full = '.'.join(ep.attrs)
base = ep.attrs[0]
basename = os.path.basename(self.egg_output)
header = (
"#!/bin/sh\n"
'if [ `basename $0` = "%(basename)s" ]\n'
'then exec python%(pyver)s -c "'
"import sys, os; sys.path.insert(0, os.path.abspath('$0')); "
"from %(pkg)s import %(base)s; sys.exit(%(full)s())"
'" "$@"\n'
'else\n'
' echo $0 is not the correct name for this egg file.\n'
' echo Please rename it back to %(basename)s and try again.\n'
' exec false\n'
'fi\n'
) % locals()
if not self.dry_run:
mkpath(os.path.dirname(self.egg_output), dry_run=self.dry_run)
f = open(self.egg_output, 'w')
f.write(header)
f.close()
return 'a'
def copy_metadata_to(self, target_dir):
"Copy metadata (egg info) to the target_dir"
# normalize the path (so that a forward-slash in egg_info will
# match using startswith below)
norm_egg_info = os.path.normpath(self.egg_info)
prefix = os.path.join(norm_egg_info, '')
for path in self.ei_cmd.filelist.files:
if path.startswith(prefix):
target = os.path.join(target_dir, path[len(prefix):])
ensure_directory(target)
self.copy_file(path, target)
def get_ext_outputs(self):
"""Get a list of relative paths to C extensions in the output distro"""
all_outputs = []
ext_outputs = []
paths = {self.bdist_dir: ''}
for base, dirs, files in os.walk(self.bdist_dir):
for filename in files:
if os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS:
all_outputs.append(paths[base] + filename)
for filename in dirs:
paths[os.path.join(base, filename)] = paths[base] + filename + '/'
if self.distribution.has_ext_modules():
build_cmd = self.get_finalized_command('build_ext')
for ext in build_cmd.extensions:
if isinstance(ext, Library):
continue
fullname = build_cmd.get_ext_fullname(ext.name)
filename = build_cmd.get_ext_filename(fullname)
if not os.path.basename(filename).startswith('dl-'):
if os.path.exists(os.path.join(self.bdist_dir, filename)):
ext_outputs.append(filename)
return all_outputs, ext_outputs
| """Walk an unpacked egg's contents, skipping the metadata directory"""
walker = os.walk(egg_dir)
base, dirs, files = next(walker)
if 'EGG-INFO' in dirs:
dirs.remove('EGG-INFO')
yield base, dirs, files
for bdf in walker:
yield bdf
def analyze_egg(egg_dir, stubs):
# check for existing flag in EGG-INFO
for flag, fn in safety_flags.items():
if os.path.exists(os.path.join(egg_dir, 'EGG-INFO', fn)):
return flag
if not can_scan(): return False
safe = True
for base, dirs, files in walk_egg(egg_dir):
for name in files:
if name.endswith('.py') or name.endswith('.pyw'):
continue
elif name.endswith('.pyc') or name.endswith('.pyo'):
# always scan, even if we already know we're not safe
safe = scan_module(egg_dir, base, name, stubs) and safe
return safe
def write_safety_flag(egg_dir, safe):
# Write or remove zip safety flag file(s)
for flag, fn in safety_flags.items():
fn = os.path.join(egg_dir, fn)
if os.path.exists(fn):
if safe is None or bool(safe) != flag:
os.unlink(fn)
elif safe is not None and bool(safe) == flag:
f = open(fn, 'wt')
f.write('\n')
f.close()
safety_flags = {
True: 'zip-safe',
False: 'not-zip-safe',
}
def scan_module(egg_dir, base, name, stubs):
"""Check whether module possibly uses unsafe-for-zipfile stuff"""
filename = os.path.join(base, name)
if filename[:-1] in stubs:
return True # Extension module
pkg = base[len(egg_dir) + 1:].replace(os.sep, '.')
module = pkg + (pkg and '.' or '') + os.path.splitext(name)[0]
if sys.version_info < (3, 3):
skip = 8 # skip magic & date
else:
skip = 12 # skip magic & date & file size
f = open(filename, 'rb')
f.read(skip)
code = marshal.load(f)
f.close()
safe = True
symbols = dict.fromkeys(iter_symbols(code))
for bad in ['__file__', '__path__']:
if bad in symbols:
log.warn("%s: module references %s", module, bad)
safe = False
if 'inspect' in symbols:
for bad in [
'getsource', 'getabsfile', 'getsourcefile', 'getfile'
'getsourcelines', 'findsource', 'getcomments', 'getframeinfo',
'getinnerframes', 'getouterframes', 'stack', 'trace'
]:
if bad in symbols:
log.warn("%s: module MAY be using inspect.%s", module, bad)
safe = False
if '__name__' in symbols and '__main__' in symbols and '.' not in module:
if sys.version[:3] == "2.4": # -m works w/zipfiles in 2.5
log.warn("%s: top-level module may be 'python -m' script", module)
safe = False
return safe
def iter_symbols(code):
"""Yield names and strings used by `code` and its nested code objects"""
for name in code.co_names: yield name
for const in code.co_consts:
if isinstance(const, basestring):
yield const
elif isinstance(const, CodeType):
for name in iter_symbols(const):
yield name
def can_scan():
if not sys.platform.startswith('java') and sys.platform != 'cli':
# CPython, PyPy, etc.
return True
log.warn("Unable to analyze compiled code on this platform.")
log.warn("Please ask the author to include a 'zip_safe'"
" setting (either True or False) in the package's setup.py")
# Attribute names of options for commands that might need to be convinced to
# install to the egg build directory
INSTALL_DIRECTORY_ATTRS = [
'install_lib', 'install_dir', 'install_data', 'install_base'
]
def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=None,
mode='w'):
"""Create a zip file from all the files under 'base_dir'. The output
zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
Python module (if available) or the InfoZIP "zip" utility (if installed
and found on the default search path). If neither tool is available,
raises DistutilsExecError. Returns the name of the output zip file.
"""
import zipfile
mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
def visit(z, dirname, names):
for name in names:
path = os.path.normpath(os.path.join(dirname, name))
if os.path.isfile(path):
p = path[len(base_dir) + 1:]
if not dry_run:
z.write(path, p)
log.debug("adding '%s'" % p)
if compress is None:
compress = (sys.version >= "2.4") # avoid 2.3 zipimport bug when 64 bits
compression = [zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED][bool(compress)]
if not dry_run:
z = zipfile.ZipFile(zip_filename, mode, compression=compression)
for dirname, dirs, files in os.walk(base_dir):
visit(z, dirname, files)
z.close()
else:
for dirname, dirs, files in os.walk(base_dir):
visit(None, dirname, files)
return zip_filename | NATIVE_EXTENSIONS = dict.fromkeys('.dll .so .dylib .pyd'.split())
def walk_egg(egg_dir): | random_line_split |
bdist_egg.py | """setuptools.command.bdist_egg
Build .egg distributions"""
# This module should be kept compatible with Python 2.3
import sys
import os
import marshal
import textwrap
from setuptools import Command
from distutils.dir_util import remove_tree, mkpath
try:
# Python 2.7 or >=3.2
from sysconfig import get_path, get_python_version
def _get_purelib():
return get_path("purelib")
except ImportError:
from distutils.sysconfig import get_python_lib, get_python_version
def _get_purelib():
return get_python_lib(False)
from distutils import log
from distutils.errors import DistutilsSetupError
from pkg_resources import get_build_platform, Distribution, ensure_directory
from pkg_resources import EntryPoint
from types import CodeType
from setuptools.compat import basestring, next
from setuptools.extension import Library
def strip_module(filename):
if '.' in filename:
filename = os.path.splitext(filename)[0]
if filename.endswith('module'):
filename = filename[:-6]
return filename
def write_stub(resource, pyfile):
_stub_template = textwrap.dedent("""
def __bootstrap__():
global __bootstrap__, __loader__, __file__
import sys, pkg_resources, imp
__file__ = pkg_resources.resource_filename(__name__, %r)
__loader__ = None; del __bootstrap__, __loader__
imp.load_dynamic(__name__,__file__)
__bootstrap__()
""").lstrip()
with open(pyfile, 'w') as f:
f.write(_stub_template % resource)
class bdist_egg(Command):
description = "create an \"egg\" distribution"
user_options = [
('bdist-dir=', 'b',
"temporary directory for creating the distribution"),
('plat-name=', 'p', "platform name to embed in generated filenames "
"(default: %s)" % get_build_platform()),
('exclude-source-files', None,
"remove all .py files from the generated egg"),
('keep-temp', 'k',
"keep the pseudo-installation tree around after " +
"creating the distribution archive"),
('dist-dir=', 'd',
"directory to put final built distributions in"),
('skip-build', None,
"skip rebuilding everything (for testing/debugging)"),
]
boolean_options = [
'keep-temp', 'skip-build', 'exclude-source-files'
]
def initialize_options(self):
self.bdist_dir = None
self.plat_name = None
self.keep_temp = 0
self.dist_dir = None
self.skip_build = 0
self.egg_output = None
self.exclude_source_files = None
def finalize_options(self):
ei_cmd = self.ei_cmd = self.get_finalized_command("egg_info")
self.egg_info = ei_cmd.egg_info
if self.bdist_dir is None:
bdist_base = self.get_finalized_command('bdist').bdist_base
self.bdist_dir = os.path.join(bdist_base, 'egg')
if self.plat_name is None:
self.plat_name = get_build_platform()
self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
if self.egg_output is None:
# Compute filename of the output egg
basename = Distribution(
None, None, ei_cmd.egg_name, ei_cmd.egg_version,
get_python_version(),
self.distribution.has_ext_modules() and self.plat_name
).egg_name()
self.egg_output = os.path.join(self.dist_dir, basename + '.egg')
def do_install_data(self):
# Hack for packages that install data to install's --install-lib
self.get_finalized_command('install').install_lib = self.bdist_dir
site_packages = os.path.normcase(os.path.realpath(_get_purelib()))
old, self.distribution.data_files = self.distribution.data_files, []
for item in old:
if isinstance(item, tuple) and len(item) == 2:
if os.path.isabs(item[0]):
realpath = os.path.realpath(item[0])
normalized = os.path.normcase(realpath)
if normalized == site_packages or normalized.startswith(
site_packages + os.sep
):
item = realpath[len(site_packages) + 1:], item[1]
# XXX else: raise ???
self.distribution.data_files.append(item)
try:
log.info("installing package data to %s" % self.bdist_dir)
self.call_command('install_data', force=0, root=None)
finally:
self.distribution.data_files = old
def get_outputs(self):
return [self.egg_output]
def call_command(self, cmdname, **kw):
"""Invoke reinitialized command `cmdname` with keyword args"""
for dirname in INSTALL_DIRECTORY_ATTRS:
kw.setdefault(dirname, self.bdist_dir)
kw.setdefault('skip_build', self.skip_build)
kw.setdefault('dry_run', self.dry_run)
cmd = self.reinitialize_command(cmdname, **kw)
self.run_command(cmdname)
return cmd
def run(self):
# Generate metadata first
self.run_command("egg_info")
# We run install_lib before install_data, because some data hacks
# pull their data path from the install_lib command.
log.info("installing library code to %s" % self.bdist_dir)
instcmd = self.get_finalized_command('install')
old_root = instcmd.root
instcmd.root = None
if self.distribution.has_c_libraries() and not self.skip_build:
self.run_command('build_clib')
cmd = self.call_command('install_lib', warn_dir=0)
instcmd.root = old_root
all_outputs, ext_outputs = self.get_ext_outputs()
self.stubs = []
to_compile = []
for (p, ext_name) in enumerate(ext_outputs):
filename, ext = os.path.splitext(ext_name)
pyfile = os.path.join(self.bdist_dir, strip_module(filename) + '.py')
self.stubs.append(pyfile)
log.info("creating stub loader for %s" % ext_name)
if not self.dry_run:
write_stub(os.path.basename(ext_name), pyfile)
to_compile.append(pyfile)
ext_outputs[p] = ext_name.replace(os.sep, '/')
if to_compile:
cmd.byte_compile(to_compile)
if self.distribution.data_files:
self.do_install_data()
# Make the EGG-INFO directory
archive_root = self.bdist_dir
egg_info = os.path.join(archive_root, 'EGG-INFO')
self.mkpath(egg_info)
if self.distribution.scripts:
script_dir = os.path.join(egg_info, 'scripts')
log.info("installing scripts to %s" % script_dir)
self.call_command('install_scripts', install_dir=script_dir, no_ep=1)
self.copy_metadata_to(egg_info)
native_libs = os.path.join(egg_info, "native_libs.txt")
if all_outputs:
log.info("writing %s" % native_libs)
if not self.dry_run:
ensure_directory(native_libs)
libs_file = open(native_libs, 'wt')
libs_file.write('\n'.join(all_outputs))
libs_file.write('\n')
libs_file.close()
elif os.path.isfile(native_libs):
log.info("removing %s" % native_libs)
if not self.dry_run:
os.unlink(native_libs)
write_safety_flag(
os.path.join(archive_root, 'EGG-INFO'), self.zip_safe()
)
if os.path.exists(os.path.join(self.egg_info, 'depends.txt')):
log.warn(
"WARNING: 'depends.txt' will not be used by setuptools 0.6!\n"
"Use the install_requires/extras_require setup() args instead."
)
if self.exclude_source_files:
self.zap_pyfiles()
# Make the archive
make_zipfile(self.egg_output, archive_root, verbose=self.verbose,
dry_run=self.dry_run, mode=self.gen_header())
if not self.keep_temp:
remove_tree(self.bdist_dir, dry_run=self.dry_run)
# Add to 'Distribution.dist_files' so that the "upload" command works
getattr(self.distribution, 'dist_files', []).append(
('bdist_egg', get_python_version(), self.egg_output))
def zap_pyfiles(self):
log.info("Removing .py files from temporary directory")
for base, dirs, files in walk_egg(self.bdist_dir):
for name in files:
if name.endswith('.py'):
path = os.path.join(base, name)
log.debug("Deleting %s", path)
os.unlink(path)
def zip_safe(self):
safe = getattr(self.distribution, 'zip_safe', None)
if safe is not None:
return safe
log.warn("zip_safe flag not set; analyzing archive contents...")
return analyze_egg(self.bdist_dir, self.stubs)
def gen_header(self):
epm = EntryPoint.parse_map(self.distribution.entry_points or '')
ep = epm.get('setuptools.installation', {}).get('eggsecutable')
if ep is None:
return 'w' # not an eggsecutable, do it the usual way.
if not ep.attrs or ep.extras:
raise DistutilsSetupError(
"eggsecutable entry point (%r) cannot have 'extras' "
"or refer to a module" % (ep,)
)
pyver = sys.version[:3]
pkg = ep.module_name
full = '.'.join(ep.attrs)
base = ep.attrs[0]
basename = os.path.basename(self.egg_output)
header = (
"#!/bin/sh\n"
'if [ `basename $0` = "%(basename)s" ]\n'
'then exec python%(pyver)s -c "'
"import sys, os; sys.path.insert(0, os.path.abspath('$0')); "
"from %(pkg)s import %(base)s; sys.exit(%(full)s())"
'" "$@"\n'
'else\n'
' echo $0 is not the correct name for this egg file.\n'
' echo Please rename it back to %(basename)s and try again.\n'
' exec false\n'
'fi\n'
) % locals()
if not self.dry_run:
mkpath(os.path.dirname(self.egg_output), dry_run=self.dry_run)
f = open(self.egg_output, 'w')
f.write(header)
f.close()
return 'a'
def copy_metadata_to(self, target_dir):
"Copy metadata (egg info) to the target_dir"
# normalize the path (so that a forward-slash in egg_info will
# match using startswith below)
norm_egg_info = os.path.normpath(self.egg_info)
prefix = os.path.join(norm_egg_info, '')
for path in self.ei_cmd.filelist.files:
if path.startswith(prefix):
target = os.path.join(target_dir, path[len(prefix):])
ensure_directory(target)
self.copy_file(path, target)
def get_ext_outputs(self):
"""Get a list of relative paths to C extensions in the output distro"""
all_outputs = []
ext_outputs = []
paths = {self.bdist_dir: ''}
for base, dirs, files in os.walk(self.bdist_dir):
for filename in files:
if os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS:
all_outputs.append(paths[base] + filename)
for filename in dirs:
paths[os.path.join(base, filename)] = paths[base] + filename + '/'
if self.distribution.has_ext_modules():
build_cmd = self.get_finalized_command('build_ext')
for ext in build_cmd.extensions:
if isinstance(ext, Library):
continue
fullname = build_cmd.get_ext_fullname(ext.name)
filename = build_cmd.get_ext_filename(fullname)
if not os.path.basename(filename).startswith('dl-'):
if os.path.exists(os.path.join(self.bdist_dir, filename)):
ext_outputs.append(filename)
return all_outputs, ext_outputs
NATIVE_EXTENSIONS = dict.fromkeys('.dll .so .dylib .pyd'.split())
def walk_egg(egg_dir):
"""Walk an unpacked egg's contents, skipping the metadata directory"""
walker = os.walk(egg_dir)
base, dirs, files = next(walker)
if 'EGG-INFO' in dirs:
dirs.remove('EGG-INFO')
yield base, dirs, files
for bdf in walker:
yield bdf
def analyze_egg(egg_dir, stubs):
# check for existing flag in EGG-INFO
for flag, fn in safety_flags.items():
if os.path.exists(os.path.join(egg_dir, 'EGG-INFO', fn)):
return flag
if not can_scan(): return False
safe = True
for base, dirs, files in walk_egg(egg_dir):
for name in files:
if name.endswith('.py') or name.endswith('.pyw'):
continue
elif name.endswith('.pyc') or name.endswith('.pyo'):
# always scan, even if we already know we're not safe
safe = scan_module(egg_dir, base, name, stubs) and safe
return safe
def write_safety_flag(egg_dir, safe):
# Write or remove zip safety flag file(s)
for flag, fn in safety_flags.items():
fn = os.path.join(egg_dir, fn)
if os.path.exists(fn):
if safe is None or bool(safe) != flag:
os.unlink(fn)
elif safe is not None and bool(safe) == flag:
f = open(fn, 'wt')
f.write('\n')
f.close()
safety_flags = {
True: 'zip-safe',
False: 'not-zip-safe',
}
def scan_module(egg_dir, base, name, stubs):
"""Check whether module possibly uses unsafe-for-zipfile stuff"""
filename = os.path.join(base, name)
if filename[:-1] in stubs:
return True # Extension module
pkg = base[len(egg_dir) + 1:].replace(os.sep, '.')
module = pkg + (pkg and '.' or '') + os.path.splitext(name)[0]
if sys.version_info < (3, 3):
skip = 8 # skip magic & date
else:
skip = 12 # skip magic & date & file size
f = open(filename, 'rb')
f.read(skip)
code = marshal.load(f)
f.close()
safe = True
symbols = dict.fromkeys(iter_symbols(code))
for bad in ['__file__', '__path__']:
if bad in symbols:
log.warn("%s: module references %s", module, bad)
safe = False
if 'inspect' in symbols:
for bad in [
'getsource', 'getabsfile', 'getsourcefile', 'getfile'
'getsourcelines', 'findsource', 'getcomments', 'getframeinfo',
'getinnerframes', 'getouterframes', 'stack', 'trace'
]:
if bad in symbols:
log.warn("%s: module MAY be using inspect.%s", module, bad)
safe = False
if '__name__' in symbols and '__main__' in symbols and '.' not in module:
if sys.version[:3] == "2.4": # -m works w/zipfiles in 2.5
log.warn("%s: top-level module may be 'python -m' script", module)
safe = False
return safe
def iter_symbols(code):
"""Yield names and strings used by `code` and its nested code objects"""
for name in code.co_names: yield name
for const in code.co_consts:
if isinstance(const, basestring):
yield const
elif isinstance(const, CodeType):
for name in iter_symbols(const):
yield name
def can_scan():
if not sys.platform.startswith('java') and sys.platform != 'cli':
# CPython, PyPy, etc.
return True
log.warn("Unable to analyze compiled code on this platform.")
log.warn("Please ask the author to include a 'zip_safe'"
" setting (either True or False) in the package's setup.py")
# Attribute names of options for commands that might need to be convinced to
# install to the egg build directory
INSTALL_DIRECTORY_ATTRS = [
'install_lib', 'install_dir', 'install_data', 'install_base'
]
def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=None,
mode='w'):
"""Create a zip file from all the files under 'base_dir'. The output
zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
Python module (if available) or the InfoZIP "zip" utility (if installed
and found on the default search path). If neither tool is available,
raises DistutilsExecError. Returns the name of the output zip file.
"""
import zipfile
mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
def visit(z, dirname, names):
for name in names:
path = os.path.normpath(os.path.join(dirname, name))
if os.path.isfile(path):
p = path[len(base_dir) + 1:]
if not dry_run:
z.write(path, p)
log.debug("adding '%s'" % p)
if compress is None:
compress = (sys.version >= "2.4") # avoid 2.3 zipimport bug when 64 bits
compression = [zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED][bool(compress)]
if not dry_run:
|
else:
for dirname, dirs, files in os.walk(base_dir):
visit(None, dirname, files)
return zip_filename
| z = zipfile.ZipFile(zip_filename, mode, compression=compression)
for dirname, dirs, files in os.walk(base_dir):
visit(z, dirname, files)
z.close() | conditional_block |
bdist_egg.py | """setuptools.command.bdist_egg
Build .egg distributions"""
# This module should be kept compatible with Python 2.3
import sys
import os
import marshal
import textwrap
from setuptools import Command
from distutils.dir_util import remove_tree, mkpath
try:
# Python 2.7 or >=3.2
from sysconfig import get_path, get_python_version
def _get_purelib():
return get_path("purelib")
except ImportError:
from distutils.sysconfig import get_python_lib, get_python_version
def _get_purelib():
return get_python_lib(False)
from distutils import log
from distutils.errors import DistutilsSetupError
from pkg_resources import get_build_platform, Distribution, ensure_directory
from pkg_resources import EntryPoint
from types import CodeType
from setuptools.compat import basestring, next
from setuptools.extension import Library
def strip_module(filename):
if '.' in filename:
filename = os.path.splitext(filename)[0]
if filename.endswith('module'):
filename = filename[:-6]
return filename
def write_stub(resource, pyfile):
_stub_template = textwrap.dedent("""
def __bootstrap__():
global __bootstrap__, __loader__, __file__
import sys, pkg_resources, imp
__file__ = pkg_resources.resource_filename(__name__, %r)
__loader__ = None; del __bootstrap__, __loader__
imp.load_dynamic(__name__,__file__)
__bootstrap__()
""").lstrip()
with open(pyfile, 'w') as f:
f.write(_stub_template % resource)
class bdist_egg(Command):
description = "create an \"egg\" distribution"
user_options = [
('bdist-dir=', 'b',
"temporary directory for creating the distribution"),
('plat-name=', 'p', "platform name to embed in generated filenames "
"(default: %s)" % get_build_platform()),
('exclude-source-files', None,
"remove all .py files from the generated egg"),
('keep-temp', 'k',
"keep the pseudo-installation tree around after " +
"creating the distribution archive"),
('dist-dir=', 'd',
"directory to put final built distributions in"),
('skip-build', None,
"skip rebuilding everything (for testing/debugging)"),
]
boolean_options = [
'keep-temp', 'skip-build', 'exclude-source-files'
]
def initialize_options(self):
self.bdist_dir = None
self.plat_name = None
self.keep_temp = 0
self.dist_dir = None
self.skip_build = 0
self.egg_output = None
self.exclude_source_files = None
def finalize_options(self):
ei_cmd = self.ei_cmd = self.get_finalized_command("egg_info")
self.egg_info = ei_cmd.egg_info
if self.bdist_dir is None:
bdist_base = self.get_finalized_command('bdist').bdist_base
self.bdist_dir = os.path.join(bdist_base, 'egg')
if self.plat_name is None:
self.plat_name = get_build_platform()
self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
if self.egg_output is None:
# Compute filename of the output egg
basename = Distribution(
None, None, ei_cmd.egg_name, ei_cmd.egg_version,
get_python_version(),
self.distribution.has_ext_modules() and self.plat_name
).egg_name()
self.egg_output = os.path.join(self.dist_dir, basename + '.egg')
def do_install_data(self):
# Hack for packages that install data to install's --install-lib
self.get_finalized_command('install').install_lib = self.bdist_dir
site_packages = os.path.normcase(os.path.realpath(_get_purelib()))
old, self.distribution.data_files = self.distribution.data_files, []
for item in old:
if isinstance(item, tuple) and len(item) == 2:
if os.path.isabs(item[0]):
realpath = os.path.realpath(item[0])
normalized = os.path.normcase(realpath)
if normalized == site_packages or normalized.startswith(
site_packages + os.sep
):
item = realpath[len(site_packages) + 1:], item[1]
# XXX else: raise ???
self.distribution.data_files.append(item)
try:
log.info("installing package data to %s" % self.bdist_dir)
self.call_command('install_data', force=0, root=None)
finally:
self.distribution.data_files = old
def | (self):
return [self.egg_output]
def call_command(self, cmdname, **kw):
"""Invoke reinitialized command `cmdname` with keyword args"""
for dirname in INSTALL_DIRECTORY_ATTRS:
kw.setdefault(dirname, self.bdist_dir)
kw.setdefault('skip_build', self.skip_build)
kw.setdefault('dry_run', self.dry_run)
cmd = self.reinitialize_command(cmdname, **kw)
self.run_command(cmdname)
return cmd
def run(self):
# Generate metadata first
self.run_command("egg_info")
# We run install_lib before install_data, because some data hacks
# pull their data path from the install_lib command.
log.info("installing library code to %s" % self.bdist_dir)
instcmd = self.get_finalized_command('install')
old_root = instcmd.root
instcmd.root = None
if self.distribution.has_c_libraries() and not self.skip_build:
self.run_command('build_clib')
cmd = self.call_command('install_lib', warn_dir=0)
instcmd.root = old_root
all_outputs, ext_outputs = self.get_ext_outputs()
self.stubs = []
to_compile = []
for (p, ext_name) in enumerate(ext_outputs):
filename, ext = os.path.splitext(ext_name)
pyfile = os.path.join(self.bdist_dir, strip_module(filename) + '.py')
self.stubs.append(pyfile)
log.info("creating stub loader for %s" % ext_name)
if not self.dry_run:
write_stub(os.path.basename(ext_name), pyfile)
to_compile.append(pyfile)
ext_outputs[p] = ext_name.replace(os.sep, '/')
if to_compile:
cmd.byte_compile(to_compile)
if self.distribution.data_files:
self.do_install_data()
# Make the EGG-INFO directory
archive_root = self.bdist_dir
egg_info = os.path.join(archive_root, 'EGG-INFO')
self.mkpath(egg_info)
if self.distribution.scripts:
script_dir = os.path.join(egg_info, 'scripts')
log.info("installing scripts to %s" % script_dir)
self.call_command('install_scripts', install_dir=script_dir, no_ep=1)
self.copy_metadata_to(egg_info)
native_libs = os.path.join(egg_info, "native_libs.txt")
if all_outputs:
log.info("writing %s" % native_libs)
if not self.dry_run:
ensure_directory(native_libs)
libs_file = open(native_libs, 'wt')
libs_file.write('\n'.join(all_outputs))
libs_file.write('\n')
libs_file.close()
elif os.path.isfile(native_libs):
log.info("removing %s" % native_libs)
if not self.dry_run:
os.unlink(native_libs)
write_safety_flag(
os.path.join(archive_root, 'EGG-INFO'), self.zip_safe()
)
if os.path.exists(os.path.join(self.egg_info, 'depends.txt')):
log.warn(
"WARNING: 'depends.txt' will not be used by setuptools 0.6!\n"
"Use the install_requires/extras_require setup() args instead."
)
if self.exclude_source_files:
self.zap_pyfiles()
# Make the archive
make_zipfile(self.egg_output, archive_root, verbose=self.verbose,
dry_run=self.dry_run, mode=self.gen_header())
if not self.keep_temp:
remove_tree(self.bdist_dir, dry_run=self.dry_run)
# Add to 'Distribution.dist_files' so that the "upload" command works
getattr(self.distribution, 'dist_files', []).append(
('bdist_egg', get_python_version(), self.egg_output))
def zap_pyfiles(self):
log.info("Removing .py files from temporary directory")
for base, dirs, files in walk_egg(self.bdist_dir):
for name in files:
if name.endswith('.py'):
path = os.path.join(base, name)
log.debug("Deleting %s", path)
os.unlink(path)
def zip_safe(self):
safe = getattr(self.distribution, 'zip_safe', None)
if safe is not None:
return safe
log.warn("zip_safe flag not set; analyzing archive contents...")
return analyze_egg(self.bdist_dir, self.stubs)
def gen_header(self):
epm = EntryPoint.parse_map(self.distribution.entry_points or '')
ep = epm.get('setuptools.installation', {}).get('eggsecutable')
if ep is None:
return 'w' # not an eggsecutable, do it the usual way.
if not ep.attrs or ep.extras:
raise DistutilsSetupError(
"eggsecutable entry point (%r) cannot have 'extras' "
"or refer to a module" % (ep,)
)
pyver = sys.version[:3]
pkg = ep.module_name
full = '.'.join(ep.attrs)
base = ep.attrs[0]
basename = os.path.basename(self.egg_output)
header = (
"#!/bin/sh\n"
'if [ `basename $0` = "%(basename)s" ]\n'
'then exec python%(pyver)s -c "'
"import sys, os; sys.path.insert(0, os.path.abspath('$0')); "
"from %(pkg)s import %(base)s; sys.exit(%(full)s())"
'" "$@"\n'
'else\n'
' echo $0 is not the correct name for this egg file.\n'
' echo Please rename it back to %(basename)s and try again.\n'
' exec false\n'
'fi\n'
) % locals()
if not self.dry_run:
mkpath(os.path.dirname(self.egg_output), dry_run=self.dry_run)
f = open(self.egg_output, 'w')
f.write(header)
f.close()
return 'a'
def copy_metadata_to(self, target_dir):
"Copy metadata (egg info) to the target_dir"
# normalize the path (so that a forward-slash in egg_info will
# match using startswith below)
norm_egg_info = os.path.normpath(self.egg_info)
prefix = os.path.join(norm_egg_info, '')
for path in self.ei_cmd.filelist.files:
if path.startswith(prefix):
target = os.path.join(target_dir, path[len(prefix):])
ensure_directory(target)
self.copy_file(path, target)
def get_ext_outputs(self):
"""Get a list of relative paths to C extensions in the output distro"""
all_outputs = []
ext_outputs = []
paths = {self.bdist_dir: ''}
for base, dirs, files in os.walk(self.bdist_dir):
for filename in files:
if os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS:
all_outputs.append(paths[base] + filename)
for filename in dirs:
paths[os.path.join(base, filename)] = paths[base] + filename + '/'
if self.distribution.has_ext_modules():
build_cmd = self.get_finalized_command('build_ext')
for ext in build_cmd.extensions:
if isinstance(ext, Library):
continue
fullname = build_cmd.get_ext_fullname(ext.name)
filename = build_cmd.get_ext_filename(fullname)
if not os.path.basename(filename).startswith('dl-'):
if os.path.exists(os.path.join(self.bdist_dir, filename)):
ext_outputs.append(filename)
return all_outputs, ext_outputs
NATIVE_EXTENSIONS = dict.fromkeys('.dll .so .dylib .pyd'.split())
def walk_egg(egg_dir):
"""Walk an unpacked egg's contents, skipping the metadata directory"""
walker = os.walk(egg_dir)
base, dirs, files = next(walker)
if 'EGG-INFO' in dirs:
dirs.remove('EGG-INFO')
yield base, dirs, files
for bdf in walker:
yield bdf
def analyze_egg(egg_dir, stubs):
# check for existing flag in EGG-INFO
for flag, fn in safety_flags.items():
if os.path.exists(os.path.join(egg_dir, 'EGG-INFO', fn)):
return flag
if not can_scan(): return False
safe = True
for base, dirs, files in walk_egg(egg_dir):
for name in files:
if name.endswith('.py') or name.endswith('.pyw'):
continue
elif name.endswith('.pyc') or name.endswith('.pyo'):
# always scan, even if we already know we're not safe
safe = scan_module(egg_dir, base, name, stubs) and safe
return safe
def write_safety_flag(egg_dir, safe):
# Write or remove zip safety flag file(s)
for flag, fn in safety_flags.items():
fn = os.path.join(egg_dir, fn)
if os.path.exists(fn):
if safe is None or bool(safe) != flag:
os.unlink(fn)
elif safe is not None and bool(safe) == flag:
f = open(fn, 'wt')
f.write('\n')
f.close()
safety_flags = {
True: 'zip-safe',
False: 'not-zip-safe',
}
def scan_module(egg_dir, base, name, stubs):
"""Check whether module possibly uses unsafe-for-zipfile stuff"""
filename = os.path.join(base, name)
if filename[:-1] in stubs:
return True # Extension module
pkg = base[len(egg_dir) + 1:].replace(os.sep, '.')
module = pkg + (pkg and '.' or '') + os.path.splitext(name)[0]
if sys.version_info < (3, 3):
skip = 8 # skip magic & date
else:
skip = 12 # skip magic & date & file size
f = open(filename, 'rb')
f.read(skip)
code = marshal.load(f)
f.close()
safe = True
symbols = dict.fromkeys(iter_symbols(code))
for bad in ['__file__', '__path__']:
if bad in symbols:
log.warn("%s: module references %s", module, bad)
safe = False
if 'inspect' in symbols:
for bad in [
'getsource', 'getabsfile', 'getsourcefile', 'getfile'
'getsourcelines', 'findsource', 'getcomments', 'getframeinfo',
'getinnerframes', 'getouterframes', 'stack', 'trace'
]:
if bad in symbols:
log.warn("%s: module MAY be using inspect.%s", module, bad)
safe = False
if '__name__' in symbols and '__main__' in symbols and '.' not in module:
if sys.version[:3] == "2.4": # -m works w/zipfiles in 2.5
log.warn("%s: top-level module may be 'python -m' script", module)
safe = False
return safe
def iter_symbols(code):
"""Yield names and strings used by `code` and its nested code objects"""
for name in code.co_names: yield name
for const in code.co_consts:
if isinstance(const, basestring):
yield const
elif isinstance(const, CodeType):
for name in iter_symbols(const):
yield name
def can_scan():
if not sys.platform.startswith('java') and sys.platform != 'cli':
# CPython, PyPy, etc.
return True
log.warn("Unable to analyze compiled code on this platform.")
log.warn("Please ask the author to include a 'zip_safe'"
" setting (either True or False) in the package's setup.py")
# Attribute names of options for commands that might need to be convinced to
# install to the egg build directory
INSTALL_DIRECTORY_ATTRS = [
'install_lib', 'install_dir', 'install_data', 'install_base'
]
def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=None,
mode='w'):
"""Create a zip file from all the files under 'base_dir'. The output
zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
Python module (if available) or the InfoZIP "zip" utility (if installed
and found on the default search path). If neither tool is available,
raises DistutilsExecError. Returns the name of the output zip file.
"""
import zipfile
mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
def visit(z, dirname, names):
for name in names:
path = os.path.normpath(os.path.join(dirname, name))
if os.path.isfile(path):
p = path[len(base_dir) + 1:]
if not dry_run:
z.write(path, p)
log.debug("adding '%s'" % p)
if compress is None:
compress = (sys.version >= "2.4") # avoid 2.3 zipimport bug when 64 bits
compression = [zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED][bool(compress)]
if not dry_run:
z = zipfile.ZipFile(zip_filename, mode, compression=compression)
for dirname, dirs, files in os.walk(base_dir):
visit(z, dirname, files)
z.close()
else:
for dirname, dirs, files in os.walk(base_dir):
visit(None, dirname, files)
return zip_filename
| get_outputs | identifier_name |
bdist_egg.py | """setuptools.command.bdist_egg
Build .egg distributions"""
# This module should be kept compatible with Python 2.3
import sys
import os
import marshal
import textwrap
from setuptools import Command
from distutils.dir_util import remove_tree, mkpath
try:
# Python 2.7 or >=3.2
from sysconfig import get_path, get_python_version
def _get_purelib():
return get_path("purelib")
except ImportError:
from distutils.sysconfig import get_python_lib, get_python_version
def _get_purelib():
return get_python_lib(False)
from distutils import log
from distutils.errors import DistutilsSetupError
from pkg_resources import get_build_platform, Distribution, ensure_directory
from pkg_resources import EntryPoint
from types import CodeType
from setuptools.compat import basestring, next
from setuptools.extension import Library
def strip_module(filename):
if '.' in filename:
filename = os.path.splitext(filename)[0]
if filename.endswith('module'):
filename = filename[:-6]
return filename
def write_stub(resource, pyfile):
_stub_template = textwrap.dedent("""
def __bootstrap__():
global __bootstrap__, __loader__, __file__
import sys, pkg_resources, imp
__file__ = pkg_resources.resource_filename(__name__, %r)
__loader__ = None; del __bootstrap__, __loader__
imp.load_dynamic(__name__,__file__)
__bootstrap__()
""").lstrip()
with open(pyfile, 'w') as f:
f.write(_stub_template % resource)
class bdist_egg(Command):
description = "create an \"egg\" distribution"
user_options = [
('bdist-dir=', 'b',
"temporary directory for creating the distribution"),
('plat-name=', 'p', "platform name to embed in generated filenames "
"(default: %s)" % get_build_platform()),
('exclude-source-files', None,
"remove all .py files from the generated egg"),
('keep-temp', 'k',
"keep the pseudo-installation tree around after " +
"creating the distribution archive"),
('dist-dir=', 'd',
"directory to put final built distributions in"),
('skip-build', None,
"skip rebuilding everything (for testing/debugging)"),
]
boolean_options = [
'keep-temp', 'skip-build', 'exclude-source-files'
]
def initialize_options(self):
self.bdist_dir = None
self.plat_name = None
self.keep_temp = 0
self.dist_dir = None
self.skip_build = 0
self.egg_output = None
self.exclude_source_files = None
def finalize_options(self):
ei_cmd = self.ei_cmd = self.get_finalized_command("egg_info")
self.egg_info = ei_cmd.egg_info
if self.bdist_dir is None:
bdist_base = self.get_finalized_command('bdist').bdist_base
self.bdist_dir = os.path.join(bdist_base, 'egg')
if self.plat_name is None:
self.plat_name = get_build_platform()
self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
if self.egg_output is None:
# Compute filename of the output egg
basename = Distribution(
None, None, ei_cmd.egg_name, ei_cmd.egg_version,
get_python_version(),
self.distribution.has_ext_modules() and self.plat_name
).egg_name()
self.egg_output = os.path.join(self.dist_dir, basename + '.egg')
def do_install_data(self):
# Hack for packages that install data to install's --install-lib
self.get_finalized_command('install').install_lib = self.bdist_dir
site_packages = os.path.normcase(os.path.realpath(_get_purelib()))
old, self.distribution.data_files = self.distribution.data_files, []
for item in old:
if isinstance(item, tuple) and len(item) == 2:
if os.path.isabs(item[0]):
realpath = os.path.realpath(item[0])
normalized = os.path.normcase(realpath)
if normalized == site_packages or normalized.startswith(
site_packages + os.sep
):
item = realpath[len(site_packages) + 1:], item[1]
# XXX else: raise ???
self.distribution.data_files.append(item)
try:
log.info("installing package data to %s" % self.bdist_dir)
self.call_command('install_data', force=0, root=None)
finally:
self.distribution.data_files = old
def get_outputs(self):
return [self.egg_output]
def call_command(self, cmdname, **kw):
"""Invoke reinitialized command `cmdname` with keyword args"""
for dirname in INSTALL_DIRECTORY_ATTRS:
kw.setdefault(dirname, self.bdist_dir)
kw.setdefault('skip_build', self.skip_build)
kw.setdefault('dry_run', self.dry_run)
cmd = self.reinitialize_command(cmdname, **kw)
self.run_command(cmdname)
return cmd
def run(self):
# Generate metadata first
self.run_command("egg_info")
# We run install_lib before install_data, because some data hacks
# pull their data path from the install_lib command.
log.info("installing library code to %s" % self.bdist_dir)
instcmd = self.get_finalized_command('install')
old_root = instcmd.root
instcmd.root = None
if self.distribution.has_c_libraries() and not self.skip_build:
self.run_command('build_clib')
cmd = self.call_command('install_lib', warn_dir=0)
instcmd.root = old_root
all_outputs, ext_outputs = self.get_ext_outputs()
self.stubs = []
to_compile = []
for (p, ext_name) in enumerate(ext_outputs):
filename, ext = os.path.splitext(ext_name)
pyfile = os.path.join(self.bdist_dir, strip_module(filename) + '.py')
self.stubs.append(pyfile)
log.info("creating stub loader for %s" % ext_name)
if not self.dry_run:
write_stub(os.path.basename(ext_name), pyfile)
to_compile.append(pyfile)
ext_outputs[p] = ext_name.replace(os.sep, '/')
if to_compile:
cmd.byte_compile(to_compile)
if self.distribution.data_files:
self.do_install_data()
# Make the EGG-INFO directory
archive_root = self.bdist_dir
egg_info = os.path.join(archive_root, 'EGG-INFO')
self.mkpath(egg_info)
if self.distribution.scripts:
script_dir = os.path.join(egg_info, 'scripts')
log.info("installing scripts to %s" % script_dir)
self.call_command('install_scripts', install_dir=script_dir, no_ep=1)
self.copy_metadata_to(egg_info)
native_libs = os.path.join(egg_info, "native_libs.txt")
if all_outputs:
log.info("writing %s" % native_libs)
if not self.dry_run:
ensure_directory(native_libs)
libs_file = open(native_libs, 'wt')
libs_file.write('\n'.join(all_outputs))
libs_file.write('\n')
libs_file.close()
elif os.path.isfile(native_libs):
log.info("removing %s" % native_libs)
if not self.dry_run:
os.unlink(native_libs)
write_safety_flag(
os.path.join(archive_root, 'EGG-INFO'), self.zip_safe()
)
if os.path.exists(os.path.join(self.egg_info, 'depends.txt')):
log.warn(
"WARNING: 'depends.txt' will not be used by setuptools 0.6!\n"
"Use the install_requires/extras_require setup() args instead."
)
if self.exclude_source_files:
self.zap_pyfiles()
# Make the archive
make_zipfile(self.egg_output, archive_root, verbose=self.verbose,
dry_run=self.dry_run, mode=self.gen_header())
if not self.keep_temp:
remove_tree(self.bdist_dir, dry_run=self.dry_run)
# Add to 'Distribution.dist_files' so that the "upload" command works
getattr(self.distribution, 'dist_files', []).append(
('bdist_egg', get_python_version(), self.egg_output))
def zap_pyfiles(self):
log.info("Removing .py files from temporary directory")
for base, dirs, files in walk_egg(self.bdist_dir):
for name in files:
if name.endswith('.py'):
path = os.path.join(base, name)
log.debug("Deleting %s", path)
os.unlink(path)
def zip_safe(self):
safe = getattr(self.distribution, 'zip_safe', None)
if safe is not None:
return safe
log.warn("zip_safe flag not set; analyzing archive contents...")
return analyze_egg(self.bdist_dir, self.stubs)
def gen_header(self):
epm = EntryPoint.parse_map(self.distribution.entry_points or '')
ep = epm.get('setuptools.installation', {}).get('eggsecutable')
if ep is None:
return 'w' # not an eggsecutable, do it the usual way.
if not ep.attrs or ep.extras:
raise DistutilsSetupError(
"eggsecutable entry point (%r) cannot have 'extras' "
"or refer to a module" % (ep,)
)
pyver = sys.version[:3]
pkg = ep.module_name
full = '.'.join(ep.attrs)
base = ep.attrs[0]
basename = os.path.basename(self.egg_output)
header = (
"#!/bin/sh\n"
'if [ `basename $0` = "%(basename)s" ]\n'
'then exec python%(pyver)s -c "'
"import sys, os; sys.path.insert(0, os.path.abspath('$0')); "
"from %(pkg)s import %(base)s; sys.exit(%(full)s())"
'" "$@"\n'
'else\n'
' echo $0 is not the correct name for this egg file.\n'
' echo Please rename it back to %(basename)s and try again.\n'
' exec false\n'
'fi\n'
) % locals()
if not self.dry_run:
mkpath(os.path.dirname(self.egg_output), dry_run=self.dry_run)
f = open(self.egg_output, 'w')
f.write(header)
f.close()
return 'a'
def copy_metadata_to(self, target_dir):
"Copy metadata (egg info) to the target_dir"
# normalize the path (so that a forward-slash in egg_info will
# match using startswith below)
norm_egg_info = os.path.normpath(self.egg_info)
prefix = os.path.join(norm_egg_info, '')
for path in self.ei_cmd.filelist.files:
if path.startswith(prefix):
target = os.path.join(target_dir, path[len(prefix):])
ensure_directory(target)
self.copy_file(path, target)
def get_ext_outputs(self):
"""Get a list of relative paths to C extensions in the output distro"""
all_outputs = []
ext_outputs = []
paths = {self.bdist_dir: ''}
for base, dirs, files in os.walk(self.bdist_dir):
for filename in files:
if os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS:
all_outputs.append(paths[base] + filename)
for filename in dirs:
paths[os.path.join(base, filename)] = paths[base] + filename + '/'
if self.distribution.has_ext_modules():
build_cmd = self.get_finalized_command('build_ext')
for ext in build_cmd.extensions:
if isinstance(ext, Library):
continue
fullname = build_cmd.get_ext_fullname(ext.name)
filename = build_cmd.get_ext_filename(fullname)
if not os.path.basename(filename).startswith('dl-'):
if os.path.exists(os.path.join(self.bdist_dir, filename)):
ext_outputs.append(filename)
return all_outputs, ext_outputs
NATIVE_EXTENSIONS = dict.fromkeys('.dll .so .dylib .pyd'.split())
def walk_egg(egg_dir):
"""Walk an unpacked egg's contents, skipping the metadata directory"""
walker = os.walk(egg_dir)
base, dirs, files = next(walker)
if 'EGG-INFO' in dirs:
dirs.remove('EGG-INFO')
yield base, dirs, files
for bdf in walker:
yield bdf
def analyze_egg(egg_dir, stubs):
# check for existing flag in EGG-INFO
for flag, fn in safety_flags.items():
if os.path.exists(os.path.join(egg_dir, 'EGG-INFO', fn)):
return flag
if not can_scan(): return False
safe = True
for base, dirs, files in walk_egg(egg_dir):
for name in files:
if name.endswith('.py') or name.endswith('.pyw'):
continue
elif name.endswith('.pyc') or name.endswith('.pyo'):
# always scan, even if we already know we're not safe
safe = scan_module(egg_dir, base, name, stubs) and safe
return safe
def write_safety_flag(egg_dir, safe):
# Write or remove zip safety flag file(s)
for flag, fn in safety_flags.items():
fn = os.path.join(egg_dir, fn)
if os.path.exists(fn):
if safe is None or bool(safe) != flag:
os.unlink(fn)
elif safe is not None and bool(safe) == flag:
f = open(fn, 'wt')
f.write('\n')
f.close()
safety_flags = {
True: 'zip-safe',
False: 'not-zip-safe',
}
def scan_module(egg_dir, base, name, stubs):
"""Check whether module possibly uses unsafe-for-zipfile stuff"""
filename = os.path.join(base, name)
if filename[:-1] in stubs:
return True # Extension module
pkg = base[len(egg_dir) + 1:].replace(os.sep, '.')
module = pkg + (pkg and '.' or '') + os.path.splitext(name)[0]
if sys.version_info < (3, 3):
skip = 8 # skip magic & date
else:
skip = 12 # skip magic & date & file size
f = open(filename, 'rb')
f.read(skip)
code = marshal.load(f)
f.close()
safe = True
symbols = dict.fromkeys(iter_symbols(code))
for bad in ['__file__', '__path__']:
if bad in symbols:
log.warn("%s: module references %s", module, bad)
safe = False
if 'inspect' in symbols:
for bad in [
'getsource', 'getabsfile', 'getsourcefile', 'getfile'
'getsourcelines', 'findsource', 'getcomments', 'getframeinfo',
'getinnerframes', 'getouterframes', 'stack', 'trace'
]:
if bad in symbols:
log.warn("%s: module MAY be using inspect.%s", module, bad)
safe = False
if '__name__' in symbols and '__main__' in symbols and '.' not in module:
if sys.version[:3] == "2.4": # -m works w/zipfiles in 2.5
log.warn("%s: top-level module may be 'python -m' script", module)
safe = False
return safe
def iter_symbols(code):
"""Yield names and strings used by `code` and its nested code objects"""
for name in code.co_names: yield name
for const in code.co_consts:
if isinstance(const, basestring):
yield const
elif isinstance(const, CodeType):
for name in iter_symbols(const):
yield name
def can_scan():
|
# Attribute names of options for commands that might need to be convinced to
# install to the egg build directory
INSTALL_DIRECTORY_ATTRS = [
'install_lib', 'install_dir', 'install_data', 'install_base'
]
def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=None,
mode='w'):
"""Create a zip file from all the files under 'base_dir'. The output
zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
Python module (if available) or the InfoZIP "zip" utility (if installed
and found on the default search path). If neither tool is available,
raises DistutilsExecError. Returns the name of the output zip file.
"""
import zipfile
mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
def visit(z, dirname, names):
for name in names:
path = os.path.normpath(os.path.join(dirname, name))
if os.path.isfile(path):
p = path[len(base_dir) + 1:]
if not dry_run:
z.write(path, p)
log.debug("adding '%s'" % p)
if compress is None:
compress = (sys.version >= "2.4") # avoid 2.3 zipimport bug when 64 bits
compression = [zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED][bool(compress)]
if not dry_run:
z = zipfile.ZipFile(zip_filename, mode, compression=compression)
for dirname, dirs, files in os.walk(base_dir):
visit(z, dirname, files)
z.close()
else:
for dirname, dirs, files in os.walk(base_dir):
visit(None, dirname, files)
return zip_filename
| if not sys.platform.startswith('java') and sys.platform != 'cli':
# CPython, PyPy, etc.
return True
log.warn("Unable to analyze compiled code on this platform.")
log.warn("Please ask the author to include a 'zip_safe'"
" setting (either True or False) in the package's setup.py") | identifier_body |
convertToMappedObjectType.ts | /* @internal */
namespace ts.codefix {
const fixIdAddMissingTypeof = "fixConvertToMappedObjectType";
const fixId = fixIdAddMissingTypeof;
const errorCodes = [Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code];
type FixableDeclaration = InterfaceDeclaration | TypeAliasDeclaration;
registerCodeFix({
errorCodes,
getCodeActions: context => {
const { sourceFile, span } = context;
const info = getInfo(sourceFile, span.start);
if (!info) return undefined;
const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, info));
const name = idText(info.container.name);
return [createCodeFixAction(fixId, changes, [Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [Diagnostics.Convert_0_to_mapped_object_type, name])];
},
fixIds: [fixId],
getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => {
const info = getInfo(diag.file, diag.start);
if (info) doChange(changes, diag.file, info);
})
});
interface Info { readonly indexSignature: IndexSignatureDeclaration; readonly container: FixableDeclaration; }
function getInfo(sourceFile: SourceFile, pos: number): Info | undefined |
function createTypeAliasFromInterface(declaration: FixableDeclaration, type: TypeNode): TypeAliasDeclaration {
return factory.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type);
}
function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, { indexSignature, container }: Info): void {
const members = isInterfaceDeclaration(container) ? container.members : (container.type as TypeLiteralNode).members;
const otherMembers = members.filter(member => !isIndexSignatureDeclaration(member));
const parameter = first(indexSignature.parameters);
const mappedTypeParameter = factory.createTypeParameterDeclaration(cast(parameter.name, isIdentifier), parameter.type);
const mappedIntersectionType = factory.createMappedTypeNode(
hasEffectiveReadonlyModifier(indexSignature) ? factory.createModifier(SyntaxKind.ReadonlyKeyword) : undefined,
mappedTypeParameter,
/*nameType*/ undefined,
indexSignature.questionToken,
indexSignature.type);
const intersectionType = factory.createIntersectionTypeNode([
...getAllSuperTypeNodes(container),
mappedIntersectionType,
...(otherMembers.length ? [factory.createTypeLiteralNode(otherMembers)] : emptyArray),
]);
changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType));
}
}
| {
const token = getTokenAtPosition(sourceFile, pos);
const indexSignature = cast(token.parent.parent, isIndexSignatureDeclaration);
if (isClassDeclaration(indexSignature.parent)) return undefined;
const container = isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : cast(indexSignature.parent.parent, isTypeAliasDeclaration);
return { indexSignature, container };
} | identifier_body |
convertToMappedObjectType.ts | /* @internal */
namespace ts.codefix {
const fixIdAddMissingTypeof = "fixConvertToMappedObjectType";
const fixId = fixIdAddMissingTypeof;
const errorCodes = [Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code];
type FixableDeclaration = InterfaceDeclaration | TypeAliasDeclaration;
registerCodeFix({
errorCodes,
getCodeActions: context => {
const { sourceFile, span } = context;
const info = getInfo(sourceFile, span.start);
if (!info) return undefined;
const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, info));
const name = idText(info.container.name);
return [createCodeFixAction(fixId, changes, [Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [Diagnostics.Convert_0_to_mapped_object_type, name])];
},
fixIds: [fixId],
getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => {
const info = getInfo(diag.file, diag.start);
if (info) doChange(changes, diag.file, info);
})
});
interface Info { readonly indexSignature: IndexSignatureDeclaration; readonly container: FixableDeclaration; }
function | (sourceFile: SourceFile, pos: number): Info | undefined {
const token = getTokenAtPosition(sourceFile, pos);
const indexSignature = cast(token.parent.parent, isIndexSignatureDeclaration);
if (isClassDeclaration(indexSignature.parent)) return undefined;
const container = isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : cast(indexSignature.parent.parent, isTypeAliasDeclaration);
return { indexSignature, container };
}
function createTypeAliasFromInterface(declaration: FixableDeclaration, type: TypeNode): TypeAliasDeclaration {
return factory.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type);
}
function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, { indexSignature, container }: Info): void {
const members = isInterfaceDeclaration(container) ? container.members : (container.type as TypeLiteralNode).members;
const otherMembers = members.filter(member => !isIndexSignatureDeclaration(member));
const parameter = first(indexSignature.parameters);
const mappedTypeParameter = factory.createTypeParameterDeclaration(cast(parameter.name, isIdentifier), parameter.type);
const mappedIntersectionType = factory.createMappedTypeNode(
hasEffectiveReadonlyModifier(indexSignature) ? factory.createModifier(SyntaxKind.ReadonlyKeyword) : undefined,
mappedTypeParameter,
/*nameType*/ undefined,
indexSignature.questionToken,
indexSignature.type);
const intersectionType = factory.createIntersectionTypeNode([
...getAllSuperTypeNodes(container),
mappedIntersectionType,
...(otherMembers.length ? [factory.createTypeLiteralNode(otherMembers)] : emptyArray),
]);
changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType));
}
}
| getInfo | identifier_name |
convertToMappedObjectType.ts | /* @internal */
| const fixId = fixIdAddMissingTypeof;
const errorCodes = [Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code];
type FixableDeclaration = InterfaceDeclaration | TypeAliasDeclaration;
registerCodeFix({
errorCodes,
getCodeActions: context => {
const { sourceFile, span } = context;
const info = getInfo(sourceFile, span.start);
if (!info) return undefined;
const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, info));
const name = idText(info.container.name);
return [createCodeFixAction(fixId, changes, [Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [Diagnostics.Convert_0_to_mapped_object_type, name])];
},
fixIds: [fixId],
getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => {
const info = getInfo(diag.file, diag.start);
if (info) doChange(changes, diag.file, info);
})
});
interface Info { readonly indexSignature: IndexSignatureDeclaration; readonly container: FixableDeclaration; }
function getInfo(sourceFile: SourceFile, pos: number): Info | undefined {
const token = getTokenAtPosition(sourceFile, pos);
const indexSignature = cast(token.parent.parent, isIndexSignatureDeclaration);
if (isClassDeclaration(indexSignature.parent)) return undefined;
const container = isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : cast(indexSignature.parent.parent, isTypeAliasDeclaration);
return { indexSignature, container };
}
function createTypeAliasFromInterface(declaration: FixableDeclaration, type: TypeNode): TypeAliasDeclaration {
return factory.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type);
}
function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, { indexSignature, container }: Info): void {
const members = isInterfaceDeclaration(container) ? container.members : (container.type as TypeLiteralNode).members;
const otherMembers = members.filter(member => !isIndexSignatureDeclaration(member));
const parameter = first(indexSignature.parameters);
const mappedTypeParameter = factory.createTypeParameterDeclaration(cast(parameter.name, isIdentifier), parameter.type);
const mappedIntersectionType = factory.createMappedTypeNode(
hasEffectiveReadonlyModifier(indexSignature) ? factory.createModifier(SyntaxKind.ReadonlyKeyword) : undefined,
mappedTypeParameter,
/*nameType*/ undefined,
indexSignature.questionToken,
indexSignature.type);
const intersectionType = factory.createIntersectionTypeNode([
...getAllSuperTypeNodes(container),
mappedIntersectionType,
...(otherMembers.length ? [factory.createTypeLiteralNode(otherMembers)] : emptyArray),
]);
changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType));
}
} | namespace ts.codefix {
const fixIdAddMissingTypeof = "fixConvertToMappedObjectType";
| random_line_split |
convert.py | # Copyright 2015 OpenStack Foundation
# 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 logging
import os
from oslo_concurrency import processutils as putils
from oslo_config import cfg
from taskflow.patterns import linear_flow as lf
from taskflow import task
from glance import i18n
_ = i18n._
_LI = i18n._LI
_LE = i18n._LE
_LW = i18n._LW
LOG = logging.getLogger(__name__)
convert_task_opts = [
cfg.StrOpt('conversion_format',
default=None,
choices=('qcow2', 'raw', 'vmdk'),
help=_("The format to which images will be automatically "
"converted.")),
]
CONF = cfg.CONF
# NOTE(flaper87): Registering under the taskflow_executor section
# for now. It seems a waste to have a whole section dedicated to a
# single task with a single option.
CONF.register_opts(convert_task_opts, group='taskflow_executor')
class _Convert(task.Task):
conversion_missing_warned = False
def __init__(self, task_id, task_type, image_repo):
self.task_id = task_id
self.task_type = task_type
self.image_repo = image_repo
super(_Convert, self).__init__(
name='%s-Convert-%s' % (task_type, task_id))
def execute(self, image_id, file_path):
# NOTE(flaper87): A format must be explicitly
# specified. There's no "sane" default for this
# because the dest format may work differently depending
# on the environment OpenStack is running in.
conversion_format = CONF.taskflow_executor.conversion_format
if conversion_format is None:
if not _Convert.conversion_missing_warned:
msg = (_LW('The conversion format is None, please add a value '
'for it in the config file for this task to '
'work: %s') %
self.task_id)
LOG.warn(msg)
_Convert.conversion_missing_warned = True
return
# TODO(flaper87): Check whether the image is in the desired
# format already. Probably using `qemu-img` just like the
# `Introspection` task.
dest_path = os.path.join(CONF.task.work_dir, "%s.converted" % image_id)
stdout, stderr = putils.trycmd('qemu-img', 'convert', '-O',
conversion_format, file_path, dest_path,
log_errors=putils.LOG_ALL_ERRORS)
if stderr:
raise RuntimeError(stderr)
os.rename(dest_path, file_path.split("file://")[-1])
return file_path
def revert(self, image_id, result=None, **kwargs):
# NOTE(flaper87): If result is None, it probably
# means this task failed. Otherwise, we would have
# a result from its execution.
if result is None:
return
fs_path = result.split("file://")[-1]
if os.path.exists(fs_path):
os.path.remove(fs_path)
def get_flow(**kwargs):
| """Return task flow for converting images to different formats.
:param task_id: Task ID.
:param task_type: Type of the task.
:param image_repo: Image repository used.
"""
task_id = kwargs.get('task_id')
task_type = kwargs.get('task_type')
image_repo = kwargs.get('image_repo')
return lf.Flow(task_type).add(
_Convert(task_id, task_type, image_repo),
) | identifier_body | |
convert.py | # Copyright 2015 OpenStack Foundation
# 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 logging
import os
from oslo_concurrency import processutils as putils
from oslo_config import cfg
from taskflow.patterns import linear_flow as lf
from taskflow import task
from glance import i18n
_ = i18n._
_LI = i18n._LI
_LE = i18n._LE
_LW = i18n._LW
LOG = logging.getLogger(__name__)
| "converted.")),
]
CONF = cfg.CONF
# NOTE(flaper87): Registering under the taskflow_executor section
# for now. It seems a waste to have a whole section dedicated to a
# single task with a single option.
CONF.register_opts(convert_task_opts, group='taskflow_executor')
class _Convert(task.Task):
conversion_missing_warned = False
def __init__(self, task_id, task_type, image_repo):
self.task_id = task_id
self.task_type = task_type
self.image_repo = image_repo
super(_Convert, self).__init__(
name='%s-Convert-%s' % (task_type, task_id))
def execute(self, image_id, file_path):
# NOTE(flaper87): A format must be explicitly
# specified. There's no "sane" default for this
# because the dest format may work differently depending
# on the environment OpenStack is running in.
conversion_format = CONF.taskflow_executor.conversion_format
if conversion_format is None:
if not _Convert.conversion_missing_warned:
msg = (_LW('The conversion format is None, please add a value '
'for it in the config file for this task to '
'work: %s') %
self.task_id)
LOG.warn(msg)
_Convert.conversion_missing_warned = True
return
# TODO(flaper87): Check whether the image is in the desired
# format already. Probably using `qemu-img` just like the
# `Introspection` task.
dest_path = os.path.join(CONF.task.work_dir, "%s.converted" % image_id)
stdout, stderr = putils.trycmd('qemu-img', 'convert', '-O',
conversion_format, file_path, dest_path,
log_errors=putils.LOG_ALL_ERRORS)
if stderr:
raise RuntimeError(stderr)
os.rename(dest_path, file_path.split("file://")[-1])
return file_path
def revert(self, image_id, result=None, **kwargs):
# NOTE(flaper87): If result is None, it probably
# means this task failed. Otherwise, we would have
# a result from its execution.
if result is None:
return
fs_path = result.split("file://")[-1]
if os.path.exists(fs_path):
os.path.remove(fs_path)
def get_flow(**kwargs):
"""Return task flow for converting images to different formats.
:param task_id: Task ID.
:param task_type: Type of the task.
:param image_repo: Image repository used.
"""
task_id = kwargs.get('task_id')
task_type = kwargs.get('task_type')
image_repo = kwargs.get('image_repo')
return lf.Flow(task_type).add(
_Convert(task_id, task_type, image_repo),
) | convert_task_opts = [
cfg.StrOpt('conversion_format',
default=None,
choices=('qcow2', 'raw', 'vmdk'),
help=_("The format to which images will be automatically " | random_line_split |
convert.py | # Copyright 2015 OpenStack Foundation
# 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 logging
import os
from oslo_concurrency import processutils as putils
from oslo_config import cfg
from taskflow.patterns import linear_flow as lf
from taskflow import task
from glance import i18n
_ = i18n._
_LI = i18n._LI
_LE = i18n._LE
_LW = i18n._LW
LOG = logging.getLogger(__name__)
convert_task_opts = [
cfg.StrOpt('conversion_format',
default=None,
choices=('qcow2', 'raw', 'vmdk'),
help=_("The format to which images will be automatically "
"converted.")),
]
CONF = cfg.CONF
# NOTE(flaper87): Registering under the taskflow_executor section
# for now. It seems a waste to have a whole section dedicated to a
# single task with a single option.
CONF.register_opts(convert_task_opts, group='taskflow_executor')
class _Convert(task.Task):
conversion_missing_warned = False
def | (self, task_id, task_type, image_repo):
self.task_id = task_id
self.task_type = task_type
self.image_repo = image_repo
super(_Convert, self).__init__(
name='%s-Convert-%s' % (task_type, task_id))
def execute(self, image_id, file_path):
# NOTE(flaper87): A format must be explicitly
# specified. There's no "sane" default for this
# because the dest format may work differently depending
# on the environment OpenStack is running in.
conversion_format = CONF.taskflow_executor.conversion_format
if conversion_format is None:
if not _Convert.conversion_missing_warned:
msg = (_LW('The conversion format is None, please add a value '
'for it in the config file for this task to '
'work: %s') %
self.task_id)
LOG.warn(msg)
_Convert.conversion_missing_warned = True
return
# TODO(flaper87): Check whether the image is in the desired
# format already. Probably using `qemu-img` just like the
# `Introspection` task.
dest_path = os.path.join(CONF.task.work_dir, "%s.converted" % image_id)
stdout, stderr = putils.trycmd('qemu-img', 'convert', '-O',
conversion_format, file_path, dest_path,
log_errors=putils.LOG_ALL_ERRORS)
if stderr:
raise RuntimeError(stderr)
os.rename(dest_path, file_path.split("file://")[-1])
return file_path
def revert(self, image_id, result=None, **kwargs):
# NOTE(flaper87): If result is None, it probably
# means this task failed. Otherwise, we would have
# a result from its execution.
if result is None:
return
fs_path = result.split("file://")[-1]
if os.path.exists(fs_path):
os.path.remove(fs_path)
def get_flow(**kwargs):
"""Return task flow for converting images to different formats.
:param task_id: Task ID.
:param task_type: Type of the task.
:param image_repo: Image repository used.
"""
task_id = kwargs.get('task_id')
task_type = kwargs.get('task_type')
image_repo = kwargs.get('image_repo')
return lf.Flow(task_type).add(
_Convert(task_id, task_type, image_repo),
)
| __init__ | identifier_name |
convert.py | # Copyright 2015 OpenStack Foundation
# 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 logging
import os
from oslo_concurrency import processutils as putils
from oslo_config import cfg
from taskflow.patterns import linear_flow as lf
from taskflow import task
from glance import i18n
_ = i18n._
_LI = i18n._LI
_LE = i18n._LE
_LW = i18n._LW
LOG = logging.getLogger(__name__)
convert_task_opts = [
cfg.StrOpt('conversion_format',
default=None,
choices=('qcow2', 'raw', 'vmdk'),
help=_("The format to which images will be automatically "
"converted.")),
]
CONF = cfg.CONF
# NOTE(flaper87): Registering under the taskflow_executor section
# for now. It seems a waste to have a whole section dedicated to a
# single task with a single option.
CONF.register_opts(convert_task_opts, group='taskflow_executor')
class _Convert(task.Task):
conversion_missing_warned = False
def __init__(self, task_id, task_type, image_repo):
self.task_id = task_id
self.task_type = task_type
self.image_repo = image_repo
super(_Convert, self).__init__(
name='%s-Convert-%s' % (task_type, task_id))
def execute(self, image_id, file_path):
# NOTE(flaper87): A format must be explicitly
# specified. There's no "sane" default for this
# because the dest format may work differently depending
# on the environment OpenStack is running in.
conversion_format = CONF.taskflow_executor.conversion_format
if conversion_format is None:
|
# TODO(flaper87): Check whether the image is in the desired
# format already. Probably using `qemu-img` just like the
# `Introspection` task.
dest_path = os.path.join(CONF.task.work_dir, "%s.converted" % image_id)
stdout, stderr = putils.trycmd('qemu-img', 'convert', '-O',
conversion_format, file_path, dest_path,
log_errors=putils.LOG_ALL_ERRORS)
if stderr:
raise RuntimeError(stderr)
os.rename(dest_path, file_path.split("file://")[-1])
return file_path
def revert(self, image_id, result=None, **kwargs):
# NOTE(flaper87): If result is None, it probably
# means this task failed. Otherwise, we would have
# a result from its execution.
if result is None:
return
fs_path = result.split("file://")[-1]
if os.path.exists(fs_path):
os.path.remove(fs_path)
def get_flow(**kwargs):
"""Return task flow for converting images to different formats.
:param task_id: Task ID.
:param task_type: Type of the task.
:param image_repo: Image repository used.
"""
task_id = kwargs.get('task_id')
task_type = kwargs.get('task_type')
image_repo = kwargs.get('image_repo')
return lf.Flow(task_type).add(
_Convert(task_id, task_type, image_repo),
)
| if not _Convert.conversion_missing_warned:
msg = (_LW('The conversion format is None, please add a value '
'for it in the config file for this task to '
'work: %s') %
self.task_id)
LOG.warn(msg)
_Convert.conversion_missing_warned = True
return | conditional_block |
tasks.py | import datetime
import httplib2
import itertools
from django.conf import settings
from django.db import connection
from django.db.models import Sum, Max
from apiclient.discovery import build
from elasticsearch.helpers import bulk_index
from oauth2client.client import OAuth2Credentials
import olympia.core.logger
from olympia import amo
from olympia.amo import search as amo_search
from olympia.addons.models import Addon
from olympia.amo.celery import task
from olympia.bandwagon.models import Collection
from olympia.reviews.models import Review
from olympia.users.models import UserProfile
from olympia.versions.models import Version
from . import search
from .models import (
AddonCollectionCount, CollectionCount, CollectionStats, DownloadCount,
ThemeUserCount, UpdateCount)
log = olympia.core.logger.getLogger('z.task')
@task
def update_addons_collections_downloads(data, **kw):
log.info("[%s] Updating addons+collections download totals." %
(len(data)))
query = (
"UPDATE addons_collections SET downloads=%s WHERE addon_id=%s "
"AND collection_id=%s;" * len(data))
with connection.cursor() as cursor:
cursor.execute(
query,
list(itertools.chain.from_iterable(
[var['sum'], var['addon'], var['collection']]
for var in data)))
@task
def update_collections_total(data, **kw):
log.info("[%s] Updating collections' download totals." %
(len(data)))
for var in data:
(Collection.objects.filter(pk=var['collection_id'])
.update(downloads=var['sum']))
def get_profile_id(service, domain):
"""
Fetch the profile ID for the given domain.
"""
accounts = service.management().accounts().list().execute()
account_ids = [a['id'] for a in accounts.get('items', ())]
for account_id in account_ids:
webproperties = service.management().webproperties().list(
accountId=account_id).execute()
webproperty_ids = [p['id'] for p in webproperties.get('items', ())]
for webproperty_id in webproperty_ids:
profiles = service.management().profiles().list(
accountId=account_id,
webPropertyId=webproperty_id).execute()
for p in profiles.get('items', ()):
# sometimes GA includes "http://", sometimes it doesn't.
if '://' in p['websiteUrl']:
name = p['websiteUrl'].partition('://')[-1]
else:
name = p['websiteUrl']
if name == domain:
return p['id']
@task
def update_google_analytics(date, **kw):
creds_data = getattr(settings, 'GOOGLE_ANALYTICS_CREDENTIALS', None)
if not creds_data:
log.critical('Failed to update global stats: '
'GOOGLE_ANALYTICS_CREDENTIALS not set')
return
creds = OAuth2Credentials(
*[creds_data[k] for k in
('access_token', 'client_id', 'client_secret',
'refresh_token', 'token_expiry', 'token_uri',
'user_agent')])
h = httplib2.Http()
creds.authorize(h)
service = build('analytics', 'v3', http=h)
domain = getattr(settings,
'GOOGLE_ANALYTICS_DOMAIN', None) or settings.DOMAIN
profile_id = get_profile_id(service, domain)
if profile_id is None:
log.critical('Failed to update global stats: could not access a Google'
' Analytics profile for ' + domain)
return
datestr = date.strftime('%Y-%m-%d')
try:
data = service.data().ga().get(ids='ga:' + profile_id,
start_date=datestr,
end_date=datestr,
metrics='ga:visits').execute()
# Storing this under the webtrends stat name so it goes on the
# same graph as the old webtrends data.
p = ['webtrends_DailyVisitors', data['rows'][0][0], date]
except Exception, e:
log.critical(
'Fetching stats data for %s from Google Analytics failed: %s' % e)
return
try:
cursor = connection.cursor()
cursor.execute('REPLACE INTO global_stats (name, count, date) '
'values (%s, %s, %s)', p)
except Exception, e:
log.critical('Failed to update global stats: (%s): %s' % (p, e))
else:
log.debug('Committed global stats details: (%s) has (%s) for (%s)'
% tuple(p))
finally:
cursor.close()
@task
def update_global_totals(job, date, **kw):
log.info('Updating global statistics totals (%s) for (%s)' % (job, date))
jobs = _get_daily_jobs(date)
jobs.update(_get_metrics_jobs(date))
num = jobs[job]()
q = """REPLACE INTO global_stats (`name`, `count`, `date`)
VALUES (%s, %s, %s)"""
p = [job, num or 0, date]
try:
cursor = connection.cursor()
cursor.execute(q, p)
except Exception, e:
log.critical('Failed to update global stats: (%s): %s' % (p, e))
else:
log.debug('Committed global stats details: (%s) has (%s) for (%s)'
% tuple(p))
finally:
cursor.close()
def _get_daily_jobs(date=None):
"""Return a dictionary of statistics queries.
If a date is specified and applies to the job it will be used. Otherwise
the date will default to the previous day.
"""
if not date:
date = datetime.date.today() - datetime.timedelta(days=1)
# Passing through a datetime would not generate an error,
# but would pass and give incorrect values.
if isinstance(date, datetime.datetime):
raise ValueError('This requires a valid date, not a datetime')
# Testing on lte created date doesn't get you todays date, you need to do
# less than next date. That's because 2012-1-1 becomes 2012-1-1 00:00
next_date = date + datetime.timedelta(days=1)
date_str = date.strftime('%Y-%m-%d')
extra = dict(where=['DATE(created)=%s'], params=[date_str])
# If you're editing these, note that you are returning a function! This
# cheesy hackery was done so that we could pass the queries to celery
# lazily and not hammer the db with a ton of these all at once.
stats = {
# Add-on Downloads
'addon_total_downloads': lambda: DownloadCount.objects.filter(
date__lt=next_date).aggregate(sum=Sum('count'))['sum'],
'addon_downloads_new': lambda: DownloadCount.objects.filter(
date=date).aggregate(sum=Sum('count'))['sum'],
# Listed Add-on counts
'addon_count_new': Addon.objects.valid().extra(**extra).count,
# Listed Version counts
'version_count_new': Version.objects.filter(
channel=amo.RELEASE_CHANNEL_LISTED).extra(**extra).count,
# User counts
'user_count_total': UserProfile.objects.filter(
created__lt=next_date).count,
'user_count_new': UserProfile.objects.extra(**extra).count,
# Review counts
'review_count_total': Review.objects.filter(created__lte=date,
editorreview=0).count,
# We can't use "**extra" here, because this query joins on reviews
# itself, and thus raises the following error:
# "Column 'created' in where clause is ambiguous".
'review_count_new': Review.objects.filter(editorreview=0).extra(
where=['DATE(reviews.created)=%s'], params=[date_str]).count,
# Collection counts
'collection_count_total': Collection.objects.filter(
created__lt=next_date).count,
'collection_count_new': Collection.objects.extra(**extra).count,
'collection_addon_downloads': (
lambda: AddonCollectionCount.objects.filter(
date__lte=date).aggregate(sum=Sum('count'))['sum']),
}
# If we're processing today's stats, we'll do some extras. We don't do
# these for re-processed stats because they change over time (eg. add-ons
# move from sandbox -> public
if date == (datetime.date.today() - datetime.timedelta(days=1)):
stats.update({
'addon_count_nominated': Addon.objects.filter(
created__lte=date, status=amo.STATUS_NOMINATED,
disabled_by_user=0).count,
'addon_count_public': Addon.objects.filter(
created__lte=date, status=amo.STATUS_PUBLIC,
disabled_by_user=0).count,
'addon_count_pending': Version.objects.filter(
created__lte=date, files__status=amo.STATUS_PENDING).count,
'collection_count_private': Collection.objects.filter(
created__lte=date, listed=0).count,
'collection_count_public': Collection.objects.filter(
created__lte=date, listed=1).count,
'collection_count_editorspicks': Collection.objects.filter(
created__lte=date, type=amo.COLLECTION_FEATURED).count,
'collection_count_normal': Collection.objects.filter(
created__lte=date, type=amo.COLLECTION_NORMAL).count,
})
return stats
def _get_metrics_jobs(date=None):
"""Return a dictionary of statistics queries.
If a date is specified and applies to the job it will be used. Otherwise
the date will default to the last date metrics put something in the db.
"""
if not date:
date = UpdateCount.objects.aggregate(max=Max('date'))['max']
# If you're editing these, note that you are returning a function!
stats = {
'addon_total_updatepings': lambda: UpdateCount.objects.filter(
date=date).aggregate(sum=Sum('count'))['sum'],
'collector_updatepings': lambda: UpdateCount.objects.get(
addon=settings.ADDON_COLLECTOR_ID, date=date).count,
}
return stats
@task
def index_update_counts(ids, index=None, **kw):
index = index or search.get_alias()
es = amo_search.get_es()
qs = UpdateCount.objects.filter(id__in=ids)
if qs:
log.info('Indexing %s updates for %s.' % (qs.count(), qs[0].date))
data = []
try:
for update in qs:
data.append(search.extract_update_count(update))
bulk_index(es, data, index=index,
doc_type=UpdateCount.get_mapping_type(), refresh=True)
except Exception, exc:
index_update_counts.retry(args=[ids, index], exc=exc, **kw)
raise
@task
def index_download_counts(ids, index=None, **kw):
index = index or search.get_alias()
es = amo_search.get_es()
qs = DownloadCount.objects.filter(id__in=ids)
if qs:
log.info('Indexing %s downloads for %s.' % (qs.count(), qs[0].date))
try:
data = []
for dl in qs:
data.append(search.extract_download_count(dl))
bulk_index(es, data, index=index,
doc_type=DownloadCount.get_mapping_type(), refresh=True)
except Exception, exc:
index_download_counts.retry(args=[ids, index], exc=exc)
raise
@task
def index_collection_counts(ids, index=None, **kw):
index = index or search.get_alias()
es = amo_search.get_es()
qs = CollectionCount.objects.filter(collection__in=ids)
if qs:
log.info('Indexing %s addon collection counts: %s'
% (qs.count(), qs[0].date))
data = []
try:
for collection_count in qs:
collection = collection_count.collection_id
filters = dict(collection=collection,
date=collection_count.date)
data.append(search.extract_addon_collection(
collection_count,
AddonCollectionCount.objects.filter(**filters),
CollectionStats.objects.filter(**filters)))
bulk_index(es, data, index=index,
doc_type=CollectionCount.get_mapping_type(),
refresh=True)
except Exception, exc:
index_collection_counts.retry(args=[ids], exc=exc)
raise
@task
def | (ids, index=None, **kw):
index = index or search.get_alias()
es = amo_search.get_es()
qs = ThemeUserCount.objects.filter(id__in=ids)
if qs:
log.info('Indexing %s theme user counts for %s.'
% (qs.count(), qs[0].date))
data = []
try:
for user_count in qs:
data.append(search.extract_theme_user_count(user_count))
bulk_index(es, data, index=index,
doc_type=ThemeUserCount.get_mapping_type(), refresh=True)
except Exception, exc:
index_theme_user_counts.retry(args=[ids], exc=exc, **kw)
raise
| index_theme_user_counts | identifier_name |
tasks.py | import datetime
import httplib2
import itertools
from django.conf import settings
from django.db import connection
from django.db.models import Sum, Max
from apiclient.discovery import build
from elasticsearch.helpers import bulk_index
from oauth2client.client import OAuth2Credentials
import olympia.core.logger
from olympia import amo
from olympia.amo import search as amo_search
from olympia.addons.models import Addon
from olympia.amo.celery import task
from olympia.bandwagon.models import Collection
from olympia.reviews.models import Review
from olympia.users.models import UserProfile
from olympia.versions.models import Version
from . import search
from .models import (
AddonCollectionCount, CollectionCount, CollectionStats, DownloadCount,
ThemeUserCount, UpdateCount)
log = olympia.core.logger.getLogger('z.task')
@task
def update_addons_collections_downloads(data, **kw):
log.info("[%s] Updating addons+collections download totals." %
(len(data)))
query = (
"UPDATE addons_collections SET downloads=%s WHERE addon_id=%s "
"AND collection_id=%s;" * len(data))
with connection.cursor() as cursor:
cursor.execute(
query,
list(itertools.chain.from_iterable(
[var['sum'], var['addon'], var['collection']]
for var in data)))
@task
def update_collections_total(data, **kw):
|
def get_profile_id(service, domain):
"""
Fetch the profile ID for the given domain.
"""
accounts = service.management().accounts().list().execute()
account_ids = [a['id'] for a in accounts.get('items', ())]
for account_id in account_ids:
webproperties = service.management().webproperties().list(
accountId=account_id).execute()
webproperty_ids = [p['id'] for p in webproperties.get('items', ())]
for webproperty_id in webproperty_ids:
profiles = service.management().profiles().list(
accountId=account_id,
webPropertyId=webproperty_id).execute()
for p in profiles.get('items', ()):
# sometimes GA includes "http://", sometimes it doesn't.
if '://' in p['websiteUrl']:
name = p['websiteUrl'].partition('://')[-1]
else:
name = p['websiteUrl']
if name == domain:
return p['id']
@task
def update_google_analytics(date, **kw):
creds_data = getattr(settings, 'GOOGLE_ANALYTICS_CREDENTIALS', None)
if not creds_data:
log.critical('Failed to update global stats: '
'GOOGLE_ANALYTICS_CREDENTIALS not set')
return
creds = OAuth2Credentials(
*[creds_data[k] for k in
('access_token', 'client_id', 'client_secret',
'refresh_token', 'token_expiry', 'token_uri',
'user_agent')])
h = httplib2.Http()
creds.authorize(h)
service = build('analytics', 'v3', http=h)
domain = getattr(settings,
'GOOGLE_ANALYTICS_DOMAIN', None) or settings.DOMAIN
profile_id = get_profile_id(service, domain)
if profile_id is None:
log.critical('Failed to update global stats: could not access a Google'
' Analytics profile for ' + domain)
return
datestr = date.strftime('%Y-%m-%d')
try:
data = service.data().ga().get(ids='ga:' + profile_id,
start_date=datestr,
end_date=datestr,
metrics='ga:visits').execute()
# Storing this under the webtrends stat name so it goes on the
# same graph as the old webtrends data.
p = ['webtrends_DailyVisitors', data['rows'][0][0], date]
except Exception, e:
log.critical(
'Fetching stats data for %s from Google Analytics failed: %s' % e)
return
try:
cursor = connection.cursor()
cursor.execute('REPLACE INTO global_stats (name, count, date) '
'values (%s, %s, %s)', p)
except Exception, e:
log.critical('Failed to update global stats: (%s): %s' % (p, e))
else:
log.debug('Committed global stats details: (%s) has (%s) for (%s)'
% tuple(p))
finally:
cursor.close()
@task
def update_global_totals(job, date, **kw):
log.info('Updating global statistics totals (%s) for (%s)' % (job, date))
jobs = _get_daily_jobs(date)
jobs.update(_get_metrics_jobs(date))
num = jobs[job]()
q = """REPLACE INTO global_stats (`name`, `count`, `date`)
VALUES (%s, %s, %s)"""
p = [job, num or 0, date]
try:
cursor = connection.cursor()
cursor.execute(q, p)
except Exception, e:
log.critical('Failed to update global stats: (%s): %s' % (p, e))
else:
log.debug('Committed global stats details: (%s) has (%s) for (%s)'
% tuple(p))
finally:
cursor.close()
def _get_daily_jobs(date=None):
"""Return a dictionary of statistics queries.
If a date is specified and applies to the job it will be used. Otherwise
the date will default to the previous day.
"""
if not date:
date = datetime.date.today() - datetime.timedelta(days=1)
# Passing through a datetime would not generate an error,
# but would pass and give incorrect values.
if isinstance(date, datetime.datetime):
raise ValueError('This requires a valid date, not a datetime')
# Testing on lte created date doesn't get you todays date, you need to do
# less than next date. That's because 2012-1-1 becomes 2012-1-1 00:00
next_date = date + datetime.timedelta(days=1)
date_str = date.strftime('%Y-%m-%d')
extra = dict(where=['DATE(created)=%s'], params=[date_str])
# If you're editing these, note that you are returning a function! This
# cheesy hackery was done so that we could pass the queries to celery
# lazily and not hammer the db with a ton of these all at once.
stats = {
# Add-on Downloads
'addon_total_downloads': lambda: DownloadCount.objects.filter(
date__lt=next_date).aggregate(sum=Sum('count'))['sum'],
'addon_downloads_new': lambda: DownloadCount.objects.filter(
date=date).aggregate(sum=Sum('count'))['sum'],
# Listed Add-on counts
'addon_count_new': Addon.objects.valid().extra(**extra).count,
# Listed Version counts
'version_count_new': Version.objects.filter(
channel=amo.RELEASE_CHANNEL_LISTED).extra(**extra).count,
# User counts
'user_count_total': UserProfile.objects.filter(
created__lt=next_date).count,
'user_count_new': UserProfile.objects.extra(**extra).count,
# Review counts
'review_count_total': Review.objects.filter(created__lte=date,
editorreview=0).count,
# We can't use "**extra" here, because this query joins on reviews
# itself, and thus raises the following error:
# "Column 'created' in where clause is ambiguous".
'review_count_new': Review.objects.filter(editorreview=0).extra(
where=['DATE(reviews.created)=%s'], params=[date_str]).count,
# Collection counts
'collection_count_total': Collection.objects.filter(
created__lt=next_date).count,
'collection_count_new': Collection.objects.extra(**extra).count,
'collection_addon_downloads': (
lambda: AddonCollectionCount.objects.filter(
date__lte=date).aggregate(sum=Sum('count'))['sum']),
}
# If we're processing today's stats, we'll do some extras. We don't do
# these for re-processed stats because they change over time (eg. add-ons
# move from sandbox -> public
if date == (datetime.date.today() - datetime.timedelta(days=1)):
stats.update({
'addon_count_nominated': Addon.objects.filter(
created__lte=date, status=amo.STATUS_NOMINATED,
disabled_by_user=0).count,
'addon_count_public': Addon.objects.filter(
created__lte=date, status=amo.STATUS_PUBLIC,
disabled_by_user=0).count,
'addon_count_pending': Version.objects.filter(
created__lte=date, files__status=amo.STATUS_PENDING).count,
'collection_count_private': Collection.objects.filter(
created__lte=date, listed=0).count,
'collection_count_public': Collection.objects.filter(
created__lte=date, listed=1).count,
'collection_count_editorspicks': Collection.objects.filter(
created__lte=date, type=amo.COLLECTION_FEATURED).count,
'collection_count_normal': Collection.objects.filter(
created__lte=date, type=amo.COLLECTION_NORMAL).count,
})
return stats
def _get_metrics_jobs(date=None):
"""Return a dictionary of statistics queries.
If a date is specified and applies to the job it will be used. Otherwise
the date will default to the last date metrics put something in the db.
"""
if not date:
date = UpdateCount.objects.aggregate(max=Max('date'))['max']
# If you're editing these, note that you are returning a function!
stats = {
'addon_total_updatepings': lambda: UpdateCount.objects.filter(
date=date).aggregate(sum=Sum('count'))['sum'],
'collector_updatepings': lambda: UpdateCount.objects.get(
addon=settings.ADDON_COLLECTOR_ID, date=date).count,
}
return stats
@task
def index_update_counts(ids, index=None, **kw):
index = index or search.get_alias()
es = amo_search.get_es()
qs = UpdateCount.objects.filter(id__in=ids)
if qs:
log.info('Indexing %s updates for %s.' % (qs.count(), qs[0].date))
data = []
try:
for update in qs:
data.append(search.extract_update_count(update))
bulk_index(es, data, index=index,
doc_type=UpdateCount.get_mapping_type(), refresh=True)
except Exception, exc:
index_update_counts.retry(args=[ids, index], exc=exc, **kw)
raise
@task
def index_download_counts(ids, index=None, **kw):
index = index or search.get_alias()
es = amo_search.get_es()
qs = DownloadCount.objects.filter(id__in=ids)
if qs:
log.info('Indexing %s downloads for %s.' % (qs.count(), qs[0].date))
try:
data = []
for dl in qs:
data.append(search.extract_download_count(dl))
bulk_index(es, data, index=index,
doc_type=DownloadCount.get_mapping_type(), refresh=True)
except Exception, exc:
index_download_counts.retry(args=[ids, index], exc=exc)
raise
@task
def index_collection_counts(ids, index=None, **kw):
index = index or search.get_alias()
es = amo_search.get_es()
qs = CollectionCount.objects.filter(collection__in=ids)
if qs:
log.info('Indexing %s addon collection counts: %s'
% (qs.count(), qs[0].date))
data = []
try:
for collection_count in qs:
collection = collection_count.collection_id
filters = dict(collection=collection,
date=collection_count.date)
data.append(search.extract_addon_collection(
collection_count,
AddonCollectionCount.objects.filter(**filters),
CollectionStats.objects.filter(**filters)))
bulk_index(es, data, index=index,
doc_type=CollectionCount.get_mapping_type(),
refresh=True)
except Exception, exc:
index_collection_counts.retry(args=[ids], exc=exc)
raise
@task
def index_theme_user_counts(ids, index=None, **kw):
index = index or search.get_alias()
es = amo_search.get_es()
qs = ThemeUserCount.objects.filter(id__in=ids)
if qs:
log.info('Indexing %s theme user counts for %s.'
% (qs.count(), qs[0].date))
data = []
try:
for user_count in qs:
data.append(search.extract_theme_user_count(user_count))
bulk_index(es, data, index=index,
doc_type=ThemeUserCount.get_mapping_type(), refresh=True)
except Exception, exc:
index_theme_user_counts.retry(args=[ids], exc=exc, **kw)
raise
| log.info("[%s] Updating collections' download totals." %
(len(data)))
for var in data:
(Collection.objects.filter(pk=var['collection_id'])
.update(downloads=var['sum'])) | identifier_body |
tasks.py | import datetime
import httplib2
import itertools
from django.conf import settings
from django.db import connection
from django.db.models import Sum, Max
from apiclient.discovery import build
from elasticsearch.helpers import bulk_index
from oauth2client.client import OAuth2Credentials
import olympia.core.logger
from olympia import amo
from olympia.amo import search as amo_search
from olympia.addons.models import Addon
from olympia.amo.celery import task
from olympia.bandwagon.models import Collection
from olympia.reviews.models import Review
from olympia.users.models import UserProfile
from olympia.versions.models import Version
from . import search
from .models import (
AddonCollectionCount, CollectionCount, CollectionStats, DownloadCount,
ThemeUserCount, UpdateCount)
log = olympia.core.logger.getLogger('z.task')
@task
def update_addons_collections_downloads(data, **kw):
log.info("[%s] Updating addons+collections download totals." %
(len(data)))
query = (
"UPDATE addons_collections SET downloads=%s WHERE addon_id=%s "
"AND collection_id=%s;" * len(data))
with connection.cursor() as cursor:
cursor.execute(
query,
list(itertools.chain.from_iterable(
[var['sum'], var['addon'], var['collection']]
for var in data)))
@task
def update_collections_total(data, **kw):
log.info("[%s] Updating collections' download totals." %
(len(data)))
for var in data:
(Collection.objects.filter(pk=var['collection_id'])
.update(downloads=var['sum']))
def get_profile_id(service, domain):
"""
Fetch the profile ID for the given domain.
"""
accounts = service.management().accounts().list().execute()
account_ids = [a['id'] for a in accounts.get('items', ())]
for account_id in account_ids:
webproperties = service.management().webproperties().list(
accountId=account_id).execute()
webproperty_ids = [p['id'] for p in webproperties.get('items', ())]
for webproperty_id in webproperty_ids:
profiles = service.management().profiles().list(
accountId=account_id,
webPropertyId=webproperty_id).execute()
for p in profiles.get('items', ()):
# sometimes GA includes "http://", sometimes it doesn't. |
if name == domain:
return p['id']
@task
def update_google_analytics(date, **kw):
creds_data = getattr(settings, 'GOOGLE_ANALYTICS_CREDENTIALS', None)
if not creds_data:
log.critical('Failed to update global stats: '
'GOOGLE_ANALYTICS_CREDENTIALS not set')
return
creds = OAuth2Credentials(
*[creds_data[k] for k in
('access_token', 'client_id', 'client_secret',
'refresh_token', 'token_expiry', 'token_uri',
'user_agent')])
h = httplib2.Http()
creds.authorize(h)
service = build('analytics', 'v3', http=h)
domain = getattr(settings,
'GOOGLE_ANALYTICS_DOMAIN', None) or settings.DOMAIN
profile_id = get_profile_id(service, domain)
if profile_id is None:
log.critical('Failed to update global stats: could not access a Google'
' Analytics profile for ' + domain)
return
datestr = date.strftime('%Y-%m-%d')
try:
data = service.data().ga().get(ids='ga:' + profile_id,
start_date=datestr,
end_date=datestr,
metrics='ga:visits').execute()
# Storing this under the webtrends stat name so it goes on the
# same graph as the old webtrends data.
p = ['webtrends_DailyVisitors', data['rows'][0][0], date]
except Exception, e:
log.critical(
'Fetching stats data for %s from Google Analytics failed: %s' % e)
return
try:
cursor = connection.cursor()
cursor.execute('REPLACE INTO global_stats (name, count, date) '
'values (%s, %s, %s)', p)
except Exception, e:
log.critical('Failed to update global stats: (%s): %s' % (p, e))
else:
log.debug('Committed global stats details: (%s) has (%s) for (%s)'
% tuple(p))
finally:
cursor.close()
@task
def update_global_totals(job, date, **kw):
log.info('Updating global statistics totals (%s) for (%s)' % (job, date))
jobs = _get_daily_jobs(date)
jobs.update(_get_metrics_jobs(date))
num = jobs[job]()
q = """REPLACE INTO global_stats (`name`, `count`, `date`)
VALUES (%s, %s, %s)"""
p = [job, num or 0, date]
try:
cursor = connection.cursor()
cursor.execute(q, p)
except Exception, e:
log.critical('Failed to update global stats: (%s): %s' % (p, e))
else:
log.debug('Committed global stats details: (%s) has (%s) for (%s)'
% tuple(p))
finally:
cursor.close()
def _get_daily_jobs(date=None):
"""Return a dictionary of statistics queries.
If a date is specified and applies to the job it will be used. Otherwise
the date will default to the previous day.
"""
if not date:
date = datetime.date.today() - datetime.timedelta(days=1)
# Passing through a datetime would not generate an error,
# but would pass and give incorrect values.
if isinstance(date, datetime.datetime):
raise ValueError('This requires a valid date, not a datetime')
# Testing on lte created date doesn't get you todays date, you need to do
# less than next date. That's because 2012-1-1 becomes 2012-1-1 00:00
next_date = date + datetime.timedelta(days=1)
date_str = date.strftime('%Y-%m-%d')
extra = dict(where=['DATE(created)=%s'], params=[date_str])
# If you're editing these, note that you are returning a function! This
# cheesy hackery was done so that we could pass the queries to celery
# lazily and not hammer the db with a ton of these all at once.
stats = {
# Add-on Downloads
'addon_total_downloads': lambda: DownloadCount.objects.filter(
date__lt=next_date).aggregate(sum=Sum('count'))['sum'],
'addon_downloads_new': lambda: DownloadCount.objects.filter(
date=date).aggregate(sum=Sum('count'))['sum'],
# Listed Add-on counts
'addon_count_new': Addon.objects.valid().extra(**extra).count,
# Listed Version counts
'version_count_new': Version.objects.filter(
channel=amo.RELEASE_CHANNEL_LISTED).extra(**extra).count,
# User counts
'user_count_total': UserProfile.objects.filter(
created__lt=next_date).count,
'user_count_new': UserProfile.objects.extra(**extra).count,
# Review counts
'review_count_total': Review.objects.filter(created__lte=date,
editorreview=0).count,
# We can't use "**extra" here, because this query joins on reviews
# itself, and thus raises the following error:
# "Column 'created' in where clause is ambiguous".
'review_count_new': Review.objects.filter(editorreview=0).extra(
where=['DATE(reviews.created)=%s'], params=[date_str]).count,
# Collection counts
'collection_count_total': Collection.objects.filter(
created__lt=next_date).count,
'collection_count_new': Collection.objects.extra(**extra).count,
'collection_addon_downloads': (
lambda: AddonCollectionCount.objects.filter(
date__lte=date).aggregate(sum=Sum('count'))['sum']),
}
# If we're processing today's stats, we'll do some extras. We don't do
# these for re-processed stats because they change over time (eg. add-ons
# move from sandbox -> public
if date == (datetime.date.today() - datetime.timedelta(days=1)):
stats.update({
'addon_count_nominated': Addon.objects.filter(
created__lte=date, status=amo.STATUS_NOMINATED,
disabled_by_user=0).count,
'addon_count_public': Addon.objects.filter(
created__lte=date, status=amo.STATUS_PUBLIC,
disabled_by_user=0).count,
'addon_count_pending': Version.objects.filter(
created__lte=date, files__status=amo.STATUS_PENDING).count,
'collection_count_private': Collection.objects.filter(
created__lte=date, listed=0).count,
'collection_count_public': Collection.objects.filter(
created__lte=date, listed=1).count,
'collection_count_editorspicks': Collection.objects.filter(
created__lte=date, type=amo.COLLECTION_FEATURED).count,
'collection_count_normal': Collection.objects.filter(
created__lte=date, type=amo.COLLECTION_NORMAL).count,
})
return stats
def _get_metrics_jobs(date=None):
"""Return a dictionary of statistics queries.
If a date is specified and applies to the job it will be used. Otherwise
the date will default to the last date metrics put something in the db.
"""
if not date:
date = UpdateCount.objects.aggregate(max=Max('date'))['max']
# If you're editing these, note that you are returning a function!
stats = {
'addon_total_updatepings': lambda: UpdateCount.objects.filter(
date=date).aggregate(sum=Sum('count'))['sum'],
'collector_updatepings': lambda: UpdateCount.objects.get(
addon=settings.ADDON_COLLECTOR_ID, date=date).count,
}
return stats
@task
def index_update_counts(ids, index=None, **kw):
index = index or search.get_alias()
es = amo_search.get_es()
qs = UpdateCount.objects.filter(id__in=ids)
if qs:
log.info('Indexing %s updates for %s.' % (qs.count(), qs[0].date))
data = []
try:
for update in qs:
data.append(search.extract_update_count(update))
bulk_index(es, data, index=index,
doc_type=UpdateCount.get_mapping_type(), refresh=True)
except Exception, exc:
index_update_counts.retry(args=[ids, index], exc=exc, **kw)
raise
@task
def index_download_counts(ids, index=None, **kw):
index = index or search.get_alias()
es = amo_search.get_es()
qs = DownloadCount.objects.filter(id__in=ids)
if qs:
log.info('Indexing %s downloads for %s.' % (qs.count(), qs[0].date))
try:
data = []
for dl in qs:
data.append(search.extract_download_count(dl))
bulk_index(es, data, index=index,
doc_type=DownloadCount.get_mapping_type(), refresh=True)
except Exception, exc:
index_download_counts.retry(args=[ids, index], exc=exc)
raise
@task
def index_collection_counts(ids, index=None, **kw):
index = index or search.get_alias()
es = amo_search.get_es()
qs = CollectionCount.objects.filter(collection__in=ids)
if qs:
log.info('Indexing %s addon collection counts: %s'
% (qs.count(), qs[0].date))
data = []
try:
for collection_count in qs:
collection = collection_count.collection_id
filters = dict(collection=collection,
date=collection_count.date)
data.append(search.extract_addon_collection(
collection_count,
AddonCollectionCount.objects.filter(**filters),
CollectionStats.objects.filter(**filters)))
bulk_index(es, data, index=index,
doc_type=CollectionCount.get_mapping_type(),
refresh=True)
except Exception, exc:
index_collection_counts.retry(args=[ids], exc=exc)
raise
@task
def index_theme_user_counts(ids, index=None, **kw):
index = index or search.get_alias()
es = amo_search.get_es()
qs = ThemeUserCount.objects.filter(id__in=ids)
if qs:
log.info('Indexing %s theme user counts for %s.'
% (qs.count(), qs[0].date))
data = []
try:
for user_count in qs:
data.append(search.extract_theme_user_count(user_count))
bulk_index(es, data, index=index,
doc_type=ThemeUserCount.get_mapping_type(), refresh=True)
except Exception, exc:
index_theme_user_counts.retry(args=[ids], exc=exc, **kw)
raise | if '://' in p['websiteUrl']:
name = p['websiteUrl'].partition('://')[-1]
else:
name = p['websiteUrl'] | random_line_split |
tasks.py | import datetime
import httplib2
import itertools
from django.conf import settings
from django.db import connection
from django.db.models import Sum, Max
from apiclient.discovery import build
from elasticsearch.helpers import bulk_index
from oauth2client.client import OAuth2Credentials
import olympia.core.logger
from olympia import amo
from olympia.amo import search as amo_search
from olympia.addons.models import Addon
from olympia.amo.celery import task
from olympia.bandwagon.models import Collection
from olympia.reviews.models import Review
from olympia.users.models import UserProfile
from olympia.versions.models import Version
from . import search
from .models import (
AddonCollectionCount, CollectionCount, CollectionStats, DownloadCount,
ThemeUserCount, UpdateCount)
log = olympia.core.logger.getLogger('z.task')
@task
def update_addons_collections_downloads(data, **kw):
log.info("[%s] Updating addons+collections download totals." %
(len(data)))
query = (
"UPDATE addons_collections SET downloads=%s WHERE addon_id=%s "
"AND collection_id=%s;" * len(data))
with connection.cursor() as cursor:
cursor.execute(
query,
list(itertools.chain.from_iterable(
[var['sum'], var['addon'], var['collection']]
for var in data)))
@task
def update_collections_total(data, **kw):
log.info("[%s] Updating collections' download totals." %
(len(data)))
for var in data:
(Collection.objects.filter(pk=var['collection_id'])
.update(downloads=var['sum']))
def get_profile_id(service, domain):
"""
Fetch the profile ID for the given domain.
"""
accounts = service.management().accounts().list().execute()
account_ids = [a['id'] for a in accounts.get('items', ())]
for account_id in account_ids:
webproperties = service.management().webproperties().list(
accountId=account_id).execute()
webproperty_ids = [p['id'] for p in webproperties.get('items', ())]
for webproperty_id in webproperty_ids:
profiles = service.management().profiles().list(
accountId=account_id,
webPropertyId=webproperty_id).execute()
for p in profiles.get('items', ()):
# sometimes GA includes "http://", sometimes it doesn't.
if '://' in p['websiteUrl']:
name = p['websiteUrl'].partition('://')[-1]
else:
name = p['websiteUrl']
if name == domain:
return p['id']
@task
def update_google_analytics(date, **kw):
creds_data = getattr(settings, 'GOOGLE_ANALYTICS_CREDENTIALS', None)
if not creds_data:
log.critical('Failed to update global stats: '
'GOOGLE_ANALYTICS_CREDENTIALS not set')
return
creds = OAuth2Credentials(
*[creds_data[k] for k in
('access_token', 'client_id', 'client_secret',
'refresh_token', 'token_expiry', 'token_uri',
'user_agent')])
h = httplib2.Http()
creds.authorize(h)
service = build('analytics', 'v3', http=h)
domain = getattr(settings,
'GOOGLE_ANALYTICS_DOMAIN', None) or settings.DOMAIN
profile_id = get_profile_id(service, domain)
if profile_id is None:
log.critical('Failed to update global stats: could not access a Google'
' Analytics profile for ' + domain)
return
datestr = date.strftime('%Y-%m-%d')
try:
data = service.data().ga().get(ids='ga:' + profile_id,
start_date=datestr,
end_date=datestr,
metrics='ga:visits').execute()
# Storing this under the webtrends stat name so it goes on the
# same graph as the old webtrends data.
p = ['webtrends_DailyVisitors', data['rows'][0][0], date]
except Exception, e:
log.critical(
'Fetching stats data for %s from Google Analytics failed: %s' % e)
return
try:
cursor = connection.cursor()
cursor.execute('REPLACE INTO global_stats (name, count, date) '
'values (%s, %s, %s)', p)
except Exception, e:
log.critical('Failed to update global stats: (%s): %s' % (p, e))
else:
log.debug('Committed global stats details: (%s) has (%s) for (%s)'
% tuple(p))
finally:
cursor.close()
@task
def update_global_totals(job, date, **kw):
log.info('Updating global statistics totals (%s) for (%s)' % (job, date))
jobs = _get_daily_jobs(date)
jobs.update(_get_metrics_jobs(date))
num = jobs[job]()
q = """REPLACE INTO global_stats (`name`, `count`, `date`)
VALUES (%s, %s, %s)"""
p = [job, num or 0, date]
try:
cursor = connection.cursor()
cursor.execute(q, p)
except Exception, e:
log.critical('Failed to update global stats: (%s): %s' % (p, e))
else:
log.debug('Committed global stats details: (%s) has (%s) for (%s)'
% tuple(p))
finally:
cursor.close()
def _get_daily_jobs(date=None):
"""Return a dictionary of statistics queries.
If a date is specified and applies to the job it will be used. Otherwise
the date will default to the previous day.
"""
if not date:
date = datetime.date.today() - datetime.timedelta(days=1)
# Passing through a datetime would not generate an error,
# but would pass and give incorrect values.
if isinstance(date, datetime.datetime):
raise ValueError('This requires a valid date, not a datetime')
# Testing on lte created date doesn't get you todays date, you need to do
# less than next date. That's because 2012-1-1 becomes 2012-1-1 00:00
next_date = date + datetime.timedelta(days=1)
date_str = date.strftime('%Y-%m-%d')
extra = dict(where=['DATE(created)=%s'], params=[date_str])
# If you're editing these, note that you are returning a function! This
# cheesy hackery was done so that we could pass the queries to celery
# lazily and not hammer the db with a ton of these all at once.
stats = {
# Add-on Downloads
'addon_total_downloads': lambda: DownloadCount.objects.filter(
date__lt=next_date).aggregate(sum=Sum('count'))['sum'],
'addon_downloads_new': lambda: DownloadCount.objects.filter(
date=date).aggregate(sum=Sum('count'))['sum'],
# Listed Add-on counts
'addon_count_new': Addon.objects.valid().extra(**extra).count,
# Listed Version counts
'version_count_new': Version.objects.filter(
channel=amo.RELEASE_CHANNEL_LISTED).extra(**extra).count,
# User counts
'user_count_total': UserProfile.objects.filter(
created__lt=next_date).count,
'user_count_new': UserProfile.objects.extra(**extra).count,
# Review counts
'review_count_total': Review.objects.filter(created__lte=date,
editorreview=0).count,
# We can't use "**extra" here, because this query joins on reviews
# itself, and thus raises the following error:
# "Column 'created' in where clause is ambiguous".
'review_count_new': Review.objects.filter(editorreview=0).extra(
where=['DATE(reviews.created)=%s'], params=[date_str]).count,
# Collection counts
'collection_count_total': Collection.objects.filter(
created__lt=next_date).count,
'collection_count_new': Collection.objects.extra(**extra).count,
'collection_addon_downloads': (
lambda: AddonCollectionCount.objects.filter(
date__lte=date).aggregate(sum=Sum('count'))['sum']),
}
# If we're processing today's stats, we'll do some extras. We don't do
# these for re-processed stats because they change over time (eg. add-ons
# move from sandbox -> public
if date == (datetime.date.today() - datetime.timedelta(days=1)):
stats.update({
'addon_count_nominated': Addon.objects.filter(
created__lte=date, status=amo.STATUS_NOMINATED,
disabled_by_user=0).count,
'addon_count_public': Addon.objects.filter(
created__lte=date, status=amo.STATUS_PUBLIC,
disabled_by_user=0).count,
'addon_count_pending': Version.objects.filter(
created__lte=date, files__status=amo.STATUS_PENDING).count,
'collection_count_private': Collection.objects.filter(
created__lte=date, listed=0).count,
'collection_count_public': Collection.objects.filter(
created__lte=date, listed=1).count,
'collection_count_editorspicks': Collection.objects.filter(
created__lte=date, type=amo.COLLECTION_FEATURED).count,
'collection_count_normal': Collection.objects.filter(
created__lte=date, type=amo.COLLECTION_NORMAL).count,
})
return stats
def _get_metrics_jobs(date=None):
"""Return a dictionary of statistics queries.
If a date is specified and applies to the job it will be used. Otherwise
the date will default to the last date metrics put something in the db.
"""
if not date:
date = UpdateCount.objects.aggregate(max=Max('date'))['max']
# If you're editing these, note that you are returning a function!
stats = {
'addon_total_updatepings': lambda: UpdateCount.objects.filter(
date=date).aggregate(sum=Sum('count'))['sum'],
'collector_updatepings': lambda: UpdateCount.objects.get(
addon=settings.ADDON_COLLECTOR_ID, date=date).count,
}
return stats
@task
def index_update_counts(ids, index=None, **kw):
index = index or search.get_alias()
es = amo_search.get_es()
qs = UpdateCount.objects.filter(id__in=ids)
if qs:
log.info('Indexing %s updates for %s.' % (qs.count(), qs[0].date))
data = []
try:
for update in qs:
data.append(search.extract_update_count(update))
bulk_index(es, data, index=index,
doc_type=UpdateCount.get_mapping_type(), refresh=True)
except Exception, exc:
index_update_counts.retry(args=[ids, index], exc=exc, **kw)
raise
@task
def index_download_counts(ids, index=None, **kw):
index = index or search.get_alias()
es = amo_search.get_es()
qs = DownloadCount.objects.filter(id__in=ids)
if qs:
log.info('Indexing %s downloads for %s.' % (qs.count(), qs[0].date))
try:
data = []
for dl in qs:
|
bulk_index(es, data, index=index,
doc_type=DownloadCount.get_mapping_type(), refresh=True)
except Exception, exc:
index_download_counts.retry(args=[ids, index], exc=exc)
raise
@task
def index_collection_counts(ids, index=None, **kw):
index = index or search.get_alias()
es = amo_search.get_es()
qs = CollectionCount.objects.filter(collection__in=ids)
if qs:
log.info('Indexing %s addon collection counts: %s'
% (qs.count(), qs[0].date))
data = []
try:
for collection_count in qs:
collection = collection_count.collection_id
filters = dict(collection=collection,
date=collection_count.date)
data.append(search.extract_addon_collection(
collection_count,
AddonCollectionCount.objects.filter(**filters),
CollectionStats.objects.filter(**filters)))
bulk_index(es, data, index=index,
doc_type=CollectionCount.get_mapping_type(),
refresh=True)
except Exception, exc:
index_collection_counts.retry(args=[ids], exc=exc)
raise
@task
def index_theme_user_counts(ids, index=None, **kw):
index = index or search.get_alias()
es = amo_search.get_es()
qs = ThemeUserCount.objects.filter(id__in=ids)
if qs:
log.info('Indexing %s theme user counts for %s.'
% (qs.count(), qs[0].date))
data = []
try:
for user_count in qs:
data.append(search.extract_theme_user_count(user_count))
bulk_index(es, data, index=index,
doc_type=ThemeUserCount.get_mapping_type(), refresh=True)
except Exception, exc:
index_theme_user_counts.retry(args=[ids], exc=exc, **kw)
raise
| data.append(search.extract_download_count(dl)) | conditional_block |
gcmservice.js | //Server settings for android push notifications with node-gcm
// Load modules
var express = require('express');
var gcm = require('node-gcm');
// The apiKey of your project on FCM
var app = express();
//var apiKey = "AAAAjo8JDg0:APA91bEkbzZbEgR7eXY1jKgmJZhoW3GaNmRYf5yICNQQEOcaHxZuYtOKLNSK98T9aFAiUpkLUukldgsYDPBvVcEWEabVnQeKyBGWWM-O7yrrufGe2N-40x4I07WLvveL8O3dzDAKKKM7";
// var apiKey = "AAAA7qUjTrg:APA91bFW2oVQ1mE9u2ANPjFy8IfkMWVGrHs0f1b1Umd_K1DDfng9h0e0hRQih8mLaXCPvu35xHBq9recmJ1EGJiCk7o2qwdN2n3FYPwHr21_p4iP2z1mgZGDdZo-uFLGrRxpqXM5L_tRvudTQJTxxH2IpQC0VquYPQ";
//iadapt
var apiKey = "AAAAjo8JDg0:APA91bEkbzZbEgR7eXY1jKgmJZhoW3GaNmRYf5yICNQQEOcaHxZuYtOKLNSK98T9aFAiUpkLUukldgsYDPBvVcEWEabVnQeKyBGWWM-O7yrrufGe2N-40x4I07WLvveL8O3dzDAKKKM7";
//Set up the server
var server = app.listen(3000, function() {
console.log('server is just fine!');
});
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
//Define the basic route
app.get('/', function(req, res) {
res.send("This is basic route");
});
app.post('/register', function(req, res) {
var device_token;
device_token = req.body.device_token;
console.log('device token received');
console.log(device_token);
res.send('ok');
});
app.get('/push', function(req, res) {
//Initialize the service
var service = new gcm.Sender(apiKey);
//the number of times to retry sending the message if it fails
var retry_times = 4;
/***** Define the message for Android Devices *****/
var message_Android = new gcm.Message();
//The title will be shown in the notification center
message_Android.addData('title', 'Hello, World');
message_Android.addData('message', 'This is a notification that will be displayed ASAP.');
//Add action buttons, set the foreground property to true the app will be brought to the front
//if foreground is false then the callback is run without the app being brought to the foreground.
message_Android.addData('actions', [
{ "icon": "accept", "title": "Accept", "callback": "window.accept", "foreground": true },
{ "icon": "reject", "title": "Reject", "callback": "window.reject", "foreground": false },
]);
//Set content-available = 1, the on('notification') event handler will be called
//even app running in background or closed
message_Android.addData('content-available', '1');
//Give every message a unique id
message_Android.addData('notId', Math.ceil(Math.random() * 100));
//priority can be: -2: minimum, -1: low, 0: default , 1: high, 2: maximum priority.
//Set priority will inform the user on the screen even though in the background or close the app.
//This priority value determines where the push notification will be put in the notification shade.
message_Android.addData('priority', 1);
/* message_Android.addData('style', 'inbox');
message_Android.addData('summaryText', 'There are %n% notifications');*/
message_Android.addData('data', { 'type': 'New Medicine', 'id': 1112 });
/***** Define the message for IOS Devices *****/
// var message_IOS = new gcm.Message({
// contentAvailable: true,
// // priority: 'high',
// notification: {
// "sound": "default",
// "icon": "default",
// title: "Hello, World",
// body: 'This is a notification that will be displayed ASAP.',
// 'click-action': 'invite'
// },
// //Add additional data to the payload
// data: {
// 'type': 'New Medicine',
// 'data': 1112,
// notId: Math.random() * 100,
// }
// });
// var payload = {
// // 'content_available': true,
// // 'prioriry': 'high',
// // notification: {
// // 'title': 'Hellow world notif',
// // 'body': 'Notification Body for both IOS and Android' | // // },
// data: {
// 'content-available': '1',
// 'priority': 1,
// 'title': 'Hellow world data',
// 'message': 'Notification Message for both IOS and Android',
// // 'icon': 'default',
// // 'sound': 'default',
// 'notId': Math.random() * 100,
// // 'actions': [
// // { "icon": "accept", "title": "Accept", "callback": "window.accept", "foreground": true },
// // { "icon": "reject", "title": "Reject", "callback": "window.reject", "foreground": false },
// // ],
// 'data': {
// 'type': 'TEST'
// }
// }
// }
// //for android
payload = {
"data": {
'priority': 1,
"content-available": "1",
"notId": Math.random() * 100,
"data": "{\n \"timestamp\" : \"2017-04-14T23:37:12Z\",\n \"content\" : \"{\\n \\\"id\\\" : 8\\n}\",\n \"type\" : \"update_goal\"\n}",
"title": "Update goal",
"message": "Goal was updated"
}
}
var message = new gcm.Message(payload); //console.log(message, message.toJson(), message_Android.toJson());
//Here get the devices from your database into an array
var deviceID_Android = "es9CSkHH6GM:APA91bH2o9_kSiV0Lv4cu5lTS30nYlHc6XzwiFqm8uFr8U8OVT7jn1Y2nGbDODDUE9P4LPwlVZxUuUhAYlRC5sUQDy2A6GJQz7emiF_1NY82QTiDczWzqJ2VaKhfiqZf8ha6M7BcCik0";
//var deviceID_Android = "m3kHS4BnrF0:APA91bGDRjNibKqDkMooSmaQlO2xVTE3D1FvmNzqttO6l_yeLCQwztRv3FY-R92T3En-3TdwH403c_4Dr7qMPL-l6PAG10-_E7pOkUhGgZXOImuYbvl29mDcwZI-WIwzUGpQUUTIzaf3";
// var deviceID_IOS = "nO19ipNbiYU:APA91bGkIiKA57BXw_IpI2rT9_gnFag3-1cbiNHDavS9N1MKqo4rk7E-oKhkp5ej--9WVtqugVolC4C6YrCOC1-3y99Q6LbbBTlrQMv36vnNKR1yUiLXi_7zvJPrhGILxbS-4DF831gN";
var deviceID_IOS = "mFtMmQH2nJs:APA91bEL6oNDbMYtJZfGInMBnBLzZ_rACEb_07BAugaDx8t68Hl8AnKIYsHw_mC23gxtcStHIvavlEEXz-HqcgGwJ_NIrMLY7HdtY6Fs0SZaw8ThWHO_n9i_UGnSo4BnrdN98BX4sVor";
/**** Send Notifications to Android devices *****/
console.log(message.toJson());
service.send(message, { registrationTokens: [deviceID_Android] }, retry_times, function(err, response) {
if (err)
console.error(err);
else
console.log(response);
});
/**** Send Notifications to IOS devices *****/
// // for ios
payload = {
"notification": {
"sound": "default",
"icon": "default",
"body": "Notify in Body",
"title": "Title Notification"
},
"contentAvailable": true,
"priority": "high",
"data": {
// "content-available": '1',
// "priority": 1,
"notId": Math.random() * 100,
"data": "{\"type\" : \"update_goal\"\n}",
"title": "Title Data",
"message": "Message in Data"
}
}
message = new gcm.Message(payload);
console.log(message.toJson());
service.send(message, { registrationTokens: [deviceID_IOS] }, retry_times, function(err, response) {
if (err)
console.error(err);
else
console.log(response);
});
}); | random_line_split | |
selectplace.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2003-2006 Donald N. Allingham
# Copyright (C) 2009-2010 Gary Burton
# Copyright (C) 2010 Nick Hall
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# $Id$
#-------------------------------------------------------------------------
#
# internationalization
#
#-------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.get_translation().gettext
#-------------------------------------------------------------------------
#
# gramps modules
#
#-------------------------------------------------------------------------
from ..views.treemodels.placemodel import PlaceListModel
from .baseselector import BaseSelector
#-------------------------------------------------------------------------
#
# SelectPlace
#
#-------------------------------------------------------------------------
class | (BaseSelector):
def _local_init(self):
"""
Perform local initialisation for this class
"""
self.width_key = 'interface.place-sel-width'
self.height_key = 'interface.place-sel-height'
def get_window_title(self):
return _("Select Place")
def get_model_class(self):
return PlaceListModel
def get_column_titles(self):
return [
(_('Title'), 350, BaseSelector.TEXT, 0),
(_('ID'), 75, BaseSelector.TEXT, 1),
(_('Street'), 75, BaseSelector.TEXT, 2),
(_('Locality'), 75, BaseSelector.TEXT, 3),
(_('City'), 75, BaseSelector.TEXT, 4),
(_('County'), 75, BaseSelector.TEXT, 5),
(_('State'), 75, BaseSelector.TEXT, 6),
(_('Country'), 75, BaseSelector.TEXT, 7),
(_('Parish'), 75, BaseSelector.TEXT, 9),
]
def get_from_handle_func(self):
return self.db.get_place_from_handle
| SelectPlace | identifier_name |
selectplace.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2003-2006 Donald N. Allingham
# Copyright (C) 2009-2010 Gary Burton
# Copyright (C) 2010 Nick Hall
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# $Id$
#-------------------------------------------------------------------------
#
# internationalization
#
#-------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.get_translation().gettext
#-------------------------------------------------------------------------
#
# gramps modules
#
#-------------------------------------------------------------------------
from ..views.treemodels.placemodel import PlaceListModel
from .baseselector import BaseSelector
#------------------------------------------------------------------------- | #
#-------------------------------------------------------------------------
class SelectPlace(BaseSelector):
def _local_init(self):
"""
Perform local initialisation for this class
"""
self.width_key = 'interface.place-sel-width'
self.height_key = 'interface.place-sel-height'
def get_window_title(self):
return _("Select Place")
def get_model_class(self):
return PlaceListModel
def get_column_titles(self):
return [
(_('Title'), 350, BaseSelector.TEXT, 0),
(_('ID'), 75, BaseSelector.TEXT, 1),
(_('Street'), 75, BaseSelector.TEXT, 2),
(_('Locality'), 75, BaseSelector.TEXT, 3),
(_('City'), 75, BaseSelector.TEXT, 4),
(_('County'), 75, BaseSelector.TEXT, 5),
(_('State'), 75, BaseSelector.TEXT, 6),
(_('Country'), 75, BaseSelector.TEXT, 7),
(_('Parish'), 75, BaseSelector.TEXT, 9),
]
def get_from_handle_func(self):
return self.db.get_place_from_handle | #
# SelectPlace | random_line_split |
selectplace.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2003-2006 Donald N. Allingham
# Copyright (C) 2009-2010 Gary Burton
# Copyright (C) 2010 Nick Hall
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# $Id$
#-------------------------------------------------------------------------
#
# internationalization
#
#-------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.get_translation().gettext
#-------------------------------------------------------------------------
#
# gramps modules
#
#-------------------------------------------------------------------------
from ..views.treemodels.placemodel import PlaceListModel
from .baseselector import BaseSelector
#-------------------------------------------------------------------------
#
# SelectPlace
#
#-------------------------------------------------------------------------
class SelectPlace(BaseSelector):
def _local_init(self):
"""
Perform local initialisation for this class
"""
self.width_key = 'interface.place-sel-width'
self.height_key = 'interface.place-sel-height'
def get_window_title(self):
return _("Select Place")
def get_model_class(self):
|
def get_column_titles(self):
return [
(_('Title'), 350, BaseSelector.TEXT, 0),
(_('ID'), 75, BaseSelector.TEXT, 1),
(_('Street'), 75, BaseSelector.TEXT, 2),
(_('Locality'), 75, BaseSelector.TEXT, 3),
(_('City'), 75, BaseSelector.TEXT, 4),
(_('County'), 75, BaseSelector.TEXT, 5),
(_('State'), 75, BaseSelector.TEXT, 6),
(_('Country'), 75, BaseSelector.TEXT, 7),
(_('Parish'), 75, BaseSelector.TEXT, 9),
]
def get_from_handle_func(self):
return self.db.get_place_from_handle
| return PlaceListModel | identifier_body |
admin.py | # Amara, universalsubtitles.org
#
# Copyright (C) 2016 Participatory Culture Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License |
# Based on: http://www.djangosnippets.org/snippets/73/
#
# Modified by Sean Reifschneider to be smarter about surrounding page
# link context. For usage documentation see:
#
# http://www.tummy.com/Community/Articles/django-pagination/
from django.contrib import admin
from django.conf import settings
from openid_consumer.models import Nonce, Association
admin.site.register(Nonce)
admin.site.register(Association) | # along with this program. If not, see
# http://www.gnu.org/licenses/agpl-3.0.html. | random_line_split |
tr_global.js | var mdeps = require('../');
var test = require('tape');
var JSONStream = require('JSONStream');
var packer = require('browser-pack');
var concat = require('concat-stream');
var path = require('path');
test('global transforms', function (t) { |
var p = mdeps({
transform: [ 'tr-c', 'tr-d' ],
globalTransform: [
path.join(__dirname, '/files/tr_global/node_modules/tr-e'),
path.join(__dirname, '/files/tr_global/node_modules/tr-f')
],
transformKey: [ 'browserify', 'transform' ]
});
p.end(path.join(__dirname, '/files/tr_global/main.js'));
var pack = packer();
p.pipe(JSONStream.stringify()).pipe(pack).pipe(concat(function (src) {
Function(['console'], src)({
log: function (msg) {
t.equal(msg, 111111);
}
});
}));
}); | t.plan(1); | random_line_split |
music_hack.py | #!/usr/bin/env python
from __future__ import division
import krpc
import vlc
import time
import random
import yaml
import os
import socket
import math
import logging
import sys
from collections import deque
import argparse
class Player(object):
def __init__(self, path, preload=True):
self.instance = vlc.Instance()
self.player = self.instance.media_player_new()
self.preload = preload
self.config = {}
self.tracks = self.parse_tracks(path)
self.conn = None
self.tracks_played = {scene:0 for scene in self.tracks}
self.poll_rate = self.config["poll_rate"]
self.current_scene = "SpaceCenter"
def can_connect(self):
address = (self.config["address"], self.config["rpc_port"])
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.connect(address)
s.shutdown(socket.SHUT_RDWR)
s.close()
return True
except Exception as e:
logging.debug(e)
return False
def wait_for_server(self):
gamelog = GameLog(self.config["gamelog"], self.config["poll_rate"])
gamelog.wait_for_game_start(self)
while True:
if self.can_connect() or gamelog.loaded_save():
self.player.stop()
logging.info("Save game loaded.")
return
if gamelog.loaded():
self.player.stop()
self.play_next_track("MainMenu")
logging.info("Main Menu reached")
logging.debug("Game still loading.")
time.sleep(self.poll_rate / 10)
def connect(self, name="Music Player"):
self.conn = krpc.connect(name=name,
address=self.config["address"],
rpc_port=self.config["rpc_port"],
stream_port=self.config["stream_port"])
def get_current_scene(self):
try:
self.conn.space_center.active_vessel
return "Flight", True
except (OSError, socket.error, KeyboardInterrupt):
print("Lost connection.")
return None, True
except krpc.error.RPCError as e:
try:
scene = str(e)[str(e).index("'") + 1:str(e).rindex("'")]
return scene, self.current_scene != scene
except:
return "SpaceCenter", self.current_scene != scene
def play(self):
while True:
try:
self.current_scene, changed = self.get_current_scene()
if not self.current_scene:
return
if self.current_scene == "Flight":
self.play_flight_music()
else:
self.play_scene_music(changed)
time.sleep(self.poll_rate)
except (OSError, socket.error, KeyboardInterrupt):
print("Connection lost.")
return
def select_track(self, scene):
""""Handle avoiding repetition of tracks and empty playlists."""
try:
total_tracks = len(self.tracks[scene])
except KeyError:
return None
if not total_tracks:
return None
if self.tracks_played[scene] == total_tracks:
last = self.tracks[scene][-1]
self.tracks[scene] = random.sample(self.tracks[scene][:-1], total_tracks - 1)
self.tracks[scene].append(last)
self.tracks_played[scene] = 0
result = self.tracks[scene][self.tracks_played[scene]]
self.tracks_played[scene] += 1
if not self.preload:
result = self.load_track(result)
return result
def play_next_track(self, scene):
while True:
next_track = self.select_track(scene)
if not next_track:
return
if self.play_track(next_track):
return
def play_scene_music(self, changed):
if changed:
self.player.stop()
if not self.player.is_playing():
self.play_next_track(self.current_scene)
def play_flight_music(self):
self.player.stop()
while True:
self.current_scene, changed = self.get_current_scene()
if self.current_scene != "Flight":
return
vessel = self.conn.space_center.active_vessel
current_body = vessel.orbit.body
# We're going to switch away from polling here to
# avoid unnecessary requests. We need to keep an eye
# out for the transitioning outside of the atmosphere
try:
with self.conn.stream(getattr, vessel.flight(), "mean_altitude") as altitude:
while altitude() < current_body.atmosphere_depth:
current_body = vessel.orbit.body
if self.player.is_playing():
self.player.stop()
while altitude() >= current_body.atmosphere_depth:
current_body = vessel.orbit.body
if not self.player.is_playing():
self.play_next_track("Space")
if vessel.parts.controlling.docking_port and self.tracks["Docking"]:
self.player.stop()
self.play_next_track("Docking")
while vessel.parts.controlling.docking_port:
if not self.player.is_playing():
self.play_next_track("Docking")
time.sleep(self.poll_rate * 0.25)
self.fade_out(1.5)
if self.conn.space_center.target_vessel and self.tracks["Rendezvous"]:
distance = math.sqrt(sum([i**2 for i in (self.conn.space_center.target_vessel.position(self.conn.space_center.active_vessel.reference_frame))]))
rendezvous_distance = self.config["rendezvous_distance"]
if distance < rendezvous_distance:
self.fade_out(1.5)
self.play_next_track("Rendezvous")
try:
with self.conn.stream(vessel.position, self.conn.space_center.target_vessel.reference_frame) as position:
while math.sqrt(sum([i**2 for i in position()])) < rendezvous_distance:
if not self.player.is_playing():
self.play_next_track("Rendezvous")
if not self.conn.space_center.target_vessel:
break
except AttributeError:
continue
finally:
self.fade_out(1.5)
except krpc.error.RPCError:
continue
def play_track(self, track):
self.player.set_media(track)
if self.player.play() == -1:
logging.warning("Couldn't play a file. Skipping.")
return False
logging.info("Playing {}.".format(track.get_mrl()))
time.sleep(self.poll_rate)
return True
def fade_out(self, seconds):
starting_volume = self.player.audio_get_volume()
sleep_increment = seconds / starting_volume
for i in range(starting_volume):
self.player.audio_set_volume(max(int(starting_volume - i), 1))
time.sleep(sleep_increment)
self.player.pause()
self.player.audio_set_volume(int(starting_volume))
self.player.stop()
def load_track(self, path):
if path[0:4] != "http":
return self.instance.media_new(os.path.abspath(path))
return self.instance.media_new(path)
def parse_tracks(self, path):
result = {}
with open(path) as text:
stuff = yaml.load(text)
for k in stuff:
if k in ["gamelog", "address", "rpc_port", "stream_port", "poll_rate", "rendezvous_distance"]:
self.config[k] = stuff[k]
continue
result[k] = []
try:
for v in stuff[k]:
if os.path.isfile(v) or v[0:4] == "http":
if self.preload:
result[k].append(self.load_track(v))
else:
result[k].append(v)
elif os.path.isdir(v):
for f in os.listdir(v):
if os.path.isfile(os.path.join(v,f)):
if self.preload:
|
else:
result[k].append(os.path.join(v, f))
else:
logging.warning("{}: {} not found.".format(k, v))
logging.info("{}: {} tracks loaded".format(k, len(result[k])))
random.shuffle(result[k])
except TypeError:
logging.warning("No music in {0}. Disabling music for {0}.".format(k))
return result
class GameLog(object):
def __init__(self, path, poll_rate, maxlen=10):
self.size = os.path.getsize(path)
self.path = path
self.valid = (path is not None) and os.path.isfile(path)
if not self.valid:
logging.warning("Invalid gamelog path!")
self.loaded_flag = False
self.size_history = deque(range(maxlen), maxlen=maxlen)
self.poll_rate = poll_rate
self.update_size()
def wait_for_game_start(self, player):
logging.info("Waiting for game start...")
if self.valid:
while True:
self.update_size()
if self.get_diff() != 0 or player.can_connect():
logging.info("Game started.")
return
time.sleep(self.poll_rate)
def loaded(self):
"""Return True only once after loaded."""
self.update_size()
lines = self.get_changed_lines()
if self.valid and not self.loaded_flag:
for line in lines:
if "Scene Change : From LOADING to MAINMENU" in line:
self.loaded_flag = True
return True
if all([i == self.size_history[0] for i in self.size_history]):
logging.info("Log hasn't changed for a while. Assume loaded.")
self.loaded_flag = True
return True
return False
def loaded_save(self):
self.update_size()
lines = self.get_changed_lines()
if self.valid:
for line in lines:
if "Scene Change : From MAINMENU to SPACECENTER" in line:
return True
return False
def update_size(self):
if self.valid:
self.size_history.append(os.path.getsize(self.path))
def get_size(self):
return self.size_history[-1]
def get_diff(self):
return self.size_history[-1] - self.size_history[-2]
def get_changed_lines(self):
if self.valid:
with open(self.path, 'r') as log:
log.seek(self.get_diff(), 2)
return log.readlines()
def main():
parser = argparse.ArgumentParser(description="Custom soundtrack player for Kerbal Space Program")
parser.add_argument("--config_path", "-c", default="music.yaml")
parser.add_argument('--verbose', '-v', action='count')
args = parser.parse_args()
levels = {1:logging.INFO, 2:logging.DEBUG}
logging.basicConfig(level=levels.get(args.verbose, logging.WARNING))
config_path = args.config_path
try:
player = Player(config_path)
player.wait_for_server()
player.connect()
player.play()
except KeyboardInterrupt:
print("Quit.")
if __name__ == "__main__":
main()
| result[k].append(self.load_track(os.path.join(v, f))) | conditional_block |
music_hack.py | #!/usr/bin/env python
from __future__ import division
import krpc
import vlc
import time
import random
import yaml
import os
import socket
import math
import logging
import sys
from collections import deque
import argparse
class Player(object):
def __init__(self, path, preload=True):
self.instance = vlc.Instance()
self.player = self.instance.media_player_new()
self.preload = preload
self.config = {}
self.tracks = self.parse_tracks(path)
self.conn = None
self.tracks_played = {scene:0 for scene in self.tracks}
self.poll_rate = self.config["poll_rate"]
self.current_scene = "SpaceCenter"
def can_connect(self):
address = (self.config["address"], self.config["rpc_port"])
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.connect(address)
s.shutdown(socket.SHUT_RDWR)
s.close()
return True
except Exception as e:
logging.debug(e)
return False
def wait_for_server(self):
gamelog = GameLog(self.config["gamelog"], self.config["poll_rate"])
gamelog.wait_for_game_start(self)
while True:
if self.can_connect() or gamelog.loaded_save():
self.player.stop()
logging.info("Save game loaded.")
return
if gamelog.loaded():
self.player.stop()
self.play_next_track("MainMenu")
logging.info("Main Menu reached")
logging.debug("Game still loading.")
time.sleep(self.poll_rate / 10)
def connect(self, name="Music Player"):
self.conn = krpc.connect(name=name,
address=self.config["address"],
rpc_port=self.config["rpc_port"],
stream_port=self.config["stream_port"])
def get_current_scene(self):
try:
self.conn.space_center.active_vessel
return "Flight", True
except (OSError, socket.error, KeyboardInterrupt):
print("Lost connection.")
return None, True
except krpc.error.RPCError as e:
try:
scene = str(e)[str(e).index("'") + 1:str(e).rindex("'")]
return scene, self.current_scene != scene
except:
return "SpaceCenter", self.current_scene != scene
def play(self):
while True:
try:
self.current_scene, changed = self.get_current_scene()
if not self.current_scene:
return
if self.current_scene == "Flight":
self.play_flight_music()
else:
self.play_scene_music(changed)
time.sleep(self.poll_rate)
except (OSError, socket.error, KeyboardInterrupt):
print("Connection lost.")
return
def select_track(self, scene):
""""Handle avoiding repetition of tracks and empty playlists."""
try:
total_tracks = len(self.tracks[scene])
except KeyError:
return None
if not total_tracks:
return None
if self.tracks_played[scene] == total_tracks:
last = self.tracks[scene][-1]
self.tracks[scene] = random.sample(self.tracks[scene][:-1], total_tracks - 1)
self.tracks[scene].append(last)
self.tracks_played[scene] = 0
result = self.tracks[scene][self.tracks_played[scene]]
self.tracks_played[scene] += 1
if not self.preload:
result = self.load_track(result)
return result
def play_next_track(self, scene):
while True:
next_track = self.select_track(scene)
if not next_track:
return
if self.play_track(next_track):
return
def play_scene_music(self, changed):
if changed:
self.player.stop()
if not self.player.is_playing():
self.play_next_track(self.current_scene)
def play_flight_music(self):
self.player.stop()
while True:
self.current_scene, changed = self.get_current_scene()
if self.current_scene != "Flight":
return
vessel = self.conn.space_center.active_vessel
current_body = vessel.orbit.body
# We're going to switch away from polling here to
# avoid unnecessary requests. We need to keep an eye
# out for the transitioning outside of the atmosphere
try:
with self.conn.stream(getattr, vessel.flight(), "mean_altitude") as altitude:
while altitude() < current_body.atmosphere_depth:
current_body = vessel.orbit.body
if self.player.is_playing():
self.player.stop()
while altitude() >= current_body.atmosphere_depth:
current_body = vessel.orbit.body
if not self.player.is_playing():
self.play_next_track("Space")
if vessel.parts.controlling.docking_port and self.tracks["Docking"]:
self.player.stop()
self.play_next_track("Docking")
while vessel.parts.controlling.docking_port:
if not self.player.is_playing():
self.play_next_track("Docking")
time.sleep(self.poll_rate * 0.25)
self.fade_out(1.5)
if self.conn.space_center.target_vessel and self.tracks["Rendezvous"]:
distance = math.sqrt(sum([i**2 for i in (self.conn.space_center.target_vessel.position(self.conn.space_center.active_vessel.reference_frame))]))
rendezvous_distance = self.config["rendezvous_distance"]
if distance < rendezvous_distance:
self.fade_out(1.5)
self.play_next_track("Rendezvous")
try:
with self.conn.stream(vessel.position, self.conn.space_center.target_vessel.reference_frame) as position:
while math.sqrt(sum([i**2 for i in position()])) < rendezvous_distance:
if not self.player.is_playing():
self.play_next_track("Rendezvous")
if not self.conn.space_center.target_vessel:
break
except AttributeError:
continue
finally:
self.fade_out(1.5)
except krpc.error.RPCError:
continue
def play_track(self, track):
self.player.set_media(track)
if self.player.play() == -1:
logging.warning("Couldn't play a file. Skipping.")
return False
logging.info("Playing {}.".format(track.get_mrl()))
time.sleep(self.poll_rate)
return True
def fade_out(self, seconds):
starting_volume = self.player.audio_get_volume()
sleep_increment = seconds / starting_volume
for i in range(starting_volume):
self.player.audio_set_volume(max(int(starting_volume - i), 1))
time.sleep(sleep_increment)
self.player.pause()
self.player.audio_set_volume(int(starting_volume))
self.player.stop()
def load_track(self, path):
if path[0:4] != "http":
return self.instance.media_new(os.path.abspath(path))
return self.instance.media_new(path)
def parse_tracks(self, path):
result = {}
with open(path) as text:
stuff = yaml.load(text)
for k in stuff:
if k in ["gamelog", "address", "rpc_port", "stream_port", "poll_rate", "rendezvous_distance"]:
self.config[k] = stuff[k]
continue
result[k] = []
try:
for v in stuff[k]:
if os.path.isfile(v) or v[0:4] == "http":
if self.preload:
result[k].append(self.load_track(v))
else:
result[k].append(v)
elif os.path.isdir(v):
for f in os.listdir(v):
if os.path.isfile(os.path.join(v,f)):
if self.preload:
result[k].append(self.load_track(os.path.join(v, f)))
else:
result[k].append(os.path.join(v, f))
else:
logging.warning("{}: {} not found.".format(k, v))
logging.info("{}: {} tracks loaded".format(k, len(result[k])))
random.shuffle(result[k])
except TypeError:
logging.warning("No music in {0}. Disabling music for {0}.".format(k))
return result
class GameLog(object):
def __init__(self, path, poll_rate, maxlen=10):
self.size = os.path.getsize(path)
self.path = path
self.valid = (path is not None) and os.path.isfile(path)
if not self.valid:
logging.warning("Invalid gamelog path!")
self.loaded_flag = False
self.size_history = deque(range(maxlen), maxlen=maxlen)
self.poll_rate = poll_rate
self.update_size()
def wait_for_game_start(self, player):
logging.info("Waiting for game start...")
if self.valid:
while True:
self.update_size()
if self.get_diff() != 0 or player.can_connect():
logging.info("Game started.")
return
time.sleep(self.poll_rate)
def loaded(self):
"""Return True only once after loaded."""
self.update_size()
lines = self.get_changed_lines()
if self.valid and not self.loaded_flag:
for line in lines:
if "Scene Change : From LOADING to MAINMENU" in line:
self.loaded_flag = True
return True
if all([i == self.size_history[0] for i in self.size_history]):
logging.info("Log hasn't changed for a while. Assume loaded.")
self.loaded_flag = True
return True
return False
def loaded_save(self):
|
def update_size(self):
if self.valid:
self.size_history.append(os.path.getsize(self.path))
def get_size(self):
return self.size_history[-1]
def get_diff(self):
return self.size_history[-1] - self.size_history[-2]
def get_changed_lines(self):
if self.valid:
with open(self.path, 'r') as log:
log.seek(self.get_diff(), 2)
return log.readlines()
def main():
parser = argparse.ArgumentParser(description="Custom soundtrack player for Kerbal Space Program")
parser.add_argument("--config_path", "-c", default="music.yaml")
parser.add_argument('--verbose', '-v', action='count')
args = parser.parse_args()
levels = {1:logging.INFO, 2:logging.DEBUG}
logging.basicConfig(level=levels.get(args.verbose, logging.WARNING))
config_path = args.config_path
try:
player = Player(config_path)
player.wait_for_server()
player.connect()
player.play()
except KeyboardInterrupt:
print("Quit.")
if __name__ == "__main__":
main()
| self.update_size()
lines = self.get_changed_lines()
if self.valid:
for line in lines:
if "Scene Change : From MAINMENU to SPACECENTER" in line:
return True
return False | identifier_body |
music_hack.py | #!/usr/bin/env python
from __future__ import division
import krpc
import vlc
import time
import random
import yaml
import os
import socket
import math
import logging
import sys
from collections import deque
import argparse
class Player(object):
def __init__(self, path, preload=True):
self.instance = vlc.Instance()
self.player = self.instance.media_player_new()
self.preload = preload
self.config = {}
self.tracks = self.parse_tracks(path)
self.conn = None
self.tracks_played = {scene:0 for scene in self.tracks}
self.poll_rate = self.config["poll_rate"]
self.current_scene = "SpaceCenter"
def can_connect(self):
address = (self.config["address"], self.config["rpc_port"])
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.connect(address)
s.shutdown(socket.SHUT_RDWR)
s.close()
return True
except Exception as e:
logging.debug(e)
return False
def wait_for_server(self):
gamelog = GameLog(self.config["gamelog"], self.config["poll_rate"])
gamelog.wait_for_game_start(self)
while True:
if self.can_connect() or gamelog.loaded_save():
self.player.stop()
logging.info("Save game loaded.")
return
if gamelog.loaded():
self.player.stop()
self.play_next_track("MainMenu")
logging.info("Main Menu reached")
logging.debug("Game still loading.")
time.sleep(self.poll_rate / 10)
def connect(self, name="Music Player"):
self.conn = krpc.connect(name=name,
address=self.config["address"],
rpc_port=self.config["rpc_port"],
stream_port=self.config["stream_port"])
def get_current_scene(self):
try:
self.conn.space_center.active_vessel
return "Flight", True
except (OSError, socket.error, KeyboardInterrupt):
print("Lost connection.")
return None, True
except krpc.error.RPCError as e:
try:
scene = str(e)[str(e).index("'") + 1:str(e).rindex("'")]
return scene, self.current_scene != scene
except:
return "SpaceCenter", self.current_scene != scene
def play(self):
while True:
try:
self.current_scene, changed = self.get_current_scene()
if not self.current_scene:
return
if self.current_scene == "Flight":
self.play_flight_music()
else:
self.play_scene_music(changed)
time.sleep(self.poll_rate)
except (OSError, socket.error, KeyboardInterrupt):
print("Connection lost.")
return
def select_track(self, scene):
""""Handle avoiding repetition of tracks and empty playlists."""
try:
total_tracks = len(self.tracks[scene])
except KeyError:
return None
if not total_tracks:
return None
if self.tracks_played[scene] == total_tracks:
last = self.tracks[scene][-1]
self.tracks[scene] = random.sample(self.tracks[scene][:-1], total_tracks - 1) | result = self.tracks[scene][self.tracks_played[scene]]
self.tracks_played[scene] += 1
if not self.preload:
result = self.load_track(result)
return result
def play_next_track(self, scene):
while True:
next_track = self.select_track(scene)
if not next_track:
return
if self.play_track(next_track):
return
def play_scene_music(self, changed):
if changed:
self.player.stop()
if not self.player.is_playing():
self.play_next_track(self.current_scene)
def play_flight_music(self):
self.player.stop()
while True:
self.current_scene, changed = self.get_current_scene()
if self.current_scene != "Flight":
return
vessel = self.conn.space_center.active_vessel
current_body = vessel.orbit.body
# We're going to switch away from polling here to
# avoid unnecessary requests. We need to keep an eye
# out for the transitioning outside of the atmosphere
try:
with self.conn.stream(getattr, vessel.flight(), "mean_altitude") as altitude:
while altitude() < current_body.atmosphere_depth:
current_body = vessel.orbit.body
if self.player.is_playing():
self.player.stop()
while altitude() >= current_body.atmosphere_depth:
current_body = vessel.orbit.body
if not self.player.is_playing():
self.play_next_track("Space")
if vessel.parts.controlling.docking_port and self.tracks["Docking"]:
self.player.stop()
self.play_next_track("Docking")
while vessel.parts.controlling.docking_port:
if not self.player.is_playing():
self.play_next_track("Docking")
time.sleep(self.poll_rate * 0.25)
self.fade_out(1.5)
if self.conn.space_center.target_vessel and self.tracks["Rendezvous"]:
distance = math.sqrt(sum([i**2 for i in (self.conn.space_center.target_vessel.position(self.conn.space_center.active_vessel.reference_frame))]))
rendezvous_distance = self.config["rendezvous_distance"]
if distance < rendezvous_distance:
self.fade_out(1.5)
self.play_next_track("Rendezvous")
try:
with self.conn.stream(vessel.position, self.conn.space_center.target_vessel.reference_frame) as position:
while math.sqrt(sum([i**2 for i in position()])) < rendezvous_distance:
if not self.player.is_playing():
self.play_next_track("Rendezvous")
if not self.conn.space_center.target_vessel:
break
except AttributeError:
continue
finally:
self.fade_out(1.5)
except krpc.error.RPCError:
continue
def play_track(self, track):
self.player.set_media(track)
if self.player.play() == -1:
logging.warning("Couldn't play a file. Skipping.")
return False
logging.info("Playing {}.".format(track.get_mrl()))
time.sleep(self.poll_rate)
return True
def fade_out(self, seconds):
starting_volume = self.player.audio_get_volume()
sleep_increment = seconds / starting_volume
for i in range(starting_volume):
self.player.audio_set_volume(max(int(starting_volume - i), 1))
time.sleep(sleep_increment)
self.player.pause()
self.player.audio_set_volume(int(starting_volume))
self.player.stop()
def load_track(self, path):
if path[0:4] != "http":
return self.instance.media_new(os.path.abspath(path))
return self.instance.media_new(path)
def parse_tracks(self, path):
result = {}
with open(path) as text:
stuff = yaml.load(text)
for k in stuff:
if k in ["gamelog", "address", "rpc_port", "stream_port", "poll_rate", "rendezvous_distance"]:
self.config[k] = stuff[k]
continue
result[k] = []
try:
for v in stuff[k]:
if os.path.isfile(v) or v[0:4] == "http":
if self.preload:
result[k].append(self.load_track(v))
else:
result[k].append(v)
elif os.path.isdir(v):
for f in os.listdir(v):
if os.path.isfile(os.path.join(v,f)):
if self.preload:
result[k].append(self.load_track(os.path.join(v, f)))
else:
result[k].append(os.path.join(v, f))
else:
logging.warning("{}: {} not found.".format(k, v))
logging.info("{}: {} tracks loaded".format(k, len(result[k])))
random.shuffle(result[k])
except TypeError:
logging.warning("No music in {0}. Disabling music for {0}.".format(k))
return result
class GameLog(object):
def __init__(self, path, poll_rate, maxlen=10):
self.size = os.path.getsize(path)
self.path = path
self.valid = (path is not None) and os.path.isfile(path)
if not self.valid:
logging.warning("Invalid gamelog path!")
self.loaded_flag = False
self.size_history = deque(range(maxlen), maxlen=maxlen)
self.poll_rate = poll_rate
self.update_size()
def wait_for_game_start(self, player):
logging.info("Waiting for game start...")
if self.valid:
while True:
self.update_size()
if self.get_diff() != 0 or player.can_connect():
logging.info("Game started.")
return
time.sleep(self.poll_rate)
def loaded(self):
"""Return True only once after loaded."""
self.update_size()
lines = self.get_changed_lines()
if self.valid and not self.loaded_flag:
for line in lines:
if "Scene Change : From LOADING to MAINMENU" in line:
self.loaded_flag = True
return True
if all([i == self.size_history[0] for i in self.size_history]):
logging.info("Log hasn't changed for a while. Assume loaded.")
self.loaded_flag = True
return True
return False
def loaded_save(self):
self.update_size()
lines = self.get_changed_lines()
if self.valid:
for line in lines:
if "Scene Change : From MAINMENU to SPACECENTER" in line:
return True
return False
def update_size(self):
if self.valid:
self.size_history.append(os.path.getsize(self.path))
def get_size(self):
return self.size_history[-1]
def get_diff(self):
return self.size_history[-1] - self.size_history[-2]
def get_changed_lines(self):
if self.valid:
with open(self.path, 'r') as log:
log.seek(self.get_diff(), 2)
return log.readlines()
def main():
parser = argparse.ArgumentParser(description="Custom soundtrack player for Kerbal Space Program")
parser.add_argument("--config_path", "-c", default="music.yaml")
parser.add_argument('--verbose', '-v', action='count')
args = parser.parse_args()
levels = {1:logging.INFO, 2:logging.DEBUG}
logging.basicConfig(level=levels.get(args.verbose, logging.WARNING))
config_path = args.config_path
try:
player = Player(config_path)
player.wait_for_server()
player.connect()
player.play()
except KeyboardInterrupt:
print("Quit.")
if __name__ == "__main__":
main() | self.tracks[scene].append(last)
self.tracks_played[scene] = 0
| random_line_split |
music_hack.py | #!/usr/bin/env python
from __future__ import division
import krpc
import vlc
import time
import random
import yaml
import os
import socket
import math
import logging
import sys
from collections import deque
import argparse
class Player(object):
def __init__(self, path, preload=True):
self.instance = vlc.Instance()
self.player = self.instance.media_player_new()
self.preload = preload
self.config = {}
self.tracks = self.parse_tracks(path)
self.conn = None
self.tracks_played = {scene:0 for scene in self.tracks}
self.poll_rate = self.config["poll_rate"]
self.current_scene = "SpaceCenter"
def can_connect(self):
address = (self.config["address"], self.config["rpc_port"])
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.connect(address)
s.shutdown(socket.SHUT_RDWR)
s.close()
return True
except Exception as e:
logging.debug(e)
return False
def | (self):
gamelog = GameLog(self.config["gamelog"], self.config["poll_rate"])
gamelog.wait_for_game_start(self)
while True:
if self.can_connect() or gamelog.loaded_save():
self.player.stop()
logging.info("Save game loaded.")
return
if gamelog.loaded():
self.player.stop()
self.play_next_track("MainMenu")
logging.info("Main Menu reached")
logging.debug("Game still loading.")
time.sleep(self.poll_rate / 10)
def connect(self, name="Music Player"):
self.conn = krpc.connect(name=name,
address=self.config["address"],
rpc_port=self.config["rpc_port"],
stream_port=self.config["stream_port"])
def get_current_scene(self):
try:
self.conn.space_center.active_vessel
return "Flight", True
except (OSError, socket.error, KeyboardInterrupt):
print("Lost connection.")
return None, True
except krpc.error.RPCError as e:
try:
scene = str(e)[str(e).index("'") + 1:str(e).rindex("'")]
return scene, self.current_scene != scene
except:
return "SpaceCenter", self.current_scene != scene
def play(self):
while True:
try:
self.current_scene, changed = self.get_current_scene()
if not self.current_scene:
return
if self.current_scene == "Flight":
self.play_flight_music()
else:
self.play_scene_music(changed)
time.sleep(self.poll_rate)
except (OSError, socket.error, KeyboardInterrupt):
print("Connection lost.")
return
def select_track(self, scene):
""""Handle avoiding repetition of tracks and empty playlists."""
try:
total_tracks = len(self.tracks[scene])
except KeyError:
return None
if not total_tracks:
return None
if self.tracks_played[scene] == total_tracks:
last = self.tracks[scene][-1]
self.tracks[scene] = random.sample(self.tracks[scene][:-1], total_tracks - 1)
self.tracks[scene].append(last)
self.tracks_played[scene] = 0
result = self.tracks[scene][self.tracks_played[scene]]
self.tracks_played[scene] += 1
if not self.preload:
result = self.load_track(result)
return result
def play_next_track(self, scene):
while True:
next_track = self.select_track(scene)
if not next_track:
return
if self.play_track(next_track):
return
def play_scene_music(self, changed):
if changed:
self.player.stop()
if not self.player.is_playing():
self.play_next_track(self.current_scene)
def play_flight_music(self):
self.player.stop()
while True:
self.current_scene, changed = self.get_current_scene()
if self.current_scene != "Flight":
return
vessel = self.conn.space_center.active_vessel
current_body = vessel.orbit.body
# We're going to switch away from polling here to
# avoid unnecessary requests. We need to keep an eye
# out for the transitioning outside of the atmosphere
try:
with self.conn.stream(getattr, vessel.flight(), "mean_altitude") as altitude:
while altitude() < current_body.atmosphere_depth:
current_body = vessel.orbit.body
if self.player.is_playing():
self.player.stop()
while altitude() >= current_body.atmosphere_depth:
current_body = vessel.orbit.body
if not self.player.is_playing():
self.play_next_track("Space")
if vessel.parts.controlling.docking_port and self.tracks["Docking"]:
self.player.stop()
self.play_next_track("Docking")
while vessel.parts.controlling.docking_port:
if not self.player.is_playing():
self.play_next_track("Docking")
time.sleep(self.poll_rate * 0.25)
self.fade_out(1.5)
if self.conn.space_center.target_vessel and self.tracks["Rendezvous"]:
distance = math.sqrt(sum([i**2 for i in (self.conn.space_center.target_vessel.position(self.conn.space_center.active_vessel.reference_frame))]))
rendezvous_distance = self.config["rendezvous_distance"]
if distance < rendezvous_distance:
self.fade_out(1.5)
self.play_next_track("Rendezvous")
try:
with self.conn.stream(vessel.position, self.conn.space_center.target_vessel.reference_frame) as position:
while math.sqrt(sum([i**2 for i in position()])) < rendezvous_distance:
if not self.player.is_playing():
self.play_next_track("Rendezvous")
if not self.conn.space_center.target_vessel:
break
except AttributeError:
continue
finally:
self.fade_out(1.5)
except krpc.error.RPCError:
continue
def play_track(self, track):
self.player.set_media(track)
if self.player.play() == -1:
logging.warning("Couldn't play a file. Skipping.")
return False
logging.info("Playing {}.".format(track.get_mrl()))
time.sleep(self.poll_rate)
return True
def fade_out(self, seconds):
starting_volume = self.player.audio_get_volume()
sleep_increment = seconds / starting_volume
for i in range(starting_volume):
self.player.audio_set_volume(max(int(starting_volume - i), 1))
time.sleep(sleep_increment)
self.player.pause()
self.player.audio_set_volume(int(starting_volume))
self.player.stop()
def load_track(self, path):
if path[0:4] != "http":
return self.instance.media_new(os.path.abspath(path))
return self.instance.media_new(path)
def parse_tracks(self, path):
result = {}
with open(path) as text:
stuff = yaml.load(text)
for k in stuff:
if k in ["gamelog", "address", "rpc_port", "stream_port", "poll_rate", "rendezvous_distance"]:
self.config[k] = stuff[k]
continue
result[k] = []
try:
for v in stuff[k]:
if os.path.isfile(v) or v[0:4] == "http":
if self.preload:
result[k].append(self.load_track(v))
else:
result[k].append(v)
elif os.path.isdir(v):
for f in os.listdir(v):
if os.path.isfile(os.path.join(v,f)):
if self.preload:
result[k].append(self.load_track(os.path.join(v, f)))
else:
result[k].append(os.path.join(v, f))
else:
logging.warning("{}: {} not found.".format(k, v))
logging.info("{}: {} tracks loaded".format(k, len(result[k])))
random.shuffle(result[k])
except TypeError:
logging.warning("No music in {0}. Disabling music for {0}.".format(k))
return result
class GameLog(object):
def __init__(self, path, poll_rate, maxlen=10):
self.size = os.path.getsize(path)
self.path = path
self.valid = (path is not None) and os.path.isfile(path)
if not self.valid:
logging.warning("Invalid gamelog path!")
self.loaded_flag = False
self.size_history = deque(range(maxlen), maxlen=maxlen)
self.poll_rate = poll_rate
self.update_size()
def wait_for_game_start(self, player):
logging.info("Waiting for game start...")
if self.valid:
while True:
self.update_size()
if self.get_diff() != 0 or player.can_connect():
logging.info("Game started.")
return
time.sleep(self.poll_rate)
def loaded(self):
"""Return True only once after loaded."""
self.update_size()
lines = self.get_changed_lines()
if self.valid and not self.loaded_flag:
for line in lines:
if "Scene Change : From LOADING to MAINMENU" in line:
self.loaded_flag = True
return True
if all([i == self.size_history[0] for i in self.size_history]):
logging.info("Log hasn't changed for a while. Assume loaded.")
self.loaded_flag = True
return True
return False
def loaded_save(self):
self.update_size()
lines = self.get_changed_lines()
if self.valid:
for line in lines:
if "Scene Change : From MAINMENU to SPACECENTER" in line:
return True
return False
def update_size(self):
if self.valid:
self.size_history.append(os.path.getsize(self.path))
def get_size(self):
return self.size_history[-1]
def get_diff(self):
return self.size_history[-1] - self.size_history[-2]
def get_changed_lines(self):
if self.valid:
with open(self.path, 'r') as log:
log.seek(self.get_diff(), 2)
return log.readlines()
def main():
parser = argparse.ArgumentParser(description="Custom soundtrack player for Kerbal Space Program")
parser.add_argument("--config_path", "-c", default="music.yaml")
parser.add_argument('--verbose', '-v', action='count')
args = parser.parse_args()
levels = {1:logging.INFO, 2:logging.DEBUG}
logging.basicConfig(level=levels.get(args.verbose, logging.WARNING))
config_path = args.config_path
try:
player = Player(config_path)
player.wait_for_server()
player.connect()
player.play()
except KeyboardInterrupt:
print("Quit.")
if __name__ == "__main__":
main()
| wait_for_server | identifier_name |
resolver.ts | import { privatize as P } from '@ember/-internals/container';
import { ENV } from '@ember/-internals/environment';
import { Factory, FactoryClass, LookupOptions, Owner } from '@ember/-internals/owner';
import { assert } from '@ember/debug';
import { _instrumentStart } from '@ember/instrumentation';
import { DEBUG } from '@glimmer/env';
import {
CompileTimeResolver,
HelperDefinitionState,
ModifierDefinitionState,
Option,
ResolvedComponentDefinition,
RuntimeResolver,
Template,
TemplateFactory,
} from '@glimmer/interfaces';
import {
getComponentTemplate,
getInternalComponentManager,
setInternalHelperManager,
} from '@glimmer/manager';
import {
array,
concat,
fn,
get,
hash,
on,
TEMPLATE_ONLY_COMPONENT_MANAGER,
templateOnlyComponent,
} from '@glimmer/runtime';
import { _WeakSet } from '@glimmer/util';
import { isCurlyManager } from './component-managers/curly';
import {
CLASSIC_HELPER_MANAGER,
HelperFactory,
HelperInstance,
isClassicHelper,
SimpleHelper,
} from './helper';
import { default as disallowDynamicResolution } from './helpers/-disallow-dynamic-resolution';
import { default as inElementNullCheckHelper } from './helpers/-in-element-null-check';
import { default as normalizeClassHelper } from './helpers/-normalize-class';
import { default as resolve } from './helpers/-resolve';
import { default as trackArray } from './helpers/-track-array';
import { default as action } from './helpers/action';
import { default as eachIn } from './helpers/each-in';
import { default as mut } from './helpers/mut';
import { default as queryParams } from './helpers/query-param';
import { default as readonly } from './helpers/readonly';
import { default as unbound } from './helpers/unbound';
import actionModifier from './modifiers/action';
import { mountHelper } from './syntax/mount';
import { outletHelper } from './syntax/outlet';
function instrumentationPayload(name: string) {
return { object: `component:${name}` };
}
function componentFor(
name: string,
owner: Owner,
options?: LookupOptions
): Option<Factory<{}, {}>> {
let fullName = `component:${name}`;
return owner.factoryFor(fullName, options) || null;
}
function layoutFor(name: string, owner: Owner, options?: LookupOptions): Option<Template> {
let templateFullName = `template:components/${name}`;
return owner.lookup(templateFullName, options) || null;
}
type LookupResult =
| {
component: Factory<{}, {}>;
layout: TemplateFactory;
}
| {
component: Factory<{}, {}>;
layout: null;
}
| {
component: null;
layout: TemplateFactory;
};
function lookupComponentPair(
owner: Owner,
name: string,
options?: LookupOptions
): Option<LookupResult> {
let component = componentFor(name, owner, options);
if (component !== null && component.class !== undefined) {
let layout = getComponentTemplate(component.class);
if (layout !== undefined) {
return { component, layout };
}
}
let layout = layoutFor(name, owner, options);
if (component === null && layout === null) {
return null;
} else {
return { component, layout } as LookupResult;
}
}
const BUILTIN_KEYWORD_HELPERS = {
action,
mut,
readonly,
unbound,
'query-params': queryParams,
'-hash': hash,
'-each-in': eachIn,
'-normalize-class': normalizeClassHelper,
'-resolve': resolve,
'-track-array': trackArray,
'-mount': mountHelper,
'-outlet': outletHelper,
'-in-el-null': inElementNullCheckHelper,
};
if (DEBUG) {
BUILTIN_KEYWORD_HELPERS['-disallow-dynamic-resolution'] = disallowDynamicResolution;
} else {
// Bug: this may be a quirk of our test setup?
// In prod builds, this is a no-op helper and is unused in practice. We shouldn't need
// to add it at all, but the current test build doesn't produce a "prod compiler", so
// we ended up running the debug-build for the template compliler in prod tests. Once
// that is fixed, this can be removed. For now, this allows the test to work and does
// not really harm anything, since it's just a no-op pass-through helper and the bytes
// has to be included anyway. In the future, perhaps we can avoid the latter by using
// `import(...)`?
BUILTIN_KEYWORD_HELPERS['-disallow-dynamic-resolution'] = disallowDynamicResolution;
}
const BUILTIN_HELPERS = {
...BUILTIN_KEYWORD_HELPERS,
array,
concat,
fn,
get,
hash,
};
const BUILTIN_KEYWORD_MODIFIERS = {
action: actionModifier,
};
const BUILTIN_MODIFIERS = {
...BUILTIN_KEYWORD_MODIFIERS,
on,
};
const CLASSIC_HELPER_MANAGER_ASSOCIATED = new _WeakSet();
export default class ResolverImpl implements RuntimeResolver<Owner>, CompileTimeResolver<Owner> {
private componentDefinitionCache: Map<object, ResolvedComponentDefinition | null> = new Map();
lookupPartial(): null {
return null;
}
lookupHelper(name: string, owner: Owner): Option<HelperDefinitionState> {
assert(
`You attempted to overwrite the built-in helper "${name}" which is not allowed. Please rename the helper.`,
!(BUILTIN_HELPERS[name] && owner.hasRegistration(`helper:${name}`))
);
const helper = BUILTIN_HELPERS[name];
if (helper !== undefined) {
return helper;
}
const factory = owner.factoryFor<
SimpleHelper | HelperInstance,
HelperFactory<SimpleHelper | HelperInstance>
>(`helper:${name}`);
if (factory === undefined) {
return null;
}
let definition = factory.class;
if (definition === undefined) {
return null;
}
if (typeof definition === 'function' && isClassicHelper(definition)) {
// For classic class based helpers, we need to pass the factoryFor result itself rather
// than the raw value (`factoryFor(...).class`). This is because injections are already
// bound in the factoryFor result, including type-based injections
if (DEBUG) {
// In DEBUG we need to only set the associated value once, otherwise
// we'll trigger an assertion
if (!CLASSIC_HELPER_MANAGER_ASSOCIATED.has(factory)) {
CLASSIC_HELPER_MANAGER_ASSOCIATED.add(factory);
setInternalHelperManager(CLASSIC_HELPER_MANAGER, factory);
}
} else {
setInternalHelperManager(CLASSIC_HELPER_MANAGER, factory);
}
return factory;
}
return definition;
}
lookupBuiltInHelper(name: string): HelperDefinitionState | null {
return BUILTIN_KEYWORD_HELPERS[name] ?? null;
}
lookupModifier(name: string, owner: Owner): Option<ModifierDefinitionState> {
let builtin = BUILTIN_MODIFIERS[name];
if (builtin !== undefined) {
return builtin;
}
let modifier = owner.factoryFor<unknown, FactoryClass>(`modifier:${name}`);
if (modifier === undefined) {
return null;
}
return modifier.class || null;
}
lookupBuiltInModifier(name: string): ModifierDefinitionState | null |
lookupComponent(name: string, owner: Owner): ResolvedComponentDefinition | null {
let pair = lookupComponentPair(owner, name);
if (pair === null) {
assert(
'Could not find component `<TextArea />` (did you mean `<Textarea />`?)',
name !== 'text-area'
);
return null;
}
let template: Template | null = null;
let key: object;
if (pair.component === null) {
key = template = pair.layout!(owner);
} else {
key = pair.component;
}
let cachedComponentDefinition = this.componentDefinitionCache.get(key);
if (cachedComponentDefinition !== undefined) {
return cachedComponentDefinition;
}
if (template === null && pair.layout !== null) {
template = pair.layout(owner);
}
let finalizer = _instrumentStart('render.getComponentDefinition', instrumentationPayload, name);
let definition: Option<ResolvedComponentDefinition> = null;
if (pair.component === null) {
if (ENV._TEMPLATE_ONLY_GLIMMER_COMPONENTS) {
definition = {
state: templateOnlyComponent(undefined, name),
manager: TEMPLATE_ONLY_COMPONENT_MANAGER,
template,
};
} else {
let factory = owner.factoryFor(P`component:-default`)!;
let manager = getInternalComponentManager(factory.class as object);
definition = {
state: factory,
manager,
template,
};
}
} else {
assert(`missing component class ${name}`, pair.component.class !== undefined);
let factory = pair.component;
let ComponentClass = factory.class!;
let manager = getInternalComponentManager(ComponentClass);
definition = {
state: isCurlyManager(manager) ? factory : ComponentClass,
manager,
template,
};
}
finalizer();
this.componentDefinitionCache.set(key, definition);
assert(
'Could not find component `<TextArea />` (did you mean `<Textarea />`?)',
!(definition === null && name === 'text-area')
);
return definition;
}
}
| {
return BUILTIN_KEYWORD_MODIFIERS[name] ?? null;
} | identifier_body |
resolver.ts | import { privatize as P } from '@ember/-internals/container';
import { ENV } from '@ember/-internals/environment';
import { Factory, FactoryClass, LookupOptions, Owner } from '@ember/-internals/owner';
import { assert } from '@ember/debug';
import { _instrumentStart } from '@ember/instrumentation';
import { DEBUG } from '@glimmer/env';
import {
CompileTimeResolver,
HelperDefinitionState,
ModifierDefinitionState,
Option,
ResolvedComponentDefinition,
RuntimeResolver,
Template,
TemplateFactory,
} from '@glimmer/interfaces';
import {
getComponentTemplate,
getInternalComponentManager,
setInternalHelperManager,
} from '@glimmer/manager';
import {
array,
concat,
fn,
get,
hash,
on,
TEMPLATE_ONLY_COMPONENT_MANAGER,
templateOnlyComponent,
} from '@glimmer/runtime';
import { _WeakSet } from '@glimmer/util';
import { isCurlyManager } from './component-managers/curly';
import {
CLASSIC_HELPER_MANAGER,
HelperFactory,
HelperInstance,
isClassicHelper,
SimpleHelper,
} from './helper';
import { default as disallowDynamicResolution } from './helpers/-disallow-dynamic-resolution';
import { default as inElementNullCheckHelper } from './helpers/-in-element-null-check';
import { default as normalizeClassHelper } from './helpers/-normalize-class';
import { default as resolve } from './helpers/-resolve';
import { default as trackArray } from './helpers/-track-array';
import { default as action } from './helpers/action';
import { default as eachIn } from './helpers/each-in';
import { default as mut } from './helpers/mut';
import { default as queryParams } from './helpers/query-param';
import { default as readonly } from './helpers/readonly';
import { default as unbound } from './helpers/unbound';
import actionModifier from './modifiers/action';
import { mountHelper } from './syntax/mount';
import { outletHelper } from './syntax/outlet';
function instrumentationPayload(name: string) {
return { object: `component:${name}` };
}
function componentFor(
name: string,
owner: Owner,
options?: LookupOptions
): Option<Factory<{}, {}>> {
let fullName = `component:${name}`;
return owner.factoryFor(fullName, options) || null;
}
function layoutFor(name: string, owner: Owner, options?: LookupOptions): Option<Template> {
let templateFullName = `template:components/${name}`;
return owner.lookup(templateFullName, options) || null;
}
type LookupResult =
| {
component: Factory<{}, {}>;
layout: TemplateFactory;
}
| {
component: Factory<{}, {}>;
layout: null;
}
| {
component: null;
layout: TemplateFactory;
};
function lookupComponentPair(
owner: Owner,
name: string,
options?: LookupOptions
): Option<LookupResult> {
let component = componentFor(name, owner, options);
if (component !== null && component.class !== undefined) {
let layout = getComponentTemplate(component.class);
if (layout !== undefined) {
return { component, layout };
}
}
let layout = layoutFor(name, owner, options);
if (component === null && layout === null) {
return null;
} else {
return { component, layout } as LookupResult;
}
}
const BUILTIN_KEYWORD_HELPERS = {
action,
mut,
readonly,
unbound,
'query-params': queryParams,
'-hash': hash,
'-each-in': eachIn,
'-normalize-class': normalizeClassHelper,
'-resolve': resolve,
'-track-array': trackArray,
'-mount': mountHelper,
'-outlet': outletHelper,
'-in-el-null': inElementNullCheckHelper,
};
if (DEBUG) {
BUILTIN_KEYWORD_HELPERS['-disallow-dynamic-resolution'] = disallowDynamicResolution;
} else {
// Bug: this may be a quirk of our test setup?
// In prod builds, this is a no-op helper and is unused in practice. We shouldn't need
// to add it at all, but the current test build doesn't produce a "prod compiler", so
// we ended up running the debug-build for the template compliler in prod tests. Once
// that is fixed, this can be removed. For now, this allows the test to work and does
// not really harm anything, since it's just a no-op pass-through helper and the bytes
// has to be included anyway. In the future, perhaps we can avoid the latter by using
// `import(...)`?
BUILTIN_KEYWORD_HELPERS['-disallow-dynamic-resolution'] = disallowDynamicResolution;
}
const BUILTIN_HELPERS = {
...BUILTIN_KEYWORD_HELPERS,
array,
concat,
fn,
get,
hash,
};
const BUILTIN_KEYWORD_MODIFIERS = {
action: actionModifier,
};
const BUILTIN_MODIFIERS = {
...BUILTIN_KEYWORD_MODIFIERS,
on,
};
const CLASSIC_HELPER_MANAGER_ASSOCIATED = new _WeakSet();
export default class ResolverImpl implements RuntimeResolver<Owner>, CompileTimeResolver<Owner> {
private componentDefinitionCache: Map<object, ResolvedComponentDefinition | null> = new Map();
lookupPartial(): null {
return null;
}
lookupHelper(name: string, owner: Owner): Option<HelperDefinitionState> {
assert(
`You attempted to overwrite the built-in helper "${name}" which is not allowed. Please rename the helper.`,
!(BUILTIN_HELPERS[name] && owner.hasRegistration(`helper:${name}`))
);
const helper = BUILTIN_HELPERS[name];
if (helper !== undefined) {
return helper;
}
const factory = owner.factoryFor<
SimpleHelper | HelperInstance,
HelperFactory<SimpleHelper | HelperInstance>
>(`helper:${name}`);
if (factory === undefined) {
return null;
}
let definition = factory.class;
if (definition === undefined) {
return null;
}
if (typeof definition === 'function' && isClassicHelper(definition)) {
// For classic class based helpers, we need to pass the factoryFor result itself rather
// than the raw value (`factoryFor(...).class`). This is because injections are already
// bound in the factoryFor result, including type-based injections
if (DEBUG) {
// In DEBUG we need to only set the associated value once, otherwise
// we'll trigger an assertion
if (!CLASSIC_HELPER_MANAGER_ASSOCIATED.has(factory)) {
CLASSIC_HELPER_MANAGER_ASSOCIATED.add(factory);
setInternalHelperManager(CLASSIC_HELPER_MANAGER, factory);
}
} else {
setInternalHelperManager(CLASSIC_HELPER_MANAGER, factory);
}
return factory;
}
return definition;
}
lookupBuiltInHelper(name: string): HelperDefinitionState | null {
return BUILTIN_KEYWORD_HELPERS[name] ?? null;
}
lookupModifier(name: string, owner: Owner): Option<ModifierDefinitionState> {
let builtin = BUILTIN_MODIFIERS[name];
if (builtin !== undefined) {
return builtin;
}
let modifier = owner.factoryFor<unknown, FactoryClass>(`modifier:${name}`);
if (modifier === undefined) {
return null;
}
return modifier.class || null;
}
lookupBuiltInModifier(name: string): ModifierDefinitionState | null {
return BUILTIN_KEYWORD_MODIFIERS[name] ?? null;
}
| (name: string, owner: Owner): ResolvedComponentDefinition | null {
let pair = lookupComponentPair(owner, name);
if (pair === null) {
assert(
'Could not find component `<TextArea />` (did you mean `<Textarea />`?)',
name !== 'text-area'
);
return null;
}
let template: Template | null = null;
let key: object;
if (pair.component === null) {
key = template = pair.layout!(owner);
} else {
key = pair.component;
}
let cachedComponentDefinition = this.componentDefinitionCache.get(key);
if (cachedComponentDefinition !== undefined) {
return cachedComponentDefinition;
}
if (template === null && pair.layout !== null) {
template = pair.layout(owner);
}
let finalizer = _instrumentStart('render.getComponentDefinition', instrumentationPayload, name);
let definition: Option<ResolvedComponentDefinition> = null;
if (pair.component === null) {
if (ENV._TEMPLATE_ONLY_GLIMMER_COMPONENTS) {
definition = {
state: templateOnlyComponent(undefined, name),
manager: TEMPLATE_ONLY_COMPONENT_MANAGER,
template,
};
} else {
let factory = owner.factoryFor(P`component:-default`)!;
let manager = getInternalComponentManager(factory.class as object);
definition = {
state: factory,
manager,
template,
};
}
} else {
assert(`missing component class ${name}`, pair.component.class !== undefined);
let factory = pair.component;
let ComponentClass = factory.class!;
let manager = getInternalComponentManager(ComponentClass);
definition = {
state: isCurlyManager(manager) ? factory : ComponentClass,
manager,
template,
};
}
finalizer();
this.componentDefinitionCache.set(key, definition);
assert(
'Could not find component `<TextArea />` (did you mean `<Textarea />`?)',
!(definition === null && name === 'text-area')
);
return definition;
}
}
| lookupComponent | identifier_name |
resolver.ts | import { privatize as P } from '@ember/-internals/container';
import { ENV } from '@ember/-internals/environment';
import { Factory, FactoryClass, LookupOptions, Owner } from '@ember/-internals/owner';
import { assert } from '@ember/debug';
import { _instrumentStart } from '@ember/instrumentation';
import { DEBUG } from '@glimmer/env';
import {
CompileTimeResolver,
HelperDefinitionState,
ModifierDefinitionState,
Option,
ResolvedComponentDefinition,
RuntimeResolver,
Template,
TemplateFactory,
} from '@glimmer/interfaces';
import {
getComponentTemplate,
getInternalComponentManager,
setInternalHelperManager,
} from '@glimmer/manager';
import {
array,
concat,
fn,
get,
hash,
on,
TEMPLATE_ONLY_COMPONENT_MANAGER,
templateOnlyComponent,
} from '@glimmer/runtime';
import { _WeakSet } from '@glimmer/util';
import { isCurlyManager } from './component-managers/curly';
import {
CLASSIC_HELPER_MANAGER,
HelperFactory,
HelperInstance,
isClassicHelper,
SimpleHelper,
} from './helper';
import { default as disallowDynamicResolution } from './helpers/-disallow-dynamic-resolution';
import { default as inElementNullCheckHelper } from './helpers/-in-element-null-check';
import { default as normalizeClassHelper } from './helpers/-normalize-class';
import { default as resolve } from './helpers/-resolve';
import { default as trackArray } from './helpers/-track-array';
import { default as action } from './helpers/action';
import { default as eachIn } from './helpers/each-in';
import { default as mut } from './helpers/mut';
import { default as queryParams } from './helpers/query-param';
import { default as readonly } from './helpers/readonly';
import { default as unbound } from './helpers/unbound';
import actionModifier from './modifiers/action';
import { mountHelper } from './syntax/mount';
import { outletHelper } from './syntax/outlet';
function instrumentationPayload(name: string) {
return { object: `component:${name}` };
}
function componentFor(
name: string,
owner: Owner,
options?: LookupOptions
): Option<Factory<{}, {}>> {
let fullName = `component:${name}`;
return owner.factoryFor(fullName, options) || null;
}
function layoutFor(name: string, owner: Owner, options?: LookupOptions): Option<Template> {
let templateFullName = `template:components/${name}`;
return owner.lookup(templateFullName, options) || null;
}
type LookupResult =
| {
component: Factory<{}, {}>;
layout: TemplateFactory;
}
| {
component: Factory<{}, {}>;
layout: null;
} | layout: TemplateFactory;
};
function lookupComponentPair(
owner: Owner,
name: string,
options?: LookupOptions
): Option<LookupResult> {
let component = componentFor(name, owner, options);
if (component !== null && component.class !== undefined) {
let layout = getComponentTemplate(component.class);
if (layout !== undefined) {
return { component, layout };
}
}
let layout = layoutFor(name, owner, options);
if (component === null && layout === null) {
return null;
} else {
return { component, layout } as LookupResult;
}
}
const BUILTIN_KEYWORD_HELPERS = {
action,
mut,
readonly,
unbound,
'query-params': queryParams,
'-hash': hash,
'-each-in': eachIn,
'-normalize-class': normalizeClassHelper,
'-resolve': resolve,
'-track-array': trackArray,
'-mount': mountHelper,
'-outlet': outletHelper,
'-in-el-null': inElementNullCheckHelper,
};
if (DEBUG) {
BUILTIN_KEYWORD_HELPERS['-disallow-dynamic-resolution'] = disallowDynamicResolution;
} else {
// Bug: this may be a quirk of our test setup?
// In prod builds, this is a no-op helper and is unused in practice. We shouldn't need
// to add it at all, but the current test build doesn't produce a "prod compiler", so
// we ended up running the debug-build for the template compliler in prod tests. Once
// that is fixed, this can be removed. For now, this allows the test to work and does
// not really harm anything, since it's just a no-op pass-through helper and the bytes
// has to be included anyway. In the future, perhaps we can avoid the latter by using
// `import(...)`?
BUILTIN_KEYWORD_HELPERS['-disallow-dynamic-resolution'] = disallowDynamicResolution;
}
const BUILTIN_HELPERS = {
...BUILTIN_KEYWORD_HELPERS,
array,
concat,
fn,
get,
hash,
};
const BUILTIN_KEYWORD_MODIFIERS = {
action: actionModifier,
};
const BUILTIN_MODIFIERS = {
...BUILTIN_KEYWORD_MODIFIERS,
on,
};
const CLASSIC_HELPER_MANAGER_ASSOCIATED = new _WeakSet();
export default class ResolverImpl implements RuntimeResolver<Owner>, CompileTimeResolver<Owner> {
private componentDefinitionCache: Map<object, ResolvedComponentDefinition | null> = new Map();
lookupPartial(): null {
return null;
}
lookupHelper(name: string, owner: Owner): Option<HelperDefinitionState> {
assert(
`You attempted to overwrite the built-in helper "${name}" which is not allowed. Please rename the helper.`,
!(BUILTIN_HELPERS[name] && owner.hasRegistration(`helper:${name}`))
);
const helper = BUILTIN_HELPERS[name];
if (helper !== undefined) {
return helper;
}
const factory = owner.factoryFor<
SimpleHelper | HelperInstance,
HelperFactory<SimpleHelper | HelperInstance>
>(`helper:${name}`);
if (factory === undefined) {
return null;
}
let definition = factory.class;
if (definition === undefined) {
return null;
}
if (typeof definition === 'function' && isClassicHelper(definition)) {
// For classic class based helpers, we need to pass the factoryFor result itself rather
// than the raw value (`factoryFor(...).class`). This is because injections are already
// bound in the factoryFor result, including type-based injections
if (DEBUG) {
// In DEBUG we need to only set the associated value once, otherwise
// we'll trigger an assertion
if (!CLASSIC_HELPER_MANAGER_ASSOCIATED.has(factory)) {
CLASSIC_HELPER_MANAGER_ASSOCIATED.add(factory);
setInternalHelperManager(CLASSIC_HELPER_MANAGER, factory);
}
} else {
setInternalHelperManager(CLASSIC_HELPER_MANAGER, factory);
}
return factory;
}
return definition;
}
lookupBuiltInHelper(name: string): HelperDefinitionState | null {
return BUILTIN_KEYWORD_HELPERS[name] ?? null;
}
lookupModifier(name: string, owner: Owner): Option<ModifierDefinitionState> {
let builtin = BUILTIN_MODIFIERS[name];
if (builtin !== undefined) {
return builtin;
}
let modifier = owner.factoryFor<unknown, FactoryClass>(`modifier:${name}`);
if (modifier === undefined) {
return null;
}
return modifier.class || null;
}
lookupBuiltInModifier(name: string): ModifierDefinitionState | null {
return BUILTIN_KEYWORD_MODIFIERS[name] ?? null;
}
lookupComponent(name: string, owner: Owner): ResolvedComponentDefinition | null {
let pair = lookupComponentPair(owner, name);
if (pair === null) {
assert(
'Could not find component `<TextArea />` (did you mean `<Textarea />`?)',
name !== 'text-area'
);
return null;
}
let template: Template | null = null;
let key: object;
if (pair.component === null) {
key = template = pair.layout!(owner);
} else {
key = pair.component;
}
let cachedComponentDefinition = this.componentDefinitionCache.get(key);
if (cachedComponentDefinition !== undefined) {
return cachedComponentDefinition;
}
if (template === null && pair.layout !== null) {
template = pair.layout(owner);
}
let finalizer = _instrumentStart('render.getComponentDefinition', instrumentationPayload, name);
let definition: Option<ResolvedComponentDefinition> = null;
if (pair.component === null) {
if (ENV._TEMPLATE_ONLY_GLIMMER_COMPONENTS) {
definition = {
state: templateOnlyComponent(undefined, name),
manager: TEMPLATE_ONLY_COMPONENT_MANAGER,
template,
};
} else {
let factory = owner.factoryFor(P`component:-default`)!;
let manager = getInternalComponentManager(factory.class as object);
definition = {
state: factory,
manager,
template,
};
}
} else {
assert(`missing component class ${name}`, pair.component.class !== undefined);
let factory = pair.component;
let ComponentClass = factory.class!;
let manager = getInternalComponentManager(ComponentClass);
definition = {
state: isCurlyManager(manager) ? factory : ComponentClass,
manager,
template,
};
}
finalizer();
this.componentDefinitionCache.set(key, definition);
assert(
'Could not find component `<TextArea />` (did you mean `<Textarea />`?)',
!(definition === null && name === 'text-area')
);
return definition;
}
} | | {
component: null; | random_line_split |
resolver.ts | import { privatize as P } from '@ember/-internals/container';
import { ENV } from '@ember/-internals/environment';
import { Factory, FactoryClass, LookupOptions, Owner } from '@ember/-internals/owner';
import { assert } from '@ember/debug';
import { _instrumentStart } from '@ember/instrumentation';
import { DEBUG } from '@glimmer/env';
import {
CompileTimeResolver,
HelperDefinitionState,
ModifierDefinitionState,
Option,
ResolvedComponentDefinition,
RuntimeResolver,
Template,
TemplateFactory,
} from '@glimmer/interfaces';
import {
getComponentTemplate,
getInternalComponentManager,
setInternalHelperManager,
} from '@glimmer/manager';
import {
array,
concat,
fn,
get,
hash,
on,
TEMPLATE_ONLY_COMPONENT_MANAGER,
templateOnlyComponent,
} from '@glimmer/runtime';
import { _WeakSet } from '@glimmer/util';
import { isCurlyManager } from './component-managers/curly';
import {
CLASSIC_HELPER_MANAGER,
HelperFactory,
HelperInstance,
isClassicHelper,
SimpleHelper,
} from './helper';
import { default as disallowDynamicResolution } from './helpers/-disallow-dynamic-resolution';
import { default as inElementNullCheckHelper } from './helpers/-in-element-null-check';
import { default as normalizeClassHelper } from './helpers/-normalize-class';
import { default as resolve } from './helpers/-resolve';
import { default as trackArray } from './helpers/-track-array';
import { default as action } from './helpers/action';
import { default as eachIn } from './helpers/each-in';
import { default as mut } from './helpers/mut';
import { default as queryParams } from './helpers/query-param';
import { default as readonly } from './helpers/readonly';
import { default as unbound } from './helpers/unbound';
import actionModifier from './modifiers/action';
import { mountHelper } from './syntax/mount';
import { outletHelper } from './syntax/outlet';
function instrumentationPayload(name: string) {
return { object: `component:${name}` };
}
function componentFor(
name: string,
owner: Owner,
options?: LookupOptions
): Option<Factory<{}, {}>> {
let fullName = `component:${name}`;
return owner.factoryFor(fullName, options) || null;
}
function layoutFor(name: string, owner: Owner, options?: LookupOptions): Option<Template> {
let templateFullName = `template:components/${name}`;
return owner.lookup(templateFullName, options) || null;
}
type LookupResult =
| {
component: Factory<{}, {}>;
layout: TemplateFactory;
}
| {
component: Factory<{}, {}>;
layout: null;
}
| {
component: null;
layout: TemplateFactory;
};
function lookupComponentPair(
owner: Owner,
name: string,
options?: LookupOptions
): Option<LookupResult> {
let component = componentFor(name, owner, options);
if (component !== null && component.class !== undefined) {
let layout = getComponentTemplate(component.class);
if (layout !== undefined) {
return { component, layout };
}
}
let layout = layoutFor(name, owner, options);
if (component === null && layout === null) {
return null;
} else {
return { component, layout } as LookupResult;
}
}
const BUILTIN_KEYWORD_HELPERS = {
action,
mut,
readonly,
unbound,
'query-params': queryParams,
'-hash': hash,
'-each-in': eachIn,
'-normalize-class': normalizeClassHelper,
'-resolve': resolve,
'-track-array': trackArray,
'-mount': mountHelper,
'-outlet': outletHelper,
'-in-el-null': inElementNullCheckHelper,
};
if (DEBUG) {
BUILTIN_KEYWORD_HELPERS['-disallow-dynamic-resolution'] = disallowDynamicResolution;
} else {
// Bug: this may be a quirk of our test setup?
// In prod builds, this is a no-op helper and is unused in practice. We shouldn't need
// to add it at all, but the current test build doesn't produce a "prod compiler", so
// we ended up running the debug-build for the template compliler in prod tests. Once
// that is fixed, this can be removed. For now, this allows the test to work and does
// not really harm anything, since it's just a no-op pass-through helper and the bytes
// has to be included anyway. In the future, perhaps we can avoid the latter by using
// `import(...)`?
BUILTIN_KEYWORD_HELPERS['-disallow-dynamic-resolution'] = disallowDynamicResolution;
}
const BUILTIN_HELPERS = {
...BUILTIN_KEYWORD_HELPERS,
array,
concat,
fn,
get,
hash,
};
const BUILTIN_KEYWORD_MODIFIERS = {
action: actionModifier,
};
const BUILTIN_MODIFIERS = {
...BUILTIN_KEYWORD_MODIFIERS,
on,
};
const CLASSIC_HELPER_MANAGER_ASSOCIATED = new _WeakSet();
export default class ResolverImpl implements RuntimeResolver<Owner>, CompileTimeResolver<Owner> {
private componentDefinitionCache: Map<object, ResolvedComponentDefinition | null> = new Map();
lookupPartial(): null {
return null;
}
lookupHelper(name: string, owner: Owner): Option<HelperDefinitionState> {
assert(
`You attempted to overwrite the built-in helper "${name}" which is not allowed. Please rename the helper.`,
!(BUILTIN_HELPERS[name] && owner.hasRegistration(`helper:${name}`))
);
const helper = BUILTIN_HELPERS[name];
if (helper !== undefined) {
return helper;
}
const factory = owner.factoryFor<
SimpleHelper | HelperInstance,
HelperFactory<SimpleHelper | HelperInstance>
>(`helper:${name}`);
if (factory === undefined) {
return null;
}
let definition = factory.class;
if (definition === undefined) {
return null;
}
if (typeof definition === 'function' && isClassicHelper(definition)) {
// For classic class based helpers, we need to pass the factoryFor result itself rather
// than the raw value (`factoryFor(...).class`). This is because injections are already
// bound in the factoryFor result, including type-based injections
if (DEBUG) {
// In DEBUG we need to only set the associated value once, otherwise
// we'll trigger an assertion
if (!CLASSIC_HELPER_MANAGER_ASSOCIATED.has(factory)) {
CLASSIC_HELPER_MANAGER_ASSOCIATED.add(factory);
setInternalHelperManager(CLASSIC_HELPER_MANAGER, factory);
}
} else {
setInternalHelperManager(CLASSIC_HELPER_MANAGER, factory);
}
return factory;
}
return definition;
}
lookupBuiltInHelper(name: string): HelperDefinitionState | null {
return BUILTIN_KEYWORD_HELPERS[name] ?? null;
}
lookupModifier(name: string, owner: Owner): Option<ModifierDefinitionState> {
let builtin = BUILTIN_MODIFIERS[name];
if (builtin !== undefined) {
return builtin;
}
let modifier = owner.factoryFor<unknown, FactoryClass>(`modifier:${name}`);
if (modifier === undefined) {
return null;
}
return modifier.class || null;
}
lookupBuiltInModifier(name: string): ModifierDefinitionState | null {
return BUILTIN_KEYWORD_MODIFIERS[name] ?? null;
}
lookupComponent(name: string, owner: Owner): ResolvedComponentDefinition | null {
let pair = lookupComponentPair(owner, name);
if (pair === null) {
assert(
'Could not find component `<TextArea />` (did you mean `<Textarea />`?)',
name !== 'text-area'
);
return null;
}
let template: Template | null = null;
let key: object;
if (pair.component === null) | else {
key = pair.component;
}
let cachedComponentDefinition = this.componentDefinitionCache.get(key);
if (cachedComponentDefinition !== undefined) {
return cachedComponentDefinition;
}
if (template === null && pair.layout !== null) {
template = pair.layout(owner);
}
let finalizer = _instrumentStart('render.getComponentDefinition', instrumentationPayload, name);
let definition: Option<ResolvedComponentDefinition> = null;
if (pair.component === null) {
if (ENV._TEMPLATE_ONLY_GLIMMER_COMPONENTS) {
definition = {
state: templateOnlyComponent(undefined, name),
manager: TEMPLATE_ONLY_COMPONENT_MANAGER,
template,
};
} else {
let factory = owner.factoryFor(P`component:-default`)!;
let manager = getInternalComponentManager(factory.class as object);
definition = {
state: factory,
manager,
template,
};
}
} else {
assert(`missing component class ${name}`, pair.component.class !== undefined);
let factory = pair.component;
let ComponentClass = factory.class!;
let manager = getInternalComponentManager(ComponentClass);
definition = {
state: isCurlyManager(manager) ? factory : ComponentClass,
manager,
template,
};
}
finalizer();
this.componentDefinitionCache.set(key, definition);
assert(
'Could not find component `<TextArea />` (did you mean `<Textarea />`?)',
!(definition === null && name === 'text-area')
);
return definition;
}
}
| {
key = template = pair.layout!(owner);
} | conditional_block |
plex.py | """
homeassistant.components.media_player.plex
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to the Plex API.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.plex/
"""
import os
import json
import logging
from datetime import timedelta
from urllib.parse import urlparse
from homeassistant.loader import get_component
import homeassistant.util as util
from homeassistant.components.media_player import (
MediaPlayerDevice, SUPPORT_PAUSE, SUPPORT_PREVIOUS_TRACK,
SUPPORT_NEXT_TRACK, MEDIA_TYPE_TVSHOW, MEDIA_TYPE_VIDEO)
from homeassistant.const import (
DEVICE_DEFAULT_NAME, STATE_IDLE, STATE_PLAYING,
STATE_PAUSED, STATE_OFF, STATE_UNKNOWN)
REQUIREMENTS = ['plexapi==1.1.0']
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=1)
PLEX_CONFIG_FILE = 'plex.conf'
# Map ip to request id for configuring
_CONFIGURING = {}
_LOGGER = logging.getLogger(__name__)
SUPPORT_PLEX = SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK
def config_from_file(filename, config=None):
''' Small configuration file management function'''
if config:
# We're writing configuration
try:
with open(filename, 'w') as fdesc:
fdesc.write(json.dumps(config))
except IOError as error:
_LOGGER.error('Saving config file failed: %s', error)
return False
return True
else:
# We're reading config
if os.path.isfile(filename):
try:
with open(filename, 'r') as fdesc:
return json.loads(fdesc.read())
except IOError as error:
_LOGGER.error('Reading config file failed: %s', error)
# This won't work yet
return False
else:
return {}
# pylint: disable=abstract-method, unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Sets up the plex platform. """
config = config_from_file(hass.config.path(PLEX_CONFIG_FILE))
if len(config):
# Setup a configured PlexServer
host, token = config.popitem()
token = token['token']
# Via discovery
elif discovery_info is not None:
# Parse discovery data
host = urlparse(discovery_info[1]).netloc
_LOGGER.info('Discovered PLEX server: %s', host)
if host in _CONFIGURING:
return
token = None
else:
return
setup_plexserver(host, token, hass, add_devices_callback)
# pylint: disable=too-many-branches
def setup_plexserver(host, token, hass, add_devices_callback):
''' Setup a plexserver based on host parameter'''
import plexapi.server
import plexapi.exceptions
try:
plexserver = plexapi.server.PlexServer('http://%s' % host, token)
except (plexapi.exceptions.BadRequest,
plexapi.exceptions.Unauthorized,
plexapi.exceptions.NotFound) as error:
_LOGGER.info(error)
# No token or wrong token
request_configuration(host, hass, add_devices_callback)
return
# If we came here and configuring this host, mark as done
if host in _CONFIGURING:
request_id = _CONFIGURING.pop(host)
configurator = get_component('configurator')
configurator.request_done(request_id)
_LOGGER.info('Discovery configuration done!')
# Save config
if not config_from_file(
hass.config.path(PLEX_CONFIG_FILE),
{host: {'token': token}}):
_LOGGER.error('failed to save config file')
_LOGGER.info('Connected to: htts://%s', host)
plex_clients = {}
plex_sessions = {}
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update_devices():
""" Updates the devices objects. """
try:
devices = plexserver.clients()
except plexapi.exceptions.BadRequest:
_LOGGER.exception("Error listing plex devices")
return
new_plex_clients = []
for device in devices:
# For now, let's allow all deviceClass types
if device.deviceClass in ['badClient']:
continue
if device.machineIdentifier not in plex_clients:
new_client = PlexClient(device, plex_sessions, update_devices,
update_sessions)
plex_clients[device.machineIdentifier] = new_client
new_plex_clients.append(new_client)
else:
plex_clients[device.machineIdentifier].set_device(device)
if new_plex_clients:
add_devices_callback(new_plex_clients)
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update_sessions():
""" Updates the sessions objects. """
try:
sessions = plexserver.sessions()
except plexapi.exceptions.BadRequest:
_LOGGER.exception("Error listing plex sessions")
return
plex_sessions.clear()
for session in sessions:
plex_sessions[session.player.machineIdentifier] = session
update_devices()
update_sessions()
def request_configuration(host, hass, add_devices_callback):
""" Request configuration steps from the user. """
configurator = get_component('configurator')
# We got an error if this method is called while we are configuring
if host in _CONFIGURING:
configurator.notify_errors(
_CONFIGURING[host], "Failed to register, please try again.")
return
def plex_configuration_callback(data):
""" Actions to do when our configuration callback is called. """
setup_plexserver(host, data.get('token'), hass, add_devices_callback)
_CONFIGURING[host] = configurator.request_config(
hass, "Plex Media Server", plex_configuration_callback,
description=('Enter the X-Plex-Token'),
description_image="/static/images/config_plex_mediaserver.png",
submit_caption="Confirm",
fields=[{'id': 'token', 'name': 'X-Plex-Token', 'type': ''}]
)
class PlexClient(MediaPlayerDevice):
""" Represents a Plex device. """
# pylint: disable=too-many-public-methods, attribute-defined-outside-init
def __init__(self, device, plex_sessions, update_devices, update_sessions):
self.plex_sessions = plex_sessions
self.update_devices = update_devices
self.update_sessions = update_sessions
self.set_device(device)
def set_device(self, device):
""" Sets the device property. """
self.device = device
@property
def unique_id(self):
""" Returns the id of this plex client """
return "{}.{}".format(
self.__class__, self.device.machineIdentifier or self.device.name)
@property
def name(self):
""" Returns the name of the device. """
return self.device.name or DEVICE_DEFAULT_NAME
@property
def session(self):
""" Returns the session, if any. """
if self.device.machineIdentifier not in self.plex_sessions:
return None
return self.plex_sessions[self.device.machineIdentifier]
@property
def state(self):
""" Returns the state of the device. """
if self.session:
state = self.session.player.state
if state == 'playing':
return STATE_PLAYING
elif state == 'paused':
return STATE_PAUSED
# This is nasty. Need to find a way to determine alive
elif self.device:
return STATE_IDLE
else:
return STATE_OFF
return STATE_UNKNOWN
def update(self):
self.update_devices(no_throttle=True)
self.update_sessions(no_throttle=True)
@property
def media_content_id(self):
""" Content ID of current playing media. """
if self.session is not None:
return self.session.ratingKey
@property
def media_content_type(self):
""" Content type of current playing media. """
if self.session is None:
return None
media_type = self.session.type
if media_type == 'episode':
return MEDIA_TYPE_TVSHOW
elif media_type == 'movie':
return MEDIA_TYPE_VIDEO
return None
@property
def media_duration(self):
""" Duration of current playing media in seconds. """
if self.session is not None:
return self.session.duration
@property
def media_image_url(self):
""" Image url of current playing media. """
if self.session is not None:
return self.session.thumbUrl
@property
def media_title(self):
""" Title of current playing media. """
# find a string we can use as a title
if self.session is not None:
return self.session.title
@property
def media_season(self):
|
@property
def media_series_title(self):
""" Series title of current playing media (TV Show only). """
from plexapi.video import Show
if isinstance(self.session, Show):
return self.session.grandparentTitle
@property
def media_episode(self):
""" Episode of current playing media (TV Show only). """
from plexapi.video import Show
if isinstance(self.session, Show):
return self.session.index
@property
def supported_media_commands(self):
""" Flags of media commands that are supported. """
return SUPPORT_PLEX
def media_play(self):
""" media_play media player. """
self.device.play()
def media_pause(self):
""" media_pause media player. """
self.device.pause()
def media_next_track(self):
""" Send next track command. """
self.device.skipNext()
def media_previous_track(self):
""" Send previous track command. """
self.device.skipPrevious()
| """ Season of curent playing media (TV Show only). """
from plexapi.video import Show
if isinstance(self.session, Show):
return self.session.seasons()[0].index | identifier_body |
plex.py | """
homeassistant.components.media_player.plex
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to the Plex API.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.plex/
"""
import os
import json
import logging
from datetime import timedelta
from urllib.parse import urlparse
from homeassistant.loader import get_component
import homeassistant.util as util
from homeassistant.components.media_player import (
MediaPlayerDevice, SUPPORT_PAUSE, SUPPORT_PREVIOUS_TRACK,
SUPPORT_NEXT_TRACK, MEDIA_TYPE_TVSHOW, MEDIA_TYPE_VIDEO)
from homeassistant.const import (
DEVICE_DEFAULT_NAME, STATE_IDLE, STATE_PLAYING,
STATE_PAUSED, STATE_OFF, STATE_UNKNOWN)
REQUIREMENTS = ['plexapi==1.1.0']
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=1)
PLEX_CONFIG_FILE = 'plex.conf'
# Map ip to request id for configuring
_CONFIGURING = {}
_LOGGER = logging.getLogger(__name__)
SUPPORT_PLEX = SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK
def config_from_file(filename, config=None):
''' Small configuration file management function'''
if config:
# We're writing configuration
try:
with open(filename, 'w') as fdesc:
fdesc.write(json.dumps(config))
except IOError as error:
_LOGGER.error('Saving config file failed: %s', error)
return False
return True
else:
# We're reading config
if os.path.isfile(filename):
try:
with open(filename, 'r') as fdesc:
return json.loads(fdesc.read())
except IOError as error:
_LOGGER.error('Reading config file failed: %s', error)
# This won't work yet
return False
else:
return {}
# pylint: disable=abstract-method, unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Sets up the plex platform. """
config = config_from_file(hass.config.path(PLEX_CONFIG_FILE))
if len(config):
# Setup a configured PlexServer
host, token = config.popitem()
token = token['token']
# Via discovery
elif discovery_info is not None:
# Parse discovery data
host = urlparse(discovery_info[1]).netloc
_LOGGER.info('Discovered PLEX server: %s', host)
if host in _CONFIGURING:
return
token = None
else:
return
setup_plexserver(host, token, hass, add_devices_callback)
# pylint: disable=too-many-branches
def setup_plexserver(host, token, hass, add_devices_callback):
''' Setup a plexserver based on host parameter'''
import plexapi.server
import plexapi.exceptions
try:
plexserver = plexapi.server.PlexServer('http://%s' % host, token)
except (plexapi.exceptions.BadRequest,
plexapi.exceptions.Unauthorized,
plexapi.exceptions.NotFound) as error:
_LOGGER.info(error)
# No token or wrong token
request_configuration(host, hass, add_devices_callback)
return
# If we came here and configuring this host, mark as done
if host in _CONFIGURING:
request_id = _CONFIGURING.pop(host)
configurator = get_component('configurator')
configurator.request_done(request_id)
_LOGGER.info('Discovery configuration done!')
# Save config
if not config_from_file(
hass.config.path(PLEX_CONFIG_FILE),
{host: {'token': token}}):
_LOGGER.error('failed to save config file')
_LOGGER.info('Connected to: htts://%s', host)
plex_clients = {}
plex_sessions = {}
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update_devices():
""" Updates the devices objects. """
try:
devices = plexserver.clients()
except plexapi.exceptions.BadRequest:
_LOGGER.exception("Error listing plex devices")
return
new_plex_clients = []
for device in devices:
# For now, let's allow all deviceClass types
if device.deviceClass in ['badClient']:
continue
if device.machineIdentifier not in plex_clients:
new_client = PlexClient(device, plex_sessions, update_devices,
update_sessions)
plex_clients[device.machineIdentifier] = new_client
new_plex_clients.append(new_client)
else:
plex_clients[device.machineIdentifier].set_device(device)
if new_plex_clients:
add_devices_callback(new_plex_clients)
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update_sessions():
""" Updates the sessions objects. """
try:
sessions = plexserver.sessions()
except plexapi.exceptions.BadRequest:
_LOGGER.exception("Error listing plex sessions")
return
plex_sessions.clear()
for session in sessions:
plex_sessions[session.player.machineIdentifier] = session
update_devices()
update_sessions()
def request_configuration(host, hass, add_devices_callback):
""" Request configuration steps from the user. """
configurator = get_component('configurator')
# We got an error if this method is called while we are configuring
if host in _CONFIGURING:
configurator.notify_errors(
_CONFIGURING[host], "Failed to register, please try again.")
return
def plex_configuration_callback(data):
""" Actions to do when our configuration callback is called. """
setup_plexserver(host, data.get('token'), hass, add_devices_callback)
_CONFIGURING[host] = configurator.request_config(
hass, "Plex Media Server", plex_configuration_callback,
description=('Enter the X-Plex-Token'),
description_image="/static/images/config_plex_mediaserver.png",
submit_caption="Confirm",
fields=[{'id': 'token', 'name': 'X-Plex-Token', 'type': ''}]
)
class PlexClient(MediaPlayerDevice):
""" Represents a Plex device. """
# pylint: disable=too-many-public-methods, attribute-defined-outside-init
def __init__(self, device, plex_sessions, update_devices, update_sessions):
self.plex_sessions = plex_sessions
self.update_devices = update_devices
self.update_sessions = update_sessions
self.set_device(device)
def set_device(self, device):
""" Sets the device property. """
self.device = device
@property
def unique_id(self):
""" Returns the id of this plex client """
return "{}.{}".format(
self.__class__, self.device.machineIdentifier or self.device.name)
@property
def name(self):
""" Returns the name of the device. """
return self.device.name or DEVICE_DEFAULT_NAME
@property
def session(self):
""" Returns the session, if any. """
if self.device.machineIdentifier not in self.plex_sessions:
return None
return self.plex_sessions[self.device.machineIdentifier]
@property
def state(self):
""" Returns the state of the device. """
if self.session:
state = self.session.player.state
if state == 'playing':
return STATE_PLAYING
elif state == 'paused':
return STATE_PAUSED
# This is nasty. Need to find a way to determine alive
elif self.device:
return STATE_IDLE
else:
return STATE_OFF
return STATE_UNKNOWN
def update(self):
self.update_devices(no_throttle=True)
self.update_sessions(no_throttle=True)
@property
def media_content_id(self):
""" Content ID of current playing media. """
if self.session is not None:
return self.session.ratingKey
@property
def media_content_type(self):
""" Content type of current playing media. """
if self.session is None:
return None
media_type = self.session.type
if media_type == 'episode':
return MEDIA_TYPE_TVSHOW
elif media_type == 'movie':
return MEDIA_TYPE_VIDEO
return None
@property
def | (self):
""" Duration of current playing media in seconds. """
if self.session is not None:
return self.session.duration
@property
def media_image_url(self):
""" Image url of current playing media. """
if self.session is not None:
return self.session.thumbUrl
@property
def media_title(self):
""" Title of current playing media. """
# find a string we can use as a title
if self.session is not None:
return self.session.title
@property
def media_season(self):
""" Season of curent playing media (TV Show only). """
from plexapi.video import Show
if isinstance(self.session, Show):
return self.session.seasons()[0].index
@property
def media_series_title(self):
""" Series title of current playing media (TV Show only). """
from plexapi.video import Show
if isinstance(self.session, Show):
return self.session.grandparentTitle
@property
def media_episode(self):
""" Episode of current playing media (TV Show only). """
from plexapi.video import Show
if isinstance(self.session, Show):
return self.session.index
@property
def supported_media_commands(self):
""" Flags of media commands that are supported. """
return SUPPORT_PLEX
def media_play(self):
""" media_play media player. """
self.device.play()
def media_pause(self):
""" media_pause media player. """
self.device.pause()
def media_next_track(self):
""" Send next track command. """
self.device.skipNext()
def media_previous_track(self):
""" Send previous track command. """
self.device.skipPrevious()
| media_duration | identifier_name |
plex.py | """
homeassistant.components.media_player.plex
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to the Plex API.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.plex/
"""
import os
import json
import logging
from datetime import timedelta
from urllib.parse import urlparse
from homeassistant.loader import get_component
import homeassistant.util as util
from homeassistant.components.media_player import (
MediaPlayerDevice, SUPPORT_PAUSE, SUPPORT_PREVIOUS_TRACK,
SUPPORT_NEXT_TRACK, MEDIA_TYPE_TVSHOW, MEDIA_TYPE_VIDEO)
from homeassistant.const import (
DEVICE_DEFAULT_NAME, STATE_IDLE, STATE_PLAYING,
STATE_PAUSED, STATE_OFF, STATE_UNKNOWN)
REQUIREMENTS = ['plexapi==1.1.0']
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=1)
PLEX_CONFIG_FILE = 'plex.conf'
# Map ip to request id for configuring
_CONFIGURING = {}
_LOGGER = logging.getLogger(__name__)
SUPPORT_PLEX = SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK
def config_from_file(filename, config=None):
''' Small configuration file management function'''
if config:
# We're writing configuration
try:
with open(filename, 'w') as fdesc:
fdesc.write(json.dumps(config))
except IOError as error:
_LOGGER.error('Saving config file failed: %s', error)
return False
return True
else:
# We're reading config
if os.path.isfile(filename):
try:
with open(filename, 'r') as fdesc:
return json.loads(fdesc.read())
except IOError as error:
_LOGGER.error('Reading config file failed: %s', error)
# This won't work yet
return False
else:
return {}
# pylint: disable=abstract-method, unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Sets up the plex platform. """
config = config_from_file(hass.config.path(PLEX_CONFIG_FILE))
if len(config):
# Setup a configured PlexServer
host, token = config.popitem()
token = token['token']
# Via discovery
elif discovery_info is not None:
# Parse discovery data
host = urlparse(discovery_info[1]).netloc
_LOGGER.info('Discovered PLEX server: %s', host)
if host in _CONFIGURING:
return
token = None
else:
return
setup_plexserver(host, token, hass, add_devices_callback)
# pylint: disable=too-many-branches
def setup_plexserver(host, token, hass, add_devices_callback):
''' Setup a plexserver based on host parameter'''
import plexapi.server
import plexapi.exceptions
try:
plexserver = plexapi.server.PlexServer('http://%s' % host, token)
except (plexapi.exceptions.BadRequest,
plexapi.exceptions.Unauthorized,
plexapi.exceptions.NotFound) as error:
_LOGGER.info(error)
# No token or wrong token
request_configuration(host, hass, add_devices_callback)
return
# If we came here and configuring this host, mark as done
if host in _CONFIGURING:
request_id = _CONFIGURING.pop(host)
configurator = get_component('configurator')
configurator.request_done(request_id)
_LOGGER.info('Discovery configuration done!')
# Save config
if not config_from_file(
hass.config.path(PLEX_CONFIG_FILE),
{host: {'token': token}}):
_LOGGER.error('failed to save config file')
_LOGGER.info('Connected to: htts://%s', host)
plex_clients = {}
plex_sessions = {}
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update_devices():
""" Updates the devices objects. """
try:
devices = plexserver.clients()
except plexapi.exceptions.BadRequest:
_LOGGER.exception("Error listing plex devices")
return
new_plex_clients = []
for device in devices:
# For now, let's allow all deviceClass types
if device.deviceClass in ['badClient']:
continue
if device.machineIdentifier not in plex_clients:
|
else:
plex_clients[device.machineIdentifier].set_device(device)
if new_plex_clients:
add_devices_callback(new_plex_clients)
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update_sessions():
""" Updates the sessions objects. """
try:
sessions = plexserver.sessions()
except plexapi.exceptions.BadRequest:
_LOGGER.exception("Error listing plex sessions")
return
plex_sessions.clear()
for session in sessions:
plex_sessions[session.player.machineIdentifier] = session
update_devices()
update_sessions()
def request_configuration(host, hass, add_devices_callback):
""" Request configuration steps from the user. """
configurator = get_component('configurator')
# We got an error if this method is called while we are configuring
if host in _CONFIGURING:
configurator.notify_errors(
_CONFIGURING[host], "Failed to register, please try again.")
return
def plex_configuration_callback(data):
""" Actions to do when our configuration callback is called. """
setup_plexserver(host, data.get('token'), hass, add_devices_callback)
_CONFIGURING[host] = configurator.request_config(
hass, "Plex Media Server", plex_configuration_callback,
description=('Enter the X-Plex-Token'),
description_image="/static/images/config_plex_mediaserver.png",
submit_caption="Confirm",
fields=[{'id': 'token', 'name': 'X-Plex-Token', 'type': ''}]
)
class PlexClient(MediaPlayerDevice):
""" Represents a Plex device. """
# pylint: disable=too-many-public-methods, attribute-defined-outside-init
def __init__(self, device, plex_sessions, update_devices, update_sessions):
self.plex_sessions = plex_sessions
self.update_devices = update_devices
self.update_sessions = update_sessions
self.set_device(device)
def set_device(self, device):
""" Sets the device property. """
self.device = device
@property
def unique_id(self):
""" Returns the id of this plex client """
return "{}.{}".format(
self.__class__, self.device.machineIdentifier or self.device.name)
@property
def name(self):
""" Returns the name of the device. """
return self.device.name or DEVICE_DEFAULT_NAME
@property
def session(self):
""" Returns the session, if any. """
if self.device.machineIdentifier not in self.plex_sessions:
return None
return self.plex_sessions[self.device.machineIdentifier]
@property
def state(self):
""" Returns the state of the device. """
if self.session:
state = self.session.player.state
if state == 'playing':
return STATE_PLAYING
elif state == 'paused':
return STATE_PAUSED
# This is nasty. Need to find a way to determine alive
elif self.device:
return STATE_IDLE
else:
return STATE_OFF
return STATE_UNKNOWN
def update(self):
self.update_devices(no_throttle=True)
self.update_sessions(no_throttle=True)
@property
def media_content_id(self):
""" Content ID of current playing media. """
if self.session is not None:
return self.session.ratingKey
@property
def media_content_type(self):
""" Content type of current playing media. """
if self.session is None:
return None
media_type = self.session.type
if media_type == 'episode':
return MEDIA_TYPE_TVSHOW
elif media_type == 'movie':
return MEDIA_TYPE_VIDEO
return None
@property
def media_duration(self):
""" Duration of current playing media in seconds. """
if self.session is not None:
return self.session.duration
@property
def media_image_url(self):
""" Image url of current playing media. """
if self.session is not None:
return self.session.thumbUrl
@property
def media_title(self):
""" Title of current playing media. """
# find a string we can use as a title
if self.session is not None:
return self.session.title
@property
def media_season(self):
""" Season of curent playing media (TV Show only). """
from plexapi.video import Show
if isinstance(self.session, Show):
return self.session.seasons()[0].index
@property
def media_series_title(self):
""" Series title of current playing media (TV Show only). """
from plexapi.video import Show
if isinstance(self.session, Show):
return self.session.grandparentTitle
@property
def media_episode(self):
""" Episode of current playing media (TV Show only). """
from plexapi.video import Show
if isinstance(self.session, Show):
return self.session.index
@property
def supported_media_commands(self):
""" Flags of media commands that are supported. """
return SUPPORT_PLEX
def media_play(self):
""" media_play media player. """
self.device.play()
def media_pause(self):
""" media_pause media player. """
self.device.pause()
def media_next_track(self):
""" Send next track command. """
self.device.skipNext()
def media_previous_track(self):
""" Send previous track command. """
self.device.skipPrevious()
| new_client = PlexClient(device, plex_sessions, update_devices,
update_sessions)
plex_clients[device.machineIdentifier] = new_client
new_plex_clients.append(new_client) | conditional_block |
plex.py | """
homeassistant.components.media_player.plex
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to the Plex API.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.plex/
"""
import os
import json
import logging
from datetime import timedelta
from urllib.parse import urlparse
from homeassistant.loader import get_component
import homeassistant.util as util
from homeassistant.components.media_player import (
MediaPlayerDevice, SUPPORT_PAUSE, SUPPORT_PREVIOUS_TRACK,
SUPPORT_NEXT_TRACK, MEDIA_TYPE_TVSHOW, MEDIA_TYPE_VIDEO)
from homeassistant.const import (
DEVICE_DEFAULT_NAME, STATE_IDLE, STATE_PLAYING,
STATE_PAUSED, STATE_OFF, STATE_UNKNOWN)
REQUIREMENTS = ['plexapi==1.1.0']
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=1)
PLEX_CONFIG_FILE = 'plex.conf'
# Map ip to request id for configuring
_CONFIGURING = {}
_LOGGER = logging.getLogger(__name__)
| if config:
# We're writing configuration
try:
with open(filename, 'w') as fdesc:
fdesc.write(json.dumps(config))
except IOError as error:
_LOGGER.error('Saving config file failed: %s', error)
return False
return True
else:
# We're reading config
if os.path.isfile(filename):
try:
with open(filename, 'r') as fdesc:
return json.loads(fdesc.read())
except IOError as error:
_LOGGER.error('Reading config file failed: %s', error)
# This won't work yet
return False
else:
return {}
# pylint: disable=abstract-method, unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Sets up the plex platform. """
config = config_from_file(hass.config.path(PLEX_CONFIG_FILE))
if len(config):
# Setup a configured PlexServer
host, token = config.popitem()
token = token['token']
# Via discovery
elif discovery_info is not None:
# Parse discovery data
host = urlparse(discovery_info[1]).netloc
_LOGGER.info('Discovered PLEX server: %s', host)
if host in _CONFIGURING:
return
token = None
else:
return
setup_plexserver(host, token, hass, add_devices_callback)
# pylint: disable=too-many-branches
def setup_plexserver(host, token, hass, add_devices_callback):
''' Setup a plexserver based on host parameter'''
import plexapi.server
import plexapi.exceptions
try:
plexserver = plexapi.server.PlexServer('http://%s' % host, token)
except (plexapi.exceptions.BadRequest,
plexapi.exceptions.Unauthorized,
plexapi.exceptions.NotFound) as error:
_LOGGER.info(error)
# No token or wrong token
request_configuration(host, hass, add_devices_callback)
return
# If we came here and configuring this host, mark as done
if host in _CONFIGURING:
request_id = _CONFIGURING.pop(host)
configurator = get_component('configurator')
configurator.request_done(request_id)
_LOGGER.info('Discovery configuration done!')
# Save config
if not config_from_file(
hass.config.path(PLEX_CONFIG_FILE),
{host: {'token': token}}):
_LOGGER.error('failed to save config file')
_LOGGER.info('Connected to: htts://%s', host)
plex_clients = {}
plex_sessions = {}
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update_devices():
""" Updates the devices objects. """
try:
devices = plexserver.clients()
except plexapi.exceptions.BadRequest:
_LOGGER.exception("Error listing plex devices")
return
new_plex_clients = []
for device in devices:
# For now, let's allow all deviceClass types
if device.deviceClass in ['badClient']:
continue
if device.machineIdentifier not in plex_clients:
new_client = PlexClient(device, plex_sessions, update_devices,
update_sessions)
plex_clients[device.machineIdentifier] = new_client
new_plex_clients.append(new_client)
else:
plex_clients[device.machineIdentifier].set_device(device)
if new_plex_clients:
add_devices_callback(new_plex_clients)
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update_sessions():
""" Updates the sessions objects. """
try:
sessions = plexserver.sessions()
except plexapi.exceptions.BadRequest:
_LOGGER.exception("Error listing plex sessions")
return
plex_sessions.clear()
for session in sessions:
plex_sessions[session.player.machineIdentifier] = session
update_devices()
update_sessions()
def request_configuration(host, hass, add_devices_callback):
""" Request configuration steps from the user. """
configurator = get_component('configurator')
# We got an error if this method is called while we are configuring
if host in _CONFIGURING:
configurator.notify_errors(
_CONFIGURING[host], "Failed to register, please try again.")
return
def plex_configuration_callback(data):
""" Actions to do when our configuration callback is called. """
setup_plexserver(host, data.get('token'), hass, add_devices_callback)
_CONFIGURING[host] = configurator.request_config(
hass, "Plex Media Server", plex_configuration_callback,
description=('Enter the X-Plex-Token'),
description_image="/static/images/config_plex_mediaserver.png",
submit_caption="Confirm",
fields=[{'id': 'token', 'name': 'X-Plex-Token', 'type': ''}]
)
class PlexClient(MediaPlayerDevice):
""" Represents a Plex device. """
# pylint: disable=too-many-public-methods, attribute-defined-outside-init
def __init__(self, device, plex_sessions, update_devices, update_sessions):
self.plex_sessions = plex_sessions
self.update_devices = update_devices
self.update_sessions = update_sessions
self.set_device(device)
def set_device(self, device):
""" Sets the device property. """
self.device = device
@property
def unique_id(self):
""" Returns the id of this plex client """
return "{}.{}".format(
self.__class__, self.device.machineIdentifier or self.device.name)
@property
def name(self):
""" Returns the name of the device. """
return self.device.name or DEVICE_DEFAULT_NAME
@property
def session(self):
""" Returns the session, if any. """
if self.device.machineIdentifier not in self.plex_sessions:
return None
return self.plex_sessions[self.device.machineIdentifier]
@property
def state(self):
""" Returns the state of the device. """
if self.session:
state = self.session.player.state
if state == 'playing':
return STATE_PLAYING
elif state == 'paused':
return STATE_PAUSED
# This is nasty. Need to find a way to determine alive
elif self.device:
return STATE_IDLE
else:
return STATE_OFF
return STATE_UNKNOWN
def update(self):
self.update_devices(no_throttle=True)
self.update_sessions(no_throttle=True)
@property
def media_content_id(self):
""" Content ID of current playing media. """
if self.session is not None:
return self.session.ratingKey
@property
def media_content_type(self):
""" Content type of current playing media. """
if self.session is None:
return None
media_type = self.session.type
if media_type == 'episode':
return MEDIA_TYPE_TVSHOW
elif media_type == 'movie':
return MEDIA_TYPE_VIDEO
return None
@property
def media_duration(self):
""" Duration of current playing media in seconds. """
if self.session is not None:
return self.session.duration
@property
def media_image_url(self):
""" Image url of current playing media. """
if self.session is not None:
return self.session.thumbUrl
@property
def media_title(self):
""" Title of current playing media. """
# find a string we can use as a title
if self.session is not None:
return self.session.title
@property
def media_season(self):
""" Season of curent playing media (TV Show only). """
from plexapi.video import Show
if isinstance(self.session, Show):
return self.session.seasons()[0].index
@property
def media_series_title(self):
""" Series title of current playing media (TV Show only). """
from plexapi.video import Show
if isinstance(self.session, Show):
return self.session.grandparentTitle
@property
def media_episode(self):
""" Episode of current playing media (TV Show only). """
from plexapi.video import Show
if isinstance(self.session, Show):
return self.session.index
@property
def supported_media_commands(self):
""" Flags of media commands that are supported. """
return SUPPORT_PLEX
def media_play(self):
""" media_play media player. """
self.device.play()
def media_pause(self):
""" media_pause media player. """
self.device.pause()
def media_next_track(self):
""" Send next track command. """
self.device.skipNext()
def media_previous_track(self):
""" Send previous track command. """
self.device.skipPrevious() | SUPPORT_PLEX = SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK
def config_from_file(filename, config=None):
''' Small configuration file management function''' | random_line_split |
ecdsa_test.py | #!/usr/bin/env python
import unittest
from pycoin.ecdsa import generator_secp256k1, sign, verify, public_pair_for_secret_exponent
class ECDSATestCase(unittest.TestCase):
def test_sign_verify(self):
def do_test(secret_exponent, val_list):
public_point = public_pair_for_secret_exponent(generator_secp256k1, secret_exponent)
for v in val_list:
signature = sign(generator_secp256k1, secret_exponent, v)
r = verify(generator_secp256k1, public_point, v, signature)
# Check that the 's' value is 'low', to prevent possible transaction malleability as per
# https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#low-s-values-in-signatures
assert signature[1] <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
assert r == True
signature = signature[0],signature[1]+1
r = verify(generator_secp256k1, public_point, v, signature)
assert r == False
val_list = [100,20000,30000000,400000000000,50000000000000000,60000000000000000000000]
do_test(0x1111111111111111111111111111111111111111111111111111111111111111, val_list)
do_test(0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd, val_list)
do_test(0x47f7616ea6f9b923076625b4488115de1ef1187f760e65f89eb6f4f7ff04b012, val_list)
if __name__ == '__main__':
| unittest.main() | conditional_block | |
ecdsa_test.py | #!/usr/bin/env python
import unittest
from pycoin.ecdsa import generator_secp256k1, sign, verify, public_pair_for_secret_exponent
class ECDSATestCase(unittest.TestCase):
def test_sign_verify(self):
def do_test(secret_exponent, val_list):
|
val_list = [100,20000,30000000,400000000000,50000000000000000,60000000000000000000000]
do_test(0x1111111111111111111111111111111111111111111111111111111111111111, val_list)
do_test(0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd, val_list)
do_test(0x47f7616ea6f9b923076625b4488115de1ef1187f760e65f89eb6f4f7ff04b012, val_list)
if __name__ == '__main__':
unittest.main()
| public_point = public_pair_for_secret_exponent(generator_secp256k1, secret_exponent)
for v in val_list:
signature = sign(generator_secp256k1, secret_exponent, v)
r = verify(generator_secp256k1, public_point, v, signature)
# Check that the 's' value is 'low', to prevent possible transaction malleability as per
# https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#low-s-values-in-signatures
assert signature[1] <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
assert r == True
signature = signature[0],signature[1]+1
r = verify(generator_secp256k1, public_point, v, signature)
assert r == False | identifier_body |
ecdsa_test.py | #!/usr/bin/env python
import unittest
from pycoin.ecdsa import generator_secp256k1, sign, verify, public_pair_for_secret_exponent
class ECDSATestCase(unittest.TestCase):
def test_sign_verify(self):
def do_test(secret_exponent, val_list):
public_point = public_pair_for_secret_exponent(generator_secp256k1, secret_exponent)
for v in val_list:
signature = sign(generator_secp256k1, secret_exponent, v)
r = verify(generator_secp256k1, public_point, v, signature)
# Check that the 's' value is 'low', to prevent possible transaction malleability as per
# https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#low-s-values-in-signatures
assert signature[1] <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
assert r == True
signature = signature[0],signature[1]+1
r = verify(generator_secp256k1, public_point, v, signature)
assert r == False
val_list = [100,20000,30000000,400000000000,50000000000000000,60000000000000000000000]
do_test(0x1111111111111111111111111111111111111111111111111111111111111111, val_list)
do_test(0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd, val_list)
do_test(0x47f7616ea6f9b923076625b4488115de1ef1187f760e65f89eb6f4f7ff04b012, val_list)
| if __name__ == '__main__':
unittest.main() | random_line_split | |
ecdsa_test.py | #!/usr/bin/env python
import unittest
from pycoin.ecdsa import generator_secp256k1, sign, verify, public_pair_for_secret_exponent
class ECDSATestCase(unittest.TestCase):
def | (self):
def do_test(secret_exponent, val_list):
public_point = public_pair_for_secret_exponent(generator_secp256k1, secret_exponent)
for v in val_list:
signature = sign(generator_secp256k1, secret_exponent, v)
r = verify(generator_secp256k1, public_point, v, signature)
# Check that the 's' value is 'low', to prevent possible transaction malleability as per
# https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#low-s-values-in-signatures
assert signature[1] <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
assert r == True
signature = signature[0],signature[1]+1
r = verify(generator_secp256k1, public_point, v, signature)
assert r == False
val_list = [100,20000,30000000,400000000000,50000000000000000,60000000000000000000000]
do_test(0x1111111111111111111111111111111111111111111111111111111111111111, val_list)
do_test(0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd, val_list)
do_test(0x47f7616ea6f9b923076625b4488115de1ef1187f760e65f89eb6f4f7ff04b012, val_list)
if __name__ == '__main__':
unittest.main()
| test_sign_verify | identifier_name |
6.py | # Nov 22, 2014
# This patch is to create all the prep/sample template files and link them in
# the database so they are present for download
from os.path import join
from time import strftime
from qiita_db.util import get_mountpoint
from qiita_db.sql_connection import SQLConnectionHandler
from qiita_db.metadata_template import SampleTemplate, PrepTemplate
conn_handler = SQLConnectionHandler() | for study_id in conn_handler.execute_fetchall(
"SELECT study_id FROM qiita.study"):
study_id = study_id[0]
if SampleTemplate.exists(study_id):
st = SampleTemplate(study_id)
fp = join(fp_base, '%d_%s.txt' % (study_id, strftime("%Y%m%d-%H%M%S")))
st.to_file(fp)
st.add_filepath(fp)
for prep_template_id in conn_handler.execute_fetchall(
"SELECT prep_template_id FROM qiita.prep_template"):
prep_template_id = prep_template_id[0]
pt = PrepTemplate(prep_template_id)
study_id = pt.study_id
fp = join(fp_base, '%d_prep_%d_%s.txt' % (pt.study_id, prep_template_id,
strftime("%Y%m%d-%H%M%S")))
pt.to_file(fp)
pt.add_filepath(fp) |
_id, fp_base = get_mountpoint('templates')[0]
| random_line_split |
6.py | # Nov 22, 2014
# This patch is to create all the prep/sample template files and link them in
# the database so they are present for download
from os.path import join
from time import strftime
from qiita_db.util import get_mountpoint
from qiita_db.sql_connection import SQLConnectionHandler
from qiita_db.metadata_template import SampleTemplate, PrepTemplate
conn_handler = SQLConnectionHandler()
_id, fp_base = get_mountpoint('templates')[0]
for study_id in conn_handler.execute_fetchall(
"SELECT study_id FROM qiita.study"):
study_id = study_id[0]
if SampleTemplate.exists(study_id):
st = SampleTemplate(study_id)
fp = join(fp_base, '%d_%s.txt' % (study_id, strftime("%Y%m%d-%H%M%S")))
st.to_file(fp)
st.add_filepath(fp)
for prep_template_id in conn_handler.execute_fetchall(
"SELECT prep_template_id FROM qiita.prep_template"):
| prep_template_id = prep_template_id[0]
pt = PrepTemplate(prep_template_id)
study_id = pt.study_id
fp = join(fp_base, '%d_prep_%d_%s.txt' % (pt.study_id, prep_template_id,
strftime("%Y%m%d-%H%M%S")))
pt.to_file(fp)
pt.add_filepath(fp) | conditional_block | |
zsys.rs | //! Module: czmq-zsys
use {czmq_sys, RawInterface, Result};
use error::{Error, ErrorKind};
use std::{error, fmt, ptr};
use std::os::raw::c_void;
use std::sync::{Once, ONCE_INIT};
use zsock::ZSock;
static INIT_ZSYS: Once = ONCE_INIT;
pub struct ZSys;
impl ZSys {
// Each new ZSock calls zsys_init(), which is a non-threadsafe
// fn. To mitigate the race condition, wrap it in a Once struct.
pub fn init() {
INIT_ZSYS.call_once(|| {
unsafe { czmq_sys::zsys_init() };
});
}
/// Create a pipe, which consists of two PAIR sockets connected
/// over inproc.
pub fn create_pipe() -> Result<(ZSock, ZSock)> {
let mut backend_raw: *mut czmq_sys::zsock_t = ptr::null_mut();
let frontend_raw = unsafe { czmq_sys::zsys_create_pipe(&mut backend_raw) };
if frontend_raw == ptr::null_mut() {
Err(Error::new(ErrorKind::NullPtr, ZSysError::CreatePipe))
} else {
Ok(unsafe { (ZSock::from_raw(frontend_raw as *mut c_void, true), ZSock::from_raw(backend_raw as *mut c_void, true)) })
}
}
pub fn is_interrupted() -> bool {
unsafe { czmq_sys::zsys_interrupted == 1 }
}
}
#[derive(Debug)]
pub enum ZSysError {
CreatePipe,
}
impl fmt::Display for ZSysError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ZSysError::CreatePipe => write!(f, "Could not create pipe"),
}
}
}
impl error::Error for ZSysError {
fn description(&self) -> &str {
match *self {
ZSysError::CreatePipe => "Could not create pipe",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_pipe() {
ZSys::init();
let (frontend, backend) = ZSys::create_pipe().unwrap();
frontend.send_str("I changed my iPod’s name to Titanic...now it’s syncing.").unwrap();
assert_eq!(backend.recv_str().unwrap().unwrap(), "I changed my iPod’s name to Titanic...now it’s syncing.");
backend.send_str("My family laughed when I told them I was going to be a comedian. Well...they aren't laughing now!").unwrap();
assert_eq!(frontend.recv_str().unwrap().unwrap(), "My family laughed when I told them I was going to be a comedian. Well...they aren't laughing now!");
}
#[test]
fn test_is_ | // This test is half hearted as we can't test the interrupt
// case.
assert!(!ZSys::is_interrupted());
}
}
| interrupted() {
| identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.