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 |
|---|---|---|---|---|
test_concurrency.py | from __future__ import absolute_import
import os
from itertools import count
from mock import Mock
from celery.concurrency.base import apply_target, BasePool
from celery.tests.case import AppCase
class test_BasePool(AppCase):
def test_apply_target(self):
scratch = {}
counter = count(0)
def gen_callback(name, retval=None):
def callback(*args):
scratch[name] = (next(counter), args)
return retval
return callback
apply_target(gen_callback('target', 42),
args=(8, 16),
callback=gen_callback('callback'),
accept_callback=gen_callback('accept_callback'))
self.assertDictContainsSubset(
{'target': (1, (8, 16)), 'callback': (2, (42, ))},
scratch,
)
pa1 = scratch['accept_callback']
self.assertEqual(0, pa1[0])
self.assertEqual(pa1[1][0], os.getpid())
self.assertTrue(pa1[1][1])
# No accept callback
scratch.clear()
apply_target(gen_callback('target', 42),
args=(8, 16),
callback=gen_callback('callback'),
accept_callback=None)
self.assertDictEqual(scratch,
{'target': (3, (8, 16)),
'callback': (4, (42, ))})
def test_does_not_debug(self):
x = BasePool(10)
x._does_debug = False
x.apply_async(object)
def test_num_processes(self):
self.assertEqual(BasePool(7).num_processes, 7)
def test_interface_on_start(self):
BasePool(10).on_start()
def test_interface_on_stop(self): |
def test_interface_on_apply(self):
BasePool(10).on_apply()
def test_interface_info(self):
self.assertDictEqual(BasePool(10).info, {})
def test_active(self):
p = BasePool(10)
self.assertFalse(p.active)
p._state = p.RUN
self.assertTrue(p.active)
def test_restart(self):
p = BasePool(10)
with self.assertRaises(NotImplementedError):
p.restart()
def test_interface_on_terminate(self):
p = BasePool(10)
p.on_terminate()
def test_interface_terminate_job(self):
with self.assertRaises(NotImplementedError):
BasePool(10).terminate_job(101)
def test_interface_did_start_ok(self):
self.assertTrue(BasePool(10).did_start_ok())
def test_interface_register_with_event_loop(self):
self.assertIsNone(
BasePool(10).register_with_event_loop(Mock()),
)
def test_interface_on_soft_timeout(self):
self.assertIsNone(BasePool(10).on_soft_timeout(Mock()))
def test_interface_on_hard_timeout(self):
self.assertIsNone(BasePool(10).on_hard_timeout(Mock()))
def test_interface_close(self):
p = BasePool(10)
p.on_close = Mock()
p.close()
self.assertEqual(p._state, p.CLOSE)
p.on_close.assert_called_with()
def test_interface_no_close(self):
self.assertIsNone(BasePool(10).on_close()) | BasePool(10).on_stop() | random_line_split |
test_concurrency.py | from __future__ import absolute_import
import os
from itertools import count
from mock import Mock
from celery.concurrency.base import apply_target, BasePool
from celery.tests.case import AppCase
class test_BasePool(AppCase):
def test_apply_target(self):
scratch = {}
counter = count(0)
def gen_callback(name, retval=None):
def callback(*args):
scratch[name] = (next(counter), args)
return retval
return callback
apply_target(gen_callback('target', 42),
args=(8, 16),
callback=gen_callback('callback'),
accept_callback=gen_callback('accept_callback'))
self.assertDictContainsSubset(
{'target': (1, (8, 16)), 'callback': (2, (42, ))},
scratch,
)
pa1 = scratch['accept_callback']
self.assertEqual(0, pa1[0])
self.assertEqual(pa1[1][0], os.getpid())
self.assertTrue(pa1[1][1])
# No accept callback
scratch.clear()
apply_target(gen_callback('target', 42),
args=(8, 16),
callback=gen_callback('callback'),
accept_callback=None)
self.assertDictEqual(scratch,
{'target': (3, (8, 16)),
'callback': (4, (42, ))})
def test_does_not_debug(self):
x = BasePool(10)
x._does_debug = False
x.apply_async(object)
def test_num_processes(self):
self.assertEqual(BasePool(7).num_processes, 7)
def test_interface_on_start(self):
BasePool(10).on_start()
def test_interface_on_stop(self):
BasePool(10).on_stop()
def test_interface_on_apply(self):
BasePool(10).on_apply()
def test_interface_info(self):
self.assertDictEqual(BasePool(10).info, {})
def test_active(self):
p = BasePool(10)
self.assertFalse(p.active)
p._state = p.RUN
self.assertTrue(p.active)
def test_restart(self):
p = BasePool(10)
with self.assertRaises(NotImplementedError):
p.restart()
def test_interface_on_terminate(self):
p = BasePool(10)
p.on_terminate()
def test_interface_terminate_job(self):
with self.assertRaises(NotImplementedError):
BasePool(10).terminate_job(101)
def test_interface_did_start_ok(self):
self.assertTrue(BasePool(10).did_start_ok())
def test_interface_register_with_event_loop(self):
self.assertIsNone(
BasePool(10).register_with_event_loop(Mock()),
)
def test_interface_on_soft_timeout(self):
self.assertIsNone(BasePool(10).on_soft_timeout(Mock()))
def | (self):
self.assertIsNone(BasePool(10).on_hard_timeout(Mock()))
def test_interface_close(self):
p = BasePool(10)
p.on_close = Mock()
p.close()
self.assertEqual(p._state, p.CLOSE)
p.on_close.assert_called_with()
def test_interface_no_close(self):
self.assertIsNone(BasePool(10).on_close())
| test_interface_on_hard_timeout | identifier_name |
test_concurrency.py | from __future__ import absolute_import
import os
from itertools import count
from mock import Mock
from celery.concurrency.base import apply_target, BasePool
from celery.tests.case import AppCase
class test_BasePool(AppCase):
def test_apply_target(self):
scratch = {}
counter = count(0)
def gen_callback(name, retval=None):
|
apply_target(gen_callback('target', 42),
args=(8, 16),
callback=gen_callback('callback'),
accept_callback=gen_callback('accept_callback'))
self.assertDictContainsSubset(
{'target': (1, (8, 16)), 'callback': (2, (42, ))},
scratch,
)
pa1 = scratch['accept_callback']
self.assertEqual(0, pa1[0])
self.assertEqual(pa1[1][0], os.getpid())
self.assertTrue(pa1[1][1])
# No accept callback
scratch.clear()
apply_target(gen_callback('target', 42),
args=(8, 16),
callback=gen_callback('callback'),
accept_callback=None)
self.assertDictEqual(scratch,
{'target': (3, (8, 16)),
'callback': (4, (42, ))})
def test_does_not_debug(self):
x = BasePool(10)
x._does_debug = False
x.apply_async(object)
def test_num_processes(self):
self.assertEqual(BasePool(7).num_processes, 7)
def test_interface_on_start(self):
BasePool(10).on_start()
def test_interface_on_stop(self):
BasePool(10).on_stop()
def test_interface_on_apply(self):
BasePool(10).on_apply()
def test_interface_info(self):
self.assertDictEqual(BasePool(10).info, {})
def test_active(self):
p = BasePool(10)
self.assertFalse(p.active)
p._state = p.RUN
self.assertTrue(p.active)
def test_restart(self):
p = BasePool(10)
with self.assertRaises(NotImplementedError):
p.restart()
def test_interface_on_terminate(self):
p = BasePool(10)
p.on_terminate()
def test_interface_terminate_job(self):
with self.assertRaises(NotImplementedError):
BasePool(10).terminate_job(101)
def test_interface_did_start_ok(self):
self.assertTrue(BasePool(10).did_start_ok())
def test_interface_register_with_event_loop(self):
self.assertIsNone(
BasePool(10).register_with_event_loop(Mock()),
)
def test_interface_on_soft_timeout(self):
self.assertIsNone(BasePool(10).on_soft_timeout(Mock()))
def test_interface_on_hard_timeout(self):
self.assertIsNone(BasePool(10).on_hard_timeout(Mock()))
def test_interface_close(self):
p = BasePool(10)
p.on_close = Mock()
p.close()
self.assertEqual(p._state, p.CLOSE)
p.on_close.assert_called_with()
def test_interface_no_close(self):
self.assertIsNone(BasePool(10).on_close())
| def callback(*args):
scratch[name] = (next(counter), args)
return retval
return callback | identifier_body |
user.ts | import {Injectable} from '@angular/core';
import {Config} from '../config';
import {Submission} from '../models/submission';
import {User} from '../models/user';
import {HttpService} from './http';
import {PollingService} from './polling';
import {ProblemService} from './problem';
@Injectable()
export class UserService {
constructor(
private _httpService: HttpService,
private _problemService: ProblemService,
private _pollingService: PollingService) {
}
getUser(id: number): Promise<User> {
return new Promise<User>((resolve) => {
this.loadUser(id, resolve);
});
}
private loadUser(id: number, resolve) {
this._httpService.get(Config.API_PATH + '/subs-user/' + id)
.then(res => {
this.subscribeUser(new User({
userid: id,
name: res.name,
username: res.uname
}), res.subs, resolve);
});
}
private subscribeUser(user, submissions, resolve) {
this._problemService.ready.then(() => {
for (let s of submissions) {
user.insertOrUpdate(new Submission([
s[0],
user,
this._problemService.getProblemById(s[1]),
s[2],
s[5],
s[3],
0, // memory
s[6],
s[4]]));
}
// this._pollingService.out_of_sync.subscribe(() => {
// uhunt_rpc.subs_since(uhunt_user.uid, uhunt_user.lastId(), function(res) {
// var arr = res.subs;
// for (var i = 0; i < arr.length; i++) {
// var s = arr[i];
// uhunt_user.update({ sid: s[0], pid: s[1], ver: s[2], run: s[3], sbt: s[4], lan: s[5], rank: s[6] });
// }
// console.log('submissions is now in sync');
// });
// });
this._pollingService.submissions.subscribe((subs: Submission[]) => {
for (var s of subs) {
if (user.id == s.user.id) |
}
});
resolve(user);
});
}
}
| {
user.insertOrUpdate(s);
} | conditional_block |
user.ts | import {Injectable} from '@angular/core';
import {Config} from '../config';
import {Submission} from '../models/submission';
import {User} from '../models/user';
import {HttpService} from './http';
import {PollingService} from './polling';
import {ProblemService} from './problem';
@Injectable()
export class UserService {
constructor(
private _httpService: HttpService,
private _problemService: ProblemService,
private _pollingService: PollingService) |
getUser(id: number): Promise<User> {
return new Promise<User>((resolve) => {
this.loadUser(id, resolve);
});
}
private loadUser(id: number, resolve) {
this._httpService.get(Config.API_PATH + '/subs-user/' + id)
.then(res => {
this.subscribeUser(new User({
userid: id,
name: res.name,
username: res.uname
}), res.subs, resolve);
});
}
private subscribeUser(user, submissions, resolve) {
this._problemService.ready.then(() => {
for (let s of submissions) {
user.insertOrUpdate(new Submission([
s[0],
user,
this._problemService.getProblemById(s[1]),
s[2],
s[5],
s[3],
0, // memory
s[6],
s[4]]));
}
// this._pollingService.out_of_sync.subscribe(() => {
// uhunt_rpc.subs_since(uhunt_user.uid, uhunt_user.lastId(), function(res) {
// var arr = res.subs;
// for (var i = 0; i < arr.length; i++) {
// var s = arr[i];
// uhunt_user.update({ sid: s[0], pid: s[1], ver: s[2], run: s[3], sbt: s[4], lan: s[5], rank: s[6] });
// }
// console.log('submissions is now in sync');
// });
// });
this._pollingService.submissions.subscribe((subs: Submission[]) => {
for (var s of subs) {
if (user.id == s.user.id) {
user.insertOrUpdate(s);
}
}
});
resolve(user);
});
}
}
| {
} | identifier_body |
user.ts | import {Injectable} from '@angular/core';
import {Config} from '../config';
import {Submission} from '../models/submission';
import {User} from '../models/user';
import {HttpService} from './http';
import {PollingService} from './polling';
import {ProblemService} from './problem';
@Injectable()
export class UserService {
| (
private _httpService: HttpService,
private _problemService: ProblemService,
private _pollingService: PollingService) {
}
getUser(id: number): Promise<User> {
return new Promise<User>((resolve) => {
this.loadUser(id, resolve);
});
}
private loadUser(id: number, resolve) {
this._httpService.get(Config.API_PATH + '/subs-user/' + id)
.then(res => {
this.subscribeUser(new User({
userid: id,
name: res.name,
username: res.uname
}), res.subs, resolve);
});
}
private subscribeUser(user, submissions, resolve) {
this._problemService.ready.then(() => {
for (let s of submissions) {
user.insertOrUpdate(new Submission([
s[0],
user,
this._problemService.getProblemById(s[1]),
s[2],
s[5],
s[3],
0, // memory
s[6],
s[4]]));
}
// this._pollingService.out_of_sync.subscribe(() => {
// uhunt_rpc.subs_since(uhunt_user.uid, uhunt_user.lastId(), function(res) {
// var arr = res.subs;
// for (var i = 0; i < arr.length; i++) {
// var s = arr[i];
// uhunt_user.update({ sid: s[0], pid: s[1], ver: s[2], run: s[3], sbt: s[4], lan: s[5], rank: s[6] });
// }
// console.log('submissions is now in sync');
// });
// });
this._pollingService.submissions.subscribe((subs: Submission[]) => {
for (var s of subs) {
if (user.id == s.user.id) {
user.insertOrUpdate(s);
}
}
});
resolve(user);
});
}
}
| constructor | identifier_name |
user.ts | import {Injectable} from '@angular/core';
import {Config} from '../config';
import {Submission} from '../models/submission';
import {User} from '../models/user';
import {HttpService} from './http';
import {PollingService} from './polling';
import {ProblemService} from './problem';
@Injectable()
export class UserService {
constructor(
private _httpService: HttpService,
private _problemService: ProblemService,
private _pollingService: PollingService) {
}
getUser(id: number): Promise<User> { | return new Promise<User>((resolve) => {
this.loadUser(id, resolve);
});
}
private loadUser(id: number, resolve) {
this._httpService.get(Config.API_PATH + '/subs-user/' + id)
.then(res => {
this.subscribeUser(new User({
userid: id,
name: res.name,
username: res.uname
}), res.subs, resolve);
});
}
private subscribeUser(user, submissions, resolve) {
this._problemService.ready.then(() => {
for (let s of submissions) {
user.insertOrUpdate(new Submission([
s[0],
user,
this._problemService.getProblemById(s[1]),
s[2],
s[5],
s[3],
0, // memory
s[6],
s[4]]));
}
// this._pollingService.out_of_sync.subscribe(() => {
// uhunt_rpc.subs_since(uhunt_user.uid, uhunt_user.lastId(), function(res) {
// var arr = res.subs;
// for (var i = 0; i < arr.length; i++) {
// var s = arr[i];
// uhunt_user.update({ sid: s[0], pid: s[1], ver: s[2], run: s[3], sbt: s[4], lan: s[5], rank: s[6] });
// }
// console.log('submissions is now in sync');
// });
// });
this._pollingService.submissions.subscribe((subs: Submission[]) => {
for (var s of subs) {
if (user.id == s.user.id) {
user.insertOrUpdate(s);
}
}
});
resolve(user);
});
}
} | random_line_split | |
intersection.rs | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
extern crate aabb_quadtree;
extern crate map_model;
use aabb_quadtree::geom::Rect;
use ezgui::canvas::GfxCtx;
use geom::geometry;
use graphics;
use graphics::math::Vec2d;
use graphics::types::Color;
use map_model::{Bounds, IntersectionID, Map};
use render::DrawRoad;
use std::f64;
#[derive(Debug)]
pub struct | {
pub id: IntersectionID,
pub point: Vec2d,
polygon: Vec<Vec2d>,
}
impl DrawIntersection {
pub fn new(
inter: &map_model::Intersection,
map: &Map,
roads: &Vec<DrawRoad>,
bounds: &Bounds,
) -> DrawIntersection {
let mut pts: Vec<Vec2d> = Vec::new();
// TODO this smashes encapsulation to bits :D
for r in &map.get_roads_to_intersection(inter.id) {
let dr = &roads[r.id.0];
pts.push(dr.polygons.last().unwrap()[2]);
pts.push(dr.polygons.last().unwrap()[3]);
}
for r in &map.get_roads_from_intersection(inter.id) {
let dr = &roads[r.id.0];
pts.push(dr.polygons[0][0]);
pts.push(dr.polygons[0][1]);
}
let center = geometry::gps_to_screen_space(&inter.point, bounds);
// Sort points by angle from the center
pts.sort_by_key(|pt| {
let mut angle = (pt[1] - center.y()).atan2(pt[0] - center.x()).to_degrees();
if angle < 0.0 {
angle += 360.0;
}
angle as i64
});
let first_pt = pts[0].clone();
pts.push(first_pt);
DrawIntersection {
id: inter.id,
point: [center.x(), center.y()],
polygon: pts,
}
}
pub fn draw(&self, g: &mut GfxCtx, color: Color) {
let poly = graphics::Polygon::new(color);
poly.draw(&self.polygon, &g.ctx.draw_state, g.ctx.transform, g.gfx);
}
pub fn contains_pt(&self, x: f64, y: f64) -> bool {
geometry::point_in_polygon(x, y, &self.polygon)
}
pub fn get_bbox(&self) -> Rect {
geometry::get_bbox_for_polygons(&[self.polygon.clone()])
}
}
| DrawIntersection | identifier_name |
intersection.rs | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
extern crate aabb_quadtree;
extern crate map_model;
use aabb_quadtree::geom::Rect;
use ezgui::canvas::GfxCtx;
use geom::geometry;
use graphics;
use graphics::math::Vec2d;
use graphics::types::Color;
use map_model::{Bounds, IntersectionID, Map};
use render::DrawRoad;
use std::f64;
#[derive(Debug)]
pub struct DrawIntersection {
pub id: IntersectionID, |
polygon: Vec<Vec2d>,
}
impl DrawIntersection {
pub fn new(
inter: &map_model::Intersection,
map: &Map,
roads: &Vec<DrawRoad>,
bounds: &Bounds,
) -> DrawIntersection {
let mut pts: Vec<Vec2d> = Vec::new();
// TODO this smashes encapsulation to bits :D
for r in &map.get_roads_to_intersection(inter.id) {
let dr = &roads[r.id.0];
pts.push(dr.polygons.last().unwrap()[2]);
pts.push(dr.polygons.last().unwrap()[3]);
}
for r in &map.get_roads_from_intersection(inter.id) {
let dr = &roads[r.id.0];
pts.push(dr.polygons[0][0]);
pts.push(dr.polygons[0][1]);
}
let center = geometry::gps_to_screen_space(&inter.point, bounds);
// Sort points by angle from the center
pts.sort_by_key(|pt| {
let mut angle = (pt[1] - center.y()).atan2(pt[0] - center.x()).to_degrees();
if angle < 0.0 {
angle += 360.0;
}
angle as i64
});
let first_pt = pts[0].clone();
pts.push(first_pt);
DrawIntersection {
id: inter.id,
point: [center.x(), center.y()],
polygon: pts,
}
}
pub fn draw(&self, g: &mut GfxCtx, color: Color) {
let poly = graphics::Polygon::new(color);
poly.draw(&self.polygon, &g.ctx.draw_state, g.ctx.transform, g.gfx);
}
pub fn contains_pt(&self, x: f64, y: f64) -> bool {
geometry::point_in_polygon(x, y, &self.polygon)
}
pub fn get_bbox(&self) -> Rect {
geometry::get_bbox_for_polygons(&[self.polygon.clone()])
}
} | pub point: Vec2d, | random_line_split |
intersection.rs | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
extern crate aabb_quadtree;
extern crate map_model;
use aabb_quadtree::geom::Rect;
use ezgui::canvas::GfxCtx;
use geom::geometry;
use graphics;
use graphics::math::Vec2d;
use graphics::types::Color;
use map_model::{Bounds, IntersectionID, Map};
use render::DrawRoad;
use std::f64;
#[derive(Debug)]
pub struct DrawIntersection {
pub id: IntersectionID,
pub point: Vec2d,
polygon: Vec<Vec2d>,
}
impl DrawIntersection {
pub fn new(
inter: &map_model::Intersection,
map: &Map,
roads: &Vec<DrawRoad>,
bounds: &Bounds,
) -> DrawIntersection {
let mut pts: Vec<Vec2d> = Vec::new();
// TODO this smashes encapsulation to bits :D
for r in &map.get_roads_to_intersection(inter.id) {
let dr = &roads[r.id.0];
pts.push(dr.polygons.last().unwrap()[2]);
pts.push(dr.polygons.last().unwrap()[3]);
}
for r in &map.get_roads_from_intersection(inter.id) {
let dr = &roads[r.id.0];
pts.push(dr.polygons[0][0]);
pts.push(dr.polygons[0][1]);
}
let center = geometry::gps_to_screen_space(&inter.point, bounds);
// Sort points by angle from the center
pts.sort_by_key(|pt| {
let mut angle = (pt[1] - center.y()).atan2(pt[0] - center.x()).to_degrees();
if angle < 0.0 |
angle as i64
});
let first_pt = pts[0].clone();
pts.push(first_pt);
DrawIntersection {
id: inter.id,
point: [center.x(), center.y()],
polygon: pts,
}
}
pub fn draw(&self, g: &mut GfxCtx, color: Color) {
let poly = graphics::Polygon::new(color);
poly.draw(&self.polygon, &g.ctx.draw_state, g.ctx.transform, g.gfx);
}
pub fn contains_pt(&self, x: f64, y: f64) -> bool {
geometry::point_in_polygon(x, y, &self.polygon)
}
pub fn get_bbox(&self) -> Rect {
geometry::get_bbox_for_polygons(&[self.polygon.clone()])
}
}
| {
angle += 360.0;
} | conditional_block |
partial_file.rs | // Copyright (c) 2017 Simon Dickson
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::cmp;
use std::fs::File;
use std::io::{self, BufReader, SeekFrom, Seek, Read};
use std::str::FromStr;
use std::path::{Path, PathBuf};
use rocket::request::Request;
use rocket::response::{Response, Responder};
use rocket::http::Status;
use rocket::http::hyper::header::{ByteRangeSpec, ContentRangeSpec, AcceptRanges, RangeUnit, Range, ContentRange, ContentLength};
#[derive(Debug)]
pub enum PartialFileRange {
AllFrom(u64),
FromTo(u64,u64),
Last(u64),
}
impl From<ByteRangeSpec> for PartialFileRange {
fn from(b: ByteRangeSpec) -> PartialFileRange {
match b {
ByteRangeSpec::AllFrom(from) => PartialFileRange::AllFrom(from),
ByteRangeSpec::FromTo(from, to) => PartialFileRange::FromTo(from, to),
ByteRangeSpec::Last(last) => PartialFileRange::Last(last),
}
}
}
impl From<Vec<ByteRangeSpec>> for PartialFileRange {
fn from(v: Vec<ByteRangeSpec>) -> PartialFileRange {
match v.into_iter().next() {
None => PartialFileRange::AllFrom(0),
Some(byte_range) => PartialFileRange::from(byte_range),
}
}
}
#[derive(Debug)]
pub struct PartialFile {
path: PathBuf,
file: File
}
impl PartialFile {
pub fn open<P: AsRef<Path>>(path: P) -> io::Result<PartialFile> {
let file = File::open(path.as_ref())?;
Ok(PartialFile{ path: path.as_ref().to_path_buf(), file: file })
}
pub fn get_partial<Range>(self, response: &mut Response, range: Range)
where Range: Into<PartialFileRange> {
use self::PartialFileRange::*;
let metadata : Option<_> = self.file.metadata().ok();
let file_length : Option<u64> = metadata.map(|m| m.len());
let range : Option<(u64, u64)> = match (range.into(), file_length) {
(FromTo(from, to), Some(file_length)) => {
if from <= to && from < file_length {
Some((from, cmp::min(to, file_length - 1)))
} else {
None
}
},
(AllFrom(from), Some(file_length)) => {
if from < file_length {
Some((from, file_length - 1))
} else {
None
}
},
(Last(last), Some(file_length)) => {
if last < file_length {
Some((file_length - last, file_length - 1))
} else {
Some((0, file_length - 1))
}
},
(_, None) => None,
};
if let Some(range) = range {
let content_range = ContentRange(ContentRangeSpec::Bytes {
range: Some(range),
instance_length: file_length,
});
let content_len = range.1 - range.0 + 1; | let mut partial_content = BufReader::new(self.file);
let _ = partial_content.seek(SeekFrom::Start(range.0));
let result = partial_content.take(content_len);
response.set_status(Status::PartialContent);
response.set_streamed_body(result);
} else {
if let Some(file_length) = file_length {
response.set_header(ContentRange(ContentRangeSpec::Bytes {
range: None,
instance_length: Some(file_length),
}));
};
response.set_status(Status::RangeNotSatisfiable);
};
}
}
impl Responder<'static> for PartialFile {
fn respond_to(self, req: &Request) -> Result<Response<'static>, Status> {
let mut response = Response::new();
response.set_header(AcceptRanges(vec![RangeUnit::Bytes]));
match req.headers().get_one("range") {
Some (range) => {
match Range::from_str(range) {
Ok(Range::Bytes(ref v)) => {
self.get_partial(&mut response, v.clone());
response.set_status(Status::PartialContent);
},
_ => {
response.set_status(Status::RangeNotSatisfiable);
},
}
},
None => {
response.set_streamed_body(BufReader::new(self.file));
},
}
Ok(response)
}
}
pub fn serve_partial(video_path: &Path) -> io::Result<PartialFile> {
PartialFile::open(video_path)
} | response.set_header(ContentLength(content_len));
response.set_header(content_range); | random_line_split |
partial_file.rs | // Copyright (c) 2017 Simon Dickson
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::cmp;
use std::fs::File;
use std::io::{self, BufReader, SeekFrom, Seek, Read};
use std::str::FromStr;
use std::path::{Path, PathBuf};
use rocket::request::Request;
use rocket::response::{Response, Responder};
use rocket::http::Status;
use rocket::http::hyper::header::{ByteRangeSpec, ContentRangeSpec, AcceptRanges, RangeUnit, Range, ContentRange, ContentLength};
#[derive(Debug)]
pub enum PartialFileRange {
AllFrom(u64),
FromTo(u64,u64),
Last(u64),
}
impl From<ByteRangeSpec> for PartialFileRange {
fn from(b: ByteRangeSpec) -> PartialFileRange {
match b {
ByteRangeSpec::AllFrom(from) => PartialFileRange::AllFrom(from),
ByteRangeSpec::FromTo(from, to) => PartialFileRange::FromTo(from, to),
ByteRangeSpec::Last(last) => PartialFileRange::Last(last),
}
}
}
impl From<Vec<ByteRangeSpec>> for PartialFileRange {
fn from(v: Vec<ByteRangeSpec>) -> PartialFileRange {
match v.into_iter().next() {
None => PartialFileRange::AllFrom(0),
Some(byte_range) => PartialFileRange::from(byte_range),
}
}
}
#[derive(Debug)]
pub struct PartialFile {
path: PathBuf,
file: File
}
impl PartialFile {
pub fn open<P: AsRef<Path>>(path: P) -> io::Result<PartialFile> {
let file = File::open(path.as_ref())?;
Ok(PartialFile{ path: path.as_ref().to_path_buf(), file: file })
}
pub fn get_partial<Range>(self, response: &mut Response, range: Range)
where Range: Into<PartialFileRange> {
use self::PartialFileRange::*;
let metadata : Option<_> = self.file.metadata().ok();
let file_length : Option<u64> = metadata.map(|m| m.len());
let range : Option<(u64, u64)> = match (range.into(), file_length) {
(FromTo(from, to), Some(file_length)) => {
if from <= to && from < file_length {
Some((from, cmp::min(to, file_length - 1)))
} else {
None
}
},
(AllFrom(from), Some(file_length)) => {
if from < file_length {
Some((from, file_length - 1))
} else {
None
}
},
(Last(last), Some(file_length)) => {
if last < file_length {
Some((file_length - last, file_length - 1))
} else {
Some((0, file_length - 1))
}
},
(_, None) => None,
};
if let Some(range) = range | else {
if let Some(file_length) = file_length {
response.set_header(ContentRange(ContentRangeSpec::Bytes {
range: None,
instance_length: Some(file_length),
}));
};
response.set_status(Status::RangeNotSatisfiable);
};
}
}
impl Responder<'static> for PartialFile {
fn respond_to(self, req: &Request) -> Result<Response<'static>, Status> {
let mut response = Response::new();
response.set_header(AcceptRanges(vec![RangeUnit::Bytes]));
match req.headers().get_one("range") {
Some (range) => {
match Range::from_str(range) {
Ok(Range::Bytes(ref v)) => {
self.get_partial(&mut response, v.clone());
response.set_status(Status::PartialContent);
},
_ => {
response.set_status(Status::RangeNotSatisfiable);
},
}
},
None => {
response.set_streamed_body(BufReader::new(self.file));
},
}
Ok(response)
}
}
pub fn serve_partial(video_path: &Path) -> io::Result<PartialFile> {
PartialFile::open(video_path)
}
| {
let content_range = ContentRange(ContentRangeSpec::Bytes {
range: Some(range),
instance_length: file_length,
});
let content_len = range.1 - range.0 + 1;
response.set_header(ContentLength(content_len));
response.set_header(content_range);
let mut partial_content = BufReader::new(self.file);
let _ = partial_content.seek(SeekFrom::Start(range.0));
let result = partial_content.take(content_len);
response.set_status(Status::PartialContent);
response.set_streamed_body(result);
} | conditional_block |
partial_file.rs | // Copyright (c) 2017 Simon Dickson
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::cmp;
use std::fs::File;
use std::io::{self, BufReader, SeekFrom, Seek, Read};
use std::str::FromStr;
use std::path::{Path, PathBuf};
use rocket::request::Request;
use rocket::response::{Response, Responder};
use rocket::http::Status;
use rocket::http::hyper::header::{ByteRangeSpec, ContentRangeSpec, AcceptRanges, RangeUnit, Range, ContentRange, ContentLength};
#[derive(Debug)]
pub enum PartialFileRange {
AllFrom(u64),
FromTo(u64,u64),
Last(u64),
}
impl From<ByteRangeSpec> for PartialFileRange {
fn from(b: ByteRangeSpec) -> PartialFileRange {
match b {
ByteRangeSpec::AllFrom(from) => PartialFileRange::AllFrom(from),
ByteRangeSpec::FromTo(from, to) => PartialFileRange::FromTo(from, to),
ByteRangeSpec::Last(last) => PartialFileRange::Last(last),
}
}
}
impl From<Vec<ByteRangeSpec>> for PartialFileRange {
fn from(v: Vec<ByteRangeSpec>) -> PartialFileRange {
match v.into_iter().next() {
None => PartialFileRange::AllFrom(0),
Some(byte_range) => PartialFileRange::from(byte_range),
}
}
}
#[derive(Debug)]
pub struct PartialFile {
path: PathBuf,
file: File
}
impl PartialFile {
pub fn open<P: AsRef<Path>>(path: P) -> io::Result<PartialFile> {
let file = File::open(path.as_ref())?;
Ok(PartialFile{ path: path.as_ref().to_path_buf(), file: file })
}
pub fn get_partial<Range>(self, response: &mut Response, range: Range)
where Range: Into<PartialFileRange> |
}
impl Responder<'static> for PartialFile {
fn respond_to(self, req: &Request) -> Result<Response<'static>, Status> {
let mut response = Response::new();
response.set_header(AcceptRanges(vec![RangeUnit::Bytes]));
match req.headers().get_one("range") {
Some (range) => {
match Range::from_str(range) {
Ok(Range::Bytes(ref v)) => {
self.get_partial(&mut response, v.clone());
response.set_status(Status::PartialContent);
},
_ => {
response.set_status(Status::RangeNotSatisfiable);
},
}
},
None => {
response.set_streamed_body(BufReader::new(self.file));
},
}
Ok(response)
}
}
pub fn serve_partial(video_path: &Path) -> io::Result<PartialFile> {
PartialFile::open(video_path)
}
| {
use self::PartialFileRange::*;
let metadata : Option<_> = self.file.metadata().ok();
let file_length : Option<u64> = metadata.map(|m| m.len());
let range : Option<(u64, u64)> = match (range.into(), file_length) {
(FromTo(from, to), Some(file_length)) => {
if from <= to && from < file_length {
Some((from, cmp::min(to, file_length - 1)))
} else {
None
}
},
(AllFrom(from), Some(file_length)) => {
if from < file_length {
Some((from, file_length - 1))
} else {
None
}
},
(Last(last), Some(file_length)) => {
if last < file_length {
Some((file_length - last, file_length - 1))
} else {
Some((0, file_length - 1))
}
},
(_, None) => None,
};
if let Some(range) = range {
let content_range = ContentRange(ContentRangeSpec::Bytes {
range: Some(range),
instance_length: file_length,
});
let content_len = range.1 - range.0 + 1;
response.set_header(ContentLength(content_len));
response.set_header(content_range);
let mut partial_content = BufReader::new(self.file);
let _ = partial_content.seek(SeekFrom::Start(range.0));
let result = partial_content.take(content_len);
response.set_status(Status::PartialContent);
response.set_streamed_body(result);
} else {
if let Some(file_length) = file_length {
response.set_header(ContentRange(ContentRangeSpec::Bytes {
range: None,
instance_length: Some(file_length),
}));
};
response.set_status(Status::RangeNotSatisfiable);
};
} | identifier_body |
partial_file.rs | // Copyright (c) 2017 Simon Dickson
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::cmp;
use std::fs::File;
use std::io::{self, BufReader, SeekFrom, Seek, Read};
use std::str::FromStr;
use std::path::{Path, PathBuf};
use rocket::request::Request;
use rocket::response::{Response, Responder};
use rocket::http::Status;
use rocket::http::hyper::header::{ByteRangeSpec, ContentRangeSpec, AcceptRanges, RangeUnit, Range, ContentRange, ContentLength};
#[derive(Debug)]
pub enum PartialFileRange {
AllFrom(u64),
FromTo(u64,u64),
Last(u64),
}
impl From<ByteRangeSpec> for PartialFileRange {
fn from(b: ByteRangeSpec) -> PartialFileRange {
match b {
ByteRangeSpec::AllFrom(from) => PartialFileRange::AllFrom(from),
ByteRangeSpec::FromTo(from, to) => PartialFileRange::FromTo(from, to),
ByteRangeSpec::Last(last) => PartialFileRange::Last(last),
}
}
}
impl From<Vec<ByteRangeSpec>> for PartialFileRange {
fn from(v: Vec<ByteRangeSpec>) -> PartialFileRange {
match v.into_iter().next() {
None => PartialFileRange::AllFrom(0),
Some(byte_range) => PartialFileRange::from(byte_range),
}
}
}
#[derive(Debug)]
pub struct PartialFile {
path: PathBuf,
file: File
}
impl PartialFile {
pub fn open<P: AsRef<Path>>(path: P) -> io::Result<PartialFile> {
let file = File::open(path.as_ref())?;
Ok(PartialFile{ path: path.as_ref().to_path_buf(), file: file })
}
pub fn get_partial<Range>(self, response: &mut Response, range: Range)
where Range: Into<PartialFileRange> {
use self::PartialFileRange::*;
let metadata : Option<_> = self.file.metadata().ok();
let file_length : Option<u64> = metadata.map(|m| m.len());
let range : Option<(u64, u64)> = match (range.into(), file_length) {
(FromTo(from, to), Some(file_length)) => {
if from <= to && from < file_length {
Some((from, cmp::min(to, file_length - 1)))
} else {
None
}
},
(AllFrom(from), Some(file_length)) => {
if from < file_length {
Some((from, file_length - 1))
} else {
None
}
},
(Last(last), Some(file_length)) => {
if last < file_length {
Some((file_length - last, file_length - 1))
} else {
Some((0, file_length - 1))
}
},
(_, None) => None,
};
if let Some(range) = range {
let content_range = ContentRange(ContentRangeSpec::Bytes {
range: Some(range),
instance_length: file_length,
});
let content_len = range.1 - range.0 + 1;
response.set_header(ContentLength(content_len));
response.set_header(content_range);
let mut partial_content = BufReader::new(self.file);
let _ = partial_content.seek(SeekFrom::Start(range.0));
let result = partial_content.take(content_len);
response.set_status(Status::PartialContent);
response.set_streamed_body(result);
} else {
if let Some(file_length) = file_length {
response.set_header(ContentRange(ContentRangeSpec::Bytes {
range: None,
instance_length: Some(file_length),
}));
};
response.set_status(Status::RangeNotSatisfiable);
};
}
}
impl Responder<'static> for PartialFile {
fn respond_to(self, req: &Request) -> Result<Response<'static>, Status> {
let mut response = Response::new();
response.set_header(AcceptRanges(vec![RangeUnit::Bytes]));
match req.headers().get_one("range") {
Some (range) => {
match Range::from_str(range) {
Ok(Range::Bytes(ref v)) => {
self.get_partial(&mut response, v.clone());
response.set_status(Status::PartialContent);
},
_ => {
response.set_status(Status::RangeNotSatisfiable);
},
}
},
None => {
response.set_streamed_body(BufReader::new(self.file));
},
}
Ok(response)
}
}
pub fn | (video_path: &Path) -> io::Result<PartialFile> {
PartialFile::open(video_path)
}
| serve_partial | identifier_name |
randsone_ldif.py | # -*- coding: utf-8 -*-
#
# Copyright 2017-2020 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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.
#
# Cerebrum 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 Cerebrum; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Mixin for contrib/no/uio/generate_randsone_ldif.py."""
from Cerebrum.modules.no.OrgLDIF import norEduLDIFMixin
class RandsoneOrgLdif(norEduLDIFMixin): # noqa: N801
def init_ou_structure(self):
# Change from original: Drop OUs outside self.root_ou_id subtree.
super(RandsoneOrgLdif, self).init_ou_structure()
ous, tree = [self.root_ou_id], self.ou_tree
for ou in ous:
|
self.ou_tree = dict((ou, tree[ou]) for ou in ous if ou in tree)
def init_attr2id2contacts(self):
self.attr2id2contacts = {}
self.id2labeledURI = {}
def init_person_titles(self):
self.person_titles = {}
def init_person_addresses(self):
self.addr_info = {}
| ous.extend(tree.get(ou, ())) | conditional_block |
randsone_ldif.py | # -*- coding: utf-8 -*-
#
# Copyright 2017-2020 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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.
#
# Cerebrum 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 Cerebrum; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Mixin for contrib/no/uio/generate_randsone_ldif.py."""
from Cerebrum.modules.no.OrgLDIF import norEduLDIFMixin
class RandsoneOrgLdif(norEduLDIFMixin): # noqa: N801
| def init_ou_structure(self):
# Change from original: Drop OUs outside self.root_ou_id subtree.
super(RandsoneOrgLdif, self).init_ou_structure()
ous, tree = [self.root_ou_id], self.ou_tree
for ou in ous:
ous.extend(tree.get(ou, ()))
self.ou_tree = dict((ou, tree[ou]) for ou in ous if ou in tree)
def init_attr2id2contacts(self):
self.attr2id2contacts = {}
self.id2labeledURI = {}
def init_person_titles(self):
self.person_titles = {}
def init_person_addresses(self):
self.addr_info = {} | identifier_body | |
randsone_ldif.py | # -*- coding: utf-8 -*-
#
# Copyright 2017-2020 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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.
#
# Cerebrum 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 Cerebrum; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Mixin for contrib/no/uio/generate_randsone_ldif.py."""
from Cerebrum.modules.no.OrgLDIF import norEduLDIFMixin
class RandsoneOrgLdif(norEduLDIFMixin): # noqa: N801
def init_ou_structure(self):
# Change from original: Drop OUs outside self.root_ou_id subtree.
super(RandsoneOrgLdif, self).init_ou_structure()
ous, tree = [self.root_ou_id], self.ou_tree
for ou in ous:
ous.extend(tree.get(ou, ()))
self.ou_tree = dict((ou, tree[ou]) for ou in ous if ou in tree)
def init_attr2id2contacts(self):
self.attr2id2contacts = {} |
def init_person_addresses(self):
self.addr_info = {} | self.id2labeledURI = {}
def init_person_titles(self):
self.person_titles = {} | random_line_split |
randsone_ldif.py | # -*- coding: utf-8 -*-
#
# Copyright 2017-2020 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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.
#
# Cerebrum 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 Cerebrum; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Mixin for contrib/no/uio/generate_randsone_ldif.py."""
from Cerebrum.modules.no.OrgLDIF import norEduLDIFMixin
class RandsoneOrgLdif(norEduLDIFMixin): # noqa: N801
def | (self):
# Change from original: Drop OUs outside self.root_ou_id subtree.
super(RandsoneOrgLdif, self).init_ou_structure()
ous, tree = [self.root_ou_id], self.ou_tree
for ou in ous:
ous.extend(tree.get(ou, ()))
self.ou_tree = dict((ou, tree[ou]) for ou in ous if ou in tree)
def init_attr2id2contacts(self):
self.attr2id2contacts = {}
self.id2labeledURI = {}
def init_person_titles(self):
self.person_titles = {}
def init_person_addresses(self):
self.addr_info = {}
| init_ou_structure | identifier_name |
drawback.component.ts | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router";
import { LiveService } from "../../live/service/live.service";
import { OrderService } from "../../order/service/order.service";
declare var $: any;
declare var layer: any;
@Component({
selector: 'app-drawback',
templateUrl: './drawback.component.html',
styleUrls: ['./drawback.component.scss'],
providers: [
LiveService,
OrderService
]
})
export class DrawbackComponent implements OnInit {
public routerParams; // 路由參數
public good; // 退款商品信息
public select = true; //默認選擇圖標
public type = 1; // 默認只退款
public step = 1; // 步驟
public step_small = 1; // 下一步 步驟
public returnDesc; // 退款類型
public radioModel = 0; // 單選
public money;
public file1;
public file2;
public file3;
public returnDetail;
constructor(
public router: Router,
public activatedRoute: ActivatedRoute,
public liveService: LiveService,
public orderService: OrderService,
) { }
ngOnInit() {
this.activatedRoute.queryParams.subscribe(
data => {
this.routerParams = data;
this.good = JSON.parse(data.goods);
this.money = this.good.goods_price;
console.log(this.good);
let stats = this.good.refund_status;
if (stats == "1") {
this.step = 2;
} else if (stats != 0 && stats != 7 && stats != 6) {
this.step = 3;
} else if (stats == 0 || stats == 6) {
this.step = 1;
}
}, error => console.log(error)
)
this.getRefundDetail(this.routerParams.order_id, this.good.goods_id); | this.select = true;
this.type = 1;
} else {
this.select = false;
this.type = 2;
}
}
next() {
this.step_small = 2;
if (this.type == 1) {
this.returnDesc = '僅退款';
} else {
this.returnDesc = '退貨退款';
}
}
getRefundDetail(order_id, goods_id) {
this.orderService.getRefundDetail(this.routerParams.order_id, this.good.goods_id)
.subscribe(
data => {
// console.log(data);
this.returnDetail = data.d;
}, error => console.log(error)
);
}
radio(num) {
this.radioModel = num;
}
coverChange1(file, event) {
this.liveService.imgUpload(file[0])
.subscribe(
data => {
// console.log(data); console.log(event);
this.file1 = data[0].url;
console.log(this.file1);
event.target.files[0] = "";
}, error => console.log(error)
)
}
coverChange2(file, event) {
this.liveService.imgUpload(file[0])
.subscribe(
data => {
// console.log(data); console.log(event);
this.file2 = data[0].url;
console.log(this.file2);
event.target.files[0] = "";
}, error => console.log(error)
)
}
coverChange3(file, event) {
this.liveService.imgUpload(file[0])
.subscribe(
data => {
// console.log(data); console.log(event);
this.file3 = data[0].url;
console.log(this.file3);
event.target.files[0] = "";
}, error => console.log(error)
)
}
submitReturn() {
let type = this.type;
let good_status = this.radioModel;
let order_id = this.routerParams.order_id;
let goods_id = this.good.goods_id;
let reason = $(".reason").val();
let amount = this.money;
let remark = $('.remark').val();
var evidence = [];
var str;
$(".uploadImg li img").each(function (i, e) {
let src = $(e).attr("src");
if (src != "/assets/img/comment_addimg.png") {
evidence.push(src);
}
});
str = evidence.join(',');
if (reason == '') {
layer.msg('退款原因必須填寫');
return;
} else if (reason.trim().length < 6) {
layer.msg('退款原因字數必須大與六位');
return;
}
// console.log(type, good_status, order_id, goods_id, reason, amount, remark, str);
this.orderService.createRefundOrder(type, good_status, order_id, goods_id, reason, amount, remark, str)
.subscribe(
data => {
console.log(data);
if (data.c == 1) {
layer.msg("提交退款申請成功");
this.step = 2;
this.getRefundDetail(this.routerParams.order_id, this.good.goods_id);
} else {
layer.msg(data.m);
}
}, error => console.log(error)
);
}
revoked(order_id, goods_id) {
let that = this;
layer.confirm('確認撤銷?', {
btn: ['確定', '取消'] //按钮
}, function () {
that.orderService.delRefund(order_id, goods_id)
.subscribe(
data => {
if (data.c == 1) {
layer.msg("撤銷申請成功");
setTimeout(function () {
that.router.navigate(["/order/orders/all"]);
}, 2000);
} else {
layer.msg(data.m);
}
}, error => console.log(error)
);
layer.closeAll();
}, function () {
});
}
} | }
selectReturn(types) {
if (types == 1) { | random_line_split |
drawback.component.ts | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router";
import { LiveService } from "../../live/service/live.service";
import { OrderService } from "../../order/service/order.service";
declare var $: any;
declare var layer: any;
@Component({
selector: 'app-drawback',
templateUrl: './drawback.component.html',
styleUrls: ['./drawback.component.scss'],
providers: [
LiveService,
OrderService
]
})
export class DrawbackComponent implements OnInit {
public routerParams; // 路由參數
public good; // 退款商品信息
public select = true; //默認選擇圖標
public type = 1; // 默認只退款
public step = 1; // 步驟
public step_small = 1; // 下一步 步驟
public returnDesc; // 退款類型
public radioModel = 0; // 單選
public money;
public file1;
public file2;
public file3;
public returnDetail;
constructor(
public router: Router,
public activatedRoute: ActivatedRoute,
public liveService: LiveService,
public orderService: OrderService,
) { }
ngOnInit() {
this.activatedRoute.queryParams.subscribe(
data => {
this.routerParams = data;
this.good = JSON.parse(data.goods);
this.money = this.good.goods_price;
console.log(this.good);
let stats = this.good.refund_status;
if (stats == "1") {
this.step = 2;
} else if (stats != 0 && stats != 7 && stats != 6) {
this.step = 3;
} else if (stats == 0 || stats == 6) {
this.step = 1;
}
}, error => console.log(error)
)
this.getRefundDetail(this.routerParams.order_id, this.good.goods_id);
}
selectReturn(types) {
if (types == 1) {
this.select = true;
this.type = | this.returnDesc = '僅退款';
} else {
this.returnDesc = '退貨退款';
}
}
getRefundDetail(order_id, goods_id) {
this.orderService.getRefundDetail(this.routerParams.order_id, this.good.goods_id)
.subscribe(
data => {
// console.log(data);
this.returnDetail = data.d;
}, error => console.log(error)
);
}
radio(num) {
this.radioModel = num;
}
coverChange1(file, event) {
this.liveService.imgUpload(file[0])
.subscribe(
data => {
// console.log(data); console.log(event);
this.file1 = data[0].url;
console.log(this.file1);
event.target.files[0] = "";
}, error => console.log(error)
)
}
coverChange2(file, event) {
this.liveService.imgUpload(file[0])
.subscribe(
data => {
// console.log(data); console.log(event);
this.file2 = data[0].url;
console.log(this.file2);
event.target.files[0] = "";
}, error => console.log(error)
)
}
coverChange3(file, event) {
this.liveService.imgUpload(file[0])
.subscribe(
data => {
// console.log(data); console.log(event);
this.file3 = data[0].url;
console.log(this.file3);
event.target.files[0] = "";
}, error => console.log(error)
)
}
submitReturn() {
let type = this.type;
let good_status = this.radioModel;
let order_id = this.routerParams.order_id;
let goods_id = this.good.goods_id;
let reason = $(".reason").val();
let amount = this.money;
let remark = $('.remark').val();
var evidence = [];
var str;
$(".uploadImg li img").each(function (i, e) {
let src = $(e).attr("src");
if (src != "/assets/img/comment_addimg.png") {
evidence.push(src);
}
});
str = evidence.join(',');
if (reason == '') {
layer.msg('退款原因必須填寫');
return;
} else if (reason.trim().length < 6) {
layer.msg('退款原因字數必須大與六位');
return;
}
// console.log(type, good_status, order_id, goods_id, reason, amount, remark, str);
this.orderService.createRefundOrder(type, good_status, order_id, goods_id, reason, amount, remark, str)
.subscribe(
data => {
console.log(data);
if (data.c == 1) {
layer.msg("提交退款申請成功");
this.step = 2;
this.getRefundDetail(this.routerParams.order_id, this.good.goods_id);
} else {
layer.msg(data.m);
}
}, error => console.log(error)
);
}
revoked(order_id, goods_id) {
let that = this;
layer.confirm('確認撤銷?', {
btn: ['確定', '取消'] //按钮
}, function () {
that.orderService.delRefund(order_id, goods_id)
.subscribe(
data => {
if (data.c == 1) {
layer.msg("撤銷申請成功");
setTimeout(function () {
that.router.navigate(["/order/orders/all"]);
}, 2000);
} else {
layer.msg(data.m);
}
}, error => console.log(error)
);
layer.closeAll();
}, function () {
});
}
}
| 1;
} else {
this.select = false;
this.type = 2;
}
}
next() {
this.step_small = 2;
if (this.type == 1) {
| identifier_body |
drawback.component.ts | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router";
import { LiveService } from "../../live/service/live.service";
import { OrderService } from "../../order/service/order.service";
declare var $: any;
declare var layer: any;
@Component({
selector: 'app-drawback',
templateUrl: './drawback.component.html',
styleUrls: ['./drawback.component.scss'],
providers: [
LiveService,
OrderService
]
})
export class DrawbackComponent implements OnInit {
public routerParams; // 路由參數
public good; // 退款商品信息
public select = true; //默認選擇圖標
public type = 1; // 默認只退款
public step = 1; // 步驟
public step_small = 1; // 下一步 步驟
public returnDesc; // 退款類型
public radioModel = 0; // 單選
public money;
public file1;
public file2;
public file3;
public returnDetail;
constructor(
public router: Router,
public activatedRoute: ActivatedRoute,
public liveService: LiveService,
public orderService: OrderService,
) { }
ngOnInit() {
this.activatedRoute.queryParams.subscribe(
data => {
this.routerParams = data;
this.good = JSON.parse(data.goods);
this.money = this.good.goods_price;
console.log(this.good);
let stats = this.good.refund_status;
if (stats == "1") {
this.step = 2;
} else if (stats != 0 && stats != 7 && stats != 6) {
this.step = 3;
} else if (stats == 0 || stats == 6) {
this.step = 1;
}
}, error => console.log(error)
)
this.getRefundDetail(this.routerParams.order_id, this.good.goods_id);
}
selectReturn(types) {
if (types == 1) {
this.select = true;
this.type = 1;
} else {
| next() {
this.step_small = 2;
if (this.type == 1) {
this.returnDesc = '僅退款';
} else {
this.returnDesc = '退貨退款';
}
}
getRefundDetail(order_id, goods_id) {
this.orderService.getRefundDetail(this.routerParams.order_id, this.good.goods_id)
.subscribe(
data => {
// console.log(data);
this.returnDetail = data.d;
}, error => console.log(error)
);
}
radio(num) {
this.radioModel = num;
}
coverChange1(file, event) {
this.liveService.imgUpload(file[0])
.subscribe(
data => {
// console.log(data); console.log(event);
this.file1 = data[0].url;
console.log(this.file1);
event.target.files[0] = "";
}, error => console.log(error)
)
}
coverChange2(file, event) {
this.liveService.imgUpload(file[0])
.subscribe(
data => {
// console.log(data); console.log(event);
this.file2 = data[0].url;
console.log(this.file2);
event.target.files[0] = "";
}, error => console.log(error)
)
}
coverChange3(file, event) {
this.liveService.imgUpload(file[0])
.subscribe(
data => {
// console.log(data); console.log(event);
this.file3 = data[0].url;
console.log(this.file3);
event.target.files[0] = "";
}, error => console.log(error)
)
}
submitReturn() {
let type = this.type;
let good_status = this.radioModel;
let order_id = this.routerParams.order_id;
let goods_id = this.good.goods_id;
let reason = $(".reason").val();
let amount = this.money;
let remark = $('.remark').val();
var evidence = [];
var str;
$(".uploadImg li img").each(function (i, e) {
let src = $(e).attr("src");
if (src != "/assets/img/comment_addimg.png") {
evidence.push(src);
}
});
str = evidence.join(',');
if (reason == '') {
layer.msg('退款原因必須填寫');
return;
} else if (reason.trim().length < 6) {
layer.msg('退款原因字數必須大與六位');
return;
}
// console.log(type, good_status, order_id, goods_id, reason, amount, remark, str);
this.orderService.createRefundOrder(type, good_status, order_id, goods_id, reason, amount, remark, str)
.subscribe(
data => {
console.log(data);
if (data.c == 1) {
layer.msg("提交退款申請成功");
this.step = 2;
this.getRefundDetail(this.routerParams.order_id, this.good.goods_id);
} else {
layer.msg(data.m);
}
}, error => console.log(error)
);
}
revoked(order_id, goods_id) {
let that = this;
layer.confirm('確認撤銷?', {
btn: ['確定', '取消'] //按钮
}, function () {
that.orderService.delRefund(order_id, goods_id)
.subscribe(
data => {
if (data.c == 1) {
layer.msg("撤銷申請成功");
setTimeout(function () {
that.router.navigate(["/order/orders/all"]);
}, 2000);
} else {
layer.msg(data.m);
}
}, error => console.log(error)
);
layer.closeAll();
}, function () {
});
}
}
| this.select = false;
this.type = 2;
}
}
| conditional_block |
drawback.component.ts | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router";
import { LiveService } from "../../live/service/live.service";
import { OrderService } from "../../order/service/order.service";
declare var $: any;
declare var layer: any;
@Component({
selector: 'app-drawback',
templateUrl: './drawback.component.html',
styleUrls: ['./drawback.component.scss'],
providers: [
LiveService,
OrderService
]
})
export class DrawbackComponent implements OnInit {
public routerParams; // 路由參數
public good; // 退款商品信息
public select = true; //默認選擇圖標
public type = 1; // 默認只退款
public step = 1; // 步驟
public step_small = 1; // 下一步 步驟
public returnDesc; // 退款類型
public radioModel = 0; // 單選
public money;
public file1;
public file2;
public file3;
public returnDetail;
constructor(
public router: Router,
public activatedRoute: ActivatedRoute,
public liveService: LiveService,
public orderService: OrderService,
) { }
ngOnInit() {
this.activatedRoute.queryParams.subscribe(
data => {
this.routerParams = data;
this.good = JSON.parse(data.goods);
this.money = this.good.goods_price;
console.log(this.good);
let stats = this.good.refund_status;
if (stats == "1") {
this.step = 2;
} else if (stats != 0 && stats != 7 && stats != 6) {
this.step = 3;
} else if (stats == 0 || stats == 6) {
this.step = 1;
}
}, error => console.log(error)
)
this.getRefundDetail(this.routerParams.order_id, this.good.goods_id);
}
selectReturn(types) {
if (types == 1) {
this.select = true;
this.type = 1;
} else {
this.select = false;
this.type = 2;
}
}
next() {
this.step_small = 2;
if (this.type == 1) {
this.returnDesc = '僅退款';
} else {
this.returnDesc = '退貨退款';
}
}
getRefundDetail(order_id, goods_id) {
this.orderService.getRefundDetail(this.routerParams.order_id, this.good.goods_id)
.subscribe(
data => {
// console.log(data);
this.returnDetail = data.d;
}, error => console.log(error)
);
}
radio(num) {
this.radioModel = num;
}
coverChange1(file, event) {
this.liveService.imgUpload(file[0])
.subscribe(
data => {
// console.log(data); console.log(event);
this.file1 = data[0].url;
console.log(this.file1);
event.target.files[0] = "";
}, error => console.log(error)
)
}
coverChange2(file, event) {
this.liveService.imgUpload(file[0])
.subscribe(
data => {
// console.log(data); console.log(event);
this.file2 = data[0].url;
console.log(this.file2);
event.target.files[0] = "";
}, error => console.log(error)
)
}
coverChange3(file, event) {
this.liveService.imgUpload(file[0])
.subscribe(
data => {
// console.log(data); console.log(event);
this.file3 = data[0].url;
console.log(this.file3);
event.target.files[0] = "";
}, error => console.log(error)
)
}
submitReturn() {
let type = this.type;
let good_status = this.radioModel;
let order_id = this.routerParams.order_id;
let goods_id = this.good.goods_id;
let reason = $(".reason").val();
let amount = this.money;
let remark = $('.remark').val();
var evidence = [];
var str;
$(".uploadImg li img").each(function (i, e) {
let src = $(e).attr("src");
if (src != "/assets/img/comment_addimg.png") {
evidence.push(src);
}
});
str = evidence.join(',');
if (reason == '') {
layer.msg('退款原因必須填寫');
return;
} else if (reason.trim().length < 6) {
layer.msg('退款原因字數必須大與六位');
return;
}
// console.log(type, good_status, order_id, goods_id, reason, amount, remark, str);
this.orderService.createRefundOrder(type, good_status, order_id, goods_id, reason, amount, remark, str)
.subscribe(
data => {
console.log(data);
if (data.c == 1) {
layer.msg("提交退款申請成功");
this.step = 2;
this.getRefundDetail(this.routerParams.order_id, this.good.goods_id);
} else {
layer.msg(data.m);
}
}, error => console.log(error)
);
}
revoked(order_id, goods_id) {
let that = this;
layer.confirm('確認撤銷?', {
btn: ['確定', '取消'] //按钮
}, function () {
th | rService.delRefund(order_id, goods_id)
.subscribe(
data => {
if (data.c == 1) {
layer.msg("撤銷申請成功");
setTimeout(function () {
that.router.navigate(["/order/orders/all"]);
}, 2000);
} else {
layer.msg(data.m);
}
}, error => console.log(error)
);
layer.closeAll();
}, function () {
});
}
}
| at.orde | identifier_name |
test_fftlog.py | import warnings
import numpy as np
from numpy.testing import assert_allclose
import pytest
from scipy.fft._fftlog import fht, ifht, fhtoffset
from scipy.special import poch
def test_fht_agrees_with_fftlog():
# check that fht numerically agrees with the output from Fortran FFTLog,
# the results were generated with the provided `fftlogtest` program,
# after fixing how the k array is generated (divide range by n-1, not n)
# test function, analytical Hankel transform is of the same form
def f(r, mu):
return r**(mu+1)*np.exp(-r**2/2)
r = np.logspace(-4, 4, 16)
dln = np.log(r[1]/r[0])
mu = 0.3
offset = 0.0
bias = 0.0
a = f(r, mu)
# test 1: compute as given
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [-0.1159922613593045E-02, +0.1625822618458832E-02,
-0.1949518286432330E-02, +0.3789220182554077E-02,
+0.5093959119952945E-03, +0.2785387803618774E-01,
+0.9944952700848897E-01, +0.4599202164586588E+00,
+0.3157462160881342E+00, -0.8201236844404755E-03,
-0.7834031308271878E-03, +0.3931444945110708E-03,
-0.2697710625194777E-03, +0.3568398050238820E-03,
-0.5554454827797206E-03, +0.8286331026468585E-03]
assert_allclose(ours, theirs)
# test 2: change to optimal offset
offset = fhtoffset(dln, mu, bias=bias)
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [+0.4353768523152057E-04, -0.9197045663594285E-05,
+0.3150140927838524E-03, +0.9149121960963704E-03,
+0.5808089753959363E-02, +0.2548065256377240E-01,
+0.1339477692089897E+00, +0.4821530509479356E+00,
+0.2659899781579785E+00, -0.1116475278448113E-01,
+0.1791441617592385E-02, -0.4181810476548056E-03,
+0.1314963536765343E-03, -0.5422057743066297E-04,
+0.3208681804170443E-04, -0.2696849476008234E-04]
assert_allclose(ours, theirs)
# test 3: positive bias
bias = 0.8
offset = fhtoffset(dln, mu, bias=bias)
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [-7.3436673558316850E+00, +0.1710271207817100E+00,
+0.1065374386206564E+00, -0.5121739602708132E-01,
+0.2636649319269470E-01, +0.1697209218849693E-01,
+0.1250215614723183E+00, +0.4739583261486729E+00,
+0.2841149874912028E+00, -0.8312764741645729E-02,
+0.1024233505508988E-02, -0.1644902767389120E-03,
+0.3305775476926270E-04, -0.7786993194882709E-05,
+0.1962258449520547E-05, -0.8977895734909250E-06]
assert_allclose(ours, theirs)
# test 4: negative bias
bias = -0.8
offset = fhtoffset(dln, mu, bias=bias)
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [+0.8985777068568745E-05, +0.4074898209936099E-04,
+0.2123969254700955E-03, +0.1009558244834628E-02,
+0.5131386375222176E-02, +0.2461678673516286E-01,
+0.1235812845384476E+00, +0.4719570096404403E+00,
+0.2893487490631317E+00, -0.1686570611318716E-01,
+0.2231398155172505E-01, -0.1480742256379873E-01,
+0.1692387813500801E+00, +0.3097490354365797E+00,
+2.7593607182401860E+00, 10.5251075070045800E+00]
assert_allclose(ours, theirs)
@pytest.mark.parametrize('optimal', [True, False])
@pytest.mark.parametrize('offset', [0.0, 1.0, -1.0])
@pytest.mark.parametrize('bias', [0, 0.1, -0.1])
@pytest.mark.parametrize('n', [64, 63])
def test_fht_identity(n, bias, offset, optimal):
rng = np.random.RandomState(3491349965)
a = rng.standard_normal(n)
dln = rng.uniform(-1, 1)
mu = rng.uniform(-2, 2)
if optimal:
offset = fhtoffset(dln, mu, initial=offset, bias=bias)
A = fht(a, dln, mu, offset=offset, bias=bias)
a_ = ifht(A, dln, mu, offset=offset, bias=bias)
assert_allclose(a, a_)
def test_fht_special_cases():
rng = np.random.RandomState(3491349965)
a = rng.standard_normal(64)
dln = rng.uniform(-1, 1)
# let xp = (mu+1+q)/2, xm = (mu+1-q)/2, M = {0, -1, -2, ...}
# case 1: xp in M, xm in M => well-defined transform
mu, bias = -4.0, 1.0
with warnings.catch_warnings(record=True) as record:
fht(a, dln, mu, bias=bias)
assert not record, 'fht warned about a well-defined transform'
# case 2: xp not in M, xm in M => well-defined transform
mu, bias = -2.5, 0.5
with warnings.catch_warnings(record=True) as record:
fht(a, dln, mu, bias=bias)
assert not record, 'fht warned about a well-defined transform'
# case 3: xp in M, xm not in M => singular transform
mu, bias = -3.5, 0.5
with pytest.warns(Warning) as record:
fht(a, dln, mu, bias=bias)
assert record, 'fht did not warn about a singular transform'
# case 4: xp not in M, xm in M => singular inverse transform
mu, bias = -2.5, 0.5
with pytest.warns(Warning) as record:
ifht(a, dln, mu, bias=bias)
assert record, 'ifht did not warn about a singular transform'
@pytest.mark.parametrize('n', [64, 63])
def test_fht_exact(n):
rng = np.random.RandomState(3491349965)
# for a(r) a power law r^\gamma, the fast Hankel transform produces the
# exact continuous Hankel transform if biased with q = \gamma
mu = rng.uniform(0, 3)
# convergence of HT: -1-mu < gamma < 1/2
gamma = rng.uniform(-1-mu, 1/2)
r = np.logspace(-2, 2, n)
a = r**gamma
dln = np.log(r[1]/r[0])
offset = fhtoffset(dln, mu, initial=0.0, bias=gamma)
A = fht(a, dln, mu, offset=offset, bias=gamma)
|
# analytical result
At = (2/k)**gamma * poch((mu+1-gamma)/2, gamma)
assert_allclose(A, At) | k = np.exp(offset)/r[::-1] | random_line_split |
test_fftlog.py | import warnings
import numpy as np
from numpy.testing import assert_allclose
import pytest
from scipy.fft._fftlog import fht, ifht, fhtoffset
from scipy.special import poch
def test_fht_agrees_with_fftlog():
# check that fht numerically agrees with the output from Fortran FFTLog,
# the results were generated with the provided `fftlogtest` program,
# after fixing how the k array is generated (divide range by n-1, not n)
# test function, analytical Hankel transform is of the same form
def f(r, mu):
return r**(mu+1)*np.exp(-r**2/2)
r = np.logspace(-4, 4, 16)
dln = np.log(r[1]/r[0])
mu = 0.3
offset = 0.0
bias = 0.0
a = f(r, mu)
# test 1: compute as given
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [-0.1159922613593045E-02, +0.1625822618458832E-02,
-0.1949518286432330E-02, +0.3789220182554077E-02,
+0.5093959119952945E-03, +0.2785387803618774E-01,
+0.9944952700848897E-01, +0.4599202164586588E+00,
+0.3157462160881342E+00, -0.8201236844404755E-03,
-0.7834031308271878E-03, +0.3931444945110708E-03,
-0.2697710625194777E-03, +0.3568398050238820E-03,
-0.5554454827797206E-03, +0.8286331026468585E-03]
assert_allclose(ours, theirs)
# test 2: change to optimal offset
offset = fhtoffset(dln, mu, bias=bias)
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [+0.4353768523152057E-04, -0.9197045663594285E-05,
+0.3150140927838524E-03, +0.9149121960963704E-03,
+0.5808089753959363E-02, +0.2548065256377240E-01,
+0.1339477692089897E+00, +0.4821530509479356E+00,
+0.2659899781579785E+00, -0.1116475278448113E-01,
+0.1791441617592385E-02, -0.4181810476548056E-03,
+0.1314963536765343E-03, -0.5422057743066297E-04,
+0.3208681804170443E-04, -0.2696849476008234E-04]
assert_allclose(ours, theirs)
# test 3: positive bias
bias = 0.8
offset = fhtoffset(dln, mu, bias=bias)
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [-7.3436673558316850E+00, +0.1710271207817100E+00,
+0.1065374386206564E+00, -0.5121739602708132E-01,
+0.2636649319269470E-01, +0.1697209218849693E-01,
+0.1250215614723183E+00, +0.4739583261486729E+00,
+0.2841149874912028E+00, -0.8312764741645729E-02,
+0.1024233505508988E-02, -0.1644902767389120E-03,
+0.3305775476926270E-04, -0.7786993194882709E-05,
+0.1962258449520547E-05, -0.8977895734909250E-06]
assert_allclose(ours, theirs)
# test 4: negative bias
bias = -0.8
offset = fhtoffset(dln, mu, bias=bias)
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [+0.8985777068568745E-05, +0.4074898209936099E-04,
+0.2123969254700955E-03, +0.1009558244834628E-02,
+0.5131386375222176E-02, +0.2461678673516286E-01,
+0.1235812845384476E+00, +0.4719570096404403E+00,
+0.2893487490631317E+00, -0.1686570611318716E-01,
+0.2231398155172505E-01, -0.1480742256379873E-01,
+0.1692387813500801E+00, +0.3097490354365797E+00,
+2.7593607182401860E+00, 10.5251075070045800E+00]
assert_allclose(ours, theirs)
@pytest.mark.parametrize('optimal', [True, False])
@pytest.mark.parametrize('offset', [0.0, 1.0, -1.0])
@pytest.mark.parametrize('bias', [0, 0.1, -0.1])
@pytest.mark.parametrize('n', [64, 63])
def test_fht_identity(n, bias, offset, optimal):
rng = np.random.RandomState(3491349965)
a = rng.standard_normal(n)
dln = rng.uniform(-1, 1)
mu = rng.uniform(-2, 2)
if optimal:
|
A = fht(a, dln, mu, offset=offset, bias=bias)
a_ = ifht(A, dln, mu, offset=offset, bias=bias)
assert_allclose(a, a_)
def test_fht_special_cases():
rng = np.random.RandomState(3491349965)
a = rng.standard_normal(64)
dln = rng.uniform(-1, 1)
# let xp = (mu+1+q)/2, xm = (mu+1-q)/2, M = {0, -1, -2, ...}
# case 1: xp in M, xm in M => well-defined transform
mu, bias = -4.0, 1.0
with warnings.catch_warnings(record=True) as record:
fht(a, dln, mu, bias=bias)
assert not record, 'fht warned about a well-defined transform'
# case 2: xp not in M, xm in M => well-defined transform
mu, bias = -2.5, 0.5
with warnings.catch_warnings(record=True) as record:
fht(a, dln, mu, bias=bias)
assert not record, 'fht warned about a well-defined transform'
# case 3: xp in M, xm not in M => singular transform
mu, bias = -3.5, 0.5
with pytest.warns(Warning) as record:
fht(a, dln, mu, bias=bias)
assert record, 'fht did not warn about a singular transform'
# case 4: xp not in M, xm in M => singular inverse transform
mu, bias = -2.5, 0.5
with pytest.warns(Warning) as record:
ifht(a, dln, mu, bias=bias)
assert record, 'ifht did not warn about a singular transform'
@pytest.mark.parametrize('n', [64, 63])
def test_fht_exact(n):
rng = np.random.RandomState(3491349965)
# for a(r) a power law r^\gamma, the fast Hankel transform produces the
# exact continuous Hankel transform if biased with q = \gamma
mu = rng.uniform(0, 3)
# convergence of HT: -1-mu < gamma < 1/2
gamma = rng.uniform(-1-mu, 1/2)
r = np.logspace(-2, 2, n)
a = r**gamma
dln = np.log(r[1]/r[0])
offset = fhtoffset(dln, mu, initial=0.0, bias=gamma)
A = fht(a, dln, mu, offset=offset, bias=gamma)
k = np.exp(offset)/r[::-1]
# analytical result
At = (2/k)**gamma * poch((mu+1-gamma)/2, gamma)
assert_allclose(A, At)
| offset = fhtoffset(dln, mu, initial=offset, bias=bias) | conditional_block |
test_fftlog.py | import warnings
import numpy as np
from numpy.testing import assert_allclose
import pytest
from scipy.fft._fftlog import fht, ifht, fhtoffset
from scipy.special import poch
def test_fht_agrees_with_fftlog():
# check that fht numerically agrees with the output from Fortran FFTLog,
# the results were generated with the provided `fftlogtest` program,
# after fixing how the k array is generated (divide range by n-1, not n)
# test function, analytical Hankel transform is of the same form
def f(r, mu):
return r**(mu+1)*np.exp(-r**2/2)
r = np.logspace(-4, 4, 16)
dln = np.log(r[1]/r[0])
mu = 0.3
offset = 0.0
bias = 0.0
a = f(r, mu)
# test 1: compute as given
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [-0.1159922613593045E-02, +0.1625822618458832E-02,
-0.1949518286432330E-02, +0.3789220182554077E-02,
+0.5093959119952945E-03, +0.2785387803618774E-01,
+0.9944952700848897E-01, +0.4599202164586588E+00,
+0.3157462160881342E+00, -0.8201236844404755E-03,
-0.7834031308271878E-03, +0.3931444945110708E-03,
-0.2697710625194777E-03, +0.3568398050238820E-03,
-0.5554454827797206E-03, +0.8286331026468585E-03]
assert_allclose(ours, theirs)
# test 2: change to optimal offset
offset = fhtoffset(dln, mu, bias=bias)
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [+0.4353768523152057E-04, -0.9197045663594285E-05,
+0.3150140927838524E-03, +0.9149121960963704E-03,
+0.5808089753959363E-02, +0.2548065256377240E-01,
+0.1339477692089897E+00, +0.4821530509479356E+00,
+0.2659899781579785E+00, -0.1116475278448113E-01,
+0.1791441617592385E-02, -0.4181810476548056E-03,
+0.1314963536765343E-03, -0.5422057743066297E-04,
+0.3208681804170443E-04, -0.2696849476008234E-04]
assert_allclose(ours, theirs)
# test 3: positive bias
bias = 0.8
offset = fhtoffset(dln, mu, bias=bias)
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [-7.3436673558316850E+00, +0.1710271207817100E+00,
+0.1065374386206564E+00, -0.5121739602708132E-01,
+0.2636649319269470E-01, +0.1697209218849693E-01,
+0.1250215614723183E+00, +0.4739583261486729E+00,
+0.2841149874912028E+00, -0.8312764741645729E-02,
+0.1024233505508988E-02, -0.1644902767389120E-03,
+0.3305775476926270E-04, -0.7786993194882709E-05,
+0.1962258449520547E-05, -0.8977895734909250E-06]
assert_allclose(ours, theirs)
# test 4: negative bias
bias = -0.8
offset = fhtoffset(dln, mu, bias=bias)
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [+0.8985777068568745E-05, +0.4074898209936099E-04,
+0.2123969254700955E-03, +0.1009558244834628E-02,
+0.5131386375222176E-02, +0.2461678673516286E-01,
+0.1235812845384476E+00, +0.4719570096404403E+00,
+0.2893487490631317E+00, -0.1686570611318716E-01,
+0.2231398155172505E-01, -0.1480742256379873E-01,
+0.1692387813500801E+00, +0.3097490354365797E+00,
+2.7593607182401860E+00, 10.5251075070045800E+00]
assert_allclose(ours, theirs)
@pytest.mark.parametrize('optimal', [True, False])
@pytest.mark.parametrize('offset', [0.0, 1.0, -1.0])
@pytest.mark.parametrize('bias', [0, 0.1, -0.1])
@pytest.mark.parametrize('n', [64, 63])
def test_fht_identity(n, bias, offset, optimal):
rng = np.random.RandomState(3491349965)
a = rng.standard_normal(n)
dln = rng.uniform(-1, 1)
mu = rng.uniform(-2, 2)
if optimal:
offset = fhtoffset(dln, mu, initial=offset, bias=bias)
A = fht(a, dln, mu, offset=offset, bias=bias)
a_ = ifht(A, dln, mu, offset=offset, bias=bias)
assert_allclose(a, a_)
def test_fht_special_cases():
rng = np.random.RandomState(3491349965)
a = rng.standard_normal(64)
dln = rng.uniform(-1, 1)
# let xp = (mu+1+q)/2, xm = (mu+1-q)/2, M = {0, -1, -2, ...}
# case 1: xp in M, xm in M => well-defined transform
mu, bias = -4.0, 1.0
with warnings.catch_warnings(record=True) as record:
fht(a, dln, mu, bias=bias)
assert not record, 'fht warned about a well-defined transform'
# case 2: xp not in M, xm in M => well-defined transform
mu, bias = -2.5, 0.5
with warnings.catch_warnings(record=True) as record:
fht(a, dln, mu, bias=bias)
assert not record, 'fht warned about a well-defined transform'
# case 3: xp in M, xm not in M => singular transform
mu, bias = -3.5, 0.5
with pytest.warns(Warning) as record:
fht(a, dln, mu, bias=bias)
assert record, 'fht did not warn about a singular transform'
# case 4: xp not in M, xm in M => singular inverse transform
mu, bias = -2.5, 0.5
with pytest.warns(Warning) as record:
ifht(a, dln, mu, bias=bias)
assert record, 'ifht did not warn about a singular transform'
@pytest.mark.parametrize('n', [64, 63])
def | (n):
rng = np.random.RandomState(3491349965)
# for a(r) a power law r^\gamma, the fast Hankel transform produces the
# exact continuous Hankel transform if biased with q = \gamma
mu = rng.uniform(0, 3)
# convergence of HT: -1-mu < gamma < 1/2
gamma = rng.uniform(-1-mu, 1/2)
r = np.logspace(-2, 2, n)
a = r**gamma
dln = np.log(r[1]/r[0])
offset = fhtoffset(dln, mu, initial=0.0, bias=gamma)
A = fht(a, dln, mu, offset=offset, bias=gamma)
k = np.exp(offset)/r[::-1]
# analytical result
At = (2/k)**gamma * poch((mu+1-gamma)/2, gamma)
assert_allclose(A, At)
| test_fht_exact | identifier_name |
test_fftlog.py | import warnings
import numpy as np
from numpy.testing import assert_allclose
import pytest
from scipy.fft._fftlog import fht, ifht, fhtoffset
from scipy.special import poch
def test_fht_agrees_with_fftlog():
# check that fht numerically agrees with the output from Fortran FFTLog,
# the results were generated with the provided `fftlogtest` program,
# after fixing how the k array is generated (divide range by n-1, not n)
# test function, analytical Hankel transform is of the same form
def f(r, mu):
return r**(mu+1)*np.exp(-r**2/2)
r = np.logspace(-4, 4, 16)
dln = np.log(r[1]/r[0])
mu = 0.3
offset = 0.0
bias = 0.0
a = f(r, mu)
# test 1: compute as given
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [-0.1159922613593045E-02, +0.1625822618458832E-02,
-0.1949518286432330E-02, +0.3789220182554077E-02,
+0.5093959119952945E-03, +0.2785387803618774E-01,
+0.9944952700848897E-01, +0.4599202164586588E+00,
+0.3157462160881342E+00, -0.8201236844404755E-03,
-0.7834031308271878E-03, +0.3931444945110708E-03,
-0.2697710625194777E-03, +0.3568398050238820E-03,
-0.5554454827797206E-03, +0.8286331026468585E-03]
assert_allclose(ours, theirs)
# test 2: change to optimal offset
offset = fhtoffset(dln, mu, bias=bias)
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [+0.4353768523152057E-04, -0.9197045663594285E-05,
+0.3150140927838524E-03, +0.9149121960963704E-03,
+0.5808089753959363E-02, +0.2548065256377240E-01,
+0.1339477692089897E+00, +0.4821530509479356E+00,
+0.2659899781579785E+00, -0.1116475278448113E-01,
+0.1791441617592385E-02, -0.4181810476548056E-03,
+0.1314963536765343E-03, -0.5422057743066297E-04,
+0.3208681804170443E-04, -0.2696849476008234E-04]
assert_allclose(ours, theirs)
# test 3: positive bias
bias = 0.8
offset = fhtoffset(dln, mu, bias=bias)
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [-7.3436673558316850E+00, +0.1710271207817100E+00,
+0.1065374386206564E+00, -0.5121739602708132E-01,
+0.2636649319269470E-01, +0.1697209218849693E-01,
+0.1250215614723183E+00, +0.4739583261486729E+00,
+0.2841149874912028E+00, -0.8312764741645729E-02,
+0.1024233505508988E-02, -0.1644902767389120E-03,
+0.3305775476926270E-04, -0.7786993194882709E-05,
+0.1962258449520547E-05, -0.8977895734909250E-06]
assert_allclose(ours, theirs)
# test 4: negative bias
bias = -0.8
offset = fhtoffset(dln, mu, bias=bias)
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [+0.8985777068568745E-05, +0.4074898209936099E-04,
+0.2123969254700955E-03, +0.1009558244834628E-02,
+0.5131386375222176E-02, +0.2461678673516286E-01,
+0.1235812845384476E+00, +0.4719570096404403E+00,
+0.2893487490631317E+00, -0.1686570611318716E-01,
+0.2231398155172505E-01, -0.1480742256379873E-01,
+0.1692387813500801E+00, +0.3097490354365797E+00,
+2.7593607182401860E+00, 10.5251075070045800E+00]
assert_allclose(ours, theirs)
@pytest.mark.parametrize('optimal', [True, False])
@pytest.mark.parametrize('offset', [0.0, 1.0, -1.0])
@pytest.mark.parametrize('bias', [0, 0.1, -0.1])
@pytest.mark.parametrize('n', [64, 63])
def test_fht_identity(n, bias, offset, optimal):
rng = np.random.RandomState(3491349965)
a = rng.standard_normal(n)
dln = rng.uniform(-1, 1)
mu = rng.uniform(-2, 2)
if optimal:
offset = fhtoffset(dln, mu, initial=offset, bias=bias)
A = fht(a, dln, mu, offset=offset, bias=bias)
a_ = ifht(A, dln, mu, offset=offset, bias=bias)
assert_allclose(a, a_)
def test_fht_special_cases():
|
@pytest.mark.parametrize('n', [64, 63])
def test_fht_exact(n):
rng = np.random.RandomState(3491349965)
# for a(r) a power law r^\gamma, the fast Hankel transform produces the
# exact continuous Hankel transform if biased with q = \gamma
mu = rng.uniform(0, 3)
# convergence of HT: -1-mu < gamma < 1/2
gamma = rng.uniform(-1-mu, 1/2)
r = np.logspace(-2, 2, n)
a = r**gamma
dln = np.log(r[1]/r[0])
offset = fhtoffset(dln, mu, initial=0.0, bias=gamma)
A = fht(a, dln, mu, offset=offset, bias=gamma)
k = np.exp(offset)/r[::-1]
# analytical result
At = (2/k)**gamma * poch((mu+1-gamma)/2, gamma)
assert_allclose(A, At)
| rng = np.random.RandomState(3491349965)
a = rng.standard_normal(64)
dln = rng.uniform(-1, 1)
# let xp = (mu+1+q)/2, xm = (mu+1-q)/2, M = {0, -1, -2, ...}
# case 1: xp in M, xm in M => well-defined transform
mu, bias = -4.0, 1.0
with warnings.catch_warnings(record=True) as record:
fht(a, dln, mu, bias=bias)
assert not record, 'fht warned about a well-defined transform'
# case 2: xp not in M, xm in M => well-defined transform
mu, bias = -2.5, 0.5
with warnings.catch_warnings(record=True) as record:
fht(a, dln, mu, bias=bias)
assert not record, 'fht warned about a well-defined transform'
# case 3: xp in M, xm not in M => singular transform
mu, bias = -3.5, 0.5
with pytest.warns(Warning) as record:
fht(a, dln, mu, bias=bias)
assert record, 'fht did not warn about a singular transform'
# case 4: xp not in M, xm in M => singular inverse transform
mu, bias = -2.5, 0.5
with pytest.warns(Warning) as record:
ifht(a, dln, mu, bias=bias)
assert record, 'ifht did not warn about a singular transform' | identifier_body |
bower.js | var gulp = require('gulp'),
config = require('../config'),
mergeStream = require('merge-stream'),
mainBowerFiles = require('main-bower-files'),
flatten = require('gulp-flatten'),
rename = require("gulp-rename"),
bowerRequireJS = require('bower-requirejs'),
wiredep = require('wiredep').stream;
gulp.task('bower:styles', function() {
return gulp.src(config.sass.src)
.pipe(wiredep({
exclude: ['jquery'],
}))
.pipe(gulp.dest(config.sass.srcPath))
});
gulp.task('bower:scripts', function(cb) {
var options = {
baseURL: config.scripts.srcPath,
config: config.scripts.src,
exclude: ['jquery'],
transitive: true
};
bowerRequireJS(options, function (rjsConfigFromBower) { | cb();
})
}); | console.info('------> Updated paths config in '+options.config); | random_line_split |
preview-thumbnail.component.spec.ts | // Copyright 2020 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for the preview thumbnail component.
*/
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { ThumbnailDisplayComponent } from 'components/forms/custom-forms-directives/thumbnail-display.component';
import { ImageUploadHelperService } from 'services/image-upload-helper.service';
import { PreviewThumbnailComponent } from './preview-thumbnail.component';
import { ContextService } from 'services/context.service';
describe('Preview Thumbnail Component', function() {
let componentInstance: PreviewThumbnailComponent;
let fixture: ComponentFixture<PreviewThumbnailComponent>;
let imageUploadHelperService: ImageUploadHelperService;
let testUrl = 'test_url';
let contextService: ContextService;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [
PreviewThumbnailComponent,
ThumbnailDisplayComponent
],
providers: [
ImageUploadHelperService,
ContextService | }));
beforeEach(() => {
fixture = TestBed.createComponent(PreviewThumbnailComponent);
componentInstance = fixture.componentInstance;
imageUploadHelperService = (
TestBed.inject(ImageUploadHelperService) as unknown) as
jasmine.SpyObj<ImageUploadHelperService>;
contextService = TestBed.inject(ContextService);
spyOn(
imageUploadHelperService, 'getTrustedResourceUrlForThumbnailFilename')
.and.returnValue(testUrl);
});
it('should create', () => {
spyOn(contextService, 'getEntityType').and.returnValue('topic');
expect(componentInstance).toBeDefined();
});
it('should initialize', () => {
spyOn(contextService, 'getEntityType').and.returnValue('topic');
componentInstance.ngOnInit();
expect(componentInstance.editableThumbnailDataUrl).toEqual(testUrl);
});
it('should throw error if no image is present for a preview', () => {
spyOn(contextService, 'getEntityType').and.returnValue(undefined);
expect(() => {
componentInstance.ngOnInit();
}).toThrowError('No image present for preview');
});
}); | ]
}).compileComponents(); | random_line_split |
modistile.js | define([
'aeris/util',
'aeris/errors/invalidargumenterror',
'aeris/maps/layers/aeristile'
], function(_, InvalidArgumentError, AerisTile) {
/**
* Representation of an Aeris Modis layer.
*
* @constructor
* @class aeris.maps.layers.ModisTile
* @extends aeris.maps.layers.AerisTile
*/
var ModisTile = function(opt_attrs, opt_options) {
var options = _.extend({
period: 14
}, opt_options);
var attrs = _.extend({
autoUpdateInterval: AerisTile.updateIntervals.MODIS,
/**
* Hash of available tileType codes by period
* Used to dynamically create layer's tileType | /* eg
1: "modis_tileType_1day",
3: "modis_tileType_3day"
*/
}
}, opt_attrs);
// Set initial tileType
_.extend(attrs, {
tileType: attrs.modisPeriodTileTypes[options.period]
});
AerisTile.call(this, attrs, opt_options);
this.setModisPeriod(options.period);
};
// Inherit from AerisTile
_.inherits(ModisTile, AerisTile);
/**
* @param {number} period
* @throws {aeris.errors.InvalidArgumentError} If the layer does not support the given MODIS period.
*/
ModisTile.prototype.setModisPeriod = function(period) {
var validPeriods = _.keys(this.get('modisPeriodTileTypes'));
period = parseInt(period);
// Validate period
if (!period || period < 1) {
throw new InvalidArgumentError('Invalid MODIS period: period must be a positive integer');
}
if (!(period in this.get('modisPeriodTileTypes'))) {
throw new InvalidArgumentError('Invalid MODIS periods: available periods are: ' + validPeriods.join(','));
}
// Set new tile type
this.set('tileType', this.get('modisPeriodTileTypes')[period], { validate: true });
};
return ModisTile;
}); | *
* @attribute modisPeriodTileTypes
* @type {Object.<number, string>}
*/
modisPeriodTileTypes: { | random_line_split |
modistile.js | define([
'aeris/util',
'aeris/errors/invalidargumenterror',
'aeris/maps/layers/aeristile'
], function(_, InvalidArgumentError, AerisTile) {
/**
* Representation of an Aeris Modis layer.
*
* @constructor
* @class aeris.maps.layers.ModisTile
* @extends aeris.maps.layers.AerisTile
*/
var ModisTile = function(opt_attrs, opt_options) {
var options = _.extend({
period: 14
}, opt_options);
var attrs = _.extend({
autoUpdateInterval: AerisTile.updateIntervals.MODIS,
/**
* Hash of available tileType codes by period
* Used to dynamically create layer's tileType
*
* @attribute modisPeriodTileTypes
* @type {Object.<number, string>}
*/
modisPeriodTileTypes: {
/* eg
1: "modis_tileType_1day",
3: "modis_tileType_3day"
*/
}
}, opt_attrs);
// Set initial tileType
_.extend(attrs, {
tileType: attrs.modisPeriodTileTypes[options.period]
});
AerisTile.call(this, attrs, opt_options);
this.setModisPeriod(options.period);
};
// Inherit from AerisTile
_.inherits(ModisTile, AerisTile);
/**
* @param {number} period
* @throws {aeris.errors.InvalidArgumentError} If the layer does not support the given MODIS period.
*/
ModisTile.prototype.setModisPeriod = function(period) {
var validPeriods = _.keys(this.get('modisPeriodTileTypes'));
period = parseInt(period);
// Validate period
if (!period || period < 1) |
if (!(period in this.get('modisPeriodTileTypes'))) {
throw new InvalidArgumentError('Invalid MODIS periods: available periods are: ' + validPeriods.join(','));
}
// Set new tile type
this.set('tileType', this.get('modisPeriodTileTypes')[period], { validate: true });
};
return ModisTile;
});
| {
throw new InvalidArgumentError('Invalid MODIS period: period must be a positive integer');
} | conditional_block |
s3.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::io;
use std::marker::PhantomData;
use futures_util::{
future::FutureExt,
io::{AsyncRead, AsyncReadExt},
stream::TryStreamExt,
};
use rusoto_core::{
request::DispatchSignedRequest,
{ByteStream, RusotoError},
};
use rusoto_s3::*;
use rusoto_util::new_client;
use super::{
util::{block_on_external_io, error_stream, retry, RetryError},
ExternalStorage,
};
use kvproto::backup::S3 as Config;
/// S3 compatible storage
#[derive(Clone)]
pub struct S3Storage {
config: Config,
client: S3Client,
// The current implementation (rosoto 0.43.0 + hyper 0.13.3) is not `Send`
// in practical. See more https://github.com/tikv/tikv/issues/7236.
// FIXME: remove it.
_not_send: PhantomData<*const ()>,
}
impl S3Storage {
/// Create a new S3 storage for the given config.
pub fn new(config: &Config) -> io::Result<S3Storage> {
Self::check_config(config)?;
let client = new_client!(S3Client, config);
Ok(S3Storage {
config: config.clone(),
client,
_not_send: PhantomData::default(),
})
}
pub fn with_request_dispatcher<D>(config: &Config, dispatcher: D) -> io::Result<S3Storage>
where
D: DispatchSignedRequest + Send + Sync + 'static,
{
Self::check_config(config)?;
let client = new_client!(S3Client, config, dispatcher);
Ok(S3Storage {
config: config.clone(),
client,
_not_send: PhantomData::default(),
})
}
fn check_config(config: &Config) -> io::Result<()> {
if config.bucket.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"missing bucket name",
));
}
Ok(())
}
fn maybe_prefix_key(&self, key: &str) -> String {
if !self.config.prefix.is_empty() {
return format!("{}/{}", self.config.prefix, key);
}
key.to_owned()
}
}
impl<E> RetryError for RusotoError<E> {
fn placeholder() -> Self {
Self::Blocking
}
fn is_retryable(&self) -> bool {
match self {
Self::HttpDispatch(_) => true,
Self::Unknown(resp) if resp.status.is_server_error() => true,
// FIXME: Retry NOT_READY & THROTTLED (403).
_ => false,
}
}
}
/// A helper for uploading a large files to S3 storage.
///
/// Note: this uploader does not support uploading files larger than 19.5 GiB.
struct S3Uploader<'client> {
client: &'client S3Client,
bucket: String,
key: String,
acl: Option<String>,
server_side_encryption: Option<String>,
ssekms_key_id: Option<String>,
storage_class: Option<String>,
upload_id: String,
parts: Vec<CompletedPart>,
}
/// Specifies the minimum size to use multi-part upload.
/// AWS S3 requires each part to be at least 5 MiB.
const MINIMUM_PART_SIZE: usize = 5 * 1024 * 1024;
impl<'client> S3Uploader<'client> {
/// Creates a new uploader with a given target location and upload configuration.
fn new(client: &'client S3Client, config: &Config, key: String) -> Self {
fn get_var(s: &str) -> Option<String> {
if s.is_empty() {
None
} else {
Some(s.to_owned())
}
}
Self {
client,
bucket: config.bucket.clone(),
key,
acl: get_var(&config.acl),
server_side_encryption: get_var(&config.sse),
ssekms_key_id: get_var(&config.sse_kms_key_id),
storage_class: get_var(&config.storage_class),
upload_id: "".to_owned(),
parts: Vec::new(),
}
}
/// Executes the upload process.
async fn run(
mut self,
reader: &mut (dyn AsyncRead + Unpin),
est_len: u64,
) -> Result<(), Box<dyn std::error::Error>> {
if est_len <= MINIMUM_PART_SIZE as u64 {
// For short files, execute one put_object to upload the entire thing.
let mut data = Vec::with_capacity(est_len as usize);
reader.read_to_end(&mut data).await?;
retry(|| self.upload(&data)).await?;
Ok(())
} else {
// Otherwise, use multipart upload to improve robustness.
self.upload_id = retry(|| self.begin()).await?;
let upload_res = async {
let mut buf = vec![0; MINIMUM_PART_SIZE];
let mut part_number = 1;
loop {
let data_size = reader.read(&mut buf).await?;
if data_size == 0 {
break;
}
let part = retry(|| self.upload_part(part_number, &buf[..data_size])).await?;
self.parts.push(part);
part_number += 1;
}
Ok(())
}
.await;
if upload_res.is_ok() {
retry(|| self.complete()).await?;
} else {
let _ = retry(|| self.abort()).await;
}
upload_res
}
}
/// Starts a multipart upload process.
async fn begin(&self) -> Result<String, RusotoError<CreateMultipartUploadError>> {
let output = self
.client
.create_multipart_upload(CreateMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
acl: self.acl.clone(),
server_side_encryption: self.server_side_encryption.clone(),
ssekms_key_id: self.ssekms_key_id.clone(),
storage_class: self.storage_class.clone(),
..Default::default()
})
.await?;
output.upload_id.ok_or_else(|| {
RusotoError::ParseError("missing upload-id from create_multipart_upload()".to_owned())
})
}
/// Completes a multipart upload process, asking S3 to join all parts into a single file.
async fn complete(&self) -> Result<(), RusotoError<CompleteMultipartUploadError>> {
self.client
.complete_multipart_upload(CompleteMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
multipart_upload: Some(CompletedMultipartUpload {
parts: Some(self.parts.clone()),
}),
..Default::default()
})
.await?;
Ok(())
}
/// Aborts the multipart upload process, deletes all uploaded parts.
async fn abort(&self) -> Result<(), RusotoError<AbortMultipartUploadError>> {
self.client
.abort_multipart_upload(AbortMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
..Default::default()
})
.await?;
Ok(())
}
/// Uploads a part of the file.
///
/// The `part_number` must be between 1 to 10000.
async fn upload_part(
&self,
part_number: i64,
data: &[u8],
) -> Result<CompletedPart, RusotoError<UploadPartError>> {
let part = self
.client
.upload_part(UploadPartRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
part_number,
content_length: Some(data.len() as i64),
body: Some(data.to_vec().into()),
..Default::default()
})
.await?;
Ok(CompletedPart {
e_tag: part.e_tag,
part_number: Some(part_number),
})
}
/// Uploads a file atomically.
///
/// This should be used only when the data is known to be short, and thus relatively cheap to
/// retry the entire upload.
async fn upload(&self, data: &[u8]) -> Result<(), RusotoError<PutObjectError>> {
self.client
.put_object(PutObjectRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
acl: self.acl.clone(),
server_side_encryption: self.server_side_encryption.clone(),
ssekms_key_id: self.ssekms_key_id.clone(),
storage_class: self.storage_class.clone(),
content_length: Some(data.len() as i64),
body: Some(data.to_vec().into()),
..Default::default()
})
.await?;
Ok(())
}
}
impl ExternalStorage for S3Storage {
fn write(
&self,
name: &str,
mut reader: Box<dyn AsyncRead + Send + Unpin>,
content_length: u64,
) -> io::Result<()> {
let key = self.maybe_prefix_key(name);
debug!("save file to s3 storage"; "key" => %key);
let uploader = S3Uploader::new(&self.client, &self.config, key);
block_on_external_io(uploader.run(&mut *reader, content_length)).map_err(|e| {
io::Error::new(io::ErrorKind::Other, format!("failed to put object {}", e))
})
}
fn read(&self, name: &str) -> Box<dyn AsyncRead + Unpin + '_> {
let key = self.maybe_prefix_key(name);
let bucket = self.config.bucket.clone();
debug!("read file from s3 storage"; "key" => %key);
let req = GetObjectRequest {
key,
bucket: bucket.clone(),
..Default::default()
};
Box::new(
self.client
.get_object(req)
.map(move |future| match future {
Ok(out) => out.body.unwrap(),
Err(RusotoError::Service(GetObjectError::NoSuchKey(key))) => {
ByteStream::new(error_stream(io::Error::new(
io::ErrorKind::NotFound,
format!("no key {} at bucket {}", key, bucket),
)))
}
Err(e) => ByteStream::new(error_stream(io::Error::new(
io::ErrorKind::Other,
format!("failed to get object {}", e),
))),
})
.flatten_stream()
.into_async_read(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::io::AsyncReadExt;
use rusoto_core::signature::SignedRequest;
use rusoto_mock::MockRequestDispatcher;
#[test]
fn test_s3_config() {
let config = Config {
region: "ap-southeast-2".to_string(),
bucket: "mybucket".to_string(),
prefix: "myprefix".to_string(),
access_key: "abc".to_string(),
secret_access_key: "xyz".to_string(),
..Default::default()
};
let cases = vec![
// bucket is empty
Config {
bucket: "".to_owned(),
..config.clone()
},
];
for case in cases {
let r = S3Storage::new(&case);
assert!(r.is_err());
}
assert!(S3Storage::new(&config).is_ok());
}
#[test]
fn test_s3_storage() |
#[test]
#[cfg(FALSE)]
// FIXME: enable this (or move this to an integration test) if we've got a
// reliable way to test s3 (rusoto_mock requires custom logic to verify the
// body stream which itself can have bug)
fn test_real_s3_storage() {
use std::f64::INFINITY;
use tikv_util::time::Limiter;
let mut s3 = Config::default();
s3.set_endpoint("http://127.0.0.1:9000".to_owned());
s3.set_bucket("bucket".to_owned());
s3.set_prefix("prefix".to_owned());
s3.set_access_key("93QZ01QRBYQQXC37XHZV".to_owned());
s3.set_secret_access_key("N2VcI4Emg0Nm7fDzGBMJvguHHUxLGpjfwt2y4+vJ".to_owned());
s3.set_force_path_style(true);
let limiter = Limiter::new(INFINITY);
let storage = S3Storage::new(&s3).unwrap();
const LEN: usize = 1024 * 1024 * 4;
static CONTENT: [u8; LEN] = [50_u8; LEN];
storage
.write(
"huge_file",
Box::new(limiter.limit(&CONTENT[..])),
LEN as u64,
)
.unwrap();
let mut reader = storage.read("huge_file");
let mut buf = Vec::new();
block_on_external_io(reader.read_to_end(&mut buf)).unwrap();
assert_eq!(buf.len(), LEN);
assert_eq!(buf.iter().position(|b| *b != 50_u8), None);
}
}
| {
let magic_contents = "5678";
let config = Config {
region: "ap-southeast-2".to_string(),
bucket: "mybucket".to_string(),
prefix: "myprefix".to_string(),
access_key: "abc".to_string(),
secret_access_key: "xyz".to_string(),
..Default::default()
};
let dispatcher = MockRequestDispatcher::with_status(200).with_request_checker(
move |req: &SignedRequest| {
assert_eq!(req.region.name(), "ap-southeast-2");
assert_eq!(req.path(), "/mybucket/myprefix/mykey");
// PutObject is translated to HTTP PUT.
assert_eq!(req.payload.is_some(), req.method() == "PUT");
},
);
let s = S3Storage::with_request_dispatcher(&config, dispatcher).unwrap();
s.write(
"mykey",
Box::new(magic_contents.as_bytes()),
magic_contents.len() as u64,
)
.unwrap();
let mut reader = s.read("mykey");
let mut buf = Vec::new();
let ret = block_on_external_io(reader.read_to_end(&mut buf));
assert!(ret.unwrap() == 0);
assert!(buf.is_empty());
} | identifier_body |
s3.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::io;
use std::marker::PhantomData;
use futures_util::{
future::FutureExt,
io::{AsyncRead, AsyncReadExt},
stream::TryStreamExt,
};
use rusoto_core::{
request::DispatchSignedRequest,
{ByteStream, RusotoError},
};
use rusoto_s3::*;
use rusoto_util::new_client;
use super::{
util::{block_on_external_io, error_stream, retry, RetryError},
ExternalStorage,
};
use kvproto::backup::S3 as Config;
/// S3 compatible storage
#[derive(Clone)]
pub struct S3Storage {
config: Config,
client: S3Client,
// The current implementation (rosoto 0.43.0 + hyper 0.13.3) is not `Send`
// in practical. See more https://github.com/tikv/tikv/issues/7236.
// FIXME: remove it.
_not_send: PhantomData<*const ()>,
}
impl S3Storage {
/// Create a new S3 storage for the given config.
pub fn new(config: &Config) -> io::Result<S3Storage> {
Self::check_config(config)?;
let client = new_client!(S3Client, config);
Ok(S3Storage {
config: config.clone(),
client,
_not_send: PhantomData::default(),
})
}
pub fn with_request_dispatcher<D>(config: &Config, dispatcher: D) -> io::Result<S3Storage>
where
D: DispatchSignedRequest + Send + Sync + 'static,
{
Self::check_config(config)?;
let client = new_client!(S3Client, config, dispatcher);
Ok(S3Storage {
config: config.clone(),
client,
_not_send: PhantomData::default(),
})
}
fn check_config(config: &Config) -> io::Result<()> {
if config.bucket.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"missing bucket name",
));
}
Ok(())
}
fn maybe_prefix_key(&self, key: &str) -> String {
if !self.config.prefix.is_empty() {
return format!("{}/{}", self.config.prefix, key);
}
key.to_owned()
}
}
impl<E> RetryError for RusotoError<E> {
fn placeholder() -> Self {
Self::Blocking
}
fn is_retryable(&self) -> bool {
match self {
Self::HttpDispatch(_) => true,
Self::Unknown(resp) if resp.status.is_server_error() => true,
// FIXME: Retry NOT_READY & THROTTLED (403).
_ => false,
}
}
}
/// A helper for uploading a large files to S3 storage.
///
/// Note: this uploader does not support uploading files larger than 19.5 GiB.
struct S3Uploader<'client> {
client: &'client S3Client,
bucket: String,
key: String,
acl: Option<String>,
server_side_encryption: Option<String>,
ssekms_key_id: Option<String>,
storage_class: Option<String>,
upload_id: String,
parts: Vec<CompletedPart>,
}
/// Specifies the minimum size to use multi-part upload.
/// AWS S3 requires each part to be at least 5 MiB.
const MINIMUM_PART_SIZE: usize = 5 * 1024 * 1024;
impl<'client> S3Uploader<'client> {
/// Creates a new uploader with a given target location and upload configuration.
fn new(client: &'client S3Client, config: &Config, key: String) -> Self {
fn get_var(s: &str) -> Option<String> {
if s.is_empty() {
None
} else {
Some(s.to_owned())
}
}
Self {
client,
bucket: config.bucket.clone(),
key,
acl: get_var(&config.acl),
server_side_encryption: get_var(&config.sse),
ssekms_key_id: get_var(&config.sse_kms_key_id),
storage_class: get_var(&config.storage_class),
upload_id: "".to_owned(),
parts: Vec::new(),
}
}
/// Executes the upload process.
async fn run(
mut self,
reader: &mut (dyn AsyncRead + Unpin),
est_len: u64,
) -> Result<(), Box<dyn std::error::Error>> {
if est_len <= MINIMUM_PART_SIZE as u64 {
// For short files, execute one put_object to upload the entire thing.
let mut data = Vec::with_capacity(est_len as usize);
reader.read_to_end(&mut data).await?;
retry(|| self.upload(&data)).await?;
Ok(())
} else {
// Otherwise, use multipart upload to improve robustness.
self.upload_id = retry(|| self.begin()).await?;
let upload_res = async {
let mut buf = vec![0; MINIMUM_PART_SIZE];
let mut part_number = 1;
loop {
let data_size = reader.read(&mut buf).await?;
if data_size == 0 {
break;
}
let part = retry(|| self.upload_part(part_number, &buf[..data_size])).await?;
self.parts.push(part);
part_number += 1;
}
Ok(())
}
.await;
if upload_res.is_ok() {
retry(|| self.complete()).await?;
} else { | }
/// Starts a multipart upload process.
async fn begin(&self) -> Result<String, RusotoError<CreateMultipartUploadError>> {
let output = self
.client
.create_multipart_upload(CreateMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
acl: self.acl.clone(),
server_side_encryption: self.server_side_encryption.clone(),
ssekms_key_id: self.ssekms_key_id.clone(),
storage_class: self.storage_class.clone(),
..Default::default()
})
.await?;
output.upload_id.ok_or_else(|| {
RusotoError::ParseError("missing upload-id from create_multipart_upload()".to_owned())
})
}
/// Completes a multipart upload process, asking S3 to join all parts into a single file.
async fn complete(&self) -> Result<(), RusotoError<CompleteMultipartUploadError>> {
self.client
.complete_multipart_upload(CompleteMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
multipart_upload: Some(CompletedMultipartUpload {
parts: Some(self.parts.clone()),
}),
..Default::default()
})
.await?;
Ok(())
}
/// Aborts the multipart upload process, deletes all uploaded parts.
async fn abort(&self) -> Result<(), RusotoError<AbortMultipartUploadError>> {
self.client
.abort_multipart_upload(AbortMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
..Default::default()
})
.await?;
Ok(())
}
/// Uploads a part of the file.
///
/// The `part_number` must be between 1 to 10000.
async fn upload_part(
&self,
part_number: i64,
data: &[u8],
) -> Result<CompletedPart, RusotoError<UploadPartError>> {
let part = self
.client
.upload_part(UploadPartRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
part_number,
content_length: Some(data.len() as i64),
body: Some(data.to_vec().into()),
..Default::default()
})
.await?;
Ok(CompletedPart {
e_tag: part.e_tag,
part_number: Some(part_number),
})
}
/// Uploads a file atomically.
///
/// This should be used only when the data is known to be short, and thus relatively cheap to
/// retry the entire upload.
async fn upload(&self, data: &[u8]) -> Result<(), RusotoError<PutObjectError>> {
self.client
.put_object(PutObjectRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
acl: self.acl.clone(),
server_side_encryption: self.server_side_encryption.clone(),
ssekms_key_id: self.ssekms_key_id.clone(),
storage_class: self.storage_class.clone(),
content_length: Some(data.len() as i64),
body: Some(data.to_vec().into()),
..Default::default()
})
.await?;
Ok(())
}
}
impl ExternalStorage for S3Storage {
fn write(
&self,
name: &str,
mut reader: Box<dyn AsyncRead + Send + Unpin>,
content_length: u64,
) -> io::Result<()> {
let key = self.maybe_prefix_key(name);
debug!("save file to s3 storage"; "key" => %key);
let uploader = S3Uploader::new(&self.client, &self.config, key);
block_on_external_io(uploader.run(&mut *reader, content_length)).map_err(|e| {
io::Error::new(io::ErrorKind::Other, format!("failed to put object {}", e))
})
}
fn read(&self, name: &str) -> Box<dyn AsyncRead + Unpin + '_> {
let key = self.maybe_prefix_key(name);
let bucket = self.config.bucket.clone();
debug!("read file from s3 storage"; "key" => %key);
let req = GetObjectRequest {
key,
bucket: bucket.clone(),
..Default::default()
};
Box::new(
self.client
.get_object(req)
.map(move |future| match future {
Ok(out) => out.body.unwrap(),
Err(RusotoError::Service(GetObjectError::NoSuchKey(key))) => {
ByteStream::new(error_stream(io::Error::new(
io::ErrorKind::NotFound,
format!("no key {} at bucket {}", key, bucket),
)))
}
Err(e) => ByteStream::new(error_stream(io::Error::new(
io::ErrorKind::Other,
format!("failed to get object {}", e),
))),
})
.flatten_stream()
.into_async_read(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::io::AsyncReadExt;
use rusoto_core::signature::SignedRequest;
use rusoto_mock::MockRequestDispatcher;
#[test]
fn test_s3_config() {
let config = Config {
region: "ap-southeast-2".to_string(),
bucket: "mybucket".to_string(),
prefix: "myprefix".to_string(),
access_key: "abc".to_string(),
secret_access_key: "xyz".to_string(),
..Default::default()
};
let cases = vec![
// bucket is empty
Config {
bucket: "".to_owned(),
..config.clone()
},
];
for case in cases {
let r = S3Storage::new(&case);
assert!(r.is_err());
}
assert!(S3Storage::new(&config).is_ok());
}
#[test]
fn test_s3_storage() {
let magic_contents = "5678";
let config = Config {
region: "ap-southeast-2".to_string(),
bucket: "mybucket".to_string(),
prefix: "myprefix".to_string(),
access_key: "abc".to_string(),
secret_access_key: "xyz".to_string(),
..Default::default()
};
let dispatcher = MockRequestDispatcher::with_status(200).with_request_checker(
move |req: &SignedRequest| {
assert_eq!(req.region.name(), "ap-southeast-2");
assert_eq!(req.path(), "/mybucket/myprefix/mykey");
// PutObject is translated to HTTP PUT.
assert_eq!(req.payload.is_some(), req.method() == "PUT");
},
);
let s = S3Storage::with_request_dispatcher(&config, dispatcher).unwrap();
s.write(
"mykey",
Box::new(magic_contents.as_bytes()),
magic_contents.len() as u64,
)
.unwrap();
let mut reader = s.read("mykey");
let mut buf = Vec::new();
let ret = block_on_external_io(reader.read_to_end(&mut buf));
assert!(ret.unwrap() == 0);
assert!(buf.is_empty());
}
#[test]
#[cfg(FALSE)]
// FIXME: enable this (or move this to an integration test) if we've got a
// reliable way to test s3 (rusoto_mock requires custom logic to verify the
// body stream which itself can have bug)
fn test_real_s3_storage() {
use std::f64::INFINITY;
use tikv_util::time::Limiter;
let mut s3 = Config::default();
s3.set_endpoint("http://127.0.0.1:9000".to_owned());
s3.set_bucket("bucket".to_owned());
s3.set_prefix("prefix".to_owned());
s3.set_access_key("93QZ01QRBYQQXC37XHZV".to_owned());
s3.set_secret_access_key("N2VcI4Emg0Nm7fDzGBMJvguHHUxLGpjfwt2y4+vJ".to_owned());
s3.set_force_path_style(true);
let limiter = Limiter::new(INFINITY);
let storage = S3Storage::new(&s3).unwrap();
const LEN: usize = 1024 * 1024 * 4;
static CONTENT: [u8; LEN] = [50_u8; LEN];
storage
.write(
"huge_file",
Box::new(limiter.limit(&CONTENT[..])),
LEN as u64,
)
.unwrap();
let mut reader = storage.read("huge_file");
let mut buf = Vec::new();
block_on_external_io(reader.read_to_end(&mut buf)).unwrap();
assert_eq!(buf.len(), LEN);
assert_eq!(buf.iter().position(|b| *b != 50_u8), None);
}
} | let _ = retry(|| self.abort()).await;
}
upload_res
} | random_line_split |
s3.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::io;
use std::marker::PhantomData;
use futures_util::{
future::FutureExt,
io::{AsyncRead, AsyncReadExt},
stream::TryStreamExt,
};
use rusoto_core::{
request::DispatchSignedRequest,
{ByteStream, RusotoError},
};
use rusoto_s3::*;
use rusoto_util::new_client;
use super::{
util::{block_on_external_io, error_stream, retry, RetryError},
ExternalStorage,
};
use kvproto::backup::S3 as Config;
/// S3 compatible storage
#[derive(Clone)]
pub struct S3Storage {
config: Config,
client: S3Client,
// The current implementation (rosoto 0.43.0 + hyper 0.13.3) is not `Send`
// in practical. See more https://github.com/tikv/tikv/issues/7236.
// FIXME: remove it.
_not_send: PhantomData<*const ()>,
}
impl S3Storage {
/// Create a new S3 storage for the given config.
pub fn new(config: &Config) -> io::Result<S3Storage> {
Self::check_config(config)?;
let client = new_client!(S3Client, config);
Ok(S3Storage {
config: config.clone(),
client,
_not_send: PhantomData::default(),
})
}
pub fn with_request_dispatcher<D>(config: &Config, dispatcher: D) -> io::Result<S3Storage>
where
D: DispatchSignedRequest + Send + Sync + 'static,
{
Self::check_config(config)?;
let client = new_client!(S3Client, config, dispatcher);
Ok(S3Storage {
config: config.clone(),
client,
_not_send: PhantomData::default(),
})
}
fn check_config(config: &Config) -> io::Result<()> {
if config.bucket.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"missing bucket name",
));
}
Ok(())
}
fn maybe_prefix_key(&self, key: &str) -> String {
if !self.config.prefix.is_empty() {
return format!("{}/{}", self.config.prefix, key);
}
key.to_owned()
}
}
impl<E> RetryError for RusotoError<E> {
fn placeholder() -> Self {
Self::Blocking
}
fn is_retryable(&self) -> bool {
match self {
Self::HttpDispatch(_) => true,
Self::Unknown(resp) if resp.status.is_server_error() => true,
// FIXME: Retry NOT_READY & THROTTLED (403).
_ => false,
}
}
}
/// A helper for uploading a large files to S3 storage.
///
/// Note: this uploader does not support uploading files larger than 19.5 GiB.
struct S3Uploader<'client> {
client: &'client S3Client,
bucket: String,
key: String,
acl: Option<String>,
server_side_encryption: Option<String>,
ssekms_key_id: Option<String>,
storage_class: Option<String>,
upload_id: String,
parts: Vec<CompletedPart>,
}
/// Specifies the minimum size to use multi-part upload.
/// AWS S3 requires each part to be at least 5 MiB.
const MINIMUM_PART_SIZE: usize = 5 * 1024 * 1024;
impl<'client> S3Uploader<'client> {
/// Creates a new uploader with a given target location and upload configuration.
fn new(client: &'client S3Client, config: &Config, key: String) -> Self {
fn get_var(s: &str) -> Option<String> {
if s.is_empty() {
None
} else {
Some(s.to_owned())
}
}
Self {
client,
bucket: config.bucket.clone(),
key,
acl: get_var(&config.acl),
server_side_encryption: get_var(&config.sse),
ssekms_key_id: get_var(&config.sse_kms_key_id),
storage_class: get_var(&config.storage_class),
upload_id: "".to_owned(),
parts: Vec::new(),
}
}
/// Executes the upload process.
async fn run(
mut self,
reader: &mut (dyn AsyncRead + Unpin),
est_len: u64,
) -> Result<(), Box<dyn std::error::Error>> {
if est_len <= MINIMUM_PART_SIZE as u64 {
// For short files, execute one put_object to upload the entire thing.
let mut data = Vec::with_capacity(est_len as usize);
reader.read_to_end(&mut data).await?;
retry(|| self.upload(&data)).await?;
Ok(())
} else {
// Otherwise, use multipart upload to improve robustness.
self.upload_id = retry(|| self.begin()).await?;
let upload_res = async {
let mut buf = vec![0; MINIMUM_PART_SIZE];
let mut part_number = 1;
loop {
let data_size = reader.read(&mut buf).await?;
if data_size == 0 {
break;
}
let part = retry(|| self.upload_part(part_number, &buf[..data_size])).await?;
self.parts.push(part);
part_number += 1;
}
Ok(())
}
.await;
if upload_res.is_ok() {
retry(|| self.complete()).await?;
} else {
let _ = retry(|| self.abort()).await;
}
upload_res
}
}
/// Starts a multipart upload process.
async fn begin(&self) -> Result<String, RusotoError<CreateMultipartUploadError>> {
let output = self
.client
.create_multipart_upload(CreateMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
acl: self.acl.clone(),
server_side_encryption: self.server_side_encryption.clone(),
ssekms_key_id: self.ssekms_key_id.clone(),
storage_class: self.storage_class.clone(),
..Default::default()
})
.await?;
output.upload_id.ok_or_else(|| {
RusotoError::ParseError("missing upload-id from create_multipart_upload()".to_owned())
})
}
/// Completes a multipart upload process, asking S3 to join all parts into a single file.
async fn complete(&self) -> Result<(), RusotoError<CompleteMultipartUploadError>> {
self.client
.complete_multipart_upload(CompleteMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
multipart_upload: Some(CompletedMultipartUpload {
parts: Some(self.parts.clone()),
}),
..Default::default()
})
.await?;
Ok(())
}
/// Aborts the multipart upload process, deletes all uploaded parts.
async fn | (&self) -> Result<(), RusotoError<AbortMultipartUploadError>> {
self.client
.abort_multipart_upload(AbortMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
..Default::default()
})
.await?;
Ok(())
}
/// Uploads a part of the file.
///
/// The `part_number` must be between 1 to 10000.
async fn upload_part(
&self,
part_number: i64,
data: &[u8],
) -> Result<CompletedPart, RusotoError<UploadPartError>> {
let part = self
.client
.upload_part(UploadPartRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
part_number,
content_length: Some(data.len() as i64),
body: Some(data.to_vec().into()),
..Default::default()
})
.await?;
Ok(CompletedPart {
e_tag: part.e_tag,
part_number: Some(part_number),
})
}
/// Uploads a file atomically.
///
/// This should be used only when the data is known to be short, and thus relatively cheap to
/// retry the entire upload.
async fn upload(&self, data: &[u8]) -> Result<(), RusotoError<PutObjectError>> {
self.client
.put_object(PutObjectRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
acl: self.acl.clone(),
server_side_encryption: self.server_side_encryption.clone(),
ssekms_key_id: self.ssekms_key_id.clone(),
storage_class: self.storage_class.clone(),
content_length: Some(data.len() as i64),
body: Some(data.to_vec().into()),
..Default::default()
})
.await?;
Ok(())
}
}
impl ExternalStorage for S3Storage {
fn write(
&self,
name: &str,
mut reader: Box<dyn AsyncRead + Send + Unpin>,
content_length: u64,
) -> io::Result<()> {
let key = self.maybe_prefix_key(name);
debug!("save file to s3 storage"; "key" => %key);
let uploader = S3Uploader::new(&self.client, &self.config, key);
block_on_external_io(uploader.run(&mut *reader, content_length)).map_err(|e| {
io::Error::new(io::ErrorKind::Other, format!("failed to put object {}", e))
})
}
fn read(&self, name: &str) -> Box<dyn AsyncRead + Unpin + '_> {
let key = self.maybe_prefix_key(name);
let bucket = self.config.bucket.clone();
debug!("read file from s3 storage"; "key" => %key);
let req = GetObjectRequest {
key,
bucket: bucket.clone(),
..Default::default()
};
Box::new(
self.client
.get_object(req)
.map(move |future| match future {
Ok(out) => out.body.unwrap(),
Err(RusotoError::Service(GetObjectError::NoSuchKey(key))) => {
ByteStream::new(error_stream(io::Error::new(
io::ErrorKind::NotFound,
format!("no key {} at bucket {}", key, bucket),
)))
}
Err(e) => ByteStream::new(error_stream(io::Error::new(
io::ErrorKind::Other,
format!("failed to get object {}", e),
))),
})
.flatten_stream()
.into_async_read(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::io::AsyncReadExt;
use rusoto_core::signature::SignedRequest;
use rusoto_mock::MockRequestDispatcher;
#[test]
fn test_s3_config() {
let config = Config {
region: "ap-southeast-2".to_string(),
bucket: "mybucket".to_string(),
prefix: "myprefix".to_string(),
access_key: "abc".to_string(),
secret_access_key: "xyz".to_string(),
..Default::default()
};
let cases = vec![
// bucket is empty
Config {
bucket: "".to_owned(),
..config.clone()
},
];
for case in cases {
let r = S3Storage::new(&case);
assert!(r.is_err());
}
assert!(S3Storage::new(&config).is_ok());
}
#[test]
fn test_s3_storage() {
let magic_contents = "5678";
let config = Config {
region: "ap-southeast-2".to_string(),
bucket: "mybucket".to_string(),
prefix: "myprefix".to_string(),
access_key: "abc".to_string(),
secret_access_key: "xyz".to_string(),
..Default::default()
};
let dispatcher = MockRequestDispatcher::with_status(200).with_request_checker(
move |req: &SignedRequest| {
assert_eq!(req.region.name(), "ap-southeast-2");
assert_eq!(req.path(), "/mybucket/myprefix/mykey");
// PutObject is translated to HTTP PUT.
assert_eq!(req.payload.is_some(), req.method() == "PUT");
},
);
let s = S3Storage::with_request_dispatcher(&config, dispatcher).unwrap();
s.write(
"mykey",
Box::new(magic_contents.as_bytes()),
magic_contents.len() as u64,
)
.unwrap();
let mut reader = s.read("mykey");
let mut buf = Vec::new();
let ret = block_on_external_io(reader.read_to_end(&mut buf));
assert!(ret.unwrap() == 0);
assert!(buf.is_empty());
}
#[test]
#[cfg(FALSE)]
// FIXME: enable this (or move this to an integration test) if we've got a
// reliable way to test s3 (rusoto_mock requires custom logic to verify the
// body stream which itself can have bug)
fn test_real_s3_storage() {
use std::f64::INFINITY;
use tikv_util::time::Limiter;
let mut s3 = Config::default();
s3.set_endpoint("http://127.0.0.1:9000".to_owned());
s3.set_bucket("bucket".to_owned());
s3.set_prefix("prefix".to_owned());
s3.set_access_key("93QZ01QRBYQQXC37XHZV".to_owned());
s3.set_secret_access_key("N2VcI4Emg0Nm7fDzGBMJvguHHUxLGpjfwt2y4+vJ".to_owned());
s3.set_force_path_style(true);
let limiter = Limiter::new(INFINITY);
let storage = S3Storage::new(&s3).unwrap();
const LEN: usize = 1024 * 1024 * 4;
static CONTENT: [u8; LEN] = [50_u8; LEN];
storage
.write(
"huge_file",
Box::new(limiter.limit(&CONTENT[..])),
LEN as u64,
)
.unwrap();
let mut reader = storage.read("huge_file");
let mut buf = Vec::new();
block_on_external_io(reader.read_to_end(&mut buf)).unwrap();
assert_eq!(buf.len(), LEN);
assert_eq!(buf.iter().position(|b| *b != 50_u8), None);
}
}
| abort | identifier_name |
member_constraints.rs | use rustc_data_structures::fx::FxHashMap;
use rustc_index::vec::IndexVec;
use rustc_middle::infer::MemberConstraint;
use rustc_middle::ty::{self, Ty};
use rustc_span::Span;
use std::hash::Hash;
use std::ops::Index;
/// Compactly stores a set of `R0 member of [R1...Rn]` constraints,
/// indexed by the region `R0`.
crate struct MemberConstraintSet<'tcx, R>
where
R: Copy + Eq,
{
/// Stores the first "member" constraint for a given `R0`. This is an
/// index into the `constraints` vector below.
first_constraints: FxHashMap<R, NllMemberConstraintIndex>,
/// Stores the data about each `R0 member of [R1..Rn]` constraint.
/// These are organized into a linked list, so each constraint
/// contains the index of the next constraint with the same `R0`.
constraints: IndexVec<NllMemberConstraintIndex, NllMemberConstraint<'tcx>>,
/// Stores the `R1..Rn` regions for *all* sets. For any given
/// constraint, we keep two indices so that we can pull out a
/// slice.
choice_regions: Vec<ty::RegionVid>,
}
/// Represents a `R0 member of [R1..Rn]` constraint
crate struct NllMemberConstraint<'tcx> {
next_constraint: Option<NllMemberConstraintIndex>,
/// The span where the hidden type was instantiated.
crate definition_span: Span,
/// The hidden type in which `R0` appears. (Used in error reporting.)
crate hidden_ty: Ty<'tcx>,
/// The region `R0`.
crate member_region_vid: ty::RegionVid,
/// Index of `R1` in `choice_regions` vector from `MemberConstraintSet`.
start_index: usize,
/// Index of `Rn` in `choice_regions` vector from `MemberConstraintSet`.
end_index: usize,
}
rustc_index::newtype_index! {
crate struct NllMemberConstraintIndex {
DEBUG_FORMAT = "MemberConstraintIndex({})"
}
}
impl Default for MemberConstraintSet<'tcx, ty::RegionVid> {
fn default() -> Self {
Self {
first_constraints: Default::default(),
constraints: Default::default(),
choice_regions: Default::default(),
}
}
}
impl<'tcx> MemberConstraintSet<'tcx, ty::RegionVid> {
/// Pushes a member constraint into the set.
///
/// The input member constraint `m_c` is in the form produced by
/// the `rustc_middle::infer` code.
///
/// The `to_region_vid` callback fn is used to convert the regions
/// within into `RegionVid` format -- it typically consults the
/// `UniversalRegions` data structure that is known to the caller
/// (but which this code is unaware of).
crate fn push_constraint(
&mut self,
m_c: &MemberConstraint<'tcx>,
mut to_region_vid: impl FnMut(ty::Region<'tcx>) -> ty::RegionVid,
) {
debug!("push_constraint(m_c={:?})", m_c);
let member_region_vid: ty::RegionVid = to_region_vid(m_c.member_region);
let next_constraint = self.first_constraints.get(&member_region_vid).cloned();
let start_index = self.choice_regions.len();
let end_index = start_index + m_c.choice_regions.len();
debug!("push_constraint: member_region_vid={:?}", member_region_vid);
let constraint_index = self.constraints.push(NllMemberConstraint {
next_constraint,
member_region_vid,
definition_span: m_c.definition_span,
hidden_ty: m_c.hidden_ty,
start_index,
end_index,
});
self.first_constraints.insert(member_region_vid, constraint_index);
self.choice_regions.extend(m_c.choice_regions.iter().map(|&r| to_region_vid(r)));
}
}
impl<R1> MemberConstraintSet<'tcx, R1>
where
R1: Copy + Hash + Eq,
{
/// Remap the "member region" key using `map_fn`, producing a new
/// member constraint set. This is used in the NLL code to map from
/// the original `RegionVid` to an scc index. In some cases, we
/// may have multiple `R1` values mapping to the same `R2` key -- that
/// is ok, the two sets will be merged.
crate fn into_mapped<R2>(
self,
mut map_fn: impl FnMut(R1) -> R2,
) -> MemberConstraintSet<'tcx, R2>
where
R2: Copy + Hash + Eq,
{
// We can re-use most of the original data, just tweaking the
// linked list links a bit.
//
// For example if we had two keys `Ra` and `Rb` that both now
// wind up mapped to the same key `S`, we would append the
// linked list for `Ra` onto the end of the linked list for
// `Rb` (or vice versa) -- this basically just requires
// rewriting the final link from one list to point at the other
// other (see `append_list`).
let MemberConstraintSet { first_constraints, mut constraints, choice_regions } = self;
let mut first_constraints2 = FxHashMap::default();
first_constraints2.reserve(first_constraints.len());
for (r1, start1) in first_constraints {
let r2 = map_fn(r1);
if let Some(&start2) = first_constraints2.get(&r2) {
append_list(&mut constraints, start1, start2);
}
first_constraints2.insert(r2, start1);
}
MemberConstraintSet { first_constraints: first_constraints2, constraints, choice_regions }
}
}
impl<R> MemberConstraintSet<'tcx, R>
where
R: Copy + Hash + Eq,
{
crate fn all_indices(&self) -> impl Iterator<Item = NllMemberConstraintIndex> {
self.constraints.indices()
}
/// Iterate down the constraint indices associated with a given
/// peek-region. You can then use `choice_regions` and other
/// methods to access data.
crate fn indices(
&self,
member_region_vid: R,
) -> impl Iterator<Item = NllMemberConstraintIndex> + '_ {
let mut next = self.first_constraints.get(&member_region_vid).cloned();
std::iter::from_fn(move || -> Option<NllMemberConstraintIndex> {
if let Some(current) = next {
next = self.constraints[current].next_constraint;
Some(current)
} else {
None
}
})
}
/// Returns the "choice regions" for a given member
/// constraint. This is the `R1..Rn` from a constraint like:
///
/// ```
/// R0 member of [R1..Rn]
/// ```
crate fn choice_regions(&self, pci: NllMemberConstraintIndex) -> &[ty::RegionVid] {
let NllMemberConstraint { start_index, end_index, .. } = &self.constraints[pci];
&self.choice_regions[*start_index..*end_index]
}
}
impl<'tcx, R> Index<NllMemberConstraintIndex> for MemberConstraintSet<'tcx, R>
where
R: Copy + Eq,
{
type Output = NllMemberConstraint<'tcx>;
fn index(&self, i: NllMemberConstraintIndex) -> &NllMemberConstraint<'tcx> |
}
/// Given a linked list starting at `source_list` and another linked
/// list starting at `target_list`, modify `target_list` so that it is
/// followed by `source_list`.
///
/// Before:
///
/// ```
/// target_list: A -> B -> C -> (None)
/// source_list: D -> E -> F -> (None)
/// ```
///
/// After:
///
/// ```
/// target_list: A -> B -> C -> D -> E -> F -> (None)
/// ```
fn append_list(
constraints: &mut IndexVec<NllMemberConstraintIndex, NllMemberConstraint<'_>>,
target_list: NllMemberConstraintIndex,
source_list: NllMemberConstraintIndex,
) {
let mut p = target_list;
loop {
let mut r = &mut constraints[p];
match r.next_constraint {
Some(q) => p = q,
None => {
r.next_constraint = Some(source_list);
return;
}
}
}
}
| {
&self.constraints[i]
} | identifier_body |
member_constraints.rs | use rustc_data_structures::fx::FxHashMap;
use rustc_index::vec::IndexVec;
use rustc_middle::infer::MemberConstraint;
use rustc_middle::ty::{self, Ty};
use rustc_span::Span;
use std::hash::Hash;
use std::ops::Index;
/// Compactly stores a set of `R0 member of [R1...Rn]` constraints,
/// indexed by the region `R0`.
crate struct MemberConstraintSet<'tcx, R>
where
R: Copy + Eq,
{
/// Stores the first "member" constraint for a given `R0`. This is an
/// index into the `constraints` vector below.
first_constraints: FxHashMap<R, NllMemberConstraintIndex>,
/// Stores the data about each `R0 member of [R1..Rn]` constraint.
/// These are organized into a linked list, so each constraint
/// contains the index of the next constraint with the same `R0`.
constraints: IndexVec<NllMemberConstraintIndex, NllMemberConstraint<'tcx>>,
/// Stores the `R1..Rn` regions for *all* sets. For any given
/// constraint, we keep two indices so that we can pull out a
/// slice.
choice_regions: Vec<ty::RegionVid>,
}
/// Represents a `R0 member of [R1..Rn]` constraint | crate struct NllMemberConstraint<'tcx> {
next_constraint: Option<NllMemberConstraintIndex>,
/// The span where the hidden type was instantiated.
crate definition_span: Span,
/// The hidden type in which `R0` appears. (Used in error reporting.)
crate hidden_ty: Ty<'tcx>,
/// The region `R0`.
crate member_region_vid: ty::RegionVid,
/// Index of `R1` in `choice_regions` vector from `MemberConstraintSet`.
start_index: usize,
/// Index of `Rn` in `choice_regions` vector from `MemberConstraintSet`.
end_index: usize,
}
rustc_index::newtype_index! {
crate struct NllMemberConstraintIndex {
DEBUG_FORMAT = "MemberConstraintIndex({})"
}
}
impl Default for MemberConstraintSet<'tcx, ty::RegionVid> {
fn default() -> Self {
Self {
first_constraints: Default::default(),
constraints: Default::default(),
choice_regions: Default::default(),
}
}
}
impl<'tcx> MemberConstraintSet<'tcx, ty::RegionVid> {
/// Pushes a member constraint into the set.
///
/// The input member constraint `m_c` is in the form produced by
/// the `rustc_middle::infer` code.
///
/// The `to_region_vid` callback fn is used to convert the regions
/// within into `RegionVid` format -- it typically consults the
/// `UniversalRegions` data structure that is known to the caller
/// (but which this code is unaware of).
crate fn push_constraint(
&mut self,
m_c: &MemberConstraint<'tcx>,
mut to_region_vid: impl FnMut(ty::Region<'tcx>) -> ty::RegionVid,
) {
debug!("push_constraint(m_c={:?})", m_c);
let member_region_vid: ty::RegionVid = to_region_vid(m_c.member_region);
let next_constraint = self.first_constraints.get(&member_region_vid).cloned();
let start_index = self.choice_regions.len();
let end_index = start_index + m_c.choice_regions.len();
debug!("push_constraint: member_region_vid={:?}", member_region_vid);
let constraint_index = self.constraints.push(NllMemberConstraint {
next_constraint,
member_region_vid,
definition_span: m_c.definition_span,
hidden_ty: m_c.hidden_ty,
start_index,
end_index,
});
self.first_constraints.insert(member_region_vid, constraint_index);
self.choice_regions.extend(m_c.choice_regions.iter().map(|&r| to_region_vid(r)));
}
}
impl<R1> MemberConstraintSet<'tcx, R1>
where
R1: Copy + Hash + Eq,
{
/// Remap the "member region" key using `map_fn`, producing a new
/// member constraint set. This is used in the NLL code to map from
/// the original `RegionVid` to an scc index. In some cases, we
/// may have multiple `R1` values mapping to the same `R2` key -- that
/// is ok, the two sets will be merged.
crate fn into_mapped<R2>(
self,
mut map_fn: impl FnMut(R1) -> R2,
) -> MemberConstraintSet<'tcx, R2>
where
R2: Copy + Hash + Eq,
{
// We can re-use most of the original data, just tweaking the
// linked list links a bit.
//
// For example if we had two keys `Ra` and `Rb` that both now
// wind up mapped to the same key `S`, we would append the
// linked list for `Ra` onto the end of the linked list for
// `Rb` (or vice versa) -- this basically just requires
// rewriting the final link from one list to point at the other
// other (see `append_list`).
let MemberConstraintSet { first_constraints, mut constraints, choice_regions } = self;
let mut first_constraints2 = FxHashMap::default();
first_constraints2.reserve(first_constraints.len());
for (r1, start1) in first_constraints {
let r2 = map_fn(r1);
if let Some(&start2) = first_constraints2.get(&r2) {
append_list(&mut constraints, start1, start2);
}
first_constraints2.insert(r2, start1);
}
MemberConstraintSet { first_constraints: first_constraints2, constraints, choice_regions }
}
}
impl<R> MemberConstraintSet<'tcx, R>
where
R: Copy + Hash + Eq,
{
crate fn all_indices(&self) -> impl Iterator<Item = NllMemberConstraintIndex> {
self.constraints.indices()
}
/// Iterate down the constraint indices associated with a given
/// peek-region. You can then use `choice_regions` and other
/// methods to access data.
crate fn indices(
&self,
member_region_vid: R,
) -> impl Iterator<Item = NllMemberConstraintIndex> + '_ {
let mut next = self.first_constraints.get(&member_region_vid).cloned();
std::iter::from_fn(move || -> Option<NllMemberConstraintIndex> {
if let Some(current) = next {
next = self.constraints[current].next_constraint;
Some(current)
} else {
None
}
})
}
/// Returns the "choice regions" for a given member
/// constraint. This is the `R1..Rn` from a constraint like:
///
/// ```
/// R0 member of [R1..Rn]
/// ```
crate fn choice_regions(&self, pci: NllMemberConstraintIndex) -> &[ty::RegionVid] {
let NllMemberConstraint { start_index, end_index, .. } = &self.constraints[pci];
&self.choice_regions[*start_index..*end_index]
}
}
impl<'tcx, R> Index<NllMemberConstraintIndex> for MemberConstraintSet<'tcx, R>
where
R: Copy + Eq,
{
type Output = NllMemberConstraint<'tcx>;
fn index(&self, i: NllMemberConstraintIndex) -> &NllMemberConstraint<'tcx> {
&self.constraints[i]
}
}
/// Given a linked list starting at `source_list` and another linked
/// list starting at `target_list`, modify `target_list` so that it is
/// followed by `source_list`.
///
/// Before:
///
/// ```
/// target_list: A -> B -> C -> (None)
/// source_list: D -> E -> F -> (None)
/// ```
///
/// After:
///
/// ```
/// target_list: A -> B -> C -> D -> E -> F -> (None)
/// ```
fn append_list(
constraints: &mut IndexVec<NllMemberConstraintIndex, NllMemberConstraint<'_>>,
target_list: NllMemberConstraintIndex,
source_list: NllMemberConstraintIndex,
) {
let mut p = target_list;
loop {
let mut r = &mut constraints[p];
match r.next_constraint {
Some(q) => p = q,
None => {
r.next_constraint = Some(source_list);
return;
}
}
}
} | random_line_split | |
member_constraints.rs | use rustc_data_structures::fx::FxHashMap;
use rustc_index::vec::IndexVec;
use rustc_middle::infer::MemberConstraint;
use rustc_middle::ty::{self, Ty};
use rustc_span::Span;
use std::hash::Hash;
use std::ops::Index;
/// Compactly stores a set of `R0 member of [R1...Rn]` constraints,
/// indexed by the region `R0`.
crate struct MemberConstraintSet<'tcx, R>
where
R: Copy + Eq,
{
/// Stores the first "member" constraint for a given `R0`. This is an
/// index into the `constraints` vector below.
first_constraints: FxHashMap<R, NllMemberConstraintIndex>,
/// Stores the data about each `R0 member of [R1..Rn]` constraint.
/// These are organized into a linked list, so each constraint
/// contains the index of the next constraint with the same `R0`.
constraints: IndexVec<NllMemberConstraintIndex, NllMemberConstraint<'tcx>>,
/// Stores the `R1..Rn` regions for *all* sets. For any given
/// constraint, we keep two indices so that we can pull out a
/// slice.
choice_regions: Vec<ty::RegionVid>,
}
/// Represents a `R0 member of [R1..Rn]` constraint
crate struct NllMemberConstraint<'tcx> {
next_constraint: Option<NllMemberConstraintIndex>,
/// The span where the hidden type was instantiated.
crate definition_span: Span,
/// The hidden type in which `R0` appears. (Used in error reporting.)
crate hidden_ty: Ty<'tcx>,
/// The region `R0`.
crate member_region_vid: ty::RegionVid,
/// Index of `R1` in `choice_regions` vector from `MemberConstraintSet`.
start_index: usize,
/// Index of `Rn` in `choice_regions` vector from `MemberConstraintSet`.
end_index: usize,
}
rustc_index::newtype_index! {
crate struct NllMemberConstraintIndex {
DEBUG_FORMAT = "MemberConstraintIndex({})"
}
}
impl Default for MemberConstraintSet<'tcx, ty::RegionVid> {
fn default() -> Self {
Self {
first_constraints: Default::default(),
constraints: Default::default(),
choice_regions: Default::default(),
}
}
}
impl<'tcx> MemberConstraintSet<'tcx, ty::RegionVid> {
/// Pushes a member constraint into the set.
///
/// The input member constraint `m_c` is in the form produced by
/// the `rustc_middle::infer` code.
///
/// The `to_region_vid` callback fn is used to convert the regions
/// within into `RegionVid` format -- it typically consults the
/// `UniversalRegions` data structure that is known to the caller
/// (but which this code is unaware of).
crate fn push_constraint(
&mut self,
m_c: &MemberConstraint<'tcx>,
mut to_region_vid: impl FnMut(ty::Region<'tcx>) -> ty::RegionVid,
) {
debug!("push_constraint(m_c={:?})", m_c);
let member_region_vid: ty::RegionVid = to_region_vid(m_c.member_region);
let next_constraint = self.first_constraints.get(&member_region_vid).cloned();
let start_index = self.choice_regions.len();
let end_index = start_index + m_c.choice_regions.len();
debug!("push_constraint: member_region_vid={:?}", member_region_vid);
let constraint_index = self.constraints.push(NllMemberConstraint {
next_constraint,
member_region_vid,
definition_span: m_c.definition_span,
hidden_ty: m_c.hidden_ty,
start_index,
end_index,
});
self.first_constraints.insert(member_region_vid, constraint_index);
self.choice_regions.extend(m_c.choice_regions.iter().map(|&r| to_region_vid(r)));
}
}
impl<R1> MemberConstraintSet<'tcx, R1>
where
R1: Copy + Hash + Eq,
{
/// Remap the "member region" key using `map_fn`, producing a new
/// member constraint set. This is used in the NLL code to map from
/// the original `RegionVid` to an scc index. In some cases, we
/// may have multiple `R1` values mapping to the same `R2` key -- that
/// is ok, the two sets will be merged.
crate fn into_mapped<R2>(
self,
mut map_fn: impl FnMut(R1) -> R2,
) -> MemberConstraintSet<'tcx, R2>
where
R2: Copy + Hash + Eq,
{
// We can re-use most of the original data, just tweaking the
// linked list links a bit.
//
// For example if we had two keys `Ra` and `Rb` that both now
// wind up mapped to the same key `S`, we would append the
// linked list for `Ra` onto the end of the linked list for
// `Rb` (or vice versa) -- this basically just requires
// rewriting the final link from one list to point at the other
// other (see `append_list`).
let MemberConstraintSet { first_constraints, mut constraints, choice_regions } = self;
let mut first_constraints2 = FxHashMap::default();
first_constraints2.reserve(first_constraints.len());
for (r1, start1) in first_constraints {
let r2 = map_fn(r1);
if let Some(&start2) = first_constraints2.get(&r2) {
append_list(&mut constraints, start1, start2);
}
first_constraints2.insert(r2, start1);
}
MemberConstraintSet { first_constraints: first_constraints2, constraints, choice_regions }
}
}
impl<R> MemberConstraintSet<'tcx, R>
where
R: Copy + Hash + Eq,
{
crate fn all_indices(&self) -> impl Iterator<Item = NllMemberConstraintIndex> {
self.constraints.indices()
}
/// Iterate down the constraint indices associated with a given
/// peek-region. You can then use `choice_regions` and other
/// methods to access data.
crate fn indices(
&self,
member_region_vid: R,
) -> impl Iterator<Item = NllMemberConstraintIndex> + '_ {
let mut next = self.first_constraints.get(&member_region_vid).cloned();
std::iter::from_fn(move || -> Option<NllMemberConstraintIndex> {
if let Some(current) = next {
next = self.constraints[current].next_constraint;
Some(current)
} else {
None
}
})
}
/// Returns the "choice regions" for a given member
/// constraint. This is the `R1..Rn` from a constraint like:
///
/// ```
/// R0 member of [R1..Rn]
/// ```
crate fn | (&self, pci: NllMemberConstraintIndex) -> &[ty::RegionVid] {
let NllMemberConstraint { start_index, end_index, .. } = &self.constraints[pci];
&self.choice_regions[*start_index..*end_index]
}
}
impl<'tcx, R> Index<NllMemberConstraintIndex> for MemberConstraintSet<'tcx, R>
where
R: Copy + Eq,
{
type Output = NllMemberConstraint<'tcx>;
fn index(&self, i: NllMemberConstraintIndex) -> &NllMemberConstraint<'tcx> {
&self.constraints[i]
}
}
/// Given a linked list starting at `source_list` and another linked
/// list starting at `target_list`, modify `target_list` so that it is
/// followed by `source_list`.
///
/// Before:
///
/// ```
/// target_list: A -> B -> C -> (None)
/// source_list: D -> E -> F -> (None)
/// ```
///
/// After:
///
/// ```
/// target_list: A -> B -> C -> D -> E -> F -> (None)
/// ```
fn append_list(
constraints: &mut IndexVec<NllMemberConstraintIndex, NllMemberConstraint<'_>>,
target_list: NllMemberConstraintIndex,
source_list: NllMemberConstraintIndex,
) {
let mut p = target_list;
loop {
let mut r = &mut constraints[p];
match r.next_constraint {
Some(q) => p = q,
None => {
r.next_constraint = Some(source_list);
return;
}
}
}
}
| choice_regions | identifier_name |
keybindingParser.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ChordKeybinding, KeyCodeUtils, Keybinding, SimpleKeybinding } from 'vs/base/common/keyCodes';
import { OperatingSystem } from 'vs/base/common/platform';
import { ScanCodeBinding, ScanCodeUtils } from 'vs/base/common/scanCode';
export class KeybindingParser {
private static _readModifiers(input: string) {
input = input.toLowerCase().trim();
let ctrl = false;
let shift = false;
let alt = false;
let meta = false;
let matchedModifier: boolean;
do | while (matchedModifier);
let key: string;
const firstSpaceIdx = input.indexOf(' ');
if (firstSpaceIdx > 0) {
key = input.substring(0, firstSpaceIdx);
input = input.substring(firstSpaceIdx);
} else {
key = input;
input = '';
}
return {
remains: input,
ctrl,
shift,
alt,
meta,
key
};
}
private static parseSimpleKeybinding(input: string): [SimpleKeybinding, string] {
const mods = this._readModifiers(input);
const keyCode = KeyCodeUtils.fromUserSettings(mods.key);
return [new SimpleKeybinding(mods.ctrl, mods.shift, mods.alt, mods.meta, keyCode), mods.remains];
}
public static parseKeybinding(input: string, OS: OperatingSystem): Keybinding | null {
if (!input) {
return null;
}
const parts: SimpleKeybinding[] = [];
let part: SimpleKeybinding;
do {
[part, input] = this.parseSimpleKeybinding(input);
parts.push(part);
} while (input.length > 0);
return new ChordKeybinding(parts);
}
private static parseSimpleUserBinding(input: string): [SimpleKeybinding | ScanCodeBinding, string] {
const mods = this._readModifiers(input);
const scanCodeMatch = mods.key.match(/^\[([^\]]+)\]$/);
if (scanCodeMatch) {
const strScanCode = scanCodeMatch[1];
const scanCode = ScanCodeUtils.lowerCaseToEnum(strScanCode);
return [new ScanCodeBinding(mods.ctrl, mods.shift, mods.alt, mods.meta, scanCode), mods.remains];
}
const keyCode = KeyCodeUtils.fromUserSettings(mods.key);
return [new SimpleKeybinding(mods.ctrl, mods.shift, mods.alt, mods.meta, keyCode), mods.remains];
}
static parseUserBinding(input: string): (SimpleKeybinding | ScanCodeBinding)[] {
if (!input) {
return [];
}
const parts: (SimpleKeybinding | ScanCodeBinding)[] = [];
let part: SimpleKeybinding | ScanCodeBinding;
while (input.length > 0) {
[part, input] = this.parseSimpleUserBinding(input);
parts.push(part);
}
return parts;
}
} | {
matchedModifier = false;
if (/^ctrl(\+|\-)/.test(input)) {
ctrl = true;
input = input.substr('ctrl-'.length);
matchedModifier = true;
}
if (/^shift(\+|\-)/.test(input)) {
shift = true;
input = input.substr('shift-'.length);
matchedModifier = true;
}
if (/^alt(\+|\-)/.test(input)) {
alt = true;
input = input.substr('alt-'.length);
matchedModifier = true;
}
if (/^meta(\+|\-)/.test(input)) {
meta = true;
input = input.substr('meta-'.length);
matchedModifier = true;
}
if (/^win(\+|\-)/.test(input)) {
meta = true;
input = input.substr('win-'.length);
matchedModifier = true;
}
if (/^cmd(\+|\-)/.test(input)) {
meta = true;
input = input.substr('cmd-'.length);
matchedModifier = true;
}
} | conditional_block |
keybindingParser.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ChordKeybinding, KeyCodeUtils, Keybinding, SimpleKeybinding } from 'vs/base/common/keyCodes';
import { OperatingSystem } from 'vs/base/common/platform';
import { ScanCodeBinding, ScanCodeUtils } from 'vs/base/common/scanCode';
export class KeybindingParser {
private static _readModifiers(input: string) {
input = input.toLowerCase().trim();
let ctrl = false;
let shift = false;
let alt = false;
let meta = false;
let matchedModifier: boolean;
do {
matchedModifier = false;
if (/^ctrl(\+|\-)/.test(input)) {
ctrl = true;
input = input.substr('ctrl-'.length);
matchedModifier = true;
}
if (/^shift(\+|\-)/.test(input)) {
shift = true;
input = input.substr('shift-'.length);
matchedModifier = true;
}
if (/^alt(\+|\-)/.test(input)) {
alt = true;
input = input.substr('alt-'.length);
matchedModifier = true;
}
if (/^meta(\+|\-)/.test(input)) {
meta = true;
input = input.substr('meta-'.length);
matchedModifier = true;
}
if (/^win(\+|\-)/.test(input)) {
meta = true;
input = input.substr('win-'.length);
matchedModifier = true;
}
if (/^cmd(\+|\-)/.test(input)) {
meta = true;
input = input.substr('cmd-'.length);
matchedModifier = true;
}
} while (matchedModifier);
let key: string;
const firstSpaceIdx = input.indexOf(' ');
if (firstSpaceIdx > 0) {
key = input.substring(0, firstSpaceIdx);
input = input.substring(firstSpaceIdx);
} else {
key = input;
input = '';
}
return {
remains: input,
ctrl,
shift,
alt,
meta,
key
};
}
private static parseSimpleKeybinding(input: string): [SimpleKeybinding, string] {
const mods = this._readModifiers(input);
const keyCode = KeyCodeUtils.fromUserSettings(mods.key);
return [new SimpleKeybinding(mods.ctrl, mods.shift, mods.alt, mods.meta, keyCode), mods.remains];
}
public static parseKeybinding(input: string, OS: OperatingSystem): Keybinding | null {
if (!input) {
return null;
}
const parts: SimpleKeybinding[] = [];
let part: SimpleKeybinding;
do {
[part, input] = this.parseSimpleKeybinding(input);
parts.push(part);
} while (input.length > 0);
return new ChordKeybinding(parts);
}
private static parseSimpleUserBinding(input: string): [SimpleKeybinding | ScanCodeBinding, string] |
static parseUserBinding(input: string): (SimpleKeybinding | ScanCodeBinding)[] {
if (!input) {
return [];
}
const parts: (SimpleKeybinding | ScanCodeBinding)[] = [];
let part: SimpleKeybinding | ScanCodeBinding;
while (input.length > 0) {
[part, input] = this.parseSimpleUserBinding(input);
parts.push(part);
}
return parts;
}
} | {
const mods = this._readModifiers(input);
const scanCodeMatch = mods.key.match(/^\[([^\]]+)\]$/);
if (scanCodeMatch) {
const strScanCode = scanCodeMatch[1];
const scanCode = ScanCodeUtils.lowerCaseToEnum(strScanCode);
return [new ScanCodeBinding(mods.ctrl, mods.shift, mods.alt, mods.meta, scanCode), mods.remains];
}
const keyCode = KeyCodeUtils.fromUserSettings(mods.key);
return [new SimpleKeybinding(mods.ctrl, mods.shift, mods.alt, mods.meta, keyCode), mods.remains];
} | identifier_body |
keybindingParser.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ChordKeybinding, KeyCodeUtils, Keybinding, SimpleKeybinding } from 'vs/base/common/keyCodes';
import { OperatingSystem } from 'vs/base/common/platform';
import { ScanCodeBinding, ScanCodeUtils } from 'vs/base/common/scanCode';
export class KeybindingParser {
private static _readModifiers(input: string) {
input = input.toLowerCase().trim();
let ctrl = false;
let shift = false;
let alt = false;
let meta = false;
let matchedModifier: boolean;
do {
matchedModifier = false;
if (/^ctrl(\+|\-)/.test(input)) {
ctrl = true;
input = input.substr('ctrl-'.length);
matchedModifier = true;
}
if (/^shift(\+|\-)/.test(input)) {
shift = true;
input = input.substr('shift-'.length);
matchedModifier = true;
}
if (/^alt(\+|\-)/.test(input)) {
alt = true;
input = input.substr('alt-'.length);
matchedModifier = true;
}
if (/^meta(\+|\-)/.test(input)) {
meta = true;
input = input.substr('meta-'.length);
matchedModifier = true;
}
if (/^win(\+|\-)/.test(input)) {
meta = true;
input = input.substr('win-'.length);
matchedModifier = true;
}
if (/^cmd(\+|\-)/.test(input)) {
meta = true;
input = input.substr('cmd-'.length);
matchedModifier = true;
}
} while (matchedModifier);
let key: string;
const firstSpaceIdx = input.indexOf(' ');
if (firstSpaceIdx > 0) {
key = input.substring(0, firstSpaceIdx);
input = input.substring(firstSpaceIdx);
} else {
key = input;
input = '';
}
return {
remains: input,
ctrl,
shift,
alt,
meta,
key
};
}
private static parseSimpleKeybinding(input: string): [SimpleKeybinding, string] {
const mods = this._readModifiers(input);
const keyCode = KeyCodeUtils.fromUserSettings(mods.key);
return [new SimpleKeybinding(mods.ctrl, mods.shift, mods.alt, mods.meta, keyCode), mods.remains];
}
public static parseKeybinding(input: string, OS: OperatingSystem): Keybinding | null {
if (!input) {
return null;
}
const parts: SimpleKeybinding[] = [];
let part: SimpleKeybinding;
do {
[part, input] = this.parseSimpleKeybinding(input);
parts.push(part);
} while (input.length > 0);
return new ChordKeybinding(parts);
}
private static parseSimpleUserBinding(input: string): [SimpleKeybinding | ScanCodeBinding, string] { | const scanCodeMatch = mods.key.match(/^\[([^\]]+)\]$/);
if (scanCodeMatch) {
const strScanCode = scanCodeMatch[1];
const scanCode = ScanCodeUtils.lowerCaseToEnum(strScanCode);
return [new ScanCodeBinding(mods.ctrl, mods.shift, mods.alt, mods.meta, scanCode), mods.remains];
}
const keyCode = KeyCodeUtils.fromUserSettings(mods.key);
return [new SimpleKeybinding(mods.ctrl, mods.shift, mods.alt, mods.meta, keyCode), mods.remains];
}
static parseUserBinding(input: string): (SimpleKeybinding | ScanCodeBinding)[] {
if (!input) {
return [];
}
const parts: (SimpleKeybinding | ScanCodeBinding)[] = [];
let part: SimpleKeybinding | ScanCodeBinding;
while (input.length > 0) {
[part, input] = this.parseSimpleUserBinding(input);
parts.push(part);
}
return parts;
}
} | const mods = this._readModifiers(input); | random_line_split |
keybindingParser.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ChordKeybinding, KeyCodeUtils, Keybinding, SimpleKeybinding } from 'vs/base/common/keyCodes';
import { OperatingSystem } from 'vs/base/common/platform';
import { ScanCodeBinding, ScanCodeUtils } from 'vs/base/common/scanCode';
export class KeybindingParser {
private static _readModifiers(input: string) {
input = input.toLowerCase().trim();
let ctrl = false;
let shift = false;
let alt = false;
let meta = false;
let matchedModifier: boolean;
do {
matchedModifier = false;
if (/^ctrl(\+|\-)/.test(input)) {
ctrl = true;
input = input.substr('ctrl-'.length);
matchedModifier = true;
}
if (/^shift(\+|\-)/.test(input)) {
shift = true;
input = input.substr('shift-'.length);
matchedModifier = true;
}
if (/^alt(\+|\-)/.test(input)) {
alt = true;
input = input.substr('alt-'.length);
matchedModifier = true;
}
if (/^meta(\+|\-)/.test(input)) {
meta = true;
input = input.substr('meta-'.length);
matchedModifier = true;
}
if (/^win(\+|\-)/.test(input)) {
meta = true;
input = input.substr('win-'.length);
matchedModifier = true;
}
if (/^cmd(\+|\-)/.test(input)) {
meta = true;
input = input.substr('cmd-'.length);
matchedModifier = true;
}
} while (matchedModifier);
let key: string;
const firstSpaceIdx = input.indexOf(' ');
if (firstSpaceIdx > 0) {
key = input.substring(0, firstSpaceIdx);
input = input.substring(firstSpaceIdx);
} else {
key = input;
input = '';
}
return {
remains: input,
ctrl,
shift,
alt,
meta,
key
};
}
private static parseSimpleKeybinding(input: string): [SimpleKeybinding, string] {
const mods = this._readModifiers(input);
const keyCode = KeyCodeUtils.fromUserSettings(mods.key);
return [new SimpleKeybinding(mods.ctrl, mods.shift, mods.alt, mods.meta, keyCode), mods.remains];
}
public static parseKeybinding(input: string, OS: OperatingSystem): Keybinding | null {
if (!input) {
return null;
}
const parts: SimpleKeybinding[] = [];
let part: SimpleKeybinding;
do {
[part, input] = this.parseSimpleKeybinding(input);
parts.push(part);
} while (input.length > 0);
return new ChordKeybinding(parts);
}
private static parseSimpleUserBinding(input: string): [SimpleKeybinding | ScanCodeBinding, string] {
const mods = this._readModifiers(input);
const scanCodeMatch = mods.key.match(/^\[([^\]]+)\]$/);
if (scanCodeMatch) {
const strScanCode = scanCodeMatch[1];
const scanCode = ScanCodeUtils.lowerCaseToEnum(strScanCode);
return [new ScanCodeBinding(mods.ctrl, mods.shift, mods.alt, mods.meta, scanCode), mods.remains];
}
const keyCode = KeyCodeUtils.fromUserSettings(mods.key);
return [new SimpleKeybinding(mods.ctrl, mods.shift, mods.alt, mods.meta, keyCode), mods.remains];
}
static | (input: string): (SimpleKeybinding | ScanCodeBinding)[] {
if (!input) {
return [];
}
const parts: (SimpleKeybinding | ScanCodeBinding)[] = [];
let part: SimpleKeybinding | ScanCodeBinding;
while (input.length > 0) {
[part, input] = this.parseSimpleUserBinding(input);
parts.push(part);
}
return parts;
}
} | parseUserBinding | identifier_name |
mount.rs | use libc::{c_ulong, c_int};
use libc;
use {Errno, Result, NixPath};
bitflags!( | const MS_NOSUID = libc::MS_NOSUID; // Ignore suid and sgid bits
const MS_NODEV = libc::MS_NODEV; // Disallow access to device special files
const MS_NOEXEC = libc::MS_NOEXEC; // Disallow program execution
const MS_SYNCHRONOUS = libc::MS_SYNCHRONOUS; // Writes are synced at once
const MS_REMOUNT = libc::MS_REMOUNT; // Alter flags of a mounted FS
const MS_MANDLOCK = libc::MS_MANDLOCK; // Allow mandatory locks on a FS
const MS_DIRSYNC = libc::MS_DIRSYNC; // Directory modifications are synchronous
const MS_NOATIME = libc::MS_NOATIME; // Do not update access times
const MS_NODIRATIME = libc::MS_NODIRATIME; // Do not update directory access times
const MS_BIND = libc::MS_BIND; // Linux 2.4.0 - Bind directory at different place
const MS_MOVE = libc::MS_MOVE;
const MS_REC = libc::MS_REC;
const MS_VERBOSE = 1 << 15; // Deprecated
const MS_SILENT = libc::MS_SILENT;
const MS_POSIXACL = libc::MS_POSIXACL;
const MS_UNBINDABLE = libc::MS_UNBINDABLE;
const MS_PRIVATE = libc::MS_PRIVATE;
const MS_SLAVE = libc::MS_SLAVE;
const MS_SHARED = libc::MS_SHARED;
const MS_RELATIME = libc::MS_RELATIME;
const MS_KERNMOUNT = libc::MS_KERNMOUNT;
const MS_I_VERSION = libc::MS_I_VERSION;
const MS_STRICTATIME = libc::MS_STRICTATIME;
const MS_NOSEC = 1 << 28;
const MS_BORN = 1 << 29;
const MS_ACTIVE = libc::MS_ACTIVE;
const MS_NOUSER = libc::MS_NOUSER;
const MS_RMT_MASK = libc::MS_RMT_MASK;
const MS_MGC_VAL = libc::MS_MGC_VAL;
const MS_MGC_MSK = libc::MS_MGC_MSK;
}
);
libc_bitflags!(
pub flags MntFlags: c_int {
MNT_FORCE,
MNT_DETACH,
MNT_EXPIRE,
}
);
pub fn mount<P1: ?Sized + NixPath, P2: ?Sized + NixPath, P3: ?Sized + NixPath, P4: ?Sized + NixPath>(
source: Option<&P1>,
target: &P2,
fstype: Option<&P3>,
flags: MsFlags,
data: Option<&P4>) -> Result<()> {
use libc;
let res = try!(try!(try!(try!(
source.with_nix_path(|source| {
target.with_nix_path(|target| {
fstype.with_nix_path(|fstype| {
data.with_nix_path(|data| {
unsafe {
libc::mount(source.as_ptr(),
target.as_ptr(),
fstype.as_ptr(),
flags.bits,
data.as_ptr() as *const libc::c_void)
}
})
})
})
})))));
Errno::result(res).map(drop)
}
pub fn umount<P: ?Sized + NixPath>(target: &P) -> Result<()> {
let res = try!(target.with_nix_path(|cstr| {
unsafe { libc::umount(cstr.as_ptr()) }
}));
Errno::result(res).map(drop)
}
pub fn umount2<P: ?Sized + NixPath>(target: &P, flags: MntFlags) -> Result<()> {
let res = try!(target.with_nix_path(|cstr| {
unsafe { libc::umount2(cstr.as_ptr(), flags.bits) }
}));
Errno::result(res).map(drop)
} | pub struct MsFlags: c_ulong {
const MS_RDONLY = libc::MS_RDONLY; // Mount read-only | random_line_split |
mount.rs | use libc::{c_ulong, c_int};
use libc;
use {Errno, Result, NixPath};
bitflags!(
pub struct MsFlags: c_ulong {
const MS_RDONLY = libc::MS_RDONLY; // Mount read-only
const MS_NOSUID = libc::MS_NOSUID; // Ignore suid and sgid bits
const MS_NODEV = libc::MS_NODEV; // Disallow access to device special files
const MS_NOEXEC = libc::MS_NOEXEC; // Disallow program execution
const MS_SYNCHRONOUS = libc::MS_SYNCHRONOUS; // Writes are synced at once
const MS_REMOUNT = libc::MS_REMOUNT; // Alter flags of a mounted FS
const MS_MANDLOCK = libc::MS_MANDLOCK; // Allow mandatory locks on a FS
const MS_DIRSYNC = libc::MS_DIRSYNC; // Directory modifications are synchronous
const MS_NOATIME = libc::MS_NOATIME; // Do not update access times
const MS_NODIRATIME = libc::MS_NODIRATIME; // Do not update directory access times
const MS_BIND = libc::MS_BIND; // Linux 2.4.0 - Bind directory at different place
const MS_MOVE = libc::MS_MOVE;
const MS_REC = libc::MS_REC;
const MS_VERBOSE = 1 << 15; // Deprecated
const MS_SILENT = libc::MS_SILENT;
const MS_POSIXACL = libc::MS_POSIXACL;
const MS_UNBINDABLE = libc::MS_UNBINDABLE;
const MS_PRIVATE = libc::MS_PRIVATE;
const MS_SLAVE = libc::MS_SLAVE;
const MS_SHARED = libc::MS_SHARED;
const MS_RELATIME = libc::MS_RELATIME;
const MS_KERNMOUNT = libc::MS_KERNMOUNT;
const MS_I_VERSION = libc::MS_I_VERSION;
const MS_STRICTATIME = libc::MS_STRICTATIME;
const MS_NOSEC = 1 << 28;
const MS_BORN = 1 << 29;
const MS_ACTIVE = libc::MS_ACTIVE;
const MS_NOUSER = libc::MS_NOUSER;
const MS_RMT_MASK = libc::MS_RMT_MASK;
const MS_MGC_VAL = libc::MS_MGC_VAL;
const MS_MGC_MSK = libc::MS_MGC_MSK;
}
);
libc_bitflags!(
pub flags MntFlags: c_int {
MNT_FORCE,
MNT_DETACH,
MNT_EXPIRE,
}
);
pub fn mount<P1: ?Sized + NixPath, P2: ?Sized + NixPath, P3: ?Sized + NixPath, P4: ?Sized + NixPath>(
source: Option<&P1>,
target: &P2,
fstype: Option<&P3>,
flags: MsFlags,
data: Option<&P4>) -> Result<()> {
use libc;
let res = try!(try!(try!(try!(
source.with_nix_path(|source| {
target.with_nix_path(|target| {
fstype.with_nix_path(|fstype| {
data.with_nix_path(|data| {
unsafe {
libc::mount(source.as_ptr(),
target.as_ptr(),
fstype.as_ptr(),
flags.bits,
data.as_ptr() as *const libc::c_void)
}
})
})
})
})))));
Errno::result(res).map(drop)
}
pub fn umount<P: ?Sized + NixPath>(target: &P) -> Result<()> |
pub fn umount2<P: ?Sized + NixPath>(target: &P, flags: MntFlags) -> Result<()> {
let res = try!(target.with_nix_path(|cstr| {
unsafe { libc::umount2(cstr.as_ptr(), flags.bits) }
}));
Errno::result(res).map(drop)
}
| {
let res = try!(target.with_nix_path(|cstr| {
unsafe { libc::umount(cstr.as_ptr()) }
}));
Errno::result(res).map(drop)
} | identifier_body |
mount.rs | use libc::{c_ulong, c_int};
use libc;
use {Errno, Result, NixPath};
bitflags!(
pub struct MsFlags: c_ulong {
const MS_RDONLY = libc::MS_RDONLY; // Mount read-only
const MS_NOSUID = libc::MS_NOSUID; // Ignore suid and sgid bits
const MS_NODEV = libc::MS_NODEV; // Disallow access to device special files
const MS_NOEXEC = libc::MS_NOEXEC; // Disallow program execution
const MS_SYNCHRONOUS = libc::MS_SYNCHRONOUS; // Writes are synced at once
const MS_REMOUNT = libc::MS_REMOUNT; // Alter flags of a mounted FS
const MS_MANDLOCK = libc::MS_MANDLOCK; // Allow mandatory locks on a FS
const MS_DIRSYNC = libc::MS_DIRSYNC; // Directory modifications are synchronous
const MS_NOATIME = libc::MS_NOATIME; // Do not update access times
const MS_NODIRATIME = libc::MS_NODIRATIME; // Do not update directory access times
const MS_BIND = libc::MS_BIND; // Linux 2.4.0 - Bind directory at different place
const MS_MOVE = libc::MS_MOVE;
const MS_REC = libc::MS_REC;
const MS_VERBOSE = 1 << 15; // Deprecated
const MS_SILENT = libc::MS_SILENT;
const MS_POSIXACL = libc::MS_POSIXACL;
const MS_UNBINDABLE = libc::MS_UNBINDABLE;
const MS_PRIVATE = libc::MS_PRIVATE;
const MS_SLAVE = libc::MS_SLAVE;
const MS_SHARED = libc::MS_SHARED;
const MS_RELATIME = libc::MS_RELATIME;
const MS_KERNMOUNT = libc::MS_KERNMOUNT;
const MS_I_VERSION = libc::MS_I_VERSION;
const MS_STRICTATIME = libc::MS_STRICTATIME;
const MS_NOSEC = 1 << 28;
const MS_BORN = 1 << 29;
const MS_ACTIVE = libc::MS_ACTIVE;
const MS_NOUSER = libc::MS_NOUSER;
const MS_RMT_MASK = libc::MS_RMT_MASK;
const MS_MGC_VAL = libc::MS_MGC_VAL;
const MS_MGC_MSK = libc::MS_MGC_MSK;
}
);
libc_bitflags!(
pub flags MntFlags: c_int {
MNT_FORCE,
MNT_DETACH,
MNT_EXPIRE,
}
);
pub fn mount<P1: ?Sized + NixPath, P2: ?Sized + NixPath, P3: ?Sized + NixPath, P4: ?Sized + NixPath>(
source: Option<&P1>,
target: &P2,
fstype: Option<&P3>,
flags: MsFlags,
data: Option<&P4>) -> Result<()> {
use libc;
let res = try!(try!(try!(try!(
source.with_nix_path(|source| {
target.with_nix_path(|target| {
fstype.with_nix_path(|fstype| {
data.with_nix_path(|data| {
unsafe {
libc::mount(source.as_ptr(),
target.as_ptr(),
fstype.as_ptr(),
flags.bits,
data.as_ptr() as *const libc::c_void)
}
})
})
})
})))));
Errno::result(res).map(drop)
}
pub fn | <P: ?Sized + NixPath>(target: &P) -> Result<()> {
let res = try!(target.with_nix_path(|cstr| {
unsafe { libc::umount(cstr.as_ptr()) }
}));
Errno::result(res).map(drop)
}
pub fn umount2<P: ?Sized + NixPath>(target: &P, flags: MntFlags) -> Result<()> {
let res = try!(target.with_nix_path(|cstr| {
unsafe { libc::umount2(cstr.as_ptr(), flags.bits) }
}));
Errno::result(res).map(drop)
}
| umount | identifier_name |
types.js | 'use strict'; | * Visible page viewport
*
* @param {number} scrollX X scroll offset in CSS pixels.
* @param {number} scrollY Y scroll offset in CSS pixels.
* @param {number} contentsWidth Contents width in CSS pixels.
* @param {number} contentsHeight Contents height in CSS pixels.
* @param {number} pageScaleFactor Page scale factor.
* @param {number} minimumPageScaleFactor Minimum page scale factor.
* @param {number} maximumPageScaleFactor Maximum page scale factor.
*/
exports.Viewport =
function Viewport(props) {
this.scrollX = props.scrollX;
this.scrollY = props.scrollY;
this.contentsWidth = props.contentsWidth;
this.contentsHeight = props.contentsHeight;
this.pageScaleFactor = props.pageScaleFactor;
this.minimumPageScaleFactor = props.minimumPageScaleFactor;
this.maximumPageScaleFactor = props.maximumPageScaleFactor;
}; | // This file is auto-generated using scripts/doc-sync.js
/** | random_line_split |
do_release.py | #!/usr/bin/env python
"""do_release.py
Usage:
do_release.py [--force] [CALICO_DOCKER_VERSION CALICO_VERSION LIBCALICO_VERSION LIBNETWORK_VERSION]
Options:
-h --help Show this screen.
"""
import subprocess
import utils
import re
from docopt import docopt
from utils import print_paragraph as para
from utils import print_user_actions as actions
from utils import print_bullet as bullet
from utils import print_next as next
from utils import print_warning as warning
# The candidate version replacement performs most of the required version
# replacements, but replaces build artifact URLs with a dynamic URL that
# can return an artifact for an arbitrary branch. This is replaced with the
# GitHub release artifact just before the release is actually cut.
CANDIDATE_VERSION_REPLACE = [
(re.compile(r'__version__\s*=\s*".*"'),
'__version__ = "{version-no-v}"'),
(re.compile(r'\*\*release\*\*'),
'{version}'),
(re.compile('http://www\.projectcalico\.org/latest/calicoctl'),
'http://www.projectcalico.org/builds/calicoctl?circleci-branch={version}-candidate'),
(re.compile(r'git\+https://github\.com/projectcalico/calico\.git'),
'git+https://github.com/projectcalico/calico.git@{calico-version}'),
(re.compile(r'git\+https://github\.com/projectcalico/libcalico\.git'),
'git+https://github.com/projectcalico/libcalico.git@{libcalico-version}'),
(re.compile(r'calico_docker_ver\s*=\s*"latest"'),
'calico_docker_ver = "{version}"'),
(re.compile('calico_node_ver\s*=\s*"latest"'),
'calico_node_ver = "{version}"'),
(re.compile('calico/node:latest'),
'calico/node:{version}'),
(re.compile('calico/node-libnetwork:latest'),
'calico/node-libnetwork:{libnetwork-version}'),
(re.compile('calico_libnetwork_ver\s*=\s*"latest"'),
'calico_libnetwork_ver = "{libnetwork-version}"')
]
# The final version replace handles migrating the dynamic (temporary) URLs to
# point to the Git archives.
FINAL_VERSION_REPLACE = [
(re.compile('http://www\.projectcalico\.org/latest/calicoctl\?circleci\-branch=.*\-candidate'),
'https://github.com/projectcalico/calico-docker/releases/download/{version}/calicoctl'),
]
# Version replacement for the master branch. We just need to update the
# python version string and the comments.
MASTER_VERSION_REPLACE = [
(re.compile(r'__version__\s*=\s*".*"'),
'__version__ = "{version-no-v}-dev"'),
(re.compile(r'https://github\.com/projectcalico/calico\-docker/blob/.*/README\.md'),
'https://github.com/projectcalico/calico-docker/blob/{version}/README.md')
]
# Load the globally required release data.
release_data = utils.load_release_data()
# ============== Define the release steps. ===============
def start_release():
"""
Start the release process, asking user for version information.
:return:
"""
para("Your git repository should be checked out to the correct revision "
"that you want to cut a release with. This is usually the HEAD of "
"the master branch.")
utils.check_or_exit("Are you currently on the correct revision")
old_version = utils.get_calicoctl_version()
para("Current version is: %s" % old_version)
new_version = arguments["CALICO_DOCKER_VERSION"]
if not new_version:
while True:
new_version = raw_input("New calicoctl version?: ")
release_type = utils.check_version_increment(old_version, new_version)
if release_type:
para("Release type: %s" % release_type)
break
calico_version = arguments["CALICO_VERSION"]
libcalico_version = arguments["LIBCALICO_VERSION"]
libnetwork_version = arguments["LIBNETWORK_VERSION"]
if not (calico_version and libcalico_version and libnetwork_version):
para("To pin the calico libraries used by calico-docker, please specify "
"the name of the requested versions as they appear in the GitHub "
"releases.")
calico_version = \
utils.get_github_library_version("calico (felix)",
"https://github.com/projectcalico/calico")
libcalico_version = \
utils.get_github_library_version("libcalico",
"https://github.com/projectcalico/libcalico")
libnetwork_version = \
utils.get_github_library_version("libnetwork-plugin",
"https://github.com/projectcalico/libnetwork-plugin")
release_data["versions"] = {"version": new_version,
"version-no-v": new_version[1:],
"calico-version": calico_version,
"libcalico-version": libcalico_version,
"libnetwork-version": libnetwork_version}
bullet("Creating a candidate release branch called "
"'%s-candidate'." % new_version)
if arguments['--force']:
subprocess.call("git branch -D %s-candidate" % new_version, shell=True)
subprocess.call("git checkout -b %s-candidate" % new_version, shell=True)
# Update the code tree
utils.update_files(CANDIDATE_VERSION_REPLACE, release_data["versions"])
new_version = release_data["versions"]["version"]
para("The codebase has been updated to reference the release candidate "
"artifacts.")
bullet("Adding, committing and pushing the updated files to "
"origin/%s-candidate" % new_version)
subprocess.call("git add --all", shell=True)
subprocess.call('git commit -m "Update version strings for release '
'candidate %s"' % new_version, shell=True)
if arguments['--force']:
subprocess.call("git push -f origin %s-candidate" % new_version, shell=True)
else:
subprocess.call("git push origin %s-candidate" % new_version, shell=True)
actions()
bullet("Create a DockerHub release called '%s'" % new_version)
bullet("Monitor the semaphore, CircleCI and Docker builds for this branch "
"until all have successfully completed. Fix any issues with the "
"build.")
bullet("Run through a subset of the demonstrations. When running the "
"vagrant instructions, make sure you are using the candidate "
"branch (e.g. git checkout %s-candidate):" % new_version)
bullet("Ubuntu libnetwork", level=1)
bullet("CoreOS default networking", level=1)
para("Follow the URL below to view the correct demonstration instructions "
"for this release candidate.")
bullet("https://github.com/projectcalico/calico-docker/tree/%s-candidate" % new_version)
next("Once you have completed the testing, re-run the script.")
def cut_release():
"""
The candidate branch has been tested, so cut the actual release.
"""
utils.check_or_exit("Have you successfully tested your release candidate")
# Update the code tree once more to set the final GitHub URLs
utils.update_files(FINAL_VERSION_REPLACE, release_data["versions"])
new_version = release_data["versions"]["version"]
para("The codebase has been updated to reference the GitHub release "
"artifacts.")
actions()
bullet("Add, commit and push the updated files to "
"origin/%s-candidate" % new_version)
bullet("git add --all", level=1)
bullet('git commit -m "Update version strings for release '
'%s"' % new_version, level=1)
bullet("git push origin %s-candidate" % new_version, level=1)
bullet("[ideally squash the two commits into one]", level=1)
bullet("Monitor the semaphore, CircleCI and Docker builds for this branch "
"until all have successfully completed. Fix any issues with the "
"build.")
bullet("Create a Pull Request and review the changes")
bullet("Create a GitHub release called '%s'" % new_version)
para("Attach the calicoctl binary to the release. It can be downloaded "
"from the following URL:")
bullet("http://www.projectcalico.org/builds/calicoctl?circleci-branch=%s-candidate" % new_version)
para("Once the release has been created on GitHub, perform a final test "
"of the release:")
bullet("Run through a subset of the demonstrations. When running the "
"vagrant instructions, make sure you are using the tagged release "
"(e.g. git checkout tags/%s):" % new_version)
bullet("CoreOS libnetwork", level=1)
bullet("Ubuntu default networking", level=1)
next("Once you have completed the testing, re-run the script.")
def change_to_master():
"""
Version has been releases and tested.
"""
utils.check_or_exit("Have you successfully tested the release")
new_version = release_data["versions"]["version"]
para("The release is now complete. We now need to update the master "
"branch and do some general branch and build tidyup.")
actions()
bullet("Delete the DockerHub build for this release")
bullet("Checkout the master branch, and ensure it is up to date")
bullet("git checkout master", level=1)
bullet("git pull origin master", level=1)
bullet("Delete the origin/%s-candidate branch" % new_version)
bullet("git branch -D %s-candidate" % new_version, level=1)
bullet("git push origin :%s-candidate" % new_version, level=1)
next("Once complete, re-run the script.")
def update_master():
"""
Master branch is now checked out and needs updating.
"""
utils.check_or_exit("Is your git repository now on master")
# Update the master files. | utils.update_files(MASTER_VERSION_REPLACE, release_data["versions"],
is_release=False)
new_version = release_data["versions"]["version"]
para("The master codebase has now been updated to reference the latest "
"release.")
actions()
bullet("Self review the latest changes to master")
bullet("Push the changes to origin/master")
bullet("git add --all", level=1)
bullet('git commit -m "Update docs to version %s"' % new_version, level=1)
bullet("git push origin master", level=1)
bullet("Verify builds are working")
next("Once complete, re-run the script")
def complete():
"""
Show complete message
"""
utils.check_or_exit("Have you pushed the version update to master?")
warning("Release process is now complete.")
RELEASE_STEPS = [
start_release,
cut_release,
change_to_master,
update_master,
complete
]
def do_steps():
"""
Do the next step in the release process.
"""
step = release_data.get("step-number", 0)
RELEASE_STEPS[step]()
step = step+ 1
if step == len(RELEASE_STEPS):
release_data.clear()
else:
release_data["step-number"] = step
utils.save_release_data(release_data)
if __name__ == "__main__":
arguments = docopt(__doc__)
do_steps() | random_line_split | |
do_release.py | #!/usr/bin/env python
"""do_release.py
Usage:
do_release.py [--force] [CALICO_DOCKER_VERSION CALICO_VERSION LIBCALICO_VERSION LIBNETWORK_VERSION]
Options:
-h --help Show this screen.
"""
import subprocess
import utils
import re
from docopt import docopt
from utils import print_paragraph as para
from utils import print_user_actions as actions
from utils import print_bullet as bullet
from utils import print_next as next
from utils import print_warning as warning
# The candidate version replacement performs most of the required version
# replacements, but replaces build artifact URLs with a dynamic URL that
# can return an artifact for an arbitrary branch. This is replaced with the
# GitHub release artifact just before the release is actually cut.
CANDIDATE_VERSION_REPLACE = [
(re.compile(r'__version__\s*=\s*".*"'),
'__version__ = "{version-no-v}"'),
(re.compile(r'\*\*release\*\*'),
'{version}'),
(re.compile('http://www\.projectcalico\.org/latest/calicoctl'),
'http://www.projectcalico.org/builds/calicoctl?circleci-branch={version}-candidate'),
(re.compile(r'git\+https://github\.com/projectcalico/calico\.git'),
'git+https://github.com/projectcalico/calico.git@{calico-version}'),
(re.compile(r'git\+https://github\.com/projectcalico/libcalico\.git'),
'git+https://github.com/projectcalico/libcalico.git@{libcalico-version}'),
(re.compile(r'calico_docker_ver\s*=\s*"latest"'),
'calico_docker_ver = "{version}"'),
(re.compile('calico_node_ver\s*=\s*"latest"'),
'calico_node_ver = "{version}"'),
(re.compile('calico/node:latest'),
'calico/node:{version}'),
(re.compile('calico/node-libnetwork:latest'),
'calico/node-libnetwork:{libnetwork-version}'),
(re.compile('calico_libnetwork_ver\s*=\s*"latest"'),
'calico_libnetwork_ver = "{libnetwork-version}"')
]
# The final version replace handles migrating the dynamic (temporary) URLs to
# point to the Git archives.
FINAL_VERSION_REPLACE = [
(re.compile('http://www\.projectcalico\.org/latest/calicoctl\?circleci\-branch=.*\-candidate'),
'https://github.com/projectcalico/calico-docker/releases/download/{version}/calicoctl'),
]
# Version replacement for the master branch. We just need to update the
# python version string and the comments.
MASTER_VERSION_REPLACE = [
(re.compile(r'__version__\s*=\s*".*"'),
'__version__ = "{version-no-v}-dev"'),
(re.compile(r'https://github\.com/projectcalico/calico\-docker/blob/.*/README\.md'),
'https://github.com/projectcalico/calico-docker/blob/{version}/README.md')
]
# Load the globally required release data.
release_data = utils.load_release_data()
# ============== Define the release steps. ===============
def start_release():
"""
Start the release process, asking user for version information.
:return:
"""
para("Your git repository should be checked out to the correct revision "
"that you want to cut a release with. This is usually the HEAD of "
"the master branch.")
utils.check_or_exit("Are you currently on the correct revision")
old_version = utils.get_calicoctl_version()
para("Current version is: %s" % old_version)
new_version = arguments["CALICO_DOCKER_VERSION"]
if not new_version:
while True:
new_version = raw_input("New calicoctl version?: ")
release_type = utils.check_version_increment(old_version, new_version)
if release_type:
para("Release type: %s" % release_type)
break
calico_version = arguments["CALICO_VERSION"]
libcalico_version = arguments["LIBCALICO_VERSION"]
libnetwork_version = arguments["LIBNETWORK_VERSION"]
if not (calico_version and libcalico_version and libnetwork_version):
para("To pin the calico libraries used by calico-docker, please specify "
"the name of the requested versions as they appear in the GitHub "
"releases.")
calico_version = \
utils.get_github_library_version("calico (felix)",
"https://github.com/projectcalico/calico")
libcalico_version = \
utils.get_github_library_version("libcalico",
"https://github.com/projectcalico/libcalico")
libnetwork_version = \
utils.get_github_library_version("libnetwork-plugin",
"https://github.com/projectcalico/libnetwork-plugin")
release_data["versions"] = {"version": new_version,
"version-no-v": new_version[1:],
"calico-version": calico_version,
"libcalico-version": libcalico_version,
"libnetwork-version": libnetwork_version}
bullet("Creating a candidate release branch called "
"'%s-candidate'." % new_version)
if arguments['--force']:
subprocess.call("git branch -D %s-candidate" % new_version, shell=True)
subprocess.call("git checkout -b %s-candidate" % new_version, shell=True)
# Update the code tree
utils.update_files(CANDIDATE_VERSION_REPLACE, release_data["versions"])
new_version = release_data["versions"]["version"]
para("The codebase has been updated to reference the release candidate "
"artifacts.")
bullet("Adding, committing and pushing the updated files to "
"origin/%s-candidate" % new_version)
subprocess.call("git add --all", shell=True)
subprocess.call('git commit -m "Update version strings for release '
'candidate %s"' % new_version, shell=True)
if arguments['--force']:
subprocess.call("git push -f origin %s-candidate" % new_version, shell=True)
else:
subprocess.call("git push origin %s-candidate" % new_version, shell=True)
actions()
bullet("Create a DockerHub release called '%s'" % new_version)
bullet("Monitor the semaphore, CircleCI and Docker builds for this branch "
"until all have successfully completed. Fix any issues with the "
"build.")
bullet("Run through a subset of the demonstrations. When running the "
"vagrant instructions, make sure you are using the candidate "
"branch (e.g. git checkout %s-candidate):" % new_version)
bullet("Ubuntu libnetwork", level=1)
bullet("CoreOS default networking", level=1)
para("Follow the URL below to view the correct demonstration instructions "
"for this release candidate.")
bullet("https://github.com/projectcalico/calico-docker/tree/%s-candidate" % new_version)
next("Once you have completed the testing, re-run the script.")
def cut_release():
"""
The candidate branch has been tested, so cut the actual release.
"""
utils.check_or_exit("Have you successfully tested your release candidate")
# Update the code tree once more to set the final GitHub URLs
utils.update_files(FINAL_VERSION_REPLACE, release_data["versions"])
new_version = release_data["versions"]["version"]
para("The codebase has been updated to reference the GitHub release "
"artifacts.")
actions()
bullet("Add, commit and push the updated files to "
"origin/%s-candidate" % new_version)
bullet("git add --all", level=1)
bullet('git commit -m "Update version strings for release '
'%s"' % new_version, level=1)
bullet("git push origin %s-candidate" % new_version, level=1)
bullet("[ideally squash the two commits into one]", level=1)
bullet("Monitor the semaphore, CircleCI and Docker builds for this branch "
"until all have successfully completed. Fix any issues with the "
"build.")
bullet("Create a Pull Request and review the changes")
bullet("Create a GitHub release called '%s'" % new_version)
para("Attach the calicoctl binary to the release. It can be downloaded "
"from the following URL:")
bullet("http://www.projectcalico.org/builds/calicoctl?circleci-branch=%s-candidate" % new_version)
para("Once the release has been created on GitHub, perform a final test "
"of the release:")
bullet("Run through a subset of the demonstrations. When running the "
"vagrant instructions, make sure you are using the tagged release "
"(e.g. git checkout tags/%s):" % new_version)
bullet("CoreOS libnetwork", level=1)
bullet("Ubuntu default networking", level=1)
next("Once you have completed the testing, re-run the script.")
def change_to_master():
"""
Version has been releases and tested.
"""
utils.check_or_exit("Have you successfully tested the release")
new_version = release_data["versions"]["version"]
para("The release is now complete. We now need to update the master "
"branch and do some general branch and build tidyup.")
actions()
bullet("Delete the DockerHub build for this release")
bullet("Checkout the master branch, and ensure it is up to date")
bullet("git checkout master", level=1)
bullet("git pull origin master", level=1)
bullet("Delete the origin/%s-candidate branch" % new_version)
bullet("git branch -D %s-candidate" % new_version, level=1)
bullet("git push origin :%s-candidate" % new_version, level=1)
next("Once complete, re-run the script.")
def update_master():
"""
Master branch is now checked out and needs updating.
"""
utils.check_or_exit("Is your git repository now on master")
# Update the master files.
utils.update_files(MASTER_VERSION_REPLACE, release_data["versions"],
is_release=False)
new_version = release_data["versions"]["version"]
para("The master codebase has now been updated to reference the latest "
"release.")
actions()
bullet("Self review the latest changes to master")
bullet("Push the changes to origin/master")
bullet("git add --all", level=1)
bullet('git commit -m "Update docs to version %s"' % new_version, level=1)
bullet("git push origin master", level=1)
bullet("Verify builds are working")
next("Once complete, re-run the script")
def | ():
"""
Show complete message
"""
utils.check_or_exit("Have you pushed the version update to master?")
warning("Release process is now complete.")
RELEASE_STEPS = [
start_release,
cut_release,
change_to_master,
update_master,
complete
]
def do_steps():
"""
Do the next step in the release process.
"""
step = release_data.get("step-number", 0)
RELEASE_STEPS[step]()
step = step+ 1
if step == len(RELEASE_STEPS):
release_data.clear()
else:
release_data["step-number"] = step
utils.save_release_data(release_data)
if __name__ == "__main__":
arguments = docopt(__doc__)
do_steps()
| complete | identifier_name |
do_release.py | #!/usr/bin/env python
"""do_release.py
Usage:
do_release.py [--force] [CALICO_DOCKER_VERSION CALICO_VERSION LIBCALICO_VERSION LIBNETWORK_VERSION]
Options:
-h --help Show this screen.
"""
import subprocess
import utils
import re
from docopt import docopt
from utils import print_paragraph as para
from utils import print_user_actions as actions
from utils import print_bullet as bullet
from utils import print_next as next
from utils import print_warning as warning
# The candidate version replacement performs most of the required version
# replacements, but replaces build artifact URLs with a dynamic URL that
# can return an artifact for an arbitrary branch. This is replaced with the
# GitHub release artifact just before the release is actually cut.
CANDIDATE_VERSION_REPLACE = [
(re.compile(r'__version__\s*=\s*".*"'),
'__version__ = "{version-no-v}"'),
(re.compile(r'\*\*release\*\*'),
'{version}'),
(re.compile('http://www\.projectcalico\.org/latest/calicoctl'),
'http://www.projectcalico.org/builds/calicoctl?circleci-branch={version}-candidate'),
(re.compile(r'git\+https://github\.com/projectcalico/calico\.git'),
'git+https://github.com/projectcalico/calico.git@{calico-version}'),
(re.compile(r'git\+https://github\.com/projectcalico/libcalico\.git'),
'git+https://github.com/projectcalico/libcalico.git@{libcalico-version}'),
(re.compile(r'calico_docker_ver\s*=\s*"latest"'),
'calico_docker_ver = "{version}"'),
(re.compile('calico_node_ver\s*=\s*"latest"'),
'calico_node_ver = "{version}"'),
(re.compile('calico/node:latest'),
'calico/node:{version}'),
(re.compile('calico/node-libnetwork:latest'),
'calico/node-libnetwork:{libnetwork-version}'),
(re.compile('calico_libnetwork_ver\s*=\s*"latest"'),
'calico_libnetwork_ver = "{libnetwork-version}"')
]
# The final version replace handles migrating the dynamic (temporary) URLs to
# point to the Git archives.
FINAL_VERSION_REPLACE = [
(re.compile('http://www\.projectcalico\.org/latest/calicoctl\?circleci\-branch=.*\-candidate'),
'https://github.com/projectcalico/calico-docker/releases/download/{version}/calicoctl'),
]
# Version replacement for the master branch. We just need to update the
# python version string and the comments.
MASTER_VERSION_REPLACE = [
(re.compile(r'__version__\s*=\s*".*"'),
'__version__ = "{version-no-v}-dev"'),
(re.compile(r'https://github\.com/projectcalico/calico\-docker/blob/.*/README\.md'),
'https://github.com/projectcalico/calico-docker/blob/{version}/README.md')
]
# Load the globally required release data.
release_data = utils.load_release_data()
# ============== Define the release steps. ===============
def start_release():
"""
Start the release process, asking user for version information.
:return:
"""
para("Your git repository should be checked out to the correct revision "
"that you want to cut a release with. This is usually the HEAD of "
"the master branch.")
utils.check_or_exit("Are you currently on the correct revision")
old_version = utils.get_calicoctl_version()
para("Current version is: %s" % old_version)
new_version = arguments["CALICO_DOCKER_VERSION"]
if not new_version:
while True:
new_version = raw_input("New calicoctl version?: ")
release_type = utils.check_version_increment(old_version, new_version)
if release_type:
para("Release type: %s" % release_type)
break
calico_version = arguments["CALICO_VERSION"]
libcalico_version = arguments["LIBCALICO_VERSION"]
libnetwork_version = arguments["LIBNETWORK_VERSION"]
if not (calico_version and libcalico_version and libnetwork_version):
para("To pin the calico libraries used by calico-docker, please specify "
"the name of the requested versions as they appear in the GitHub "
"releases.")
calico_version = \
utils.get_github_library_version("calico (felix)",
"https://github.com/projectcalico/calico")
libcalico_version = \
utils.get_github_library_version("libcalico",
"https://github.com/projectcalico/libcalico")
libnetwork_version = \
utils.get_github_library_version("libnetwork-plugin",
"https://github.com/projectcalico/libnetwork-plugin")
release_data["versions"] = {"version": new_version,
"version-no-v": new_version[1:],
"calico-version": calico_version,
"libcalico-version": libcalico_version,
"libnetwork-version": libnetwork_version}
bullet("Creating a candidate release branch called "
"'%s-candidate'." % new_version)
if arguments['--force']:
subprocess.call("git branch -D %s-candidate" % new_version, shell=True)
subprocess.call("git checkout -b %s-candidate" % new_version, shell=True)
# Update the code tree
utils.update_files(CANDIDATE_VERSION_REPLACE, release_data["versions"])
new_version = release_data["versions"]["version"]
para("The codebase has been updated to reference the release candidate "
"artifacts.")
bullet("Adding, committing and pushing the updated files to "
"origin/%s-candidate" % new_version)
subprocess.call("git add --all", shell=True)
subprocess.call('git commit -m "Update version strings for release '
'candidate %s"' % new_version, shell=True)
if arguments['--force']:
subprocess.call("git push -f origin %s-candidate" % new_version, shell=True)
else:
subprocess.call("git push origin %s-candidate" % new_version, shell=True)
actions()
bullet("Create a DockerHub release called '%s'" % new_version)
bullet("Monitor the semaphore, CircleCI and Docker builds for this branch "
"until all have successfully completed. Fix any issues with the "
"build.")
bullet("Run through a subset of the demonstrations. When running the "
"vagrant instructions, make sure you are using the candidate "
"branch (e.g. git checkout %s-candidate):" % new_version)
bullet("Ubuntu libnetwork", level=1)
bullet("CoreOS default networking", level=1)
para("Follow the URL below to view the correct demonstration instructions "
"for this release candidate.")
bullet("https://github.com/projectcalico/calico-docker/tree/%s-candidate" % new_version)
next("Once you have completed the testing, re-run the script.")
def cut_release():
"""
The candidate branch has been tested, so cut the actual release.
"""
utils.check_or_exit("Have you successfully tested your release candidate")
# Update the code tree once more to set the final GitHub URLs
utils.update_files(FINAL_VERSION_REPLACE, release_data["versions"])
new_version = release_data["versions"]["version"]
para("The codebase has been updated to reference the GitHub release "
"artifacts.")
actions()
bullet("Add, commit and push the updated files to "
"origin/%s-candidate" % new_version)
bullet("git add --all", level=1)
bullet('git commit -m "Update version strings for release '
'%s"' % new_version, level=1)
bullet("git push origin %s-candidate" % new_version, level=1)
bullet("[ideally squash the two commits into one]", level=1)
bullet("Monitor the semaphore, CircleCI and Docker builds for this branch "
"until all have successfully completed. Fix any issues with the "
"build.")
bullet("Create a Pull Request and review the changes")
bullet("Create a GitHub release called '%s'" % new_version)
para("Attach the calicoctl binary to the release. It can be downloaded "
"from the following URL:")
bullet("http://www.projectcalico.org/builds/calicoctl?circleci-branch=%s-candidate" % new_version)
para("Once the release has been created on GitHub, perform a final test "
"of the release:")
bullet("Run through a subset of the demonstrations. When running the "
"vagrant instructions, make sure you are using the tagged release "
"(e.g. git checkout tags/%s):" % new_version)
bullet("CoreOS libnetwork", level=1)
bullet("Ubuntu default networking", level=1)
next("Once you have completed the testing, re-run the script.")
def change_to_master():
"""
Version has been releases and tested.
"""
utils.check_or_exit("Have you successfully tested the release")
new_version = release_data["versions"]["version"]
para("The release is now complete. We now need to update the master "
"branch and do some general branch and build tidyup.")
actions()
bullet("Delete the DockerHub build for this release")
bullet("Checkout the master branch, and ensure it is up to date")
bullet("git checkout master", level=1)
bullet("git pull origin master", level=1)
bullet("Delete the origin/%s-candidate branch" % new_version)
bullet("git branch -D %s-candidate" % new_version, level=1)
bullet("git push origin :%s-candidate" % new_version, level=1)
next("Once complete, re-run the script.")
def update_master():
|
def complete():
"""
Show complete message
"""
utils.check_or_exit("Have you pushed the version update to master?")
warning("Release process is now complete.")
RELEASE_STEPS = [
start_release,
cut_release,
change_to_master,
update_master,
complete
]
def do_steps():
"""
Do the next step in the release process.
"""
step = release_data.get("step-number", 0)
RELEASE_STEPS[step]()
step = step+ 1
if step == len(RELEASE_STEPS):
release_data.clear()
else:
release_data["step-number"] = step
utils.save_release_data(release_data)
if __name__ == "__main__":
arguments = docopt(__doc__)
do_steps()
| """
Master branch is now checked out and needs updating.
"""
utils.check_or_exit("Is your git repository now on master")
# Update the master files.
utils.update_files(MASTER_VERSION_REPLACE, release_data["versions"],
is_release=False)
new_version = release_data["versions"]["version"]
para("The master codebase has now been updated to reference the latest "
"release.")
actions()
bullet("Self review the latest changes to master")
bullet("Push the changes to origin/master")
bullet("git add --all", level=1)
bullet('git commit -m "Update docs to version %s"' % new_version, level=1)
bullet("git push origin master", level=1)
bullet("Verify builds are working")
next("Once complete, re-run the script") | identifier_body |
do_release.py | #!/usr/bin/env python
"""do_release.py
Usage:
do_release.py [--force] [CALICO_DOCKER_VERSION CALICO_VERSION LIBCALICO_VERSION LIBNETWORK_VERSION]
Options:
-h --help Show this screen.
"""
import subprocess
import utils
import re
from docopt import docopt
from utils import print_paragraph as para
from utils import print_user_actions as actions
from utils import print_bullet as bullet
from utils import print_next as next
from utils import print_warning as warning
# The candidate version replacement performs most of the required version
# replacements, but replaces build artifact URLs with a dynamic URL that
# can return an artifact for an arbitrary branch. This is replaced with the
# GitHub release artifact just before the release is actually cut.
CANDIDATE_VERSION_REPLACE = [
(re.compile(r'__version__\s*=\s*".*"'),
'__version__ = "{version-no-v}"'),
(re.compile(r'\*\*release\*\*'),
'{version}'),
(re.compile('http://www\.projectcalico\.org/latest/calicoctl'),
'http://www.projectcalico.org/builds/calicoctl?circleci-branch={version}-candidate'),
(re.compile(r'git\+https://github\.com/projectcalico/calico\.git'),
'git+https://github.com/projectcalico/calico.git@{calico-version}'),
(re.compile(r'git\+https://github\.com/projectcalico/libcalico\.git'),
'git+https://github.com/projectcalico/libcalico.git@{libcalico-version}'),
(re.compile(r'calico_docker_ver\s*=\s*"latest"'),
'calico_docker_ver = "{version}"'),
(re.compile('calico_node_ver\s*=\s*"latest"'),
'calico_node_ver = "{version}"'),
(re.compile('calico/node:latest'),
'calico/node:{version}'),
(re.compile('calico/node-libnetwork:latest'),
'calico/node-libnetwork:{libnetwork-version}'),
(re.compile('calico_libnetwork_ver\s*=\s*"latest"'),
'calico_libnetwork_ver = "{libnetwork-version}"')
]
# The final version replace handles migrating the dynamic (temporary) URLs to
# point to the Git archives.
FINAL_VERSION_REPLACE = [
(re.compile('http://www\.projectcalico\.org/latest/calicoctl\?circleci\-branch=.*\-candidate'),
'https://github.com/projectcalico/calico-docker/releases/download/{version}/calicoctl'),
]
# Version replacement for the master branch. We just need to update the
# python version string and the comments.
MASTER_VERSION_REPLACE = [
(re.compile(r'__version__\s*=\s*".*"'),
'__version__ = "{version-no-v}-dev"'),
(re.compile(r'https://github\.com/projectcalico/calico\-docker/blob/.*/README\.md'),
'https://github.com/projectcalico/calico-docker/blob/{version}/README.md')
]
# Load the globally required release data.
release_data = utils.load_release_data()
# ============== Define the release steps. ===============
def start_release():
"""
Start the release process, asking user for version information.
:return:
"""
para("Your git repository should be checked out to the correct revision "
"that you want to cut a release with. This is usually the HEAD of "
"the master branch.")
utils.check_or_exit("Are you currently on the correct revision")
old_version = utils.get_calicoctl_version()
para("Current version is: %s" % old_version)
new_version = arguments["CALICO_DOCKER_VERSION"]
if not new_version:
while True:
new_version = raw_input("New calicoctl version?: ")
release_type = utils.check_version_increment(old_version, new_version)
if release_type:
para("Release type: %s" % release_type)
break
calico_version = arguments["CALICO_VERSION"]
libcalico_version = arguments["LIBCALICO_VERSION"]
libnetwork_version = arguments["LIBNETWORK_VERSION"]
if not (calico_version and libcalico_version and libnetwork_version):
para("To pin the calico libraries used by calico-docker, please specify "
"the name of the requested versions as they appear in the GitHub "
"releases.")
calico_version = \
utils.get_github_library_version("calico (felix)",
"https://github.com/projectcalico/calico")
libcalico_version = \
utils.get_github_library_version("libcalico",
"https://github.com/projectcalico/libcalico")
libnetwork_version = \
utils.get_github_library_version("libnetwork-plugin",
"https://github.com/projectcalico/libnetwork-plugin")
release_data["versions"] = {"version": new_version,
"version-no-v": new_version[1:],
"calico-version": calico_version,
"libcalico-version": libcalico_version,
"libnetwork-version": libnetwork_version}
bullet("Creating a candidate release branch called "
"'%s-candidate'." % new_version)
if arguments['--force']:
subprocess.call("git branch -D %s-candidate" % new_version, shell=True)
subprocess.call("git checkout -b %s-candidate" % new_version, shell=True)
# Update the code tree
utils.update_files(CANDIDATE_VERSION_REPLACE, release_data["versions"])
new_version = release_data["versions"]["version"]
para("The codebase has been updated to reference the release candidate "
"artifacts.")
bullet("Adding, committing and pushing the updated files to "
"origin/%s-candidate" % new_version)
subprocess.call("git add --all", shell=True)
subprocess.call('git commit -m "Update version strings for release '
'candidate %s"' % new_version, shell=True)
if arguments['--force']:
|
else:
subprocess.call("git push origin %s-candidate" % new_version, shell=True)
actions()
bullet("Create a DockerHub release called '%s'" % new_version)
bullet("Monitor the semaphore, CircleCI and Docker builds for this branch "
"until all have successfully completed. Fix any issues with the "
"build.")
bullet("Run through a subset of the demonstrations. When running the "
"vagrant instructions, make sure you are using the candidate "
"branch (e.g. git checkout %s-candidate):" % new_version)
bullet("Ubuntu libnetwork", level=1)
bullet("CoreOS default networking", level=1)
para("Follow the URL below to view the correct demonstration instructions "
"for this release candidate.")
bullet("https://github.com/projectcalico/calico-docker/tree/%s-candidate" % new_version)
next("Once you have completed the testing, re-run the script.")
def cut_release():
"""
The candidate branch has been tested, so cut the actual release.
"""
utils.check_or_exit("Have you successfully tested your release candidate")
# Update the code tree once more to set the final GitHub URLs
utils.update_files(FINAL_VERSION_REPLACE, release_data["versions"])
new_version = release_data["versions"]["version"]
para("The codebase has been updated to reference the GitHub release "
"artifacts.")
actions()
bullet("Add, commit and push the updated files to "
"origin/%s-candidate" % new_version)
bullet("git add --all", level=1)
bullet('git commit -m "Update version strings for release '
'%s"' % new_version, level=1)
bullet("git push origin %s-candidate" % new_version, level=1)
bullet("[ideally squash the two commits into one]", level=1)
bullet("Monitor the semaphore, CircleCI and Docker builds for this branch "
"until all have successfully completed. Fix any issues with the "
"build.")
bullet("Create a Pull Request and review the changes")
bullet("Create a GitHub release called '%s'" % new_version)
para("Attach the calicoctl binary to the release. It can be downloaded "
"from the following URL:")
bullet("http://www.projectcalico.org/builds/calicoctl?circleci-branch=%s-candidate" % new_version)
para("Once the release has been created on GitHub, perform a final test "
"of the release:")
bullet("Run through a subset of the demonstrations. When running the "
"vagrant instructions, make sure you are using the tagged release "
"(e.g. git checkout tags/%s):" % new_version)
bullet("CoreOS libnetwork", level=1)
bullet("Ubuntu default networking", level=1)
next("Once you have completed the testing, re-run the script.")
def change_to_master():
"""
Version has been releases and tested.
"""
utils.check_or_exit("Have you successfully tested the release")
new_version = release_data["versions"]["version"]
para("The release is now complete. We now need to update the master "
"branch and do some general branch and build tidyup.")
actions()
bullet("Delete the DockerHub build for this release")
bullet("Checkout the master branch, and ensure it is up to date")
bullet("git checkout master", level=1)
bullet("git pull origin master", level=1)
bullet("Delete the origin/%s-candidate branch" % new_version)
bullet("git branch -D %s-candidate" % new_version, level=1)
bullet("git push origin :%s-candidate" % new_version, level=1)
next("Once complete, re-run the script.")
def update_master():
"""
Master branch is now checked out and needs updating.
"""
utils.check_or_exit("Is your git repository now on master")
# Update the master files.
utils.update_files(MASTER_VERSION_REPLACE, release_data["versions"],
is_release=False)
new_version = release_data["versions"]["version"]
para("The master codebase has now been updated to reference the latest "
"release.")
actions()
bullet("Self review the latest changes to master")
bullet("Push the changes to origin/master")
bullet("git add --all", level=1)
bullet('git commit -m "Update docs to version %s"' % new_version, level=1)
bullet("git push origin master", level=1)
bullet("Verify builds are working")
next("Once complete, re-run the script")
def complete():
"""
Show complete message
"""
utils.check_or_exit("Have you pushed the version update to master?")
warning("Release process is now complete.")
RELEASE_STEPS = [
start_release,
cut_release,
change_to_master,
update_master,
complete
]
def do_steps():
"""
Do the next step in the release process.
"""
step = release_data.get("step-number", 0)
RELEASE_STEPS[step]()
step = step+ 1
if step == len(RELEASE_STEPS):
release_data.clear()
else:
release_data["step-number"] = step
utils.save_release_data(release_data)
if __name__ == "__main__":
arguments = docopt(__doc__)
do_steps()
| subprocess.call("git push -f origin %s-candidate" % new_version, shell=True) | conditional_block |
mod.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Lints, aka compiler warnings.
//!
//! A 'lint' check is a kind of miscellaneous constraint that a user _might_
//! want to enforce, but might reasonably want to permit as well, on a
//! module-by-module basis. They contrast with static constraints enforced by
//! other phases of the compiler, which are generally required to hold in order
//! to compile the program at all.
//!
//! Most lints can be written as `LintPass` instances. These run just before
//! translation to LLVM bytecode. The `LintPass`es built into rustc are defined
//! within `builtin.rs`, which has further comments on how to add such a lint.
//! rustc can also load user-defined lint plugins via the plugin mechanism.
//!
//! Some of rustc's lints are defined elsewhere in the compiler and work by
//! calling `add_lint()` on the overall `Session` object. This works when
//! it happens before the main lint pass, which emits the lints stored by
//! `add_lint()`. To emit lints after the main lint pass (from trans, for
//! example) requires more effort. See `emit_lint` and `GatherNodeLevels`
//! in `context.rs`.
pub use self::Level::*;
pub use self::LintSource::*;
use std::hash;
use std::ascii::AsciiExt;
use syntax::codemap::Span;
use syntax::visit::FnKind;
use syntax::ast;
pub use lint::context::{Context, LintStore, raw_emit_lint, check_crate, gather_attrs};
/// Specification of a single lint.
#[derive(Copy, Show)]
pub struct Lint {
/// A string identifier for the lint.
///
/// This identifies the lint in attributes and in command-line arguments.
/// In those contexts it is always lowercase, but this field is compared
/// in a way which is case-insensitive for ASCII characters. This allows
/// `declare_lint!()` invocations to follow the convention of upper-case
/// statics without repeating the name.
///
/// The name is written with underscores, e.g. "unused_imports".
/// On the command line, underscores become dashes.
pub name: &'static str,
/// Default level for the lint.
pub default_level: Level,
/// Description of the lint or the issue it detects.
///
/// e.g. "imports that are never used"
pub desc: &'static str,
}
impl Lint {
/// Get the lint's name, with ASCII letters converted to lowercase.
pub fn name_lower(&self) -> String {
self.name.to_ascii_lowercase()
}
}
/// Build a `Lint` initializer.
#[macro_export]
macro_rules! lint_initializer {
($name:ident, $level:ident, $desc:expr) => (
::rustc::lint::Lint {
name: stringify!($name),
default_level: ::rustc::lint::$level,
desc: $desc,
}
)
}
/// Declare a static item of type `&'static Lint`.
#[macro_export]
macro_rules! declare_lint {
// FIXME(#14660): deduplicate
(pub $name:ident, $level:ident, $desc:expr) => (
pub static $name: &'static ::rustc::lint::Lint
= &lint_initializer!($name, $level, $desc);
);
($name:ident, $level:ident, $desc:expr) => (
static $name: &'static ::rustc::lint::Lint
= &lint_initializer!($name, $level, $desc);
);
}
/// Declare a static `LintArray` and return it as an expression.
#[macro_export]
macro_rules! lint_array { ($( $lint:expr ),*) => (
{
#[allow(non_upper_case_globals)]
static array: LintArray = &[ $( &$lint ),* ];
array
}
) }
pub type LintArray = &'static [&'static &'static Lint];
/// Trait for types providing lint checks.
///
/// Each `check` method checks a single syntax node, and should not
/// invoke methods recursively (unlike `Visitor`). By default they
/// do nothing.
//
// FIXME: eliminate the duplication with `Visitor`. But this also
// contains a few lint-specific methods with no equivalent in `Visitor`.
pub trait LintPass {
/// Get descriptions of the lints this `LintPass` object can emit.
///
/// NB: there is no enforcement that the object only emits lints it registered.
/// And some `rustc` internal `LintPass`es register lints to be emitted by other
/// parts of the compiler. If you want enforced access restrictions for your
/// `Lint`, make it a private `static` item in its own module.
fn get_lints(&self) -> LintArray;
fn check_crate(&mut self, _: &Context, _: &ast::Crate) { }
fn check_ident(&mut self, _: &Context, _: Span, _: ast::Ident) { }
fn check_mod(&mut self, _: &Context, _: &ast::Mod, _: Span, _: ast::NodeId) { }
fn check_foreign_item(&mut self, _: &Context, _: &ast::ForeignItem) { }
fn check_item(&mut self, _: &Context, _: &ast::Item) { }
fn check_local(&mut self, _: &Context, _: &ast::Local) { }
fn check_block(&mut self, _: &Context, _: &ast::Block) { }
fn check_stmt(&mut self, _: &Context, _: &ast::Stmt) { }
fn check_arm(&mut self, _: &Context, _: &ast::Arm) { }
fn check_pat(&mut self, _: &Context, _: &ast::Pat) { }
fn check_decl(&mut self, _: &Context, _: &ast::Decl) { }
fn check_expr(&mut self, _: &Context, _: &ast::Expr) { }
fn check_expr_post(&mut self, _: &Context, _: &ast::Expr) { }
fn check_ty(&mut self, _: &Context, _: &ast::Ty) { }
fn check_generics(&mut self, _: &Context, _: &ast::Generics) { }
fn check_fn(&mut self, _: &Context,
_: FnKind, _: &ast::FnDecl, _: &ast::Block, _: Span, _: ast::NodeId) { }
fn check_ty_method(&mut self, _: &Context, _: &ast::TypeMethod) { }
fn check_trait_method(&mut self, _: &Context, _: &ast::TraitItem) { }
fn check_struct_def(&mut self, _: &Context,
_: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
fn check_struct_def_post(&mut self, _: &Context,
_: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
fn check_struct_field(&mut self, _: &Context, _: &ast::StructField) { }
fn check_variant(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { }
fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { }
fn check_opt_lifetime_ref(&mut self, _: &Context, _: Span, _: &Option<ast::Lifetime>) { }
fn check_lifetime_ref(&mut self, _: &Context, _: &ast::Lifetime) { }
fn check_lifetime_def(&mut self, _: &Context, _: &ast::LifetimeDef) { }
fn check_explicit_self(&mut self, _: &Context, _: &ast::ExplicitSelf) { }
fn check_mac(&mut self, _: &Context, _: &ast::Mac) { }
fn check_path(&mut self, _: &Context, _: &ast::Path, _: ast::NodeId) { }
fn check_attribute(&mut self, _: &Context, _: &ast::Attribute) { }
/// Called when entering a syntax node that can have lint attributes such
/// as `#[allow(...)]`. Called with *all* the attributes of that node.
fn enter_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { }
/// Counterpart to `enter_lint_attrs`.
fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { }
}
/// A lint pass boxed up as a trait object.
pub type LintPassObject = Box<LintPass + 'static>;
/// Identifies a lint known to the compiler.
#[derive(Clone, Copy)]
pub struct LintId {
// Identity is based on pointer equality of this field.
lint: &'static Lint,
}
impl PartialEq for LintId {
fn eq(&self, other: &LintId) -> bool {
(self.lint as *const Lint) == (other.lint as *const Lint)
}
}
impl Eq for LintId { }
impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for LintId {
fn hash(&self, state: &mut S) {
let ptr = self.lint as *const Lint;
ptr.hash(state);
}
}
impl LintId {
/// Get the `LintId` for a `Lint`.
pub fn of(lint: &'static Lint) -> LintId {
LintId {
lint: lint,
}
}
/// Get the name of the lint.
pub fn as_str(&self) -> String {
self.lint.name_lower()
}
}
/// Setting for how to handle a lint.
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Show)]
pub enum | {
Allow, Warn, Deny, Forbid
}
impl Level {
/// Convert a level to a lower-case string.
pub fn as_str(self) -> &'static str {
match self {
Allow => "allow",
Warn => "warn",
Deny => "deny",
Forbid => "forbid",
}
}
/// Convert a lower-case string to a level.
pub fn from_str(x: &str) -> Option<Level> {
match x {
"allow" => Some(Allow),
"warn" => Some(Warn),
"deny" => Some(Deny),
"forbid" => Some(Forbid),
_ => None,
}
}
}
/// How a lint level was set.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum LintSource {
/// Lint is at the default level as declared
/// in rustc or a plugin.
Default,
/// Lint level was set by an attribute.
Node(Span),
/// Lint level was set by a command-line flag.
CommandLine,
/// Lint level was set by the release channel.
ReleaseChannel
}
pub type LevelSource = (Level, LintSource);
pub mod builtin;
mod context;
| Level | identifier_name |
mod.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Lints, aka compiler warnings.
//!
//! A 'lint' check is a kind of miscellaneous constraint that a user _might_
//! want to enforce, but might reasonably want to permit as well, on a
//! module-by-module basis. They contrast with static constraints enforced by
//! other phases of the compiler, which are generally required to hold in order
//! to compile the program at all.
//!
//! Most lints can be written as `LintPass` instances. These run just before
//! translation to LLVM bytecode. The `LintPass`es built into rustc are defined
//! within `builtin.rs`, which has further comments on how to add such a lint.
//! rustc can also load user-defined lint plugins via the plugin mechanism.
//!
//! Some of rustc's lints are defined elsewhere in the compiler and work by
//! calling `add_lint()` on the overall `Session` object. This works when
//! it happens before the main lint pass, which emits the lints stored by
//! `add_lint()`. To emit lints after the main lint pass (from trans, for
//! example) requires more effort. See `emit_lint` and `GatherNodeLevels`
//! in `context.rs`.
pub use self::Level::*;
pub use self::LintSource::*;
use std::hash;
use std::ascii::AsciiExt;
use syntax::codemap::Span;
use syntax::visit::FnKind;
use syntax::ast;
pub use lint::context::{Context, LintStore, raw_emit_lint, check_crate, gather_attrs};
/// Specification of a single lint.
#[derive(Copy, Show)]
pub struct Lint {
/// A string identifier for the lint.
///
/// This identifies the lint in attributes and in command-line arguments.
/// In those contexts it is always lowercase, but this field is compared
/// in a way which is case-insensitive for ASCII characters. This allows
/// `declare_lint!()` invocations to follow the convention of upper-case
/// statics without repeating the name.
///
/// The name is written with underscores, e.g. "unused_imports".
/// On the command line, underscores become dashes.
pub name: &'static str,
/// Default level for the lint.
pub default_level: Level,
/// Description of the lint or the issue it detects.
///
/// e.g. "imports that are never used"
pub desc: &'static str,
}
impl Lint {
/// Get the lint's name, with ASCII letters converted to lowercase.
pub fn name_lower(&self) -> String {
self.name.to_ascii_lowercase()
}
}
/// Build a `Lint` initializer.
#[macro_export]
macro_rules! lint_initializer {
($name:ident, $level:ident, $desc:expr) => (
::rustc::lint::Lint {
name: stringify!($name),
default_level: ::rustc::lint::$level,
desc: $desc,
}
)
}
/// Declare a static item of type `&'static Lint`.
#[macro_export]
macro_rules! declare_lint {
// FIXME(#14660): deduplicate
(pub $name:ident, $level:ident, $desc:expr) => (
pub static $name: &'static ::rustc::lint::Lint
= &lint_initializer!($name, $level, $desc);
);
($name:ident, $level:ident, $desc:expr) => (
static $name: &'static ::rustc::lint::Lint
= &lint_initializer!($name, $level, $desc);
);
}
/// Declare a static `LintArray` and return it as an expression.
#[macro_export]
macro_rules! lint_array { ($( $lint:expr ),*) => (
{
#[allow(non_upper_case_globals)]
static array: LintArray = &[ $( &$lint ),* ];
array
}
) }
pub type LintArray = &'static [&'static &'static Lint];
/// Trait for types providing lint checks.
///
/// Each `check` method checks a single syntax node, and should not
/// invoke methods recursively (unlike `Visitor`). By default they
/// do nothing.
//
// FIXME: eliminate the duplication with `Visitor`. But this also
// contains a few lint-specific methods with no equivalent in `Visitor`.
pub trait LintPass {
/// Get descriptions of the lints this `LintPass` object can emit.
///
/// NB: there is no enforcement that the object only emits lints it registered.
/// And some `rustc` internal `LintPass`es register lints to be emitted by other
/// parts of the compiler. If you want enforced access restrictions for your
/// `Lint`, make it a private `static` item in its own module.
fn get_lints(&self) -> LintArray;
fn check_crate(&mut self, _: &Context, _: &ast::Crate) { }
fn check_ident(&mut self, _: &Context, _: Span, _: ast::Ident) { }
fn check_mod(&mut self, _: &Context, _: &ast::Mod, _: Span, _: ast::NodeId) { }
fn check_foreign_item(&mut self, _: &Context, _: &ast::ForeignItem) { }
fn check_item(&mut self, _: &Context, _: &ast::Item) { }
fn check_local(&mut self, _: &Context, _: &ast::Local) { }
fn check_block(&mut self, _: &Context, _: &ast::Block) { }
fn check_stmt(&mut self, _: &Context, _: &ast::Stmt) { }
fn check_arm(&mut self, _: &Context, _: &ast::Arm) { }
fn check_pat(&mut self, _: &Context, _: &ast::Pat) { }
fn check_decl(&mut self, _: &Context, _: &ast::Decl) { }
fn check_expr(&mut self, _: &Context, _: &ast::Expr) { }
fn check_expr_post(&mut self, _: &Context, _: &ast::Expr) { }
fn check_ty(&mut self, _: &Context, _: &ast::Ty) { }
fn check_generics(&mut self, _: &Context, _: &ast::Generics) { }
fn check_fn(&mut self, _: &Context,
_: FnKind, _: &ast::FnDecl, _: &ast::Block, _: Span, _: ast::NodeId) { }
fn check_ty_method(&mut self, _: &Context, _: &ast::TypeMethod) { }
fn check_trait_method(&mut self, _: &Context, _: &ast::TraitItem) { }
fn check_struct_def(&mut self, _: &Context,
_: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
fn check_struct_def_post(&mut self, _: &Context,
_: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) |
fn check_struct_field(&mut self, _: &Context, _: &ast::StructField) { }
fn check_variant(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { }
fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { }
fn check_opt_lifetime_ref(&mut self, _: &Context, _: Span, _: &Option<ast::Lifetime>) { }
fn check_lifetime_ref(&mut self, _: &Context, _: &ast::Lifetime) { }
fn check_lifetime_def(&mut self, _: &Context, _: &ast::LifetimeDef) { }
fn check_explicit_self(&mut self, _: &Context, _: &ast::ExplicitSelf) { }
fn check_mac(&mut self, _: &Context, _: &ast::Mac) { }
fn check_path(&mut self, _: &Context, _: &ast::Path, _: ast::NodeId) { }
fn check_attribute(&mut self, _: &Context, _: &ast::Attribute) { }
/// Called when entering a syntax node that can have lint attributes such
/// as `#[allow(...)]`. Called with *all* the attributes of that node.
fn enter_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { }
/// Counterpart to `enter_lint_attrs`.
fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { }
}
/// A lint pass boxed up as a trait object.
pub type LintPassObject = Box<LintPass + 'static>;
/// Identifies a lint known to the compiler.
#[derive(Clone, Copy)]
pub struct LintId {
// Identity is based on pointer equality of this field.
lint: &'static Lint,
}
impl PartialEq for LintId {
fn eq(&self, other: &LintId) -> bool {
(self.lint as *const Lint) == (other.lint as *const Lint)
}
}
impl Eq for LintId { }
impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for LintId {
fn hash(&self, state: &mut S) {
let ptr = self.lint as *const Lint;
ptr.hash(state);
}
}
impl LintId {
/// Get the `LintId` for a `Lint`.
pub fn of(lint: &'static Lint) -> LintId {
LintId {
lint: lint,
}
}
/// Get the name of the lint.
pub fn as_str(&self) -> String {
self.lint.name_lower()
}
}
/// Setting for how to handle a lint.
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Show)]
pub enum Level {
Allow, Warn, Deny, Forbid
}
impl Level {
/// Convert a level to a lower-case string.
pub fn as_str(self) -> &'static str {
match self {
Allow => "allow",
Warn => "warn",
Deny => "deny",
Forbid => "forbid",
}
}
/// Convert a lower-case string to a level.
pub fn from_str(x: &str) -> Option<Level> {
match x {
"allow" => Some(Allow),
"warn" => Some(Warn),
"deny" => Some(Deny),
"forbid" => Some(Forbid),
_ => None,
}
}
}
/// How a lint level was set.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum LintSource {
/// Lint is at the default level as declared
/// in rustc or a plugin.
Default,
/// Lint level was set by an attribute.
Node(Span),
/// Lint level was set by a command-line flag.
CommandLine,
/// Lint level was set by the release channel.
ReleaseChannel
}
pub type LevelSource = (Level, LintSource);
pub mod builtin;
mod context;
| { } | identifier_body |
mod.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Lints, aka compiler warnings.
//!
//! A 'lint' check is a kind of miscellaneous constraint that a user _might_
//! want to enforce, but might reasonably want to permit as well, on a
//! module-by-module basis. They contrast with static constraints enforced by
//! other phases of the compiler, which are generally required to hold in order
//! to compile the program at all.
//!
//! Most lints can be written as `LintPass` instances. These run just before
//! translation to LLVM bytecode. The `LintPass`es built into rustc are defined
//! within `builtin.rs`, which has further comments on how to add such a lint.
//! rustc can also load user-defined lint plugins via the plugin mechanism.
//!
//! Some of rustc's lints are defined elsewhere in the compiler and work by
//! calling `add_lint()` on the overall `Session` object. This works when
//! it happens before the main lint pass, which emits the lints stored by
//! `add_lint()`. To emit lints after the main lint pass (from trans, for
//! example) requires more effort. See `emit_lint` and `GatherNodeLevels`
//! in `context.rs`.
pub use self::Level::*;
pub use self::LintSource::*;
use std::hash;
use std::ascii::AsciiExt;
use syntax::codemap::Span;
use syntax::visit::FnKind;
use syntax::ast;
pub use lint::context::{Context, LintStore, raw_emit_lint, check_crate, gather_attrs};
/// Specification of a single lint.
#[derive(Copy, Show)]
pub struct Lint {
/// A string identifier for the lint.
///
/// This identifies the lint in attributes and in command-line arguments.
/// In those contexts it is always lowercase, but this field is compared
/// in a way which is case-insensitive for ASCII characters. This allows
/// `declare_lint!()` invocations to follow the convention of upper-case
/// statics without repeating the name.
///
/// The name is written with underscores, e.g. "unused_imports".
/// On the command line, underscores become dashes.
pub name: &'static str,
/// Default level for the lint.
pub default_level: Level,
/// Description of the lint or the issue it detects.
///
/// e.g. "imports that are never used"
pub desc: &'static str,
}
impl Lint {
/// Get the lint's name, with ASCII letters converted to lowercase.
pub fn name_lower(&self) -> String {
self.name.to_ascii_lowercase()
}
}
/// Build a `Lint` initializer.
#[macro_export]
macro_rules! lint_initializer {
($name:ident, $level:ident, $desc:expr) => (
::rustc::lint::Lint {
name: stringify!($name),
default_level: ::rustc::lint::$level,
desc: $desc,
}
)
}
/// Declare a static item of type `&'static Lint`.
#[macro_export]
macro_rules! declare_lint {
// FIXME(#14660): deduplicate
(pub $name:ident, $level:ident, $desc:expr) => (
pub static $name: &'static ::rustc::lint::Lint
= &lint_initializer!($name, $level, $desc);
);
($name:ident, $level:ident, $desc:expr) => (
static $name: &'static ::rustc::lint::Lint | );
}
/// Declare a static `LintArray` and return it as an expression.
#[macro_export]
macro_rules! lint_array { ($( $lint:expr ),*) => (
{
#[allow(non_upper_case_globals)]
static array: LintArray = &[ $( &$lint ),* ];
array
}
) }
pub type LintArray = &'static [&'static &'static Lint];
/// Trait for types providing lint checks.
///
/// Each `check` method checks a single syntax node, and should not
/// invoke methods recursively (unlike `Visitor`). By default they
/// do nothing.
//
// FIXME: eliminate the duplication with `Visitor`. But this also
// contains a few lint-specific methods with no equivalent in `Visitor`.
pub trait LintPass {
/// Get descriptions of the lints this `LintPass` object can emit.
///
/// NB: there is no enforcement that the object only emits lints it registered.
/// And some `rustc` internal `LintPass`es register lints to be emitted by other
/// parts of the compiler. If you want enforced access restrictions for your
/// `Lint`, make it a private `static` item in its own module.
fn get_lints(&self) -> LintArray;
fn check_crate(&mut self, _: &Context, _: &ast::Crate) { }
fn check_ident(&mut self, _: &Context, _: Span, _: ast::Ident) { }
fn check_mod(&mut self, _: &Context, _: &ast::Mod, _: Span, _: ast::NodeId) { }
fn check_foreign_item(&mut self, _: &Context, _: &ast::ForeignItem) { }
fn check_item(&mut self, _: &Context, _: &ast::Item) { }
fn check_local(&mut self, _: &Context, _: &ast::Local) { }
fn check_block(&mut self, _: &Context, _: &ast::Block) { }
fn check_stmt(&mut self, _: &Context, _: &ast::Stmt) { }
fn check_arm(&mut self, _: &Context, _: &ast::Arm) { }
fn check_pat(&mut self, _: &Context, _: &ast::Pat) { }
fn check_decl(&mut self, _: &Context, _: &ast::Decl) { }
fn check_expr(&mut self, _: &Context, _: &ast::Expr) { }
fn check_expr_post(&mut self, _: &Context, _: &ast::Expr) { }
fn check_ty(&mut self, _: &Context, _: &ast::Ty) { }
fn check_generics(&mut self, _: &Context, _: &ast::Generics) { }
fn check_fn(&mut self, _: &Context,
_: FnKind, _: &ast::FnDecl, _: &ast::Block, _: Span, _: ast::NodeId) { }
fn check_ty_method(&mut self, _: &Context, _: &ast::TypeMethod) { }
fn check_trait_method(&mut self, _: &Context, _: &ast::TraitItem) { }
fn check_struct_def(&mut self, _: &Context,
_: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
fn check_struct_def_post(&mut self, _: &Context,
_: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
fn check_struct_field(&mut self, _: &Context, _: &ast::StructField) { }
fn check_variant(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { }
fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { }
fn check_opt_lifetime_ref(&mut self, _: &Context, _: Span, _: &Option<ast::Lifetime>) { }
fn check_lifetime_ref(&mut self, _: &Context, _: &ast::Lifetime) { }
fn check_lifetime_def(&mut self, _: &Context, _: &ast::LifetimeDef) { }
fn check_explicit_self(&mut self, _: &Context, _: &ast::ExplicitSelf) { }
fn check_mac(&mut self, _: &Context, _: &ast::Mac) { }
fn check_path(&mut self, _: &Context, _: &ast::Path, _: ast::NodeId) { }
fn check_attribute(&mut self, _: &Context, _: &ast::Attribute) { }
/// Called when entering a syntax node that can have lint attributes such
/// as `#[allow(...)]`. Called with *all* the attributes of that node.
fn enter_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { }
/// Counterpart to `enter_lint_attrs`.
fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { }
}
/// A lint pass boxed up as a trait object.
pub type LintPassObject = Box<LintPass + 'static>;
/// Identifies a lint known to the compiler.
#[derive(Clone, Copy)]
pub struct LintId {
// Identity is based on pointer equality of this field.
lint: &'static Lint,
}
impl PartialEq for LintId {
fn eq(&self, other: &LintId) -> bool {
(self.lint as *const Lint) == (other.lint as *const Lint)
}
}
impl Eq for LintId { }
impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for LintId {
fn hash(&self, state: &mut S) {
let ptr = self.lint as *const Lint;
ptr.hash(state);
}
}
impl LintId {
/// Get the `LintId` for a `Lint`.
pub fn of(lint: &'static Lint) -> LintId {
LintId {
lint: lint,
}
}
/// Get the name of the lint.
pub fn as_str(&self) -> String {
self.lint.name_lower()
}
}
/// Setting for how to handle a lint.
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Show)]
pub enum Level {
Allow, Warn, Deny, Forbid
}
impl Level {
/// Convert a level to a lower-case string.
pub fn as_str(self) -> &'static str {
match self {
Allow => "allow",
Warn => "warn",
Deny => "deny",
Forbid => "forbid",
}
}
/// Convert a lower-case string to a level.
pub fn from_str(x: &str) -> Option<Level> {
match x {
"allow" => Some(Allow),
"warn" => Some(Warn),
"deny" => Some(Deny),
"forbid" => Some(Forbid),
_ => None,
}
}
}
/// How a lint level was set.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum LintSource {
/// Lint is at the default level as declared
/// in rustc or a plugin.
Default,
/// Lint level was set by an attribute.
Node(Span),
/// Lint level was set by a command-line flag.
CommandLine,
/// Lint level was set by the release channel.
ReleaseChannel
}
pub type LevelSource = (Level, LintSource);
pub mod builtin;
mod context; | = &lint_initializer!($name, $level, $desc); | random_line_split |
views.py | import logging
from requests_oauthlib import OAuth1Session
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from .models import QuickbooksToken, get_quickbooks_token
from .api import QuickbooksApi, AuthenticationFailure
from .signals import qb_connected
REQUEST_TOKEN_URL = 'https://oauth.intuit.com/oauth/v1/get_request_token'
ACCESS_TOKEN_URL = 'https://oauth.intuit.com/oauth/v1/get_access_token'
AUTHORIZATION_URL = 'https://appcenter.intuit.com/Connect/Begin'
BLUE_DOT_CACHE_KEY = 'quickbooks:blue_dot_menu'
@login_required
def request_oauth_token(request):
# We'll require a refresh in the blue dot cache
if BLUE_DOT_CACHE_KEY in request.session:
del request.session[BLUE_DOT_CACHE_KEY]
access_token_callback = settings.QUICKBOOKS['OAUTH_CALLBACK_URL']
if callable(access_token_callback):
access_token_callback = access_token_callback(request)
session = OAuth1Session(client_key=settings.QUICKBOOKS['CONSUMER_KEY'],
client_secret=settings.QUICKBOOKS['CONSUMER_SECRET'],
callback_uri=access_token_callback)
response = session.fetch_request_token(REQUEST_TOKEN_URL)
try:
request_token = response['oauth_token']
request_token_secret = response['oauth_token_secret']
request.session['qb_oauth_token'] = request_token
request.session['qb_oauth_token_secret'] = request_token_secret
except:
logger = logging.getLogger('quickbooks.views.request_oauth_token')
logger.exception(("Couldn't extract oAuth parameters from token " +
"request response. Response was '%s'"), response)
raise
return HttpResponseRedirect("%s?oauth_token=%s" % (AUTHORIZATION_URL, request_token))
@login_required
def get_access_token(request):
# [todo] - add doc string for get_access_token
|
@login_required
def blue_dot_menu(request):
""" Returns the blue dot menu. If possible a cached copy is returned.
"""
html = request.session.get(BLUE_DOT_CACHE_KEY)
if not html:
html = request.session[BLUE_DOT_CACHE_KEY] = \
HttpResponse(QuickbooksApi(request.user).app_menu())
return html
@login_required
def disconnect(request):
""" Try to disconnect from Intuit, then destroy our tokens."""
token = get_quickbooks_token(request)
try:
QuickbooksApi(token).disconnect()
except AuthenticationFailure:
# If there is an authentication error, then these tokens are bad
# We need to destroy them in any case.
pass
request.user.quickbookstoken_set.all().delete()
return HttpResponseRedirect(settings.QUICKBOOKS['ACCESS_COMPLETE_URL'])
| session = OAuth1Session(client_key=settings.QUICKBOOKS['CONSUMER_KEY'],
client_secret=settings.QUICKBOOKS['CONSUMER_SECRET'],
resource_owner_key=request.session['qb_oauth_token'],
resource_owner_secret=request.session['qb_oauth_token_secret'])
remote_response = session.parse_authorization_response('?{}'.format(request.META.get('QUERY_STRING')))
realm_id = remote_response['realmId']
data_source = remote_response['dataSource']
oauth_verifier = remote_response['oauth_verifier']
# [review] - Possible bug? This should be taken care of by session.parse_authorization_response
session.auth.client.verifier = unicode(oauth_verifier)
response = session.fetch_access_token(ACCESS_TOKEN_URL)
# Delete any existing access tokens
request.user.quickbookstoken_set.all().delete()
token = QuickbooksToken.objects.create(
user=request.user,
access_token=response['oauth_token'],
access_token_secret=response['oauth_token_secret'],
realm_id=realm_id,
data_source=data_source)
# Cache blue dot menu
try:
request.session[BLUE_DOT_CACHE_KEY] = None
blue_dot_menu(request)
except AttributeError:
raise Exception('The sessions framework must be installed for this ' +
'application to work.')
# Let everyone else know we conneted
qb_connected.send(None, token=token)
return render_to_response('oauth_callback.html',
{'complete_url': settings.QUICKBOOKS['ACCESS_COMPLETE_URL']}) | identifier_body |
views.py | import logging
from requests_oauthlib import OAuth1Session
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from .models import QuickbooksToken, get_quickbooks_token
from .api import QuickbooksApi, AuthenticationFailure
from .signals import qb_connected
REQUEST_TOKEN_URL = 'https://oauth.intuit.com/oauth/v1/get_request_token'
ACCESS_TOKEN_URL = 'https://oauth.intuit.com/oauth/v1/get_access_token'
AUTHORIZATION_URL = 'https://appcenter.intuit.com/Connect/Begin'
BLUE_DOT_CACHE_KEY = 'quickbooks:blue_dot_menu'
@login_required
def request_oauth_token(request):
# We'll require a refresh in the blue dot cache
if BLUE_DOT_CACHE_KEY in request.session:
del request.session[BLUE_DOT_CACHE_KEY]
access_token_callback = settings.QUICKBOOKS['OAUTH_CALLBACK_URL']
if callable(access_token_callback):
access_token_callback = access_token_callback(request)
session = OAuth1Session(client_key=settings.QUICKBOOKS['CONSUMER_KEY'],
client_secret=settings.QUICKBOOKS['CONSUMER_SECRET'],
callback_uri=access_token_callback)
response = session.fetch_request_token(REQUEST_TOKEN_URL)
try:
request_token = response['oauth_token']
request_token_secret = response['oauth_token_secret']
request.session['qb_oauth_token'] = request_token
request.session['qb_oauth_token_secret'] = request_token_secret
except:
logger = logging.getLogger('quickbooks.views.request_oauth_token')
logger.exception(("Couldn't extract oAuth parameters from token " +
"request response. Response was '%s'"), response)
raise
return HttpResponseRedirect("%s?oauth_token=%s" % (AUTHORIZATION_URL, request_token))
@login_required
def get_access_token(request):
# [todo] - add doc string for get_access_token
session = OAuth1Session(client_key=settings.QUICKBOOKS['CONSUMER_KEY'],
client_secret=settings.QUICKBOOKS['CONSUMER_SECRET'],
resource_owner_key=request.session['qb_oauth_token'],
resource_owner_secret=request.session['qb_oauth_token_secret'])
remote_response = session.parse_authorization_response('?{}'.format(request.META.get('QUERY_STRING')))
realm_id = remote_response['realmId']
data_source = remote_response['dataSource']
oauth_verifier = remote_response['oauth_verifier']
# [review] - Possible bug? This should be taken care of by session.parse_authorization_response
session.auth.client.verifier = unicode(oauth_verifier)
response = session.fetch_access_token(ACCESS_TOKEN_URL)
# Delete any existing access tokens
request.user.quickbookstoken_set.all().delete()
token = QuickbooksToken.objects.create(
user=request.user,
access_token=response['oauth_token'],
access_token_secret=response['oauth_token_secret'],
realm_id=realm_id,
data_source=data_source)
# Cache blue dot menu
try:
request.session[BLUE_DOT_CACHE_KEY] = None
blue_dot_menu(request)
except AttributeError:
raise Exception('The sessions framework must be installed for this ' +
'application to work.')
# Let everyone else know we conneted
qb_connected.send(None, token=token)
return render_to_response('oauth_callback.html',
{'complete_url': settings.QUICKBOOKS['ACCESS_COMPLETE_URL']})
@login_required
def blue_dot_menu(request):
""" Returns the blue dot menu. If possible a cached copy is returned.
"""
html = request.session.get(BLUE_DOT_CACHE_KEY)
if not html:
html = request.session[BLUE_DOT_CACHE_KEY] = \
HttpResponse(QuickbooksApi(request.user).app_menu())
return html
@login_required
def disconnect(request):
""" Try to disconnect from Intuit, then destroy our tokens.""" | try:
QuickbooksApi(token).disconnect()
except AuthenticationFailure:
# If there is an authentication error, then these tokens are bad
# We need to destroy them in any case.
pass
request.user.quickbookstoken_set.all().delete()
return HttpResponseRedirect(settings.QUICKBOOKS['ACCESS_COMPLETE_URL']) |
token = get_quickbooks_token(request) | random_line_split |
views.py | import logging
from requests_oauthlib import OAuth1Session
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from .models import QuickbooksToken, get_quickbooks_token
from .api import QuickbooksApi, AuthenticationFailure
from .signals import qb_connected
REQUEST_TOKEN_URL = 'https://oauth.intuit.com/oauth/v1/get_request_token'
ACCESS_TOKEN_URL = 'https://oauth.intuit.com/oauth/v1/get_access_token'
AUTHORIZATION_URL = 'https://appcenter.intuit.com/Connect/Begin'
BLUE_DOT_CACHE_KEY = 'quickbooks:blue_dot_menu'
@login_required
def request_oauth_token(request):
# We'll require a refresh in the blue dot cache
if BLUE_DOT_CACHE_KEY in request.session:
|
access_token_callback = settings.QUICKBOOKS['OAUTH_CALLBACK_URL']
if callable(access_token_callback):
access_token_callback = access_token_callback(request)
session = OAuth1Session(client_key=settings.QUICKBOOKS['CONSUMER_KEY'],
client_secret=settings.QUICKBOOKS['CONSUMER_SECRET'],
callback_uri=access_token_callback)
response = session.fetch_request_token(REQUEST_TOKEN_URL)
try:
request_token = response['oauth_token']
request_token_secret = response['oauth_token_secret']
request.session['qb_oauth_token'] = request_token
request.session['qb_oauth_token_secret'] = request_token_secret
except:
logger = logging.getLogger('quickbooks.views.request_oauth_token')
logger.exception(("Couldn't extract oAuth parameters from token " +
"request response. Response was '%s'"), response)
raise
return HttpResponseRedirect("%s?oauth_token=%s" % (AUTHORIZATION_URL, request_token))
@login_required
def get_access_token(request):
# [todo] - add doc string for get_access_token
session = OAuth1Session(client_key=settings.QUICKBOOKS['CONSUMER_KEY'],
client_secret=settings.QUICKBOOKS['CONSUMER_SECRET'],
resource_owner_key=request.session['qb_oauth_token'],
resource_owner_secret=request.session['qb_oauth_token_secret'])
remote_response = session.parse_authorization_response('?{}'.format(request.META.get('QUERY_STRING')))
realm_id = remote_response['realmId']
data_source = remote_response['dataSource']
oauth_verifier = remote_response['oauth_verifier']
# [review] - Possible bug? This should be taken care of by session.parse_authorization_response
session.auth.client.verifier = unicode(oauth_verifier)
response = session.fetch_access_token(ACCESS_TOKEN_URL)
# Delete any existing access tokens
request.user.quickbookstoken_set.all().delete()
token = QuickbooksToken.objects.create(
user=request.user,
access_token=response['oauth_token'],
access_token_secret=response['oauth_token_secret'],
realm_id=realm_id,
data_source=data_source)
# Cache blue dot menu
try:
request.session[BLUE_DOT_CACHE_KEY] = None
blue_dot_menu(request)
except AttributeError:
raise Exception('The sessions framework must be installed for this ' +
'application to work.')
# Let everyone else know we conneted
qb_connected.send(None, token=token)
return render_to_response('oauth_callback.html',
{'complete_url': settings.QUICKBOOKS['ACCESS_COMPLETE_URL']})
@login_required
def blue_dot_menu(request):
""" Returns the blue dot menu. If possible a cached copy is returned.
"""
html = request.session.get(BLUE_DOT_CACHE_KEY)
if not html:
html = request.session[BLUE_DOT_CACHE_KEY] = \
HttpResponse(QuickbooksApi(request.user).app_menu())
return html
@login_required
def disconnect(request):
""" Try to disconnect from Intuit, then destroy our tokens."""
token = get_quickbooks_token(request)
try:
QuickbooksApi(token).disconnect()
except AuthenticationFailure:
# If there is an authentication error, then these tokens are bad
# We need to destroy them in any case.
pass
request.user.quickbookstoken_set.all().delete()
return HttpResponseRedirect(settings.QUICKBOOKS['ACCESS_COMPLETE_URL'])
| del request.session[BLUE_DOT_CACHE_KEY] | conditional_block |
views.py | import logging
from requests_oauthlib import OAuth1Session
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from .models import QuickbooksToken, get_quickbooks_token
from .api import QuickbooksApi, AuthenticationFailure
from .signals import qb_connected
REQUEST_TOKEN_URL = 'https://oauth.intuit.com/oauth/v1/get_request_token'
ACCESS_TOKEN_URL = 'https://oauth.intuit.com/oauth/v1/get_access_token'
AUTHORIZATION_URL = 'https://appcenter.intuit.com/Connect/Begin'
BLUE_DOT_CACHE_KEY = 'quickbooks:blue_dot_menu'
@login_required
def request_oauth_token(request):
# We'll require a refresh in the blue dot cache
if BLUE_DOT_CACHE_KEY in request.session:
del request.session[BLUE_DOT_CACHE_KEY]
access_token_callback = settings.QUICKBOOKS['OAUTH_CALLBACK_URL']
if callable(access_token_callback):
access_token_callback = access_token_callback(request)
session = OAuth1Session(client_key=settings.QUICKBOOKS['CONSUMER_KEY'],
client_secret=settings.QUICKBOOKS['CONSUMER_SECRET'],
callback_uri=access_token_callback)
response = session.fetch_request_token(REQUEST_TOKEN_URL)
try:
request_token = response['oauth_token']
request_token_secret = response['oauth_token_secret']
request.session['qb_oauth_token'] = request_token
request.session['qb_oauth_token_secret'] = request_token_secret
except:
logger = logging.getLogger('quickbooks.views.request_oauth_token')
logger.exception(("Couldn't extract oAuth parameters from token " +
"request response. Response was '%s'"), response)
raise
return HttpResponseRedirect("%s?oauth_token=%s" % (AUTHORIZATION_URL, request_token))
@login_required
def get_access_token(request):
# [todo] - add doc string for get_access_token
session = OAuth1Session(client_key=settings.QUICKBOOKS['CONSUMER_KEY'],
client_secret=settings.QUICKBOOKS['CONSUMER_SECRET'],
resource_owner_key=request.session['qb_oauth_token'],
resource_owner_secret=request.session['qb_oauth_token_secret'])
remote_response = session.parse_authorization_response('?{}'.format(request.META.get('QUERY_STRING')))
realm_id = remote_response['realmId']
data_source = remote_response['dataSource']
oauth_verifier = remote_response['oauth_verifier']
# [review] - Possible bug? This should be taken care of by session.parse_authorization_response
session.auth.client.verifier = unicode(oauth_verifier)
response = session.fetch_access_token(ACCESS_TOKEN_URL)
# Delete any existing access tokens
request.user.quickbookstoken_set.all().delete()
token = QuickbooksToken.objects.create(
user=request.user,
access_token=response['oauth_token'],
access_token_secret=response['oauth_token_secret'],
realm_id=realm_id,
data_source=data_source)
# Cache blue dot menu
try:
request.session[BLUE_DOT_CACHE_KEY] = None
blue_dot_menu(request)
except AttributeError:
raise Exception('The sessions framework must be installed for this ' +
'application to work.')
# Let everyone else know we conneted
qb_connected.send(None, token=token)
return render_to_response('oauth_callback.html',
{'complete_url': settings.QUICKBOOKS['ACCESS_COMPLETE_URL']})
@login_required
def | (request):
""" Returns the blue dot menu. If possible a cached copy is returned.
"""
html = request.session.get(BLUE_DOT_CACHE_KEY)
if not html:
html = request.session[BLUE_DOT_CACHE_KEY] = \
HttpResponse(QuickbooksApi(request.user).app_menu())
return html
@login_required
def disconnect(request):
""" Try to disconnect from Intuit, then destroy our tokens."""
token = get_quickbooks_token(request)
try:
QuickbooksApi(token).disconnect()
except AuthenticationFailure:
# If there is an authentication error, then these tokens are bad
# We need to destroy them in any case.
pass
request.user.quickbookstoken_set.all().delete()
return HttpResponseRedirect(settings.QUICKBOOKS['ACCESS_COMPLETE_URL'])
| blue_dot_menu | identifier_name |
AddCommand.py | # Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
""" Provides the AddCommand class that implements the 'add' subcommand. """
import codecs
import re
from datetime import date
from os.path import expanduser
from sys import stdin
from topydo.lib.Config import config
from topydo.lib.prettyprinters.Numbers import PrettyPrinterNumbers
from topydo.lib.WriteCommand import WriteCommand
class AddCommand(WriteCommand):
def __init__(self, p_args, p_todolist, # pragma: no branch
p_out=lambda a: None,
p_err=lambda a: None,
p_prompt=lambda a: None):
super().__init__(
p_args, p_todolist, p_out, p_err, p_prompt)
self.text = ' '.join(p_args)
self.from_file = None
def _process_flags(self):
opts, args = self.getopt('f:')
for opt, value in opts:
if opt == '-f':
self.from_file = expanduser(value)
self.args = args
def get_todos_from_file(self):
if self.from_file == '-':
f = stdin
else:
f = codecs.open(self.from_file, 'r', encoding='utf-8')
todos = f.read().splitlines()
return todos
def | (self, p_todo_text):
def _preprocess_input_todo(p_todo_text):
"""
Pre-processes user input when adding a task.
It detects a priority mid-sentence and puts it at the start.
"""
todo_text = re.sub(r'^(.+) (\([A-Z]\))(.*)$', r'\2 \1\3',
p_todo_text)
return todo_text
todo_text = _preprocess_input_todo(p_todo_text)
todo = self.todolist.add(todo_text)
self.postprocess_input_todo(todo)
if config().auto_creation_date():
todo.set_creation_date(date.today())
self.out(self.printer.print_todo(todo))
def execute(self):
""" Adds a todo item to the list. """
if not super().execute():
return False
self.printer.add_filter(PrettyPrinterNumbers(self.todolist))
self._process_flags()
if self.from_file:
try:
new_todos = self.get_todos_from_file()
for todo in new_todos:
self._add_todo(todo)
except (IOError, OSError):
self.error('File not found: ' + self.from_file)
else:
if self.text:
self._add_todo(self.text)
else:
self.error(self.usage())
def usage(self):
return """Synopsis:
add <TEXT>
add -f <FILE> | -"""
def help(self):
return """\
This subcommand automatically adds the creation date to the added item.
TEXT may contain:
* Priorities mid-sentence. Example: add "Water flowers (C)"
* Dependencies using before, after, partof, parents-of and children-of tags.
These are translated to the corresponding 'id' and 'p' tags. The values of
these tags correspond to the todo number (not the dependency number).
Example: add "Subtask partof:1"
-f : Add todo items from specified FILE or from standard input.\
"""
| _add_todo | identifier_name |
AddCommand.py | # Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
""" Provides the AddCommand class that implements the 'add' subcommand. """
import codecs
import re
from datetime import date
from os.path import expanduser
from sys import stdin
from topydo.lib.Config import config
from topydo.lib.prettyprinters.Numbers import PrettyPrinterNumbers
from topydo.lib.WriteCommand import WriteCommand
class AddCommand(WriteCommand):
| def __init__(self, p_args, p_todolist, # pragma: no branch
p_out=lambda a: None,
p_err=lambda a: None,
p_prompt=lambda a: None):
super().__init__(
p_args, p_todolist, p_out, p_err, p_prompt)
self.text = ' '.join(p_args)
self.from_file = None
def _process_flags(self):
opts, args = self.getopt('f:')
for opt, value in opts:
if opt == '-f':
self.from_file = expanduser(value)
self.args = args
def get_todos_from_file(self):
if self.from_file == '-':
f = stdin
else:
f = codecs.open(self.from_file, 'r', encoding='utf-8')
todos = f.read().splitlines()
return todos
def _add_todo(self, p_todo_text):
def _preprocess_input_todo(p_todo_text):
"""
Pre-processes user input when adding a task.
It detects a priority mid-sentence and puts it at the start.
"""
todo_text = re.sub(r'^(.+) (\([A-Z]\))(.*)$', r'\2 \1\3',
p_todo_text)
return todo_text
todo_text = _preprocess_input_todo(p_todo_text)
todo = self.todolist.add(todo_text)
self.postprocess_input_todo(todo)
if config().auto_creation_date():
todo.set_creation_date(date.today())
self.out(self.printer.print_todo(todo))
def execute(self):
""" Adds a todo item to the list. """
if not super().execute():
return False
self.printer.add_filter(PrettyPrinterNumbers(self.todolist))
self._process_flags()
if self.from_file:
try:
new_todos = self.get_todos_from_file()
for todo in new_todos:
self._add_todo(todo)
except (IOError, OSError):
self.error('File not found: ' + self.from_file)
else:
if self.text:
self._add_todo(self.text)
else:
self.error(self.usage())
def usage(self):
return """Synopsis:
add <TEXT>
add -f <FILE> | -"""
def help(self):
return """\
This subcommand automatically adds the creation date to the added item.
TEXT may contain:
* Priorities mid-sentence. Example: add "Water flowers (C)"
* Dependencies using before, after, partof, parents-of and children-of tags.
These are translated to the corresponding 'id' and 'p' tags. The values of
these tags correspond to the todo number (not the dependency number).
Example: add "Subtask partof:1"
-f : Add todo items from specified FILE or from standard input.\
""" | identifier_body | |
AddCommand.py | # Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
""" Provides the AddCommand class that implements the 'add' subcommand. """
import codecs
import re
from datetime import date | from sys import stdin
from topydo.lib.Config import config
from topydo.lib.prettyprinters.Numbers import PrettyPrinterNumbers
from topydo.lib.WriteCommand import WriteCommand
class AddCommand(WriteCommand):
def __init__(self, p_args, p_todolist, # pragma: no branch
p_out=lambda a: None,
p_err=lambda a: None,
p_prompt=lambda a: None):
super().__init__(
p_args, p_todolist, p_out, p_err, p_prompt)
self.text = ' '.join(p_args)
self.from_file = None
def _process_flags(self):
opts, args = self.getopt('f:')
for opt, value in opts:
if opt == '-f':
self.from_file = expanduser(value)
self.args = args
def get_todos_from_file(self):
if self.from_file == '-':
f = stdin
else:
f = codecs.open(self.from_file, 'r', encoding='utf-8')
todos = f.read().splitlines()
return todos
def _add_todo(self, p_todo_text):
def _preprocess_input_todo(p_todo_text):
"""
Pre-processes user input when adding a task.
It detects a priority mid-sentence and puts it at the start.
"""
todo_text = re.sub(r'^(.+) (\([A-Z]\))(.*)$', r'\2 \1\3',
p_todo_text)
return todo_text
todo_text = _preprocess_input_todo(p_todo_text)
todo = self.todolist.add(todo_text)
self.postprocess_input_todo(todo)
if config().auto_creation_date():
todo.set_creation_date(date.today())
self.out(self.printer.print_todo(todo))
def execute(self):
""" Adds a todo item to the list. """
if not super().execute():
return False
self.printer.add_filter(PrettyPrinterNumbers(self.todolist))
self._process_flags()
if self.from_file:
try:
new_todos = self.get_todos_from_file()
for todo in new_todos:
self._add_todo(todo)
except (IOError, OSError):
self.error('File not found: ' + self.from_file)
else:
if self.text:
self._add_todo(self.text)
else:
self.error(self.usage())
def usage(self):
return """Synopsis:
add <TEXT>
add -f <FILE> | -"""
def help(self):
return """\
This subcommand automatically adds the creation date to the added item.
TEXT may contain:
* Priorities mid-sentence. Example: add "Water flowers (C)"
* Dependencies using before, after, partof, parents-of and children-of tags.
These are translated to the corresponding 'id' and 'p' tags. The values of
these tags correspond to the todo number (not the dependency number).
Example: add "Subtask partof:1"
-f : Add todo items from specified FILE or from standard input.\
""" | from os.path import expanduser | random_line_split |
AddCommand.py | # Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
""" Provides the AddCommand class that implements the 'add' subcommand. """
import codecs
import re
from datetime import date
from os.path import expanduser
from sys import stdin
from topydo.lib.Config import config
from topydo.lib.prettyprinters.Numbers import PrettyPrinterNumbers
from topydo.lib.WriteCommand import WriteCommand
class AddCommand(WriteCommand):
def __init__(self, p_args, p_todolist, # pragma: no branch
p_out=lambda a: None,
p_err=lambda a: None,
p_prompt=lambda a: None):
super().__init__(
p_args, p_todolist, p_out, p_err, p_prompt)
self.text = ' '.join(p_args)
self.from_file = None
def _process_flags(self):
opts, args = self.getopt('f:')
for opt, value in opts:
if opt == '-f':
self.from_file = expanduser(value)
self.args = args
def get_todos_from_file(self):
if self.from_file == '-':
f = stdin
else:
f = codecs.open(self.from_file, 'r', encoding='utf-8')
todos = f.read().splitlines()
return todos
def _add_todo(self, p_todo_text):
def _preprocess_input_todo(p_todo_text):
"""
Pre-processes user input when adding a task.
It detects a priority mid-sentence and puts it at the start.
"""
todo_text = re.sub(r'^(.+) (\([A-Z]\))(.*)$', r'\2 \1\3',
p_todo_text)
return todo_text
todo_text = _preprocess_input_todo(p_todo_text)
todo = self.todolist.add(todo_text)
self.postprocess_input_todo(todo)
if config().auto_creation_date():
todo.set_creation_date(date.today())
self.out(self.printer.print_todo(todo))
def execute(self):
""" Adds a todo item to the list. """
if not super().execute():
return False
self.printer.add_filter(PrettyPrinterNumbers(self.todolist))
self._process_flags()
if self.from_file:
try:
new_todos = self.get_todos_from_file()
for todo in new_todos:
self._add_todo(todo)
except (IOError, OSError):
self.error('File not found: ' + self.from_file)
else:
if self.text:
|
else:
self.error(self.usage())
def usage(self):
return """Synopsis:
add <TEXT>
add -f <FILE> | -"""
def help(self):
return """\
This subcommand automatically adds the creation date to the added item.
TEXT may contain:
* Priorities mid-sentence. Example: add "Water flowers (C)"
* Dependencies using before, after, partof, parents-of and children-of tags.
These are translated to the corresponding 'id' and 'p' tags. The values of
these tags correspond to the todo number (not the dependency number).
Example: add "Subtask partof:1"
-f : Add todo items from specified FILE or from standard input.\
"""
| self._add_todo(self.text) | conditional_block |
check_no_handler_pragma.ts | import {Issue} from "../issue";
import * as Statements from "../abap/2_statements/statements";
import {ABAPRule} from "./_abap_rule";
import {BasicRuleConfig} from "./_basic_rule_config";
import {StatementNode} from "../abap/nodes";
import {Comment} from "../abap/2_statements/statements/_statement";
import {IRuleMetadata, RuleTag} from "./_irule";
import {ABAPFile} from "../abap/abap_file";
export class CheckNoHandlerPragmaConf extends BasicRuleConfig {
}
export class CheckNoHandlerPragma extends ABAPRule {
private conf = new CheckNoHandlerPragmaConf();
public getMetadata(): IRuleMetadata |
public getConfig() {
return this.conf;
}
public setConfig(conf: CheckNoHandlerPragmaConf) {
this.conf = conf;
}
public runParsed(file: ABAPFile) {
const issues: Issue[] = [];
let noHandler: boolean = false;
const statements = file.getStatements();
for (let i = 0; i < statements.length; i++) {
const statement = statements[i];
if (statement.get() instanceof Statements.EndTry) {
noHandler = false;
} else if (statement.get() instanceof Comment) {
continue;
} else if (noHandler === true && !(statement.get() instanceof Statements.Catch)) {
const message = "NO_HANDLER pragma or pseudo comment can be removed";
const issue = Issue.atStatement(file, statement, message, this.getMetadata().key, this.conf.severity);
issues.push(issue);
noHandler = false;
} else {
noHandler = this.containsNoHandler(statement, statements[i + 1]);
}
}
return issues;
}
private containsNoHandler(statement: StatementNode, next: StatementNode | undefined): boolean {
for (const t of statement.getPragmas()) {
if (t.getStr().toUpperCase() === "##NO_HANDLER") {
return true;
}
}
if (next
&& next.get() instanceof Comment
&& next.concatTokens().toUpperCase().includes("#EC NO_HANDLER")) {
return true;
}
return false;
}
} | {
return {
key: "check_no_handler_pragma",
title: "Check if NO_HANDLER can be removed",
shortDescription: `Checks NO_HANDLER pragmas that can be removed`,
tags: [RuleTag.SingleFile],
badExample: `TRY.
...
CATCH zcx_abapgit_exception ##NO_HANDLER.
RETURN. " it has a handler
ENDTRY.`,
goodExample: `TRY.
...
CATCH zcx_abapgit_exception.
RETURN.
ENDTRY.`,
};
} | identifier_body |
check_no_handler_pragma.ts | import {Issue} from "../issue";
import * as Statements from "../abap/2_statements/statements";
import {ABAPRule} from "./_abap_rule";
import {BasicRuleConfig} from "./_basic_rule_config";
import {StatementNode} from "../abap/nodes";
import {Comment} from "../abap/2_statements/statements/_statement";
import {IRuleMetadata, RuleTag} from "./_irule";
import {ABAPFile} from "../abap/abap_file";
export class CheckNoHandlerPragmaConf extends BasicRuleConfig {
}
export class CheckNoHandlerPragma extends ABAPRule {
private conf = new CheckNoHandlerPragmaConf();
public getMetadata(): IRuleMetadata {
return {
key: "check_no_handler_pragma",
title: "Check if NO_HANDLER can be removed",
shortDescription: `Checks NO_HANDLER pragmas that can be removed`,
tags: [RuleTag.SingleFile],
badExample: `TRY.
...
CATCH zcx_abapgit_exception ##NO_HANDLER.
RETURN. " it has a handler
ENDTRY.`,
goodExample: `TRY.
...
CATCH zcx_abapgit_exception.
RETURN.
ENDTRY.`,
};
}
public getConfig() {
return this.conf;
}
public setConfig(conf: CheckNoHandlerPragmaConf) {
this.conf = conf;
}
public runParsed(file: ABAPFile) {
const issues: Issue[] = [];
let noHandler: boolean = false;
const statements = file.getStatements();
for (let i = 0; i < statements.length; i++) {
const statement = statements[i];
if (statement.get() instanceof Statements.EndTry) { | noHandler = false;
} else if (statement.get() instanceof Comment) {
continue;
} else if (noHandler === true && !(statement.get() instanceof Statements.Catch)) {
const message = "NO_HANDLER pragma or pseudo comment can be removed";
const issue = Issue.atStatement(file, statement, message, this.getMetadata().key, this.conf.severity);
issues.push(issue);
noHandler = false;
} else {
noHandler = this.containsNoHandler(statement, statements[i + 1]);
}
}
return issues;
}
private containsNoHandler(statement: StatementNode, next: StatementNode | undefined): boolean {
for (const t of statement.getPragmas()) {
if (t.getStr().toUpperCase() === "##NO_HANDLER") {
return true;
}
}
if (next
&& next.get() instanceof Comment
&& next.concatTokens().toUpperCase().includes("#EC NO_HANDLER")) {
return true;
}
return false;
}
} | random_line_split | |
check_no_handler_pragma.ts | import {Issue} from "../issue";
import * as Statements from "../abap/2_statements/statements";
import {ABAPRule} from "./_abap_rule";
import {BasicRuleConfig} from "./_basic_rule_config";
import {StatementNode} from "../abap/nodes";
import {Comment} from "../abap/2_statements/statements/_statement";
import {IRuleMetadata, RuleTag} from "./_irule";
import {ABAPFile} from "../abap/abap_file";
export class CheckNoHandlerPragmaConf extends BasicRuleConfig {
}
export class CheckNoHandlerPragma extends ABAPRule {
private conf = new CheckNoHandlerPragmaConf();
public | (): IRuleMetadata {
return {
key: "check_no_handler_pragma",
title: "Check if NO_HANDLER can be removed",
shortDescription: `Checks NO_HANDLER pragmas that can be removed`,
tags: [RuleTag.SingleFile],
badExample: `TRY.
...
CATCH zcx_abapgit_exception ##NO_HANDLER.
RETURN. " it has a handler
ENDTRY.`,
goodExample: `TRY.
...
CATCH zcx_abapgit_exception.
RETURN.
ENDTRY.`,
};
}
public getConfig() {
return this.conf;
}
public setConfig(conf: CheckNoHandlerPragmaConf) {
this.conf = conf;
}
public runParsed(file: ABAPFile) {
const issues: Issue[] = [];
let noHandler: boolean = false;
const statements = file.getStatements();
for (let i = 0; i < statements.length; i++) {
const statement = statements[i];
if (statement.get() instanceof Statements.EndTry) {
noHandler = false;
} else if (statement.get() instanceof Comment) {
continue;
} else if (noHandler === true && !(statement.get() instanceof Statements.Catch)) {
const message = "NO_HANDLER pragma or pseudo comment can be removed";
const issue = Issue.atStatement(file, statement, message, this.getMetadata().key, this.conf.severity);
issues.push(issue);
noHandler = false;
} else {
noHandler = this.containsNoHandler(statement, statements[i + 1]);
}
}
return issues;
}
private containsNoHandler(statement: StatementNode, next: StatementNode | undefined): boolean {
for (const t of statement.getPragmas()) {
if (t.getStr().toUpperCase() === "##NO_HANDLER") {
return true;
}
}
if (next
&& next.get() instanceof Comment
&& next.concatTokens().toUpperCase().includes("#EC NO_HANDLER")) {
return true;
}
return false;
}
} | getMetadata | identifier_name |
check_no_handler_pragma.ts | import {Issue} from "../issue";
import * as Statements from "../abap/2_statements/statements";
import {ABAPRule} from "./_abap_rule";
import {BasicRuleConfig} from "./_basic_rule_config";
import {StatementNode} from "../abap/nodes";
import {Comment} from "../abap/2_statements/statements/_statement";
import {IRuleMetadata, RuleTag} from "./_irule";
import {ABAPFile} from "../abap/abap_file";
export class CheckNoHandlerPragmaConf extends BasicRuleConfig {
}
export class CheckNoHandlerPragma extends ABAPRule {
private conf = new CheckNoHandlerPragmaConf();
public getMetadata(): IRuleMetadata {
return {
key: "check_no_handler_pragma",
title: "Check if NO_HANDLER can be removed",
shortDescription: `Checks NO_HANDLER pragmas that can be removed`,
tags: [RuleTag.SingleFile],
badExample: `TRY.
...
CATCH zcx_abapgit_exception ##NO_HANDLER.
RETURN. " it has a handler
ENDTRY.`,
goodExample: `TRY.
...
CATCH zcx_abapgit_exception.
RETURN.
ENDTRY.`,
};
}
public getConfig() {
return this.conf;
}
public setConfig(conf: CheckNoHandlerPragmaConf) {
this.conf = conf;
}
public runParsed(file: ABAPFile) {
const issues: Issue[] = [];
let noHandler: boolean = false;
const statements = file.getStatements();
for (let i = 0; i < statements.length; i++) {
const statement = statements[i];
if (statement.get() instanceof Statements.EndTry) {
noHandler = false;
} else if (statement.get() instanceof Comment) {
continue;
} else if (noHandler === true && !(statement.get() instanceof Statements.Catch)) {
const message = "NO_HANDLER pragma or pseudo comment can be removed";
const issue = Issue.atStatement(file, statement, message, this.getMetadata().key, this.conf.severity);
issues.push(issue);
noHandler = false;
} else |
}
return issues;
}
private containsNoHandler(statement: StatementNode, next: StatementNode | undefined): boolean {
for (const t of statement.getPragmas()) {
if (t.getStr().toUpperCase() === "##NO_HANDLER") {
return true;
}
}
if (next
&& next.get() instanceof Comment
&& next.concatTokens().toUpperCase().includes("#EC NO_HANDLER")) {
return true;
}
return false;
}
} | {
noHandler = this.containsNoHandler(statement, statements[i + 1]);
} | conditional_block |
browser-clean.js | /**
* @author ddchen
*/
var objectRinser = require("./objectRinser.js");
var originalEventRinser = require("./originalEventRinser.js");
var cleanRules = [];
var confs = null;
var addCleanRule = function(rule) {
cleanRules.push(rule);
}
var isFunction = function(fn) {
return !!fn && !fn.nodeName && fn.constructor != String &&
fn.constructor != RegExp && fn.constructor != Array &&
/function/i.test(fn + "");
}
addCleanRule(function() {
objectRinser.clean();
if (confs.events && confs.events.on === true) |
});
module.exports = {
addCleanRule: addCleanRule,
addEventIgnore: originalEventRinser.addEventIgnore,
record: function(opts) {
confs = opts || {};
objectRinser.record(confs.objects);
if (confs.events && confs.events.on === true) {
originalEventRinser.record(confs.events);
}
},
clean: function() {
for (var i = 0; i < cleanRules.length; i++) {
var rule = cleanRules[i];
isFunction(rule) && rule();
}
},
generalConf: {
windowIgnore: [/webkit/, "location", "document.location", "localStorage", "name", "sessionStorage", "history"]
}
} | {
originalEventRinser.clean();
} | conditional_block |
browser-clean.js | /**
* @author ddchen
*/
var objectRinser = require("./objectRinser.js");
var originalEventRinser = require("./originalEventRinser.js");
var cleanRules = [];
var confs = null;
var addCleanRule = function(rule) {
cleanRules.push(rule);
}
| }
addCleanRule(function() {
objectRinser.clean();
if (confs.events && confs.events.on === true) {
originalEventRinser.clean();
}
});
module.exports = {
addCleanRule: addCleanRule,
addEventIgnore: originalEventRinser.addEventIgnore,
record: function(opts) {
confs = opts || {};
objectRinser.record(confs.objects);
if (confs.events && confs.events.on === true) {
originalEventRinser.record(confs.events);
}
},
clean: function() {
for (var i = 0; i < cleanRules.length; i++) {
var rule = cleanRules[i];
isFunction(rule) && rule();
}
},
generalConf: {
windowIgnore: [/webkit/, "location", "document.location", "localStorage", "name", "sessionStorage", "history"]
}
} | var isFunction = function(fn) {
return !!fn && !fn.nodeName && fn.constructor != String &&
fn.constructor != RegExp && fn.constructor != Array &&
/function/i.test(fn + ""); | random_line_split |
custom_sharding.py | #!/usr/bin/env python
#
# Copyright 2015, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
import unittest
import environment
import utils
import tablet
# shards
shard_0_master = tablet.Tablet()
shard_0_rdonly = tablet.Tablet()
shard_1_master = tablet.Tablet()
shard_1_rdonly = tablet.Tablet()
def setUpModule():
try:
environment.topo_server().setup()
setup_procs = [
shard_0_master.init_mysql(),
shard_0_rdonly.init_mysql(),
shard_1_master.init_mysql(),
shard_1_rdonly.init_mysql(),
]
utils.Vtctld().start()
utils.VtGate().start()
utils.wait_procs(setup_procs)
except:
tearDownModule()
raise
def tearDownModule():
|
class TestCustomSharding(unittest.TestCase):
def _insert_data(self, shard, start, count, table='data'):
sql = 'insert into %s(id, name) values (:id, :name)' % table
for x in xrange(count):
bindvars = {
'id': start+x,
'name': 'row %d' % (start+x),
}
utils.vtgate.execute_shard(sql, 'test_keyspace', shard,
bindvars=bindvars)
def _check_data(self, shard, start, count, table='data'):
sql = 'select name from %s where id=:id' % table
for x in xrange(count):
bindvars = {
'id': start+x,
}
qr = utils.vtgate.execute_shard(sql, 'test_keyspace', shard,
bindvars=bindvars)
self.assertEqual(len(qr['Rows']), 1)
v = qr['Rows'][0][0]
self.assertEqual(v, 'row %d' % (start+x))
def test_custom_end_to_end(self):
"""Runs through the common operations of a custom sharded keyspace.
Tests creation with one shard, schema change, reading / writing
data, adding one more shard, reading / writing data from both
shards, applying schema changes again, and reading / writing data
from both shards again.
"""
utils.run_vtctl(['CreateKeyspace', 'test_keyspace'])
# start the first shard only for now
shard_0_master.init_tablet('master', 'test_keyspace', '0')
shard_0_rdonly.init_tablet('rdonly', 'test_keyspace', '0')
for t in [shard_0_master, shard_0_rdonly]:
t.create_db('vt_test_keyspace')
t.start_vttablet(wait_for_state=None)
for t in [shard_0_master, shard_0_rdonly]:
t.wait_for_vttablet_state('SERVING')
utils.run_vtctl(['InitShardMaster', 'test_keyspace/0',
shard_0_master.tablet_alias], auto_log=True)
utils.run_vtctl(['RebuildKeyspaceGraph', 'test_keyspace'], auto_log=True)
ks = utils.run_vtctl_json(['GetSrvKeyspace', 'test_nj', 'test_keyspace'])
self.assertEqual(len(ks['Partitions']['master']['ShardReferences']), 1)
self.assertEqual(len(ks['Partitions']['rdonly']['ShardReferences']), 1)
s = utils.run_vtctl_json(['GetShard', 'test_keyspace/0'])
self.assertEqual(len(s['served_types']), 3)
# create a table on shard 0
sql = '''create table data(
id bigint auto_increment,
name varchar(64),
primary key (id)
) Engine=InnoDB'''
utils.run_vtctl(['ApplySchema', '-sql=' + sql, 'test_keyspace'],
auto_log=True)
# insert data on shard 0
self._insert_data('0', 100, 10)
# re-read shard 0 data
self._check_data('0', 100, 10)
# create shard 1
shard_1_master.init_tablet('master', 'test_keyspace', '1')
shard_1_rdonly.init_tablet('rdonly', 'test_keyspace', '1')
for t in [shard_1_master, shard_1_rdonly]:
t.start_vttablet(wait_for_state=None)
for t in [shard_1_master, shard_1_rdonly]:
t.wait_for_vttablet_state('NOT_SERVING')
s = utils.run_vtctl_json(['GetShard', 'test_keyspace/1'])
self.assertEqual(len(s['served_types']), 3)
utils.run_vtctl(['InitShardMaster', 'test_keyspace/1',
shard_1_master.tablet_alias], auto_log=True)
utils.run_vtctl(['CopySchemaShard', shard_0_rdonly.tablet_alias,
'test_keyspace/1'], auto_log=True)
for t in [shard_1_master, shard_1_rdonly]:
utils.run_vtctl(['RefreshState', t.tablet_alias], auto_log=True)
t.wait_for_vttablet_state('SERVING')
# rebuild the keyspace serving graph now that the new shard was added
utils.run_vtctl(['RebuildKeyspaceGraph', 'test_keyspace'], auto_log=True)
# insert data on shard 1
self._insert_data('1', 200, 10)
# re-read shard 1 data
self._check_data('1', 200, 10)
# create a second table on all shards
sql = '''create table data2(
id bigint auto_increment,
name varchar(64),
primary key (id)
) Engine=InnoDB'''
utils.run_vtctl(['ApplySchema', '-sql=' + sql, 'test_keyspace'],
auto_log=True)
# insert and read data on all shards
self._insert_data('0', 300, 10, table='data2')
self._insert_data('1', 400, 10, table='data2')
self._check_data('0', 300, 10, table='data2')
self._check_data('1', 400, 10, table='data2')
# reload schema everywhere so the QueryService knows about the tables
for t in [shard_0_master, shard_0_rdonly, shard_1_master, shard_1_rdonly]:
utils.run_vtctl(['ReloadSchema', t.tablet_alias], auto_log=True)
utils.run_vtctl(['RebuildKeyspaceGraph', 'test_keyspace'], auto_log=True)
ks = utils.run_vtctl_json(['GetSrvKeyspace', 'test_nj', 'test_keyspace'])
self.assertEqual(len(ks['Partitions']['master']['ShardReferences']), 2)
self.assertEqual(len(ks['Partitions']['rdonly']['ShardReferences']), 2)
# Now test SplitQuery API works (used in MapReduce usually, but bringing
# up a full MR-capable cluster is too much for this test environment)
sql = 'select id, name from data'
s = utils.vtgate.split_query(sql, 'test_keyspace', 4)
self.assertEqual(len(s), 4)
shard0count = 0
shard1count = 0
for q in s:
if q['QueryShard']['Shards'][0] == '0':
shard0count += 1
if q['QueryShard']['Shards'][0] == '1':
shard1count += 1
self.assertEqual(shard0count, 2)
self.assertEqual(shard1count, 2)
# run the queries, aggregate the results, make sure we have all rows
rows = {}
for q in s:
qr = utils.vtgate.execute_shard(
q['QueryShard']['Sql'],
'test_keyspace', ','.join(q['QueryShard']['Shards']),
tablet_type='master', bindvars=q['QueryShard']['BindVariables'])
for r in qr['Rows']:
id = int(r[0])
rows[id] = r[1]
self.assertEqual(len(rows), 20)
expected = {}
for i in xrange(10):
expected[100 + i] = 'row %d' % (100 + i)
expected[200 + i] = 'row %d' % (200 + i)
self.assertEqual(rows, expected)
if __name__ == '__main__':
utils.main()
| if utils.options.skip_teardown:
return
teardown_procs = [
shard_0_master.teardown_mysql(),
shard_0_rdonly.teardown_mysql(),
shard_1_master.teardown_mysql(),
shard_1_rdonly.teardown_mysql(),
]
utils.wait_procs(teardown_procs, raise_on_error=False)
environment.topo_server().teardown()
utils.kill_sub_processes()
utils.remove_tmp_files()
shard_0_master.remove_tree()
shard_0_rdonly.remove_tree()
shard_1_master.remove_tree()
shard_1_rdonly.remove_tree() | identifier_body |
custom_sharding.py | #!/usr/bin/env python
#
# Copyright 2015, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
import unittest
import environment
import utils
import tablet
# shards
shard_0_master = tablet.Tablet()
shard_0_rdonly = tablet.Tablet()
shard_1_master = tablet.Tablet()
shard_1_rdonly = tablet.Tablet()
def setUpModule():
try:
environment.topo_server().setup()
setup_procs = [
shard_0_master.init_mysql(),
shard_0_rdonly.init_mysql(),
shard_1_master.init_mysql(),
shard_1_rdonly.init_mysql(),
]
utils.Vtctld().start()
utils.VtGate().start()
utils.wait_procs(setup_procs)
except:
tearDownModule()
raise
def tearDownModule():
if utils.options.skip_teardown:
return
teardown_procs = [
shard_0_master.teardown_mysql(),
shard_0_rdonly.teardown_mysql(),
shard_1_master.teardown_mysql(),
shard_1_rdonly.teardown_mysql(),
]
utils.wait_procs(teardown_procs, raise_on_error=False)
environment.topo_server().teardown()
utils.kill_sub_processes()
utils.remove_tmp_files()
shard_0_master.remove_tree()
shard_0_rdonly.remove_tree()
shard_1_master.remove_tree()
shard_1_rdonly.remove_tree()
class TestCustomSharding(unittest.TestCase):
def _insert_data(self, shard, start, count, table='data'):
sql = 'insert into %s(id, name) values (:id, :name)' % table
for x in xrange(count):
bindvars = {
'id': start+x,
'name': 'row %d' % (start+x),
}
utils.vtgate.execute_shard(sql, 'test_keyspace', shard,
bindvars=bindvars)
def _check_data(self, shard, start, count, table='data'):
sql = 'select name from %s where id=:id' % table
for x in xrange(count):
bindvars = {
'id': start+x,
}
qr = utils.vtgate.execute_shard(sql, 'test_keyspace', shard,
bindvars=bindvars)
self.assertEqual(len(qr['Rows']), 1)
v = qr['Rows'][0][0]
self.assertEqual(v, 'row %d' % (start+x))
def | (self):
"""Runs through the common operations of a custom sharded keyspace.
Tests creation with one shard, schema change, reading / writing
data, adding one more shard, reading / writing data from both
shards, applying schema changes again, and reading / writing data
from both shards again.
"""
utils.run_vtctl(['CreateKeyspace', 'test_keyspace'])
# start the first shard only for now
shard_0_master.init_tablet('master', 'test_keyspace', '0')
shard_0_rdonly.init_tablet('rdonly', 'test_keyspace', '0')
for t in [shard_0_master, shard_0_rdonly]:
t.create_db('vt_test_keyspace')
t.start_vttablet(wait_for_state=None)
for t in [shard_0_master, shard_0_rdonly]:
t.wait_for_vttablet_state('SERVING')
utils.run_vtctl(['InitShardMaster', 'test_keyspace/0',
shard_0_master.tablet_alias], auto_log=True)
utils.run_vtctl(['RebuildKeyspaceGraph', 'test_keyspace'], auto_log=True)
ks = utils.run_vtctl_json(['GetSrvKeyspace', 'test_nj', 'test_keyspace'])
self.assertEqual(len(ks['Partitions']['master']['ShardReferences']), 1)
self.assertEqual(len(ks['Partitions']['rdonly']['ShardReferences']), 1)
s = utils.run_vtctl_json(['GetShard', 'test_keyspace/0'])
self.assertEqual(len(s['served_types']), 3)
# create a table on shard 0
sql = '''create table data(
id bigint auto_increment,
name varchar(64),
primary key (id)
) Engine=InnoDB'''
utils.run_vtctl(['ApplySchema', '-sql=' + sql, 'test_keyspace'],
auto_log=True)
# insert data on shard 0
self._insert_data('0', 100, 10)
# re-read shard 0 data
self._check_data('0', 100, 10)
# create shard 1
shard_1_master.init_tablet('master', 'test_keyspace', '1')
shard_1_rdonly.init_tablet('rdonly', 'test_keyspace', '1')
for t in [shard_1_master, shard_1_rdonly]:
t.start_vttablet(wait_for_state=None)
for t in [shard_1_master, shard_1_rdonly]:
t.wait_for_vttablet_state('NOT_SERVING')
s = utils.run_vtctl_json(['GetShard', 'test_keyspace/1'])
self.assertEqual(len(s['served_types']), 3)
utils.run_vtctl(['InitShardMaster', 'test_keyspace/1',
shard_1_master.tablet_alias], auto_log=True)
utils.run_vtctl(['CopySchemaShard', shard_0_rdonly.tablet_alias,
'test_keyspace/1'], auto_log=True)
for t in [shard_1_master, shard_1_rdonly]:
utils.run_vtctl(['RefreshState', t.tablet_alias], auto_log=True)
t.wait_for_vttablet_state('SERVING')
# rebuild the keyspace serving graph now that the new shard was added
utils.run_vtctl(['RebuildKeyspaceGraph', 'test_keyspace'], auto_log=True)
# insert data on shard 1
self._insert_data('1', 200, 10)
# re-read shard 1 data
self._check_data('1', 200, 10)
# create a second table on all shards
sql = '''create table data2(
id bigint auto_increment,
name varchar(64),
primary key (id)
) Engine=InnoDB'''
utils.run_vtctl(['ApplySchema', '-sql=' + sql, 'test_keyspace'],
auto_log=True)
# insert and read data on all shards
self._insert_data('0', 300, 10, table='data2')
self._insert_data('1', 400, 10, table='data2')
self._check_data('0', 300, 10, table='data2')
self._check_data('1', 400, 10, table='data2')
# reload schema everywhere so the QueryService knows about the tables
for t in [shard_0_master, shard_0_rdonly, shard_1_master, shard_1_rdonly]:
utils.run_vtctl(['ReloadSchema', t.tablet_alias], auto_log=True)
utils.run_vtctl(['RebuildKeyspaceGraph', 'test_keyspace'], auto_log=True)
ks = utils.run_vtctl_json(['GetSrvKeyspace', 'test_nj', 'test_keyspace'])
self.assertEqual(len(ks['Partitions']['master']['ShardReferences']), 2)
self.assertEqual(len(ks['Partitions']['rdonly']['ShardReferences']), 2)
# Now test SplitQuery API works (used in MapReduce usually, but bringing
# up a full MR-capable cluster is too much for this test environment)
sql = 'select id, name from data'
s = utils.vtgate.split_query(sql, 'test_keyspace', 4)
self.assertEqual(len(s), 4)
shard0count = 0
shard1count = 0
for q in s:
if q['QueryShard']['Shards'][0] == '0':
shard0count += 1
if q['QueryShard']['Shards'][0] == '1':
shard1count += 1
self.assertEqual(shard0count, 2)
self.assertEqual(shard1count, 2)
# run the queries, aggregate the results, make sure we have all rows
rows = {}
for q in s:
qr = utils.vtgate.execute_shard(
q['QueryShard']['Sql'],
'test_keyspace', ','.join(q['QueryShard']['Shards']),
tablet_type='master', bindvars=q['QueryShard']['BindVariables'])
for r in qr['Rows']:
id = int(r[0])
rows[id] = r[1]
self.assertEqual(len(rows), 20)
expected = {}
for i in xrange(10):
expected[100 + i] = 'row %d' % (100 + i)
expected[200 + i] = 'row %d' % (200 + i)
self.assertEqual(rows, expected)
if __name__ == '__main__':
utils.main()
| test_custom_end_to_end | identifier_name |
custom_sharding.py | #!/usr/bin/env python
#
# Copyright 2015, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
import unittest
import environment
import utils
import tablet
# shards
shard_0_master = tablet.Tablet()
shard_0_rdonly = tablet.Tablet()
shard_1_master = tablet.Tablet()
shard_1_rdonly = tablet.Tablet()
def setUpModule():
try:
environment.topo_server().setup()
setup_procs = [
shard_0_master.init_mysql(),
shard_0_rdonly.init_mysql(),
shard_1_master.init_mysql(),
shard_1_rdonly.init_mysql(),
]
utils.Vtctld().start()
utils.VtGate().start()
utils.wait_procs(setup_procs)
except:
tearDownModule()
raise
def tearDownModule():
if utils.options.skip_teardown:
return
teardown_procs = [
shard_0_master.teardown_mysql(),
shard_0_rdonly.teardown_mysql(),
shard_1_master.teardown_mysql(),
shard_1_rdonly.teardown_mysql(),
]
utils.wait_procs(teardown_procs, raise_on_error=False)
environment.topo_server().teardown()
utils.kill_sub_processes()
utils.remove_tmp_files()
shard_0_master.remove_tree()
shard_0_rdonly.remove_tree()
shard_1_master.remove_tree()
shard_1_rdonly.remove_tree()
class TestCustomSharding(unittest.TestCase):
def _insert_data(self, shard, start, count, table='data'):
sql = 'insert into %s(id, name) values (:id, :name)' % table
for x in xrange(count):
bindvars = {
'id': start+x,
'name': 'row %d' % (start+x),
}
utils.vtgate.execute_shard(sql, 'test_keyspace', shard,
bindvars=bindvars)
def _check_data(self, shard, start, count, table='data'):
sql = 'select name from %s where id=:id' % table
for x in xrange(count):
bindvars = {
'id': start+x,
}
qr = utils.vtgate.execute_shard(sql, 'test_keyspace', shard,
bindvars=bindvars)
self.assertEqual(len(qr['Rows']), 1)
v = qr['Rows'][0][0]
self.assertEqual(v, 'row %d' % (start+x))
def test_custom_end_to_end(self):
"""Runs through the common operations of a custom sharded keyspace.
Tests creation with one shard, schema change, reading / writing
data, adding one more shard, reading / writing data from both
shards, applying schema changes again, and reading / writing data
from both shards again.
"""
utils.run_vtctl(['CreateKeyspace', 'test_keyspace'])
# start the first shard only for now
shard_0_master.init_tablet('master', 'test_keyspace', '0')
shard_0_rdonly.init_tablet('rdonly', 'test_keyspace', '0')
for t in [shard_0_master, shard_0_rdonly]:
|
for t in [shard_0_master, shard_0_rdonly]:
t.wait_for_vttablet_state('SERVING')
utils.run_vtctl(['InitShardMaster', 'test_keyspace/0',
shard_0_master.tablet_alias], auto_log=True)
utils.run_vtctl(['RebuildKeyspaceGraph', 'test_keyspace'], auto_log=True)
ks = utils.run_vtctl_json(['GetSrvKeyspace', 'test_nj', 'test_keyspace'])
self.assertEqual(len(ks['Partitions']['master']['ShardReferences']), 1)
self.assertEqual(len(ks['Partitions']['rdonly']['ShardReferences']), 1)
s = utils.run_vtctl_json(['GetShard', 'test_keyspace/0'])
self.assertEqual(len(s['served_types']), 3)
# create a table on shard 0
sql = '''create table data(
id bigint auto_increment,
name varchar(64),
primary key (id)
) Engine=InnoDB'''
utils.run_vtctl(['ApplySchema', '-sql=' + sql, 'test_keyspace'],
auto_log=True)
# insert data on shard 0
self._insert_data('0', 100, 10)
# re-read shard 0 data
self._check_data('0', 100, 10)
# create shard 1
shard_1_master.init_tablet('master', 'test_keyspace', '1')
shard_1_rdonly.init_tablet('rdonly', 'test_keyspace', '1')
for t in [shard_1_master, shard_1_rdonly]:
t.start_vttablet(wait_for_state=None)
for t in [shard_1_master, shard_1_rdonly]:
t.wait_for_vttablet_state('NOT_SERVING')
s = utils.run_vtctl_json(['GetShard', 'test_keyspace/1'])
self.assertEqual(len(s['served_types']), 3)
utils.run_vtctl(['InitShardMaster', 'test_keyspace/1',
shard_1_master.tablet_alias], auto_log=True)
utils.run_vtctl(['CopySchemaShard', shard_0_rdonly.tablet_alias,
'test_keyspace/1'], auto_log=True)
for t in [shard_1_master, shard_1_rdonly]:
utils.run_vtctl(['RefreshState', t.tablet_alias], auto_log=True)
t.wait_for_vttablet_state('SERVING')
# rebuild the keyspace serving graph now that the new shard was added
utils.run_vtctl(['RebuildKeyspaceGraph', 'test_keyspace'], auto_log=True)
# insert data on shard 1
self._insert_data('1', 200, 10)
# re-read shard 1 data
self._check_data('1', 200, 10)
# create a second table on all shards
sql = '''create table data2(
id bigint auto_increment,
name varchar(64),
primary key (id)
) Engine=InnoDB'''
utils.run_vtctl(['ApplySchema', '-sql=' + sql, 'test_keyspace'],
auto_log=True)
# insert and read data on all shards
self._insert_data('0', 300, 10, table='data2')
self._insert_data('1', 400, 10, table='data2')
self._check_data('0', 300, 10, table='data2')
self._check_data('1', 400, 10, table='data2')
# reload schema everywhere so the QueryService knows about the tables
for t in [shard_0_master, shard_0_rdonly, shard_1_master, shard_1_rdonly]:
utils.run_vtctl(['ReloadSchema', t.tablet_alias], auto_log=True)
utils.run_vtctl(['RebuildKeyspaceGraph', 'test_keyspace'], auto_log=True)
ks = utils.run_vtctl_json(['GetSrvKeyspace', 'test_nj', 'test_keyspace'])
self.assertEqual(len(ks['Partitions']['master']['ShardReferences']), 2)
self.assertEqual(len(ks['Partitions']['rdonly']['ShardReferences']), 2)
# Now test SplitQuery API works (used in MapReduce usually, but bringing
# up a full MR-capable cluster is too much for this test environment)
sql = 'select id, name from data'
s = utils.vtgate.split_query(sql, 'test_keyspace', 4)
self.assertEqual(len(s), 4)
shard0count = 0
shard1count = 0
for q in s:
if q['QueryShard']['Shards'][0] == '0':
shard0count += 1
if q['QueryShard']['Shards'][0] == '1':
shard1count += 1
self.assertEqual(shard0count, 2)
self.assertEqual(shard1count, 2)
# run the queries, aggregate the results, make sure we have all rows
rows = {}
for q in s:
qr = utils.vtgate.execute_shard(
q['QueryShard']['Sql'],
'test_keyspace', ','.join(q['QueryShard']['Shards']),
tablet_type='master', bindvars=q['QueryShard']['BindVariables'])
for r in qr['Rows']:
id = int(r[0])
rows[id] = r[1]
self.assertEqual(len(rows), 20)
expected = {}
for i in xrange(10):
expected[100 + i] = 'row %d' % (100 + i)
expected[200 + i] = 'row %d' % (200 + i)
self.assertEqual(rows, expected)
if __name__ == '__main__':
utils.main()
| t.create_db('vt_test_keyspace')
t.start_vttablet(wait_for_state=None) | conditional_block |
custom_sharding.py | #!/usr/bin/env python
#
# Copyright 2015, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
import unittest
import environment
import utils
import tablet
# shards
shard_0_master = tablet.Tablet()
shard_0_rdonly = tablet.Tablet()
shard_1_master = tablet.Tablet()
shard_1_rdonly = tablet.Tablet()
def setUpModule():
try:
environment.topo_server().setup()
setup_procs = [
shard_0_master.init_mysql(),
shard_0_rdonly.init_mysql(),
shard_1_master.init_mysql(),
shard_1_rdonly.init_mysql(),
]
utils.Vtctld().start()
utils.VtGate().start()
utils.wait_procs(setup_procs)
except: | raise
def tearDownModule():
if utils.options.skip_teardown:
return
teardown_procs = [
shard_0_master.teardown_mysql(),
shard_0_rdonly.teardown_mysql(),
shard_1_master.teardown_mysql(),
shard_1_rdonly.teardown_mysql(),
]
utils.wait_procs(teardown_procs, raise_on_error=False)
environment.topo_server().teardown()
utils.kill_sub_processes()
utils.remove_tmp_files()
shard_0_master.remove_tree()
shard_0_rdonly.remove_tree()
shard_1_master.remove_tree()
shard_1_rdonly.remove_tree()
class TestCustomSharding(unittest.TestCase):
def _insert_data(self, shard, start, count, table='data'):
sql = 'insert into %s(id, name) values (:id, :name)' % table
for x in xrange(count):
bindvars = {
'id': start+x,
'name': 'row %d' % (start+x),
}
utils.vtgate.execute_shard(sql, 'test_keyspace', shard,
bindvars=bindvars)
def _check_data(self, shard, start, count, table='data'):
sql = 'select name from %s where id=:id' % table
for x in xrange(count):
bindvars = {
'id': start+x,
}
qr = utils.vtgate.execute_shard(sql, 'test_keyspace', shard,
bindvars=bindvars)
self.assertEqual(len(qr['Rows']), 1)
v = qr['Rows'][0][0]
self.assertEqual(v, 'row %d' % (start+x))
def test_custom_end_to_end(self):
"""Runs through the common operations of a custom sharded keyspace.
Tests creation with one shard, schema change, reading / writing
data, adding one more shard, reading / writing data from both
shards, applying schema changes again, and reading / writing data
from both shards again.
"""
utils.run_vtctl(['CreateKeyspace', 'test_keyspace'])
# start the first shard only for now
shard_0_master.init_tablet('master', 'test_keyspace', '0')
shard_0_rdonly.init_tablet('rdonly', 'test_keyspace', '0')
for t in [shard_0_master, shard_0_rdonly]:
t.create_db('vt_test_keyspace')
t.start_vttablet(wait_for_state=None)
for t in [shard_0_master, shard_0_rdonly]:
t.wait_for_vttablet_state('SERVING')
utils.run_vtctl(['InitShardMaster', 'test_keyspace/0',
shard_0_master.tablet_alias], auto_log=True)
utils.run_vtctl(['RebuildKeyspaceGraph', 'test_keyspace'], auto_log=True)
ks = utils.run_vtctl_json(['GetSrvKeyspace', 'test_nj', 'test_keyspace'])
self.assertEqual(len(ks['Partitions']['master']['ShardReferences']), 1)
self.assertEqual(len(ks['Partitions']['rdonly']['ShardReferences']), 1)
s = utils.run_vtctl_json(['GetShard', 'test_keyspace/0'])
self.assertEqual(len(s['served_types']), 3)
# create a table on shard 0
sql = '''create table data(
id bigint auto_increment,
name varchar(64),
primary key (id)
) Engine=InnoDB'''
utils.run_vtctl(['ApplySchema', '-sql=' + sql, 'test_keyspace'],
auto_log=True)
# insert data on shard 0
self._insert_data('0', 100, 10)
# re-read shard 0 data
self._check_data('0', 100, 10)
# create shard 1
shard_1_master.init_tablet('master', 'test_keyspace', '1')
shard_1_rdonly.init_tablet('rdonly', 'test_keyspace', '1')
for t in [shard_1_master, shard_1_rdonly]:
t.start_vttablet(wait_for_state=None)
for t in [shard_1_master, shard_1_rdonly]:
t.wait_for_vttablet_state('NOT_SERVING')
s = utils.run_vtctl_json(['GetShard', 'test_keyspace/1'])
self.assertEqual(len(s['served_types']), 3)
utils.run_vtctl(['InitShardMaster', 'test_keyspace/1',
shard_1_master.tablet_alias], auto_log=True)
utils.run_vtctl(['CopySchemaShard', shard_0_rdonly.tablet_alias,
'test_keyspace/1'], auto_log=True)
for t in [shard_1_master, shard_1_rdonly]:
utils.run_vtctl(['RefreshState', t.tablet_alias], auto_log=True)
t.wait_for_vttablet_state('SERVING')
# rebuild the keyspace serving graph now that the new shard was added
utils.run_vtctl(['RebuildKeyspaceGraph', 'test_keyspace'], auto_log=True)
# insert data on shard 1
self._insert_data('1', 200, 10)
# re-read shard 1 data
self._check_data('1', 200, 10)
# create a second table on all shards
sql = '''create table data2(
id bigint auto_increment,
name varchar(64),
primary key (id)
) Engine=InnoDB'''
utils.run_vtctl(['ApplySchema', '-sql=' + sql, 'test_keyspace'],
auto_log=True)
# insert and read data on all shards
self._insert_data('0', 300, 10, table='data2')
self._insert_data('1', 400, 10, table='data2')
self._check_data('0', 300, 10, table='data2')
self._check_data('1', 400, 10, table='data2')
# reload schema everywhere so the QueryService knows about the tables
for t in [shard_0_master, shard_0_rdonly, shard_1_master, shard_1_rdonly]:
utils.run_vtctl(['ReloadSchema', t.tablet_alias], auto_log=True)
utils.run_vtctl(['RebuildKeyspaceGraph', 'test_keyspace'], auto_log=True)
ks = utils.run_vtctl_json(['GetSrvKeyspace', 'test_nj', 'test_keyspace'])
self.assertEqual(len(ks['Partitions']['master']['ShardReferences']), 2)
self.assertEqual(len(ks['Partitions']['rdonly']['ShardReferences']), 2)
# Now test SplitQuery API works (used in MapReduce usually, but bringing
# up a full MR-capable cluster is too much for this test environment)
sql = 'select id, name from data'
s = utils.vtgate.split_query(sql, 'test_keyspace', 4)
self.assertEqual(len(s), 4)
shard0count = 0
shard1count = 0
for q in s:
if q['QueryShard']['Shards'][0] == '0':
shard0count += 1
if q['QueryShard']['Shards'][0] == '1':
shard1count += 1
self.assertEqual(shard0count, 2)
self.assertEqual(shard1count, 2)
# run the queries, aggregate the results, make sure we have all rows
rows = {}
for q in s:
qr = utils.vtgate.execute_shard(
q['QueryShard']['Sql'],
'test_keyspace', ','.join(q['QueryShard']['Shards']),
tablet_type='master', bindvars=q['QueryShard']['BindVariables'])
for r in qr['Rows']:
id = int(r[0])
rows[id] = r[1]
self.assertEqual(len(rows), 20)
expected = {}
for i in xrange(10):
expected[100 + i] = 'row %d' % (100 + i)
expected[200 + i] = 'row %d' % (200 + i)
self.assertEqual(rows, expected)
if __name__ == '__main__':
utils.main() | tearDownModule() | random_line_split |
window.rs | use std::collections::vec_deque::IntoIter as VecDequeIter;
use std::default::Default;
use Api;
use BuilderAttribs;
use ContextError;
use CreationError;
use CursorState;
use Event;
use GlContext;
use GlProfile;
use GlRequest;
use MouseCursor;
use PixelFormat;
use Robustness;
use native_monitor::NativeMonitorId;
use gl_common;
use libc;
use platform;
/// Object that allows you to build windows.
pub struct WindowBuilder<'a> {
attribs: BuilderAttribs<'a>
}
impl<'a> WindowBuilder<'a> {
/// Initializes a new `WindowBuilder` with default values.
pub fn new() -> WindowBuilder<'a> {
WindowBuilder {
attribs: BuilderAttribs::new(),
}
}
/// Requests the window to be of specific dimensions.
///
/// Width and height are in pixels.
pub fn with_dimensions(mut self, width: u32, height: u32) -> WindowBuilder<'a> {
self.attribs.dimensions = Some((width, height));
self
}
/// Requests a specific title for the window.
pub fn with_title(mut self, title: String) -> WindowBuilder<'a> {
self.attribs.title = title;
self
}
/// Requests fullscreen mode.
///
/// If you don't specify dimensions for the window, it will match the monitor's.
pub fn with_fullscreen(mut self, monitor: MonitorID) -> WindowBuilder<'a> {
let MonitorID(monitor) = monitor;
self.attribs.monitor = Some(monitor);
self
}
/// The created window will share all its OpenGL objects with the window in the parameter.
///
/// There are some exceptions, like FBOs or VAOs. See the OpenGL documentation.
pub fn with_shared_lists(mut self, other: &'a Window) -> WindowBuilder<'a> {
self.attribs.sharing = Some(&other.window);
self
}
/// Sets how the backend should choose the OpenGL API and version.
pub fn with_gl(mut self, request: GlRequest) -> WindowBuilder<'a> {
self.attribs.gl_version = request;
self
}
/// Sets the desired OpenGL context profile.
pub fn with_gl_profile(mut self, profile: GlProfile) -> WindowBuilder<'a> {
self.attribs.gl_profile = Some(profile);
self
}
/// Sets the *debug* flag for the OpenGL context.
///
/// The default value for this flag is `cfg!(debug_assertions)`, which means that it's enabled
/// when you run `cargo build` and disabled when you run `cargo build --release`.
pub fn with_gl_debug_flag(mut self, flag: bool) -> WindowBuilder<'a> {
self.attribs.gl_debug = flag;
self
}
/// Sets the robustness of the OpenGL context. See the docs of `Robustness`.
pub fn with_gl_robustness(mut self, robustness: Robustness) -> WindowBuilder<'a> {
self.attribs.gl_robustness = robustness;
self
}
/// Requests that the window has vsync enabled.
pub fn with_vsync(mut self) -> WindowBuilder<'a> {
self.attribs.vsync = true;
self
}
/// Sets whether the window will be initially hidden or visible.
pub fn with_visibility(mut self, visible: bool) -> WindowBuilder<'a> {
self.attribs.visible = visible;
self
}
/// Sets the multisampling level to request.
///
/// # Panic
///
/// Will panic if `samples` is not a power of two.
pub fn with_multisampling(mut self, samples: u16) -> WindowBuilder<'a> {
assert!(samples.is_power_of_two());
self.attribs.multisampling = Some(samples);
self
}
/// Sets the number of bits in the depth buffer.
pub fn with_depth_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.depth_bits = Some(bits);
self
}
/// Sets the number of bits in the stencil buffer.
pub fn with_stencil_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.stencil_bits = Some(bits);
self
}
/// Sets the number of bits in the color buffer.
pub fn with_pixel_format(mut self, color_bits: u8, alpha_bits: u8) -> WindowBuilder<'a> {
self.attribs.color_bits = Some(color_bits);
self.attribs.alpha_bits = Some(alpha_bits);
self
}
/// Request the backend to be stereoscopic.
pub fn with_stereoscopy(mut self) -> WindowBuilder<'a> {
self.attribs.stereoscopy = true;
self
}
/// Sets whether sRGB should be enabled on the window. `None` means "I don't care".
pub fn with_srgb(mut self, srgb_enabled: Option<bool>) -> WindowBuilder<'a> {
self.attribs.srgb = srgb_enabled;
self
}
/// Sets whether the background of the window should be transparent.
pub fn with_transparency(mut self, transparent: bool) -> WindowBuilder<'a> {
self.attribs.transparent = transparent;
self
}
/// Sets whether the window should have a border, a title bar, etc.
pub fn with_decorations(mut self, decorations: bool) -> WindowBuilder<'a> {
self.attribs.decorations = decorations;
self
}
/// Builds the window.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
pub fn build(mut self) -> Result<Window, CreationError> {
// resizing the window to the dimensions of the monitor when fullscreen
if self.attribs.dimensions.is_none() && self.attribs.monitor.is_some() {
self.attribs.dimensions = Some(self.attribs.monitor.as_ref().unwrap().get_dimensions())
}
// default dimensions
if self.attribs.dimensions.is_none() {
self.attribs.dimensions = Some((1024, 768));
}
// building
platform::Window::new(self.attribs).map(|w| Window { window: w })
}
/// Builds the window.
///
/// The context is build in a *strict* way. That means that if the backend couldn't give
/// you what you requested, an `Err` will be returned.
pub fn build_strict(mut self) -> Result<Window, CreationError> {
self.attribs.strict = true;
self.build()
}
}
/// Represents an OpenGL context and the Window or environment around it.
///
/// # Example
///
/// ```ignore
/// let window = Window::new().unwrap();
///
/// unsafe { window.make_current() };
///
/// loop {
/// for event in window.poll_events() {
/// match(event) {
/// // process events here
/// _ => ()
/// }
/// }
///
/// // draw everything here
///
/// window.swap_buffers();
/// std::old_io::timer::sleep(17);
/// }
/// ```
pub struct Window {
window: platform::Window,
}
impl Default for Window {
fn default() -> Window {
Window::new().unwrap()
}
}
impl Window {
/// Creates a new OpenGL context, and a Window for platforms where this is appropriate.
///
/// This function is equivalent to `WindowBuilder::new().build()`.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
#[inline]
pub fn new() -> Result<Window, CreationError> {
let builder = WindowBuilder::new();
builder.build()
}
/// Modifies the title of the window.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_title(&self, title: &str) {
self.window.set_title(title)
}
/// Shows the window if it was hidden.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn show(&self) {
self.window.show()
}
/// Hides the window if it was visible.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn hide(&self) {
self.window.hide()
}
/// Returns the position of the top-left hand corner of the window relative to the
/// top-left hand corner of the desktop.
///
/// Note that the top-left hand corner of the desktop is not necessarily the same as
/// the screen. If the user uses a desktop with multiple monitors, the top-left hand corner
/// of the desktop is the top-left hand corner of the monitor at the top-left of the desktop.
///
/// The coordinates can be negative if the top-left hand corner of the window is outside
/// of the visible screen region.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_position(&self) -> Option<(i32, i32)> {
self.window.get_position()
}
/// Modifies the position of the window.
///
/// See `get_position` for more informations about the coordinates.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_position(&self, x: i32, y: i32) {
self.window.set_position(x, y)
}
/// Returns the size in pixels of the client area of the window.
///
/// The client area is the content of the window, excluding the title bar and borders.
/// These are the dimensions of the frame buffer, and the dimensions that you should use
/// when you call `glViewport`.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
self.window.get_inner_size()
}
/// Returns the size in pixels of the window.
///
/// These dimensions include title bar and borders. If you don't want these, you should use
/// use `get_inner_size` instead.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.window.get_outer_size()
}
/// Modifies the inner size of the window.
///
/// See `get_inner_size` for more informations about the values.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_inner_size(&self, x: u32, y: u32) {
self.window.set_inner_size(x, y)
}
/// Returns an iterator that poll for the next event in the window's events queue.
/// Returns `None` if there is no event in the queue.
///
/// Contrary to `wait_events`, this function never blocks.
#[inline]
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator(self.window.poll_events())
}
/// Returns an iterator that returns events one by one, blocking if necessary until one is
/// available.
///
/// The iterator never returns `None`.
#[inline]
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator(self.window.wait_events())
}
/// Sets the context as the current context.
#[inline] | self.window.make_current()
}
/// Returns true if this context is the current one in this thread.
#[inline]
pub fn is_current(&self) -> bool {
self.window.is_current()
}
/// Returns the address of an OpenGL function.
///
/// Contrary to `wglGetProcAddress`, all available OpenGL functions return an address.
#[inline]
pub fn get_proc_address(&self, addr: &str) -> *const libc::c_void {
self.window.get_proc_address(addr) as *const libc::c_void
}
/// Swaps the buffers in case of double or triple buffering.
///
/// You should call this function every time you have finished rendering, or the image
/// may not be displayed on the screen.
///
/// **Warning**: if you enabled vsync, this function will block until the next time the screen
/// is refreshed. However drivers can choose to override your vsync settings, which means that
/// you can't know in advance whether `swap_buffers` will block or not.
#[inline]
pub fn swap_buffers(&self) -> Result<(), ContextError> {
self.window.swap_buffers()
}
/// Gets the native platform specific display for this window.
/// This is typically only required when integrating with
/// other libraries that need this information.
#[inline]
pub unsafe fn platform_display(&self) -> *mut libc::c_void {
self.window.platform_display()
}
/// Gets the native platform specific window handle. This is
/// typically only required when integrating with other libraries
/// that need this information.
#[inline]
pub unsafe fn platform_window(&self) -> *mut libc::c_void {
self.window.platform_window()
}
/// Returns the API that is currently provided by this window.
///
/// - On Windows and OS/X, this always returns `OpenGl`.
/// - On Android, this always returns `OpenGlEs`.
/// - On Linux, it must be checked at runtime.
pub fn get_api(&self) -> Api {
self.window.get_api()
}
/// Returns the pixel format of this window.
pub fn get_pixel_format(&self) -> PixelFormat {
self.window.get_pixel_format()
}
/// Create a window proxy for this window, that can be freely
/// passed to different threads.
#[inline]
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy {
proxy: self.window.create_window_proxy()
}
}
/// Sets a resize callback that is called by Mac (and potentially other
/// operating systems) during resize operations. This can be used to repaint
/// during window resizing.
pub fn set_window_resize_callback(&mut self, callback: Option<fn(u32, u32)>) {
self.window.set_window_resize_callback(callback);
}
/// Modifies the mouse cursor of the window.
/// Has no effect on Android.
pub fn set_cursor(&self, cursor: MouseCursor) {
self.window.set_cursor(cursor);
}
/// Returns the ratio between the backing framebuffer resolution and the
/// window size in screen pixels. This is typically one for a normal display
/// and two for a retina display.
pub fn hidpi_factor(&self) -> f32 {
self.window.hidpi_factor()
}
/// Changes the position of the cursor in window coordinates.
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
self.window.set_cursor_position(x, y)
}
/// Sets how glutin handles the cursor. See the documentation of `CursorState` for details.
///
/// Has no effect on Android.
pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> {
self.window.set_cursor_state(state)
}
}
impl gl_common::GlFunctionsSource for Window {
fn get_proc_addr(&self, addr: &str) -> *const libc::c_void {
self.get_proc_address(addr)
}
}
impl GlContext for Window {
unsafe fn make_current(&self) -> Result<(), ContextError> {
self.make_current()
}
fn is_current(&self) -> bool {
self.is_current()
}
fn get_proc_address(&self, addr: &str) -> *const libc::c_void {
self.get_proc_address(addr)
}
fn swap_buffers(&self) -> Result<(), ContextError> {
self.swap_buffers()
}
fn get_api(&self) -> Api {
self.get_api()
}
fn get_pixel_format(&self) -> PixelFormat {
self.get_pixel_format()
}
}
/// Represents a thread safe subset of operations that can be called
/// on a window. This structure can be safely cloned and sent between
/// threads.
#[derive(Clone)]
pub struct WindowProxy {
proxy: platform::WindowProxy,
}
impl WindowProxy {
/// Triggers a blocked event loop to wake up. This is
/// typically called when another thread wants to wake
/// up the blocked rendering thread to cause a refresh.
#[inline]
pub fn wakeup_event_loop(&self) {
self.proxy.wakeup_event_loop();
}
}
/// An iterator for the `poll_events` function.
pub struct PollEventsIterator<'a>(platform::PollEventsIterator<'a>);
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the `wait_events` function.
pub struct WaitEventsIterator<'a>(platform::WaitEventsIterator<'a>);
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the list of available monitors.
// Implementation note: we retreive the list once, then serve each element by one by one.
// This may change in the future.
pub struct AvailableMonitorsIter {
data: VecDequeIter<platform::MonitorID>,
}
impl Iterator for AvailableMonitorsIter {
type Item = MonitorID;
fn next(&mut self) -> Option<MonitorID> {
self.data.next().map(|id| MonitorID(id))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.data.size_hint()
}
}
/// Returns the list of all available monitors.
pub fn get_available_monitors() -> AvailableMonitorsIter {
let data = platform::get_available_monitors();
AvailableMonitorsIter{ data: data.into_iter() }
}
/// Returns the primary monitor of the system.
pub fn get_primary_monitor() -> MonitorID {
MonitorID(platform::get_primary_monitor())
}
/// Identifier for a monitor.
pub struct MonitorID(platform::MonitorID);
impl MonitorID {
/// Returns a human-readable name of the monitor.
pub fn get_name(&self) -> Option<String> {
let &MonitorID(ref id) = self;
id.get_name()
}
/// Returns the native platform identifier for this monitor.
pub fn get_native_identifier(&self) -> NativeMonitorId {
let &MonitorID(ref id) = self;
id.get_native_identifier()
}
/// Returns the number of pixels currently displayed on the monitor.
pub fn get_dimensions(&self) -> (u32, u32) {
let &MonitorID(ref id) = self;
id.get_dimensions()
}
} | pub unsafe fn make_current(&self) -> Result<(), ContextError> { | random_line_split |
window.rs | use std::collections::vec_deque::IntoIter as VecDequeIter;
use std::default::Default;
use Api;
use BuilderAttribs;
use ContextError;
use CreationError;
use CursorState;
use Event;
use GlContext;
use GlProfile;
use GlRequest;
use MouseCursor;
use PixelFormat;
use Robustness;
use native_monitor::NativeMonitorId;
use gl_common;
use libc;
use platform;
/// Object that allows you to build windows.
pub struct WindowBuilder<'a> {
attribs: BuilderAttribs<'a>
}
impl<'a> WindowBuilder<'a> {
/// Initializes a new `WindowBuilder` with default values.
pub fn new() -> WindowBuilder<'a> {
WindowBuilder {
attribs: BuilderAttribs::new(),
}
}
/// Requests the window to be of specific dimensions.
///
/// Width and height are in pixels.
pub fn with_dimensions(mut self, width: u32, height: u32) -> WindowBuilder<'a> {
self.attribs.dimensions = Some((width, height));
self
}
/// Requests a specific title for the window.
pub fn with_title(mut self, title: String) -> WindowBuilder<'a> {
self.attribs.title = title;
self
}
/// Requests fullscreen mode.
///
/// If you don't specify dimensions for the window, it will match the monitor's.
pub fn with_fullscreen(mut self, monitor: MonitorID) -> WindowBuilder<'a> {
let MonitorID(monitor) = monitor;
self.attribs.monitor = Some(monitor);
self
}
/// The created window will share all its OpenGL objects with the window in the parameter.
///
/// There are some exceptions, like FBOs or VAOs. See the OpenGL documentation.
pub fn with_shared_lists(mut self, other: &'a Window) -> WindowBuilder<'a> {
self.attribs.sharing = Some(&other.window);
self
}
/// Sets how the backend should choose the OpenGL API and version.
pub fn with_gl(mut self, request: GlRequest) -> WindowBuilder<'a> {
self.attribs.gl_version = request;
self
}
/// Sets the desired OpenGL context profile.
pub fn with_gl_profile(mut self, profile: GlProfile) -> WindowBuilder<'a> {
self.attribs.gl_profile = Some(profile);
self
}
/// Sets the *debug* flag for the OpenGL context.
///
/// The default value for this flag is `cfg!(debug_assertions)`, which means that it's enabled
/// when you run `cargo build` and disabled when you run `cargo build --release`.
pub fn with_gl_debug_flag(mut self, flag: bool) -> WindowBuilder<'a> {
self.attribs.gl_debug = flag;
self
}
/// Sets the robustness of the OpenGL context. See the docs of `Robustness`.
pub fn with_gl_robustness(mut self, robustness: Robustness) -> WindowBuilder<'a> {
self.attribs.gl_robustness = robustness;
self
}
/// Requests that the window has vsync enabled.
pub fn with_vsync(mut self) -> WindowBuilder<'a> {
self.attribs.vsync = true;
self
}
/// Sets whether the window will be initially hidden or visible.
pub fn with_visibility(mut self, visible: bool) -> WindowBuilder<'a> {
self.attribs.visible = visible;
self
}
/// Sets the multisampling level to request.
///
/// # Panic
///
/// Will panic if `samples` is not a power of two.
pub fn with_multisampling(mut self, samples: u16) -> WindowBuilder<'a> {
assert!(samples.is_power_of_two());
self.attribs.multisampling = Some(samples);
self
}
/// Sets the number of bits in the depth buffer.
pub fn with_depth_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.depth_bits = Some(bits);
self
}
/// Sets the number of bits in the stencil buffer.
pub fn with_stencil_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.stencil_bits = Some(bits);
self
}
/// Sets the number of bits in the color buffer.
pub fn with_pixel_format(mut self, color_bits: u8, alpha_bits: u8) -> WindowBuilder<'a> {
self.attribs.color_bits = Some(color_bits);
self.attribs.alpha_bits = Some(alpha_bits);
self
}
/// Request the backend to be stereoscopic.
pub fn with_stereoscopy(mut self) -> WindowBuilder<'a> {
self.attribs.stereoscopy = true;
self
}
/// Sets whether sRGB should be enabled on the window. `None` means "I don't care".
pub fn with_srgb(mut self, srgb_enabled: Option<bool>) -> WindowBuilder<'a> {
self.attribs.srgb = srgb_enabled;
self
}
/// Sets whether the background of the window should be transparent.
pub fn with_transparency(mut self, transparent: bool) -> WindowBuilder<'a> {
self.attribs.transparent = transparent;
self
}
/// Sets whether the window should have a border, a title bar, etc.
pub fn with_decorations(mut self, decorations: bool) -> WindowBuilder<'a> {
self.attribs.decorations = decorations;
self
}
/// Builds the window.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
pub fn build(mut self) -> Result<Window, CreationError> {
// resizing the window to the dimensions of the monitor when fullscreen
if self.attribs.dimensions.is_none() && self.attribs.monitor.is_some() |
// default dimensions
if self.attribs.dimensions.is_none() {
self.attribs.dimensions = Some((1024, 768));
}
// building
platform::Window::new(self.attribs).map(|w| Window { window: w })
}
/// Builds the window.
///
/// The context is build in a *strict* way. That means that if the backend couldn't give
/// you what you requested, an `Err` will be returned.
pub fn build_strict(mut self) -> Result<Window, CreationError> {
self.attribs.strict = true;
self.build()
}
}
/// Represents an OpenGL context and the Window or environment around it.
///
/// # Example
///
/// ```ignore
/// let window = Window::new().unwrap();
///
/// unsafe { window.make_current() };
///
/// loop {
/// for event in window.poll_events() {
/// match(event) {
/// // process events here
/// _ => ()
/// }
/// }
///
/// // draw everything here
///
/// window.swap_buffers();
/// std::old_io::timer::sleep(17);
/// }
/// ```
pub struct Window {
window: platform::Window,
}
impl Default for Window {
fn default() -> Window {
Window::new().unwrap()
}
}
impl Window {
/// Creates a new OpenGL context, and a Window for platforms where this is appropriate.
///
/// This function is equivalent to `WindowBuilder::new().build()`.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
#[inline]
pub fn new() -> Result<Window, CreationError> {
let builder = WindowBuilder::new();
builder.build()
}
/// Modifies the title of the window.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_title(&self, title: &str) {
self.window.set_title(title)
}
/// Shows the window if it was hidden.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn show(&self) {
self.window.show()
}
/// Hides the window if it was visible.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn hide(&self) {
self.window.hide()
}
/// Returns the position of the top-left hand corner of the window relative to the
/// top-left hand corner of the desktop.
///
/// Note that the top-left hand corner of the desktop is not necessarily the same as
/// the screen. If the user uses a desktop with multiple monitors, the top-left hand corner
/// of the desktop is the top-left hand corner of the monitor at the top-left of the desktop.
///
/// The coordinates can be negative if the top-left hand corner of the window is outside
/// of the visible screen region.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_position(&self) -> Option<(i32, i32)> {
self.window.get_position()
}
/// Modifies the position of the window.
///
/// See `get_position` for more informations about the coordinates.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_position(&self, x: i32, y: i32) {
self.window.set_position(x, y)
}
/// Returns the size in pixels of the client area of the window.
///
/// The client area is the content of the window, excluding the title bar and borders.
/// These are the dimensions of the frame buffer, and the dimensions that you should use
/// when you call `glViewport`.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
self.window.get_inner_size()
}
/// Returns the size in pixels of the window.
///
/// These dimensions include title bar and borders. If you don't want these, you should use
/// use `get_inner_size` instead.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.window.get_outer_size()
}
/// Modifies the inner size of the window.
///
/// See `get_inner_size` for more informations about the values.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_inner_size(&self, x: u32, y: u32) {
self.window.set_inner_size(x, y)
}
/// Returns an iterator that poll for the next event in the window's events queue.
/// Returns `None` if there is no event in the queue.
///
/// Contrary to `wait_events`, this function never blocks.
#[inline]
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator(self.window.poll_events())
}
/// Returns an iterator that returns events one by one, blocking if necessary until one is
/// available.
///
/// The iterator never returns `None`.
#[inline]
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator(self.window.wait_events())
}
/// Sets the context as the current context.
#[inline]
pub unsafe fn make_current(&self) -> Result<(), ContextError> {
self.window.make_current()
}
/// Returns true if this context is the current one in this thread.
#[inline]
pub fn is_current(&self) -> bool {
self.window.is_current()
}
/// Returns the address of an OpenGL function.
///
/// Contrary to `wglGetProcAddress`, all available OpenGL functions return an address.
#[inline]
pub fn get_proc_address(&self, addr: &str) -> *const libc::c_void {
self.window.get_proc_address(addr) as *const libc::c_void
}
/// Swaps the buffers in case of double or triple buffering.
///
/// You should call this function every time you have finished rendering, or the image
/// may not be displayed on the screen.
///
/// **Warning**: if you enabled vsync, this function will block until the next time the screen
/// is refreshed. However drivers can choose to override your vsync settings, which means that
/// you can't know in advance whether `swap_buffers` will block or not.
#[inline]
pub fn swap_buffers(&self) -> Result<(), ContextError> {
self.window.swap_buffers()
}
/// Gets the native platform specific display for this window.
/// This is typically only required when integrating with
/// other libraries that need this information.
#[inline]
pub unsafe fn platform_display(&self) -> *mut libc::c_void {
self.window.platform_display()
}
/// Gets the native platform specific window handle. This is
/// typically only required when integrating with other libraries
/// that need this information.
#[inline]
pub unsafe fn platform_window(&self) -> *mut libc::c_void {
self.window.platform_window()
}
/// Returns the API that is currently provided by this window.
///
/// - On Windows and OS/X, this always returns `OpenGl`.
/// - On Android, this always returns `OpenGlEs`.
/// - On Linux, it must be checked at runtime.
pub fn get_api(&self) -> Api {
self.window.get_api()
}
/// Returns the pixel format of this window.
pub fn get_pixel_format(&self) -> PixelFormat {
self.window.get_pixel_format()
}
/// Create a window proxy for this window, that can be freely
/// passed to different threads.
#[inline]
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy {
proxy: self.window.create_window_proxy()
}
}
/// Sets a resize callback that is called by Mac (and potentially other
/// operating systems) during resize operations. This can be used to repaint
/// during window resizing.
pub fn set_window_resize_callback(&mut self, callback: Option<fn(u32, u32)>) {
self.window.set_window_resize_callback(callback);
}
/// Modifies the mouse cursor of the window.
/// Has no effect on Android.
pub fn set_cursor(&self, cursor: MouseCursor) {
self.window.set_cursor(cursor);
}
/// Returns the ratio between the backing framebuffer resolution and the
/// window size in screen pixels. This is typically one for a normal display
/// and two for a retina display.
pub fn hidpi_factor(&self) -> f32 {
self.window.hidpi_factor()
}
/// Changes the position of the cursor in window coordinates.
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
self.window.set_cursor_position(x, y)
}
/// Sets how glutin handles the cursor. See the documentation of `CursorState` for details.
///
/// Has no effect on Android.
pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> {
self.window.set_cursor_state(state)
}
}
impl gl_common::GlFunctionsSource for Window {
fn get_proc_addr(&self, addr: &str) -> *const libc::c_void {
self.get_proc_address(addr)
}
}
impl GlContext for Window {
unsafe fn make_current(&self) -> Result<(), ContextError> {
self.make_current()
}
fn is_current(&self) -> bool {
self.is_current()
}
fn get_proc_address(&self, addr: &str) -> *const libc::c_void {
self.get_proc_address(addr)
}
fn swap_buffers(&self) -> Result<(), ContextError> {
self.swap_buffers()
}
fn get_api(&self) -> Api {
self.get_api()
}
fn get_pixel_format(&self) -> PixelFormat {
self.get_pixel_format()
}
}
/// Represents a thread safe subset of operations that can be called
/// on a window. This structure can be safely cloned and sent between
/// threads.
#[derive(Clone)]
pub struct WindowProxy {
proxy: platform::WindowProxy,
}
impl WindowProxy {
/// Triggers a blocked event loop to wake up. This is
/// typically called when another thread wants to wake
/// up the blocked rendering thread to cause a refresh.
#[inline]
pub fn wakeup_event_loop(&self) {
self.proxy.wakeup_event_loop();
}
}
/// An iterator for the `poll_events` function.
pub struct PollEventsIterator<'a>(platform::PollEventsIterator<'a>);
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the `wait_events` function.
pub struct WaitEventsIterator<'a>(platform::WaitEventsIterator<'a>);
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the list of available monitors.
// Implementation note: we retreive the list once, then serve each element by one by one.
// This may change in the future.
pub struct AvailableMonitorsIter {
data: VecDequeIter<platform::MonitorID>,
}
impl Iterator for AvailableMonitorsIter {
type Item = MonitorID;
fn next(&mut self) -> Option<MonitorID> {
self.data.next().map(|id| MonitorID(id))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.data.size_hint()
}
}
/// Returns the list of all available monitors.
pub fn get_available_monitors() -> AvailableMonitorsIter {
let data = platform::get_available_monitors();
AvailableMonitorsIter{ data: data.into_iter() }
}
/// Returns the primary monitor of the system.
pub fn get_primary_monitor() -> MonitorID {
MonitorID(platform::get_primary_monitor())
}
/// Identifier for a monitor.
pub struct MonitorID(platform::MonitorID);
impl MonitorID {
/// Returns a human-readable name of the monitor.
pub fn get_name(&self) -> Option<String> {
let &MonitorID(ref id) = self;
id.get_name()
}
/// Returns the native platform identifier for this monitor.
pub fn get_native_identifier(&self) -> NativeMonitorId {
let &MonitorID(ref id) = self;
id.get_native_identifier()
}
/// Returns the number of pixels currently displayed on the monitor.
pub fn get_dimensions(&self) -> (u32, u32) {
let &MonitorID(ref id) = self;
id.get_dimensions()
}
}
| {
self.attribs.dimensions = Some(self.attribs.monitor.as_ref().unwrap().get_dimensions())
} | conditional_block |
window.rs | use std::collections::vec_deque::IntoIter as VecDequeIter;
use std::default::Default;
use Api;
use BuilderAttribs;
use ContextError;
use CreationError;
use CursorState;
use Event;
use GlContext;
use GlProfile;
use GlRequest;
use MouseCursor;
use PixelFormat;
use Robustness;
use native_monitor::NativeMonitorId;
use gl_common;
use libc;
use platform;
/// Object that allows you to build windows.
pub struct WindowBuilder<'a> {
attribs: BuilderAttribs<'a>
}
impl<'a> WindowBuilder<'a> {
/// Initializes a new `WindowBuilder` with default values.
pub fn new() -> WindowBuilder<'a> {
WindowBuilder {
attribs: BuilderAttribs::new(),
}
}
/// Requests the window to be of specific dimensions.
///
/// Width and height are in pixels.
pub fn with_dimensions(mut self, width: u32, height: u32) -> WindowBuilder<'a> {
self.attribs.dimensions = Some((width, height));
self
}
/// Requests a specific title for the window.
pub fn with_title(mut self, title: String) -> WindowBuilder<'a> {
self.attribs.title = title;
self
}
/// Requests fullscreen mode.
///
/// If you don't specify dimensions for the window, it will match the monitor's.
pub fn with_fullscreen(mut self, monitor: MonitorID) -> WindowBuilder<'a> {
let MonitorID(monitor) = monitor;
self.attribs.monitor = Some(monitor);
self
}
/// The created window will share all its OpenGL objects with the window in the parameter.
///
/// There are some exceptions, like FBOs or VAOs. See the OpenGL documentation.
pub fn with_shared_lists(mut self, other: &'a Window) -> WindowBuilder<'a> {
self.attribs.sharing = Some(&other.window);
self
}
/// Sets how the backend should choose the OpenGL API and version.
pub fn with_gl(mut self, request: GlRequest) -> WindowBuilder<'a> {
self.attribs.gl_version = request;
self
}
/// Sets the desired OpenGL context profile.
pub fn with_gl_profile(mut self, profile: GlProfile) -> WindowBuilder<'a> {
self.attribs.gl_profile = Some(profile);
self
}
/// Sets the *debug* flag for the OpenGL context.
///
/// The default value for this flag is `cfg!(debug_assertions)`, which means that it's enabled
/// when you run `cargo build` and disabled when you run `cargo build --release`.
pub fn with_gl_debug_flag(mut self, flag: bool) -> WindowBuilder<'a> {
self.attribs.gl_debug = flag;
self
}
/// Sets the robustness of the OpenGL context. See the docs of `Robustness`.
pub fn with_gl_robustness(mut self, robustness: Robustness) -> WindowBuilder<'a> {
self.attribs.gl_robustness = robustness;
self
}
/// Requests that the window has vsync enabled.
pub fn with_vsync(mut self) -> WindowBuilder<'a> {
self.attribs.vsync = true;
self
}
/// Sets whether the window will be initially hidden or visible.
pub fn with_visibility(mut self, visible: bool) -> WindowBuilder<'a> {
self.attribs.visible = visible;
self
}
/// Sets the multisampling level to request.
///
/// # Panic
///
/// Will panic if `samples` is not a power of two.
pub fn with_multisampling(mut self, samples: u16) -> WindowBuilder<'a> {
assert!(samples.is_power_of_two());
self.attribs.multisampling = Some(samples);
self
}
/// Sets the number of bits in the depth buffer.
pub fn with_depth_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.depth_bits = Some(bits);
self
}
/// Sets the number of bits in the stencil buffer.
pub fn with_stencil_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.stencil_bits = Some(bits);
self
}
/// Sets the number of bits in the color buffer.
pub fn with_pixel_format(mut self, color_bits: u8, alpha_bits: u8) -> WindowBuilder<'a> {
self.attribs.color_bits = Some(color_bits);
self.attribs.alpha_bits = Some(alpha_bits);
self
}
/// Request the backend to be stereoscopic.
pub fn with_stereoscopy(mut self) -> WindowBuilder<'a> {
self.attribs.stereoscopy = true;
self
}
/// Sets whether sRGB should be enabled on the window. `None` means "I don't care".
pub fn with_srgb(mut self, srgb_enabled: Option<bool>) -> WindowBuilder<'a> {
self.attribs.srgb = srgb_enabled;
self
}
/// Sets whether the background of the window should be transparent.
pub fn with_transparency(mut self, transparent: bool) -> WindowBuilder<'a> {
self.attribs.transparent = transparent;
self
}
/// Sets whether the window should have a border, a title bar, etc.
pub fn with_decorations(mut self, decorations: bool) -> WindowBuilder<'a> {
self.attribs.decorations = decorations;
self
}
/// Builds the window.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
pub fn build(mut self) -> Result<Window, CreationError> {
// resizing the window to the dimensions of the monitor when fullscreen
if self.attribs.dimensions.is_none() && self.attribs.monitor.is_some() {
self.attribs.dimensions = Some(self.attribs.monitor.as_ref().unwrap().get_dimensions())
}
// default dimensions
if self.attribs.dimensions.is_none() {
self.attribs.dimensions = Some((1024, 768));
}
// building
platform::Window::new(self.attribs).map(|w| Window { window: w })
}
/// Builds the window.
///
/// The context is build in a *strict* way. That means that if the backend couldn't give
/// you what you requested, an `Err` will be returned.
pub fn build_strict(mut self) -> Result<Window, CreationError> {
self.attribs.strict = true;
self.build()
}
}
/// Represents an OpenGL context and the Window or environment around it.
///
/// # Example
///
/// ```ignore
/// let window = Window::new().unwrap();
///
/// unsafe { window.make_current() };
///
/// loop {
/// for event in window.poll_events() {
/// match(event) {
/// // process events here
/// _ => ()
/// }
/// }
///
/// // draw everything here
///
/// window.swap_buffers();
/// std::old_io::timer::sleep(17);
/// }
/// ```
pub struct Window {
window: platform::Window,
}
impl Default for Window {
fn default() -> Window {
Window::new().unwrap()
}
}
impl Window {
/// Creates a new OpenGL context, and a Window for platforms where this is appropriate.
///
/// This function is equivalent to `WindowBuilder::new().build()`.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
#[inline]
pub fn new() -> Result<Window, CreationError> {
let builder = WindowBuilder::new();
builder.build()
}
/// Modifies the title of the window.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_title(&self, title: &str) {
self.window.set_title(title)
}
/// Shows the window if it was hidden.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn show(&self) {
self.window.show()
}
/// Hides the window if it was visible.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn hide(&self) {
self.window.hide()
}
/// Returns the position of the top-left hand corner of the window relative to the
/// top-left hand corner of the desktop.
///
/// Note that the top-left hand corner of the desktop is not necessarily the same as
/// the screen. If the user uses a desktop with multiple monitors, the top-left hand corner
/// of the desktop is the top-left hand corner of the monitor at the top-left of the desktop.
///
/// The coordinates can be negative if the top-left hand corner of the window is outside
/// of the visible screen region.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_position(&self) -> Option<(i32, i32)> {
self.window.get_position()
}
/// Modifies the position of the window.
///
/// See `get_position` for more informations about the coordinates.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_position(&self, x: i32, y: i32) {
self.window.set_position(x, y)
}
/// Returns the size in pixels of the client area of the window.
///
/// The client area is the content of the window, excluding the title bar and borders.
/// These are the dimensions of the frame buffer, and the dimensions that you should use
/// when you call `glViewport`.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
self.window.get_inner_size()
}
/// Returns the size in pixels of the window.
///
/// These dimensions include title bar and borders. If you don't want these, you should use
/// use `get_inner_size` instead.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.window.get_outer_size()
}
/// Modifies the inner size of the window.
///
/// See `get_inner_size` for more informations about the values.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_inner_size(&self, x: u32, y: u32) {
self.window.set_inner_size(x, y)
}
/// Returns an iterator that poll for the next event in the window's events queue.
/// Returns `None` if there is no event in the queue.
///
/// Contrary to `wait_events`, this function never blocks.
#[inline]
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator(self.window.poll_events())
}
/// Returns an iterator that returns events one by one, blocking if necessary until one is
/// available.
///
/// The iterator never returns `None`.
#[inline]
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator(self.window.wait_events())
}
/// Sets the context as the current context.
#[inline]
pub unsafe fn make_current(&self) -> Result<(), ContextError> {
self.window.make_current()
}
/// Returns true if this context is the current one in this thread.
#[inline]
pub fn is_current(&self) -> bool {
self.window.is_current()
}
/// Returns the address of an OpenGL function.
///
/// Contrary to `wglGetProcAddress`, all available OpenGL functions return an address.
#[inline]
pub fn get_proc_address(&self, addr: &str) -> *const libc::c_void {
self.window.get_proc_address(addr) as *const libc::c_void
}
/// Swaps the buffers in case of double or triple buffering.
///
/// You should call this function every time you have finished rendering, or the image
/// may not be displayed on the screen.
///
/// **Warning**: if you enabled vsync, this function will block until the next time the screen
/// is refreshed. However drivers can choose to override your vsync settings, which means that
/// you can't know in advance whether `swap_buffers` will block or not.
#[inline]
pub fn swap_buffers(&self) -> Result<(), ContextError> {
self.window.swap_buffers()
}
/// Gets the native platform specific display for this window.
/// This is typically only required when integrating with
/// other libraries that need this information.
#[inline]
pub unsafe fn platform_display(&self) -> *mut libc::c_void {
self.window.platform_display()
}
/// Gets the native platform specific window handle. This is
/// typically only required when integrating with other libraries
/// that need this information.
#[inline]
pub unsafe fn platform_window(&self) -> *mut libc::c_void {
self.window.platform_window()
}
/// Returns the API that is currently provided by this window.
///
/// - On Windows and OS/X, this always returns `OpenGl`.
/// - On Android, this always returns `OpenGlEs`.
/// - On Linux, it must be checked at runtime.
pub fn get_api(&self) -> Api {
self.window.get_api()
}
/// Returns the pixel format of this window.
pub fn get_pixel_format(&self) -> PixelFormat {
self.window.get_pixel_format()
}
/// Create a window proxy for this window, that can be freely
/// passed to different threads.
#[inline]
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy {
proxy: self.window.create_window_proxy()
}
}
/// Sets a resize callback that is called by Mac (and potentially other
/// operating systems) during resize operations. This can be used to repaint
/// during window resizing.
pub fn set_window_resize_callback(&mut self, callback: Option<fn(u32, u32)>) {
self.window.set_window_resize_callback(callback);
}
/// Modifies the mouse cursor of the window.
/// Has no effect on Android.
pub fn set_cursor(&self, cursor: MouseCursor) {
self.window.set_cursor(cursor);
}
/// Returns the ratio between the backing framebuffer resolution and the
/// window size in screen pixels. This is typically one for a normal display
/// and two for a retina display.
pub fn hidpi_factor(&self) -> f32 {
self.window.hidpi_factor()
}
/// Changes the position of the cursor in window coordinates.
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
self.window.set_cursor_position(x, y)
}
/// Sets how glutin handles the cursor. See the documentation of `CursorState` for details.
///
/// Has no effect on Android.
pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> {
self.window.set_cursor_state(state)
}
}
impl gl_common::GlFunctionsSource for Window {
fn get_proc_addr(&self, addr: &str) -> *const libc::c_void {
self.get_proc_address(addr)
}
}
impl GlContext for Window {
unsafe fn make_current(&self) -> Result<(), ContextError> {
self.make_current()
}
fn is_current(&self) -> bool {
self.is_current()
}
fn get_proc_address(&self, addr: &str) -> *const libc::c_void {
self.get_proc_address(addr)
}
fn swap_buffers(&self) -> Result<(), ContextError> {
self.swap_buffers()
}
fn get_api(&self) -> Api {
self.get_api()
}
fn get_pixel_format(&self) -> PixelFormat {
self.get_pixel_format()
}
}
/// Represents a thread safe subset of operations that can be called
/// on a window. This structure can be safely cloned and sent between
/// threads.
#[derive(Clone)]
pub struct WindowProxy {
proxy: platform::WindowProxy,
}
impl WindowProxy {
/// Triggers a blocked event loop to wake up. This is
/// typically called when another thread wants to wake
/// up the blocked rendering thread to cause a refresh.
#[inline]
pub fn wakeup_event_loop(&self) |
}
/// An iterator for the `poll_events` function.
pub struct PollEventsIterator<'a>(platform::PollEventsIterator<'a>);
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the `wait_events` function.
pub struct WaitEventsIterator<'a>(platform::WaitEventsIterator<'a>);
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the list of available monitors.
// Implementation note: we retreive the list once, then serve each element by one by one.
// This may change in the future.
pub struct AvailableMonitorsIter {
data: VecDequeIter<platform::MonitorID>,
}
impl Iterator for AvailableMonitorsIter {
type Item = MonitorID;
fn next(&mut self) -> Option<MonitorID> {
self.data.next().map(|id| MonitorID(id))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.data.size_hint()
}
}
/// Returns the list of all available monitors.
pub fn get_available_monitors() -> AvailableMonitorsIter {
let data = platform::get_available_monitors();
AvailableMonitorsIter{ data: data.into_iter() }
}
/// Returns the primary monitor of the system.
pub fn get_primary_monitor() -> MonitorID {
MonitorID(platform::get_primary_monitor())
}
/// Identifier for a monitor.
pub struct MonitorID(platform::MonitorID);
impl MonitorID {
/// Returns a human-readable name of the monitor.
pub fn get_name(&self) -> Option<String> {
let &MonitorID(ref id) = self;
id.get_name()
}
/// Returns the native platform identifier for this monitor.
pub fn get_native_identifier(&self) -> NativeMonitorId {
let &MonitorID(ref id) = self;
id.get_native_identifier()
}
/// Returns the number of pixels currently displayed on the monitor.
pub fn get_dimensions(&self) -> (u32, u32) {
let &MonitorID(ref id) = self;
id.get_dimensions()
}
}
| {
self.proxy.wakeup_event_loop();
} | identifier_body |
window.rs | use std::collections::vec_deque::IntoIter as VecDequeIter;
use std::default::Default;
use Api;
use BuilderAttribs;
use ContextError;
use CreationError;
use CursorState;
use Event;
use GlContext;
use GlProfile;
use GlRequest;
use MouseCursor;
use PixelFormat;
use Robustness;
use native_monitor::NativeMonitorId;
use gl_common;
use libc;
use platform;
/// Object that allows you to build windows.
pub struct WindowBuilder<'a> {
attribs: BuilderAttribs<'a>
}
impl<'a> WindowBuilder<'a> {
/// Initializes a new `WindowBuilder` with default values.
pub fn new() -> WindowBuilder<'a> {
WindowBuilder {
attribs: BuilderAttribs::new(),
}
}
/// Requests the window to be of specific dimensions.
///
/// Width and height are in pixels.
pub fn with_dimensions(mut self, width: u32, height: u32) -> WindowBuilder<'a> {
self.attribs.dimensions = Some((width, height));
self
}
/// Requests a specific title for the window.
pub fn | (mut self, title: String) -> WindowBuilder<'a> {
self.attribs.title = title;
self
}
/// Requests fullscreen mode.
///
/// If you don't specify dimensions for the window, it will match the monitor's.
pub fn with_fullscreen(mut self, monitor: MonitorID) -> WindowBuilder<'a> {
let MonitorID(monitor) = monitor;
self.attribs.monitor = Some(monitor);
self
}
/// The created window will share all its OpenGL objects with the window in the parameter.
///
/// There are some exceptions, like FBOs or VAOs. See the OpenGL documentation.
pub fn with_shared_lists(mut self, other: &'a Window) -> WindowBuilder<'a> {
self.attribs.sharing = Some(&other.window);
self
}
/// Sets how the backend should choose the OpenGL API and version.
pub fn with_gl(mut self, request: GlRequest) -> WindowBuilder<'a> {
self.attribs.gl_version = request;
self
}
/// Sets the desired OpenGL context profile.
pub fn with_gl_profile(mut self, profile: GlProfile) -> WindowBuilder<'a> {
self.attribs.gl_profile = Some(profile);
self
}
/// Sets the *debug* flag for the OpenGL context.
///
/// The default value for this flag is `cfg!(debug_assertions)`, which means that it's enabled
/// when you run `cargo build` and disabled when you run `cargo build --release`.
pub fn with_gl_debug_flag(mut self, flag: bool) -> WindowBuilder<'a> {
self.attribs.gl_debug = flag;
self
}
/// Sets the robustness of the OpenGL context. See the docs of `Robustness`.
pub fn with_gl_robustness(mut self, robustness: Robustness) -> WindowBuilder<'a> {
self.attribs.gl_robustness = robustness;
self
}
/// Requests that the window has vsync enabled.
pub fn with_vsync(mut self) -> WindowBuilder<'a> {
self.attribs.vsync = true;
self
}
/// Sets whether the window will be initially hidden or visible.
pub fn with_visibility(mut self, visible: bool) -> WindowBuilder<'a> {
self.attribs.visible = visible;
self
}
/// Sets the multisampling level to request.
///
/// # Panic
///
/// Will panic if `samples` is not a power of two.
pub fn with_multisampling(mut self, samples: u16) -> WindowBuilder<'a> {
assert!(samples.is_power_of_two());
self.attribs.multisampling = Some(samples);
self
}
/// Sets the number of bits in the depth buffer.
pub fn with_depth_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.depth_bits = Some(bits);
self
}
/// Sets the number of bits in the stencil buffer.
pub fn with_stencil_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.stencil_bits = Some(bits);
self
}
/// Sets the number of bits in the color buffer.
pub fn with_pixel_format(mut self, color_bits: u8, alpha_bits: u8) -> WindowBuilder<'a> {
self.attribs.color_bits = Some(color_bits);
self.attribs.alpha_bits = Some(alpha_bits);
self
}
/// Request the backend to be stereoscopic.
pub fn with_stereoscopy(mut self) -> WindowBuilder<'a> {
self.attribs.stereoscopy = true;
self
}
/// Sets whether sRGB should be enabled on the window. `None` means "I don't care".
pub fn with_srgb(mut self, srgb_enabled: Option<bool>) -> WindowBuilder<'a> {
self.attribs.srgb = srgb_enabled;
self
}
/// Sets whether the background of the window should be transparent.
pub fn with_transparency(mut self, transparent: bool) -> WindowBuilder<'a> {
self.attribs.transparent = transparent;
self
}
/// Sets whether the window should have a border, a title bar, etc.
pub fn with_decorations(mut self, decorations: bool) -> WindowBuilder<'a> {
self.attribs.decorations = decorations;
self
}
/// Builds the window.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
pub fn build(mut self) -> Result<Window, CreationError> {
// resizing the window to the dimensions of the monitor when fullscreen
if self.attribs.dimensions.is_none() && self.attribs.monitor.is_some() {
self.attribs.dimensions = Some(self.attribs.monitor.as_ref().unwrap().get_dimensions())
}
// default dimensions
if self.attribs.dimensions.is_none() {
self.attribs.dimensions = Some((1024, 768));
}
// building
platform::Window::new(self.attribs).map(|w| Window { window: w })
}
/// Builds the window.
///
/// The context is build in a *strict* way. That means that if the backend couldn't give
/// you what you requested, an `Err` will be returned.
pub fn build_strict(mut self) -> Result<Window, CreationError> {
self.attribs.strict = true;
self.build()
}
}
/// Represents an OpenGL context and the Window or environment around it.
///
/// # Example
///
/// ```ignore
/// let window = Window::new().unwrap();
///
/// unsafe { window.make_current() };
///
/// loop {
/// for event in window.poll_events() {
/// match(event) {
/// // process events here
/// _ => ()
/// }
/// }
///
/// // draw everything here
///
/// window.swap_buffers();
/// std::old_io::timer::sleep(17);
/// }
/// ```
pub struct Window {
window: platform::Window,
}
impl Default for Window {
fn default() -> Window {
Window::new().unwrap()
}
}
impl Window {
/// Creates a new OpenGL context, and a Window for platforms where this is appropriate.
///
/// This function is equivalent to `WindowBuilder::new().build()`.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
#[inline]
pub fn new() -> Result<Window, CreationError> {
let builder = WindowBuilder::new();
builder.build()
}
/// Modifies the title of the window.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_title(&self, title: &str) {
self.window.set_title(title)
}
/// Shows the window if it was hidden.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn show(&self) {
self.window.show()
}
/// Hides the window if it was visible.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn hide(&self) {
self.window.hide()
}
/// Returns the position of the top-left hand corner of the window relative to the
/// top-left hand corner of the desktop.
///
/// Note that the top-left hand corner of the desktop is not necessarily the same as
/// the screen. If the user uses a desktop with multiple monitors, the top-left hand corner
/// of the desktop is the top-left hand corner of the monitor at the top-left of the desktop.
///
/// The coordinates can be negative if the top-left hand corner of the window is outside
/// of the visible screen region.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_position(&self) -> Option<(i32, i32)> {
self.window.get_position()
}
/// Modifies the position of the window.
///
/// See `get_position` for more informations about the coordinates.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_position(&self, x: i32, y: i32) {
self.window.set_position(x, y)
}
/// Returns the size in pixels of the client area of the window.
///
/// The client area is the content of the window, excluding the title bar and borders.
/// These are the dimensions of the frame buffer, and the dimensions that you should use
/// when you call `glViewport`.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
self.window.get_inner_size()
}
/// Returns the size in pixels of the window.
///
/// These dimensions include title bar and borders. If you don't want these, you should use
/// use `get_inner_size` instead.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.window.get_outer_size()
}
/// Modifies the inner size of the window.
///
/// See `get_inner_size` for more informations about the values.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_inner_size(&self, x: u32, y: u32) {
self.window.set_inner_size(x, y)
}
/// Returns an iterator that poll for the next event in the window's events queue.
/// Returns `None` if there is no event in the queue.
///
/// Contrary to `wait_events`, this function never blocks.
#[inline]
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator(self.window.poll_events())
}
/// Returns an iterator that returns events one by one, blocking if necessary until one is
/// available.
///
/// The iterator never returns `None`.
#[inline]
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator(self.window.wait_events())
}
/// Sets the context as the current context.
#[inline]
pub unsafe fn make_current(&self) -> Result<(), ContextError> {
self.window.make_current()
}
/// Returns true if this context is the current one in this thread.
#[inline]
pub fn is_current(&self) -> bool {
self.window.is_current()
}
/// Returns the address of an OpenGL function.
///
/// Contrary to `wglGetProcAddress`, all available OpenGL functions return an address.
#[inline]
pub fn get_proc_address(&self, addr: &str) -> *const libc::c_void {
self.window.get_proc_address(addr) as *const libc::c_void
}
/// Swaps the buffers in case of double or triple buffering.
///
/// You should call this function every time you have finished rendering, or the image
/// may not be displayed on the screen.
///
/// **Warning**: if you enabled vsync, this function will block until the next time the screen
/// is refreshed. However drivers can choose to override your vsync settings, which means that
/// you can't know in advance whether `swap_buffers` will block or not.
#[inline]
pub fn swap_buffers(&self) -> Result<(), ContextError> {
self.window.swap_buffers()
}
/// Gets the native platform specific display for this window.
/// This is typically only required when integrating with
/// other libraries that need this information.
#[inline]
pub unsafe fn platform_display(&self) -> *mut libc::c_void {
self.window.platform_display()
}
/// Gets the native platform specific window handle. This is
/// typically only required when integrating with other libraries
/// that need this information.
#[inline]
pub unsafe fn platform_window(&self) -> *mut libc::c_void {
self.window.platform_window()
}
/// Returns the API that is currently provided by this window.
///
/// - On Windows and OS/X, this always returns `OpenGl`.
/// - On Android, this always returns `OpenGlEs`.
/// - On Linux, it must be checked at runtime.
pub fn get_api(&self) -> Api {
self.window.get_api()
}
/// Returns the pixel format of this window.
pub fn get_pixel_format(&self) -> PixelFormat {
self.window.get_pixel_format()
}
/// Create a window proxy for this window, that can be freely
/// passed to different threads.
#[inline]
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy {
proxy: self.window.create_window_proxy()
}
}
/// Sets a resize callback that is called by Mac (and potentially other
/// operating systems) during resize operations. This can be used to repaint
/// during window resizing.
pub fn set_window_resize_callback(&mut self, callback: Option<fn(u32, u32)>) {
self.window.set_window_resize_callback(callback);
}
/// Modifies the mouse cursor of the window.
/// Has no effect on Android.
pub fn set_cursor(&self, cursor: MouseCursor) {
self.window.set_cursor(cursor);
}
/// Returns the ratio between the backing framebuffer resolution and the
/// window size in screen pixels. This is typically one for a normal display
/// and two for a retina display.
pub fn hidpi_factor(&self) -> f32 {
self.window.hidpi_factor()
}
/// Changes the position of the cursor in window coordinates.
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
self.window.set_cursor_position(x, y)
}
/// Sets how glutin handles the cursor. See the documentation of `CursorState` for details.
///
/// Has no effect on Android.
pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> {
self.window.set_cursor_state(state)
}
}
impl gl_common::GlFunctionsSource for Window {
fn get_proc_addr(&self, addr: &str) -> *const libc::c_void {
self.get_proc_address(addr)
}
}
impl GlContext for Window {
unsafe fn make_current(&self) -> Result<(), ContextError> {
self.make_current()
}
fn is_current(&self) -> bool {
self.is_current()
}
fn get_proc_address(&self, addr: &str) -> *const libc::c_void {
self.get_proc_address(addr)
}
fn swap_buffers(&self) -> Result<(), ContextError> {
self.swap_buffers()
}
fn get_api(&self) -> Api {
self.get_api()
}
fn get_pixel_format(&self) -> PixelFormat {
self.get_pixel_format()
}
}
/// Represents a thread safe subset of operations that can be called
/// on a window. This structure can be safely cloned and sent between
/// threads.
#[derive(Clone)]
pub struct WindowProxy {
proxy: platform::WindowProxy,
}
impl WindowProxy {
/// Triggers a blocked event loop to wake up. This is
/// typically called when another thread wants to wake
/// up the blocked rendering thread to cause a refresh.
#[inline]
pub fn wakeup_event_loop(&self) {
self.proxy.wakeup_event_loop();
}
}
/// An iterator for the `poll_events` function.
pub struct PollEventsIterator<'a>(platform::PollEventsIterator<'a>);
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the `wait_events` function.
pub struct WaitEventsIterator<'a>(platform::WaitEventsIterator<'a>);
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the list of available monitors.
// Implementation note: we retreive the list once, then serve each element by one by one.
// This may change in the future.
pub struct AvailableMonitorsIter {
data: VecDequeIter<platform::MonitorID>,
}
impl Iterator for AvailableMonitorsIter {
type Item = MonitorID;
fn next(&mut self) -> Option<MonitorID> {
self.data.next().map(|id| MonitorID(id))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.data.size_hint()
}
}
/// Returns the list of all available monitors.
pub fn get_available_monitors() -> AvailableMonitorsIter {
let data = platform::get_available_monitors();
AvailableMonitorsIter{ data: data.into_iter() }
}
/// Returns the primary monitor of the system.
pub fn get_primary_monitor() -> MonitorID {
MonitorID(platform::get_primary_monitor())
}
/// Identifier for a monitor.
pub struct MonitorID(platform::MonitorID);
impl MonitorID {
/// Returns a human-readable name of the monitor.
pub fn get_name(&self) -> Option<String> {
let &MonitorID(ref id) = self;
id.get_name()
}
/// Returns the native platform identifier for this monitor.
pub fn get_native_identifier(&self) -> NativeMonitorId {
let &MonitorID(ref id) = self;
id.get_native_identifier()
}
/// Returns the number of pixels currently displayed on the monitor.
pub fn get_dimensions(&self) -> (u32, u32) {
let &MonitorID(ref id) = self;
id.get_dimensions()
}
}
| with_title | identifier_name |
urls.py | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
# not sure about line 7
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^dropzone-drag-drop/$', include('dragdrop.urls', namespace="dragdrop", app_name="dragdrop")),
url(r'^index/$', 'dragdrop.views.GetUserImages'),
url(r'^$', 'signups.views.home', name='home'),
url(r'^register/$', 'drinker.views.DrinkerRegistration'),
url(r'^login/$', 'drinker.views.LoginRequest'),
url(r'^logout/$', 'drinker.views.LogOutRequest'),
url(r'^index/filter/$', 'filter.views.changeBright'),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
|
if settings.DEBUG:
# urlpatterns add STATIC_URL and serves the STATIC_ROOT file
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT) | # not sure if I need an actual url wrapper in this code.
# url(r'^admin/varnish/', include('varnishapp.urls')),
)
| random_line_split |
urls.py | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
# not sure about line 7
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^dropzone-drag-drop/$', include('dragdrop.urls', namespace="dragdrop", app_name="dragdrop")),
url(r'^index/$', 'dragdrop.views.GetUserImages'),
url(r'^$', 'signups.views.home', name='home'),
url(r'^register/$', 'drinker.views.DrinkerRegistration'),
url(r'^login/$', 'drinker.views.LoginRequest'),
url(r'^logout/$', 'drinker.views.LogOutRequest'),
url(r'^index/filter/$', 'filter.views.changeBright'),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# not sure if I need an actual url wrapper in this code.
# url(r'^admin/varnish/', include('varnishapp.urls')),
)
if settings.DEBUG:
# urlpatterns add STATIC_URL and serves the STATIC_ROOT file
| urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT) | conditional_block | |
client.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 OpenStack LLC.
# 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 urlparse
from keystoneclient import client
from keystoneclient import exceptions
_logger = logging.getLogger(__name__)
class Client(client.HTTPClient):
"""Client for the OpenStack Keystone pre-version calls API.
:param string endpoint: A user-supplied endpoint URL for the keystone
service.
:param integer timeout: Allows customization of the timeout for client
http requests. (optional)
Example::
>>> from keystoneclient.generic import client
>>> root = client.Client(auth_url=KEYSTONE_URL)
>>> versions = root.discover()
...
>>> from keystoneclient.v2_0 import client as v2client
>>> keystone = v2client.Client(auth_url=versions['v2.0']['url'])
...
>>> user = keystone.users.get(USER_ID)
>>> user.delete()
"""
def __init__(self, endpoint=None, **kwargs):
""" Initialize a new client for the Keystone v2.0 API. """
super(Client, self).__init__(endpoint=endpoint, **kwargs)
self.endpoint = endpoint
def discover(self, url=None):
""" Discover Keystone servers and return API versions supported.
:param url: optional url to test (without version)
Returns::
{
'message': 'Keystone found at http://127.0.0.1:5000/',
'v2.0': {
'status': 'beta',
'url': 'http://127.0.0.1:5000/v2.0/',
'id': 'v2.0'
},
}
"""
if url:
return self._check_keystone_versions(url)
else:
return self._local_keystone_exists()
def _local_keystone_exists(self):
""" Checks if Keystone is available on default local port 35357 """
return self._check_keystone_versions("http://localhost:35357")
def _check_keystone_versions(self, url):
""" Calls Keystone URL and detects the available API versions """
try:
httpclient = client.HTTPClient()
resp, body = httpclient.request(url, "GET",
headers={'Accept': 'application/json'})
if resp.status in (200, 204): # in some cases we get No Content
try:
results = {}
if 'version' in body:
results['message'] = "Keystone found at %s" % url
version = body['version']
# Stable/diablo incorrect format
id, status, version_url = self._get_version_info(
version, url)
results[str(id)] = {"id": id,
"status": status,
"url": version_url}
return results
elif 'versions' in body:
# Correct format
results['message'] = "Keystone found at %s" % url
for version in body['versions']['values']:
id, status, version_url = self._get_version_info(
version, url)
results[str(id)] = {"id": id,
"status": status,
"url": version_url}
return results
else:
results['message'] = "Unrecognized response from %s" \
% url
return results
except KeyError:
raise exceptions.AuthorizationFailure()
elif resp.status == 305:
return self._check_keystone_versions(resp['location'])
else:
raise exceptions.from_response(resp, body)
except Exception as e:
_logger.exception(e)
def discover_extensions(self, url=None):
""" Discover Keystone extensions supported.
:param url: optional url to test (should have a version in it)
Returns::
{
'message': 'Keystone extensions at http://127.0.0.1:35357/v2',
'OS-KSEC2': 'OpenStack EC2 Credentials Extension',
}
"""
if url:
return self._check_keystone_extensions(url)
def _check_keystone_extensions(self, url):
""" Calls Keystone URL and detects the available extensions """
try:
httpclient = client.HTTPClient()
if not url.endswith("/"): | resp, body = httpclient.request("%sextensions" % url, "GET",
headers={'Accept': 'application/json'})
if resp.status in (200, 204): # in some cases we get No Content
try:
results = {}
if 'extensions' in body:
if 'values' in body['extensions']:
# Parse correct format (per contract)
for extension in body['extensions']['values']:
alias, name = self._get_extension_info(
extension['extension'])
results[alias] = name
return results
else:
# Support incorrect, but prevalent format
for extension in body['extensions']:
alias, name = self._get_extension_info(
extension)
results[alias] = name
return results
else:
results['message'] = "Unrecognized extensions" \
" response from %s" % url
return results
except KeyError:
raise exceptions.AuthorizationFailure()
elif resp.status == 305:
return self._check_keystone_extensions(resp['location'])
else:
raise exceptions.from_response(resp, body)
except Exception as e:
_logger.exception(e)
@staticmethod
def _get_version_info(version, root_url):
""" Parses version information
:param version: a dict of a Keystone version response
:param root_url: string url used to construct
the version if no URL is provided.
:returns: tuple - (verionId, versionStatus, versionUrl)
"""
id = version['id']
status = version['status']
ref = urlparse.urljoin(root_url, id)
if 'links' in version:
for link in version['links']:
if link['rel'] == 'self':
ref = link['href']
break
return (id, status, ref)
@staticmethod
def _get_extension_info(extension):
""" Parses extension information
:param extension: a dict of a Keystone extension response
:returns: tuple - (alias, name)
"""
alias = extension['alias']
name = extension['name']
return (alias, name) | url += '/' | random_line_split |
client.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 OpenStack LLC.
# 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 urlparse
from keystoneclient import client
from keystoneclient import exceptions
_logger = logging.getLogger(__name__)
class Client(client.HTTPClient):
"""Client for the OpenStack Keystone pre-version calls API.
:param string endpoint: A user-supplied endpoint URL for the keystone
service.
:param integer timeout: Allows customization of the timeout for client
http requests. (optional)
Example::
>>> from keystoneclient.generic import client
>>> root = client.Client(auth_url=KEYSTONE_URL)
>>> versions = root.discover()
...
>>> from keystoneclient.v2_0 import client as v2client
>>> keystone = v2client.Client(auth_url=versions['v2.0']['url'])
...
>>> user = keystone.users.get(USER_ID)
>>> user.delete()
"""
def __init__(self, endpoint=None, **kwargs):
""" Initialize a new client for the Keystone v2.0 API. """
super(Client, self).__init__(endpoint=endpoint, **kwargs)
self.endpoint = endpoint
def discover(self, url=None):
""" Discover Keystone servers and return API versions supported.
:param url: optional url to test (without version)
Returns::
{
'message': 'Keystone found at http://127.0.0.1:5000/',
'v2.0': {
'status': 'beta',
'url': 'http://127.0.0.1:5000/v2.0/',
'id': 'v2.0'
},
}
"""
if url:
return self._check_keystone_versions(url)
else:
return self._local_keystone_exists()
def _local_keystone_exists(self):
""" Checks if Keystone is available on default local port 35357 """
return self._check_keystone_versions("http://localhost:35357")
def _check_keystone_versions(self, url):
""" Calls Keystone URL and detects the available API versions """
try:
httpclient = client.HTTPClient()
resp, body = httpclient.request(url, "GET",
headers={'Accept': 'application/json'})
if resp.status in (200, 204): # in some cases we get No Content
try:
results = {}
if 'version' in body:
results['message'] = "Keystone found at %s" % url
version = body['version']
# Stable/diablo incorrect format
id, status, version_url = self._get_version_info(
version, url)
results[str(id)] = {"id": id,
"status": status,
"url": version_url}
return results
elif 'versions' in body:
# Correct format
results['message'] = "Keystone found at %s" % url
for version in body['versions']['values']:
id, status, version_url = self._get_version_info(
version, url)
results[str(id)] = {"id": id,
"status": status,
"url": version_url}
return results
else:
results['message'] = "Unrecognized response from %s" \
% url
return results
except KeyError:
raise exceptions.AuthorizationFailure()
elif resp.status == 305:
return self._check_keystone_versions(resp['location'])
else:
raise exceptions.from_response(resp, body)
except Exception as e:
_logger.exception(e)
def discover_extensions(self, url=None):
""" Discover Keystone extensions supported.
:param url: optional url to test (should have a version in it)
Returns::
{
'message': 'Keystone extensions at http://127.0.0.1:35357/v2',
'OS-KSEC2': 'OpenStack EC2 Credentials Extension',
}
"""
if url:
return self._check_keystone_extensions(url)
def _check_keystone_extensions(self, url):
""" Calls Keystone URL and detects the available extensions """
try:
httpclient = client.HTTPClient()
if not url.endswith("/"):
url += '/'
resp, body = httpclient.request("%sextensions" % url, "GET",
headers={'Accept': 'application/json'})
if resp.status in (200, 204): # in some cases we get No Content
try:
results = {}
if 'extensions' in body:
if 'values' in body['extensions']:
# Parse correct format (per contract)
|
else:
# Support incorrect, but prevalent format
for extension in body['extensions']:
alias, name = self._get_extension_info(
extension)
results[alias] = name
return results
else:
results['message'] = "Unrecognized extensions" \
" response from %s" % url
return results
except KeyError:
raise exceptions.AuthorizationFailure()
elif resp.status == 305:
return self._check_keystone_extensions(resp['location'])
else:
raise exceptions.from_response(resp, body)
except Exception as e:
_logger.exception(e)
@staticmethod
def _get_version_info(version, root_url):
""" Parses version information
:param version: a dict of a Keystone version response
:param root_url: string url used to construct
the version if no URL is provided.
:returns: tuple - (verionId, versionStatus, versionUrl)
"""
id = version['id']
status = version['status']
ref = urlparse.urljoin(root_url, id)
if 'links' in version:
for link in version['links']:
if link['rel'] == 'self':
ref = link['href']
break
return (id, status, ref)
@staticmethod
def _get_extension_info(extension):
""" Parses extension information
:param extension: a dict of a Keystone extension response
:returns: tuple - (alias, name)
"""
alias = extension['alias']
name = extension['name']
return (alias, name)
| for extension in body['extensions']['values']:
alias, name = self._get_extension_info(
extension['extension'])
results[alias] = name
return results | conditional_block |
client.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 OpenStack LLC.
# 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 urlparse
from keystoneclient import client
from keystoneclient import exceptions
_logger = logging.getLogger(__name__)
class Client(client.HTTPClient):
"""Client for the OpenStack Keystone pre-version calls API.
:param string endpoint: A user-supplied endpoint URL for the keystone
service.
:param integer timeout: Allows customization of the timeout for client
http requests. (optional)
Example::
>>> from keystoneclient.generic import client
>>> root = client.Client(auth_url=KEYSTONE_URL)
>>> versions = root.discover()
...
>>> from keystoneclient.v2_0 import client as v2client
>>> keystone = v2client.Client(auth_url=versions['v2.0']['url'])
...
>>> user = keystone.users.get(USER_ID)
>>> user.delete()
"""
def __init__(self, endpoint=None, **kwargs):
""" Initialize a new client for the Keystone v2.0 API. """
super(Client, self).__init__(endpoint=endpoint, **kwargs)
self.endpoint = endpoint
def | (self, url=None):
""" Discover Keystone servers and return API versions supported.
:param url: optional url to test (without version)
Returns::
{
'message': 'Keystone found at http://127.0.0.1:5000/',
'v2.0': {
'status': 'beta',
'url': 'http://127.0.0.1:5000/v2.0/',
'id': 'v2.0'
},
}
"""
if url:
return self._check_keystone_versions(url)
else:
return self._local_keystone_exists()
def _local_keystone_exists(self):
""" Checks if Keystone is available on default local port 35357 """
return self._check_keystone_versions("http://localhost:35357")
def _check_keystone_versions(self, url):
""" Calls Keystone URL and detects the available API versions """
try:
httpclient = client.HTTPClient()
resp, body = httpclient.request(url, "GET",
headers={'Accept': 'application/json'})
if resp.status in (200, 204): # in some cases we get No Content
try:
results = {}
if 'version' in body:
results['message'] = "Keystone found at %s" % url
version = body['version']
# Stable/diablo incorrect format
id, status, version_url = self._get_version_info(
version, url)
results[str(id)] = {"id": id,
"status": status,
"url": version_url}
return results
elif 'versions' in body:
# Correct format
results['message'] = "Keystone found at %s" % url
for version in body['versions']['values']:
id, status, version_url = self._get_version_info(
version, url)
results[str(id)] = {"id": id,
"status": status,
"url": version_url}
return results
else:
results['message'] = "Unrecognized response from %s" \
% url
return results
except KeyError:
raise exceptions.AuthorizationFailure()
elif resp.status == 305:
return self._check_keystone_versions(resp['location'])
else:
raise exceptions.from_response(resp, body)
except Exception as e:
_logger.exception(e)
def discover_extensions(self, url=None):
""" Discover Keystone extensions supported.
:param url: optional url to test (should have a version in it)
Returns::
{
'message': 'Keystone extensions at http://127.0.0.1:35357/v2',
'OS-KSEC2': 'OpenStack EC2 Credentials Extension',
}
"""
if url:
return self._check_keystone_extensions(url)
def _check_keystone_extensions(self, url):
""" Calls Keystone URL and detects the available extensions """
try:
httpclient = client.HTTPClient()
if not url.endswith("/"):
url += '/'
resp, body = httpclient.request("%sextensions" % url, "GET",
headers={'Accept': 'application/json'})
if resp.status in (200, 204): # in some cases we get No Content
try:
results = {}
if 'extensions' in body:
if 'values' in body['extensions']:
# Parse correct format (per contract)
for extension in body['extensions']['values']:
alias, name = self._get_extension_info(
extension['extension'])
results[alias] = name
return results
else:
# Support incorrect, but prevalent format
for extension in body['extensions']:
alias, name = self._get_extension_info(
extension)
results[alias] = name
return results
else:
results['message'] = "Unrecognized extensions" \
" response from %s" % url
return results
except KeyError:
raise exceptions.AuthorizationFailure()
elif resp.status == 305:
return self._check_keystone_extensions(resp['location'])
else:
raise exceptions.from_response(resp, body)
except Exception as e:
_logger.exception(e)
@staticmethod
def _get_version_info(version, root_url):
""" Parses version information
:param version: a dict of a Keystone version response
:param root_url: string url used to construct
the version if no URL is provided.
:returns: tuple - (verionId, versionStatus, versionUrl)
"""
id = version['id']
status = version['status']
ref = urlparse.urljoin(root_url, id)
if 'links' in version:
for link in version['links']:
if link['rel'] == 'self':
ref = link['href']
break
return (id, status, ref)
@staticmethod
def _get_extension_info(extension):
""" Parses extension information
:param extension: a dict of a Keystone extension response
:returns: tuple - (alias, name)
"""
alias = extension['alias']
name = extension['name']
return (alias, name)
| discover | identifier_name |
client.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 OpenStack LLC.
# 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 urlparse
from keystoneclient import client
from keystoneclient import exceptions
_logger = logging.getLogger(__name__)
class Client(client.HTTPClient):
"""Client for the OpenStack Keystone pre-version calls API.
:param string endpoint: A user-supplied endpoint URL for the keystone
service.
:param integer timeout: Allows customization of the timeout for client
http requests. (optional)
Example::
>>> from keystoneclient.generic import client
>>> root = client.Client(auth_url=KEYSTONE_URL)
>>> versions = root.discover()
...
>>> from keystoneclient.v2_0 import client as v2client
>>> keystone = v2client.Client(auth_url=versions['v2.0']['url'])
...
>>> user = keystone.users.get(USER_ID)
>>> user.delete()
"""
def __init__(self, endpoint=None, **kwargs):
|
def discover(self, url=None):
""" Discover Keystone servers and return API versions supported.
:param url: optional url to test (without version)
Returns::
{
'message': 'Keystone found at http://127.0.0.1:5000/',
'v2.0': {
'status': 'beta',
'url': 'http://127.0.0.1:5000/v2.0/',
'id': 'v2.0'
},
}
"""
if url:
return self._check_keystone_versions(url)
else:
return self._local_keystone_exists()
def _local_keystone_exists(self):
""" Checks if Keystone is available on default local port 35357 """
return self._check_keystone_versions("http://localhost:35357")
def _check_keystone_versions(self, url):
""" Calls Keystone URL and detects the available API versions """
try:
httpclient = client.HTTPClient()
resp, body = httpclient.request(url, "GET",
headers={'Accept': 'application/json'})
if resp.status in (200, 204): # in some cases we get No Content
try:
results = {}
if 'version' in body:
results['message'] = "Keystone found at %s" % url
version = body['version']
# Stable/diablo incorrect format
id, status, version_url = self._get_version_info(
version, url)
results[str(id)] = {"id": id,
"status": status,
"url": version_url}
return results
elif 'versions' in body:
# Correct format
results['message'] = "Keystone found at %s" % url
for version in body['versions']['values']:
id, status, version_url = self._get_version_info(
version, url)
results[str(id)] = {"id": id,
"status": status,
"url": version_url}
return results
else:
results['message'] = "Unrecognized response from %s" \
% url
return results
except KeyError:
raise exceptions.AuthorizationFailure()
elif resp.status == 305:
return self._check_keystone_versions(resp['location'])
else:
raise exceptions.from_response(resp, body)
except Exception as e:
_logger.exception(e)
def discover_extensions(self, url=None):
""" Discover Keystone extensions supported.
:param url: optional url to test (should have a version in it)
Returns::
{
'message': 'Keystone extensions at http://127.0.0.1:35357/v2',
'OS-KSEC2': 'OpenStack EC2 Credentials Extension',
}
"""
if url:
return self._check_keystone_extensions(url)
def _check_keystone_extensions(self, url):
""" Calls Keystone URL and detects the available extensions """
try:
httpclient = client.HTTPClient()
if not url.endswith("/"):
url += '/'
resp, body = httpclient.request("%sextensions" % url, "GET",
headers={'Accept': 'application/json'})
if resp.status in (200, 204): # in some cases we get No Content
try:
results = {}
if 'extensions' in body:
if 'values' in body['extensions']:
# Parse correct format (per contract)
for extension in body['extensions']['values']:
alias, name = self._get_extension_info(
extension['extension'])
results[alias] = name
return results
else:
# Support incorrect, but prevalent format
for extension in body['extensions']:
alias, name = self._get_extension_info(
extension)
results[alias] = name
return results
else:
results['message'] = "Unrecognized extensions" \
" response from %s" % url
return results
except KeyError:
raise exceptions.AuthorizationFailure()
elif resp.status == 305:
return self._check_keystone_extensions(resp['location'])
else:
raise exceptions.from_response(resp, body)
except Exception as e:
_logger.exception(e)
@staticmethod
def _get_version_info(version, root_url):
""" Parses version information
:param version: a dict of a Keystone version response
:param root_url: string url used to construct
the version if no URL is provided.
:returns: tuple - (verionId, versionStatus, versionUrl)
"""
id = version['id']
status = version['status']
ref = urlparse.urljoin(root_url, id)
if 'links' in version:
for link in version['links']:
if link['rel'] == 'self':
ref = link['href']
break
return (id, status, ref)
@staticmethod
def _get_extension_info(extension):
""" Parses extension information
:param extension: a dict of a Keystone extension response
:returns: tuple - (alias, name)
"""
alias = extension['alias']
name = extension['name']
return (alias, name)
| """ Initialize a new client for the Keystone v2.0 API. """
super(Client, self).__init__(endpoint=endpoint, **kwargs)
self.endpoint = endpoint | identifier_body |
index.d.ts | import * as React from "react";
import ReactToolbox from "../index";
export interface DropdownTheme {
/**
* Added to the root element when the dropdown is active.
*/
active?: string;
/**
* Added to the root element when it's disabled.
*/
disabled?: string;
/**
* Root element class.
*/
dropdown?: string;
/**
* Used for the error element.
*/
error?: string;
/**
* Added to the inner wrapper if it's errored.
*/
errored?: string;
/**
* Used for the inner wrapper of the component.
*/
field?: string;
/**
* Used for the the label element.
*/
label?: string;
/**
* Used to highlight the selected value.
*/
selected?: string;
/**
* Used as a wrapper for the given template value.
*/
templateValue?: string;
/**
* Added to the root element when it's opening up.
*/
up?: string;
/**
* Used for each value in the dropdown component.
*/ | value?: string;
/**
* Used for the list of values.
*/
values?: string;
}
interface DropdownProps extends ReactToolbox.Props {
/**
* If true the dropdown will preselect the first item if the supplied value matches none of the options' values.
* @default true
*/
allowBlank?: boolean;
/**
* If true, the dropdown will open up or down depending on the position in the screen.
* @default true
*/
auto?: boolean;
/**
* Set the component as disabled.
* @default false
*/
disabled?: boolean;
/**
* Give an error string to display under the field.
*/
error?: string;
/**
* The text string to use for the floating label element.
*/
label?: string;
/**
* Name for the input field.
*/
name?: string;
/**
* Callback function that is fired when the component is blurred.
*/
onBlur?: Function;
/**
* Callback function that is fired when the component's value changes.
*/
onChange?: Function;
/**
* Callback function that is fired when the component is focused.
*/
onFocus?: Function;
/**
* Array of data objects with the data to represent in the dropdown.
*/
source: any[];
/**
* Callback function that returns a JSX template to represent the element.
*/
template?: Function;
/**
* Classnames object defining the component style.
*/
theme?: DropdownTheme;
/**
* Default value using JSON data.
*/
value?: string | number;
}
export class Dropdown extends React.Component<DropdownProps, {}> { }
export default Dropdown; | random_line_split | |
index.d.ts | import * as React from "react";
import ReactToolbox from "../index";
export interface DropdownTheme {
/**
* Added to the root element when the dropdown is active.
*/
active?: string;
/**
* Added to the root element when it's disabled.
*/
disabled?: string;
/**
* Root element class.
*/
dropdown?: string;
/**
* Used for the error element.
*/
error?: string;
/**
* Added to the inner wrapper if it's errored.
*/
errored?: string;
/**
* Used for the inner wrapper of the component.
*/
field?: string;
/**
* Used for the the label element.
*/
label?: string;
/**
* Used to highlight the selected value.
*/
selected?: string;
/**
* Used as a wrapper for the given template value.
*/
templateValue?: string;
/**
* Added to the root element when it's opening up.
*/
up?: string;
/**
* Used for each value in the dropdown component.
*/
value?: string;
/**
* Used for the list of values.
*/
values?: string;
}
interface DropdownProps extends ReactToolbox.Props {
/**
* If true the dropdown will preselect the first item if the supplied value matches none of the options' values.
* @default true
*/
allowBlank?: boolean;
/**
* If true, the dropdown will open up or down depending on the position in the screen.
* @default true
*/
auto?: boolean;
/**
* Set the component as disabled.
* @default false
*/
disabled?: boolean;
/**
* Give an error string to display under the field.
*/
error?: string;
/**
* The text string to use for the floating label element.
*/
label?: string;
/**
* Name for the input field.
*/
name?: string;
/**
* Callback function that is fired when the component is blurred.
*/
onBlur?: Function;
/**
* Callback function that is fired when the component's value changes.
*/
onChange?: Function;
/**
* Callback function that is fired when the component is focused.
*/
onFocus?: Function;
/**
* Array of data objects with the data to represent in the dropdown.
*/
source: any[];
/**
* Callback function that returns a JSX template to represent the element.
*/
template?: Function;
/**
* Classnames object defining the component style.
*/
theme?: DropdownTheme;
/**
* Default value using JSON data.
*/
value?: string | number;
}
export class | extends React.Component<DropdownProps, {}> { }
export default Dropdown;
| Dropdown | identifier_name |
build.server.prod.ts | import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import * as merge from 'merge-stream';
import { join/*, sep, relative*/ } from 'path';
import Config from '../../config';
import { makeTsProject, TemplateLocalsBuilder } from '../../utils';
import { TypeScriptTask } from '../typescript_task';
const plugins = <any>gulpLoadPlugins();
let typedBuildCounter = Config.TYPED_COMPILE_INTERVAL; // Always start with the typed build.
/**
* Executes the build process, transpiling the TypeScript files (except the spec and e2e-spec files) for the development
* environment.
*/
export =
class BuildServerDev extends TypeScriptTask {
| () {
const tsProject: any;
const typings = gulp.src([
Config.TOOLS_DIR + '/manual_typings/**/*.d.ts'
]);
const src = [
join(Config.APP_SERVER_SRC, '**/*.ts')
];
let projectFiles = gulp.src(src);
let result: any;
let isFullCompile = true;
// Only do a typed build every X builds, otherwise do a typeless build to speed things up
if (typedBuildCounter < Config.TYPED_COMPILE_INTERVAL) {
isFullCompile = false;
tsProject = makeTsProject({isolatedModules: true});
projectFiles = projectFiles.pipe(plugins.cached());
} else {
tsProject = makeTsProject();
projectFiles = merge(typings, projectFiles);
}
result = projectFiles
.pipe(plugins.plumber())
.pipe(plugins.sourcemaps.init())
.pipe(tsProject())
.on('error', () => {
typedBuildCounter = Config.TYPED_COMPILE_INTERVAL;
});
if (isFullCompile) {
typedBuildCounter = 0;
} else {
typedBuildCounter++;
}
return result.js
.pipe(plugins.sourcemaps.write())
// Use for debugging with Webstorm/IntelliJ
// https://github.com/mgechev/angular2-seed/issues/1220
// .pipe(plugins.sourcemaps.write('.', {
// includeContent: false,
// sourceRoot: (file: any) =>
// relative(file.path, PROJECT_ROOT + '/' + APP_SRC).replace(sep, '/') + '/' + APP_SRC
// }))
.pipe(plugins.template(new TemplateLocalsBuilder().withStringifiedSystemConfigDev().build()))
.pipe(gulp.dest(Config.APP_SERVER_DEST));
}
};
| run | identifier_name |
build.server.prod.ts | import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import * as merge from 'merge-stream';
import { join/*, sep, relative*/ } from 'path';
import Config from '../../config';
import { makeTsProject, TemplateLocalsBuilder } from '../../utils';
import { TypeScriptTask } from '../typescript_task';
const plugins = <any>gulpLoadPlugins();
let typedBuildCounter = Config.TYPED_COMPILE_INTERVAL; // Always start with the typed build.
/**
* Executes the build process, transpiling the TypeScript files (except the spec and e2e-spec files) for the development
* environment.
*/
export =
class BuildServerDev extends TypeScriptTask {
run() {
const tsProject: any;
const typings = gulp.src([
Config.TOOLS_DIR + '/manual_typings/**/*.d.ts'
]);
const src = [
join(Config.APP_SERVER_SRC, '**/*.ts')
];
let projectFiles = gulp.src(src);
let result: any;
let isFullCompile = true;
// Only do a typed build every X builds, otherwise do a typeless build to speed things up
if (typedBuildCounter < Config.TYPED_COMPILE_INTERVAL) {
isFullCompile = false;
tsProject = makeTsProject({isolatedModules: true});
projectFiles = projectFiles.pipe(plugins.cached());
} else |
result = projectFiles
.pipe(plugins.plumber())
.pipe(plugins.sourcemaps.init())
.pipe(tsProject())
.on('error', () => {
typedBuildCounter = Config.TYPED_COMPILE_INTERVAL;
});
if (isFullCompile) {
typedBuildCounter = 0;
} else {
typedBuildCounter++;
}
return result.js
.pipe(plugins.sourcemaps.write())
// Use for debugging with Webstorm/IntelliJ
// https://github.com/mgechev/angular2-seed/issues/1220
// .pipe(plugins.sourcemaps.write('.', {
// includeContent: false,
// sourceRoot: (file: any) =>
// relative(file.path, PROJECT_ROOT + '/' + APP_SRC).replace(sep, '/') + '/' + APP_SRC
// }))
.pipe(plugins.template(new TemplateLocalsBuilder().withStringifiedSystemConfigDev().build()))
.pipe(gulp.dest(Config.APP_SERVER_DEST));
}
};
| {
tsProject = makeTsProject();
projectFiles = merge(typings, projectFiles);
} | conditional_block |
build.server.prod.ts | import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import * as merge from 'merge-stream';
import { join/*, sep, relative*/ } from 'path';
import Config from '../../config';
import { makeTsProject, TemplateLocalsBuilder } from '../../utils';
import { TypeScriptTask } from '../typescript_task';
const plugins = <any>gulpLoadPlugins();
let typedBuildCounter = Config.TYPED_COMPILE_INTERVAL; // Always start with the typed build.
/**
* Executes the build process, transpiling the TypeScript files (except the spec and e2e-spec files) for the development
* environment.
*/
export =
class BuildServerDev extends TypeScriptTask {
run() |
};
| {
const tsProject: any;
const typings = gulp.src([
Config.TOOLS_DIR + '/manual_typings/**/*.d.ts'
]);
const src = [
join(Config.APP_SERVER_SRC, '**/*.ts')
];
let projectFiles = gulp.src(src);
let result: any;
let isFullCompile = true;
// Only do a typed build every X builds, otherwise do a typeless build to speed things up
if (typedBuildCounter < Config.TYPED_COMPILE_INTERVAL) {
isFullCompile = false;
tsProject = makeTsProject({isolatedModules: true});
projectFiles = projectFiles.pipe(plugins.cached());
} else {
tsProject = makeTsProject();
projectFiles = merge(typings, projectFiles);
}
result = projectFiles
.pipe(plugins.plumber())
.pipe(plugins.sourcemaps.init())
.pipe(tsProject())
.on('error', () => {
typedBuildCounter = Config.TYPED_COMPILE_INTERVAL;
});
if (isFullCompile) {
typedBuildCounter = 0;
} else {
typedBuildCounter++;
}
return result.js
.pipe(plugins.sourcemaps.write())
// Use for debugging with Webstorm/IntelliJ
// https://github.com/mgechev/angular2-seed/issues/1220
// .pipe(plugins.sourcemaps.write('.', {
// includeContent: false,
// sourceRoot: (file: any) =>
// relative(file.path, PROJECT_ROOT + '/' + APP_SRC).replace(sep, '/') + '/' + APP_SRC
// }))
.pipe(plugins.template(new TemplateLocalsBuilder().withStringifiedSystemConfigDev().build()))
.pipe(gulp.dest(Config.APP_SERVER_DEST));
} | identifier_body |
build.server.prod.ts | import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import * as merge from 'merge-stream';
import { join/*, sep, relative*/ } from 'path';
import Config from '../../config';
import { makeTsProject, TemplateLocalsBuilder } from '../../utils';
import { TypeScriptTask } from '../typescript_task';
const plugins = <any>gulpLoadPlugins();
let typedBuildCounter = Config.TYPED_COMPILE_INTERVAL; // Always start with the typed build. | /**
* Executes the build process, transpiling the TypeScript files (except the spec and e2e-spec files) for the development
* environment.
*/
export =
class BuildServerDev extends TypeScriptTask {
run() {
const tsProject: any;
const typings = gulp.src([
Config.TOOLS_DIR + '/manual_typings/**/*.d.ts'
]);
const src = [
join(Config.APP_SERVER_SRC, '**/*.ts')
];
let projectFiles = gulp.src(src);
let result: any;
let isFullCompile = true;
// Only do a typed build every X builds, otherwise do a typeless build to speed things up
if (typedBuildCounter < Config.TYPED_COMPILE_INTERVAL) {
isFullCompile = false;
tsProject = makeTsProject({isolatedModules: true});
projectFiles = projectFiles.pipe(plugins.cached());
} else {
tsProject = makeTsProject();
projectFiles = merge(typings, projectFiles);
}
result = projectFiles
.pipe(plugins.plumber())
.pipe(plugins.sourcemaps.init())
.pipe(tsProject())
.on('error', () => {
typedBuildCounter = Config.TYPED_COMPILE_INTERVAL;
});
if (isFullCompile) {
typedBuildCounter = 0;
} else {
typedBuildCounter++;
}
return result.js
.pipe(plugins.sourcemaps.write())
// Use for debugging with Webstorm/IntelliJ
// https://github.com/mgechev/angular2-seed/issues/1220
// .pipe(plugins.sourcemaps.write('.', {
// includeContent: false,
// sourceRoot: (file: any) =>
// relative(file.path, PROJECT_ROOT + '/' + APP_SRC).replace(sep, '/') + '/' + APP_SRC
// }))
.pipe(plugins.template(new TemplateLocalsBuilder().withStringifiedSystemConfigDev().build()))
.pipe(gulp.dest(Config.APP_SERVER_DEST));
}
}; | random_line_split | |
NumberUtil.ts | /**
* Provides helper functions for Number handling.
*
* @author Tim Duesterhus
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @module WoltLabSuite/Core/NumberUtil
*/
/**
* Decimal adjustment of a number.
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
*/
export function round(value: number, exp: number): number {
// If the exp is undefined or zero...
if (typeof exp === "undefined" || +exp === 0) |
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof (exp as any) === "number" && exp % 1 === 0)) {
return NaN;
}
// Shift
let tmp = value.toString().split("e");
let exponent = tmp[1] ? +tmp[1] - exp : -exp;
value = Math.round(+`${tmp[0]}e${exponent}`);
// Shift back
tmp = value.toString().split("e");
exponent = tmp[1] ? +tmp[1] + exp : exp;
return +`${tmp[0]}e${exponent}`;
}
| {
return Math.round(value);
} | conditional_block |
NumberUtil.ts | /**
* Provides helper functions for Number handling.
*
* @author Tim Duesterhus
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @module WoltLabSuite/Core/NumberUtil
*/
/**
* Decimal adjustment of a number.
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
*/
export function | (value: number, exp: number): number {
// If the exp is undefined or zero...
if (typeof exp === "undefined" || +exp === 0) {
return Math.round(value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof (exp as any) === "number" && exp % 1 === 0)) {
return NaN;
}
// Shift
let tmp = value.toString().split("e");
let exponent = tmp[1] ? +tmp[1] - exp : -exp;
value = Math.round(+`${tmp[0]}e${exponent}`);
// Shift back
tmp = value.toString().split("e");
exponent = tmp[1] ? +tmp[1] + exp : exp;
return +`${tmp[0]}e${exponent}`;
}
| round | identifier_name |
NumberUtil.ts | /**
* Provides helper functions for Number handling.
*
* @author Tim Duesterhus
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @module WoltLabSuite/Core/NumberUtil
*/
/**
* Decimal adjustment of a number.
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
*/
export function round(value: number, exp: number): number {
// If the exp is undefined or zero...
if (typeof exp === "undefined" || +exp === 0) {
return Math.round(value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof (exp as any) === "number" && exp % 1 === 0)) {
return NaN; | }
// Shift
let tmp = value.toString().split("e");
let exponent = tmp[1] ? +tmp[1] - exp : -exp;
value = Math.round(+`${tmp[0]}e${exponent}`);
// Shift back
tmp = value.toString().split("e");
exponent = tmp[1] ? +tmp[1] + exp : exp;
return +`${tmp[0]}e${exponent}`;
} | random_line_split | |
NumberUtil.ts | /**
* Provides helper functions for Number handling.
*
* @author Tim Duesterhus
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @module WoltLabSuite/Core/NumberUtil
*/
/**
* Decimal adjustment of a number.
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
*/
export function round(value: number, exp: number): number | {
// If the exp is undefined or zero...
if (typeof exp === "undefined" || +exp === 0) {
return Math.round(value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof (exp as any) === "number" && exp % 1 === 0)) {
return NaN;
}
// Shift
let tmp = value.toString().split("e");
let exponent = tmp[1] ? +tmp[1] - exp : -exp;
value = Math.round(+`${tmp[0]}e${exponent}`);
// Shift back
tmp = value.toString().split("e");
exponent = tmp[1] ? +tmp[1] + exp : exp;
return +`${tmp[0]}e${exponent}`;
} | identifier_body | |
libs.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import datetime
import logging
import csv
import six
from datetime import date
from django.apps import apps
from django.utils import timezone
logger = logging.getLogger(__name__)
ats_settings = apps.get_app_config('ats')
def get_user_realname(first_name, last_name, is_last_name_front):
if is_last_name_front:
return '%s %s' % (last_name, first_name)
else:
return '%s %s' % (first_name, last_name)
def format_totaltime(td):
totalhour = (td.days * 24) + int(td.seconds / 3600)
minute = int(td.seconds / 60) - (int(td.seconds / 3600) * 60)
return '%d:%02d' % (totalhour, minute)
def format_hours_float(td):
return (td.days * 24) + (td.seconds / 3600.0)
def format_time(timedata):
return '%d:%02d' % (timedata.hour, timedata.minute)
def get_localtime():
_now = timezone.localtime()
# logger.debug("get_localtime() : %s" % (_now))
return _now
def get_thismonth_1st():
|
def export_csv_task(datalist, add_header, new_line):
_s = ''
if six.PY2:
bufffer = six.BytesIO()
else:
bufffer = six.StringIO()
try:
if True:
_writer = csv.writer(
bufffer, lineterminator=new_line,
quotechar='"', quoting=csv.QUOTE_ALL)
if add_header:
_header = [
'date',
'project',
'code',
'job',
'task',
'user',
'tasktime',
'task_userdata1',
'task_userdata2',
'task_userdata3',
'task_userdata4',
'task_userdata5',
'comment',
]
_writer.writerow(_header)
for d in datalist:
_line = []
_date = d['taskdate'].isoformat()
_line.append(_date)
_line.append(d['project__name'])
if d['project__external_project__code']:
_line.append(d['project__external_project__code'])
else:
_line.append('')
_line.append(d['task__job__name'])
_line.append(d['task__name'])
_line.append(get_user_realname(d['user__first_name'], d['user__last_name'], ats_settings.ATS_IS_LASTNAME_FRONT))
_line.append(format_time(d['tasktime']))
_line.append(d['task__userdata1'])
_line.append(d['task__userdata2'])
_line.append(d['task__userdata3'])
_line.append(d['task__userdata4'])
_line.append(d['task__userdata5'])
_line.append(d['comment'])
if six.PY2:
for i in range(len(_line)):
_line[i] = _line[i].encode('utf8')
_writer.writerow(_line)
_s = bufffer.getvalue()
bufffer.close()
if six.PY3:
_s = _s.encode('utf8')
except Exception as e:
logger.error('fail export_csv_task().')
logger.error('EXCEPT: export_csv_task(). e=%s, msg1=%s,msg2=%s',
e, sys.exc_info()[1], sys.exc_info()[2])
return None
return _s
| _now = timezone.localtime()
_ret = _now.replace(day=1)
# logger.debug("get_thismonth_1st(): %s" % (_ret))
return _ret | identifier_body |
libs.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import datetime
import logging
import csv
import six
from datetime import date
from django.apps import apps
from django.utils import timezone
logger = logging.getLogger(__name__)
ats_settings = apps.get_app_config('ats')
def get_user_realname(first_name, last_name, is_last_name_front):
if is_last_name_front:
return '%s %s' % (last_name, first_name)
else:
return '%s %s' % (first_name, last_name)
def format_totaltime(td):
totalhour = (td.days * 24) + int(td.seconds / 3600)
minute = int(td.seconds / 60) - (int(td.seconds / 3600) * 60)
return '%d:%02d' % (totalhour, minute)
def format_hours_float(td):
return (td.days * 24) + (td.seconds / 3600.0)
def format_time(timedata):
return '%d:%02d' % (timedata.hour, timedata.minute)
def get_localtime():
_now = timezone.localtime()
# logger.debug("get_localtime() : %s" % (_now))
return _now
def get_thismonth_1st():
_now = timezone.localtime()
_ret = _now.replace(day=1)
# logger.debug("get_thismonth_1st(): %s" % (_ret))
return _ret
def export_csv_task(datalist, add_header, new_line):
_s = ''
if six.PY2:
bufffer = six.BytesIO()
else:
|
try:
if True:
_writer = csv.writer(
bufffer, lineterminator=new_line,
quotechar='"', quoting=csv.QUOTE_ALL)
if add_header:
_header = [
'date',
'project',
'code',
'job',
'task',
'user',
'tasktime',
'task_userdata1',
'task_userdata2',
'task_userdata3',
'task_userdata4',
'task_userdata5',
'comment',
]
_writer.writerow(_header)
for d in datalist:
_line = []
_date = d['taskdate'].isoformat()
_line.append(_date)
_line.append(d['project__name'])
if d['project__external_project__code']:
_line.append(d['project__external_project__code'])
else:
_line.append('')
_line.append(d['task__job__name'])
_line.append(d['task__name'])
_line.append(get_user_realname(d['user__first_name'], d['user__last_name'], ats_settings.ATS_IS_LASTNAME_FRONT))
_line.append(format_time(d['tasktime']))
_line.append(d['task__userdata1'])
_line.append(d['task__userdata2'])
_line.append(d['task__userdata3'])
_line.append(d['task__userdata4'])
_line.append(d['task__userdata5'])
_line.append(d['comment'])
if six.PY2:
for i in range(len(_line)):
_line[i] = _line[i].encode('utf8')
_writer.writerow(_line)
_s = bufffer.getvalue()
bufffer.close()
if six.PY3:
_s = _s.encode('utf8')
except Exception as e:
logger.error('fail export_csv_task().')
logger.error('EXCEPT: export_csv_task(). e=%s, msg1=%s,msg2=%s',
e, sys.exc_info()[1], sys.exc_info()[2])
return None
return _s
| bufffer = six.StringIO() | conditional_block |
libs.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import datetime
import logging
import csv
import six
from datetime import date
from django.apps import apps
from django.utils import timezone
logger = logging.getLogger(__name__)
ats_settings = apps.get_app_config('ats')
def get_user_realname(first_name, last_name, is_last_name_front):
if is_last_name_front:
return '%s %s' % (last_name, first_name)
else:
return '%s %s' % (first_name, last_name)
def format_totaltime(td):
totalhour = (td.days * 24) + int(td.seconds / 3600)
minute = int(td.seconds / 60) - (int(td.seconds / 3600) * 60)
return '%d:%02d' % (totalhour, minute)
def format_hours_float(td):
return (td.days * 24) + (td.seconds / 3600.0)
def format_time(timedata):
return '%d:%02d' % (timedata.hour, timedata.minute)
def | ():
_now = timezone.localtime()
# logger.debug("get_localtime() : %s" % (_now))
return _now
def get_thismonth_1st():
_now = timezone.localtime()
_ret = _now.replace(day=1)
# logger.debug("get_thismonth_1st(): %s" % (_ret))
return _ret
def export_csv_task(datalist, add_header, new_line):
_s = ''
if six.PY2:
bufffer = six.BytesIO()
else:
bufffer = six.StringIO()
try:
if True:
_writer = csv.writer(
bufffer, lineterminator=new_line,
quotechar='"', quoting=csv.QUOTE_ALL)
if add_header:
_header = [
'date',
'project',
'code',
'job',
'task',
'user',
'tasktime',
'task_userdata1',
'task_userdata2',
'task_userdata3',
'task_userdata4',
'task_userdata5',
'comment',
]
_writer.writerow(_header)
for d in datalist:
_line = []
_date = d['taskdate'].isoformat()
_line.append(_date)
_line.append(d['project__name'])
if d['project__external_project__code']:
_line.append(d['project__external_project__code'])
else:
_line.append('')
_line.append(d['task__job__name'])
_line.append(d['task__name'])
_line.append(get_user_realname(d['user__first_name'], d['user__last_name'], ats_settings.ATS_IS_LASTNAME_FRONT))
_line.append(format_time(d['tasktime']))
_line.append(d['task__userdata1'])
_line.append(d['task__userdata2'])
_line.append(d['task__userdata3'])
_line.append(d['task__userdata4'])
_line.append(d['task__userdata5'])
_line.append(d['comment'])
if six.PY2:
for i in range(len(_line)):
_line[i] = _line[i].encode('utf8')
_writer.writerow(_line)
_s = bufffer.getvalue()
bufffer.close()
if six.PY3:
_s = _s.encode('utf8')
except Exception as e:
logger.error('fail export_csv_task().')
logger.error('EXCEPT: export_csv_task(). e=%s, msg1=%s,msg2=%s',
e, sys.exc_info()[1], sys.exc_info()[2])
return None
return _s
| get_localtime | identifier_name |
libs.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import datetime
import logging
import csv
import six
from datetime import date
from django.apps import apps
from django.utils import timezone
logger = logging.getLogger(__name__)
ats_settings = apps.get_app_config('ats')
def get_user_realname(first_name, last_name, is_last_name_front):
if is_last_name_front:
return '%s %s' % (last_name, first_name)
else:
return '%s %s' % (first_name, last_name)
def format_totaltime(td):
totalhour = (td.days * 24) + int(td.seconds / 3600)
minute = int(td.seconds / 60) - (int(td.seconds / 3600) * 60)
return '%d:%02d' % (totalhour, minute)
def format_hours_float(td):
return (td.days * 24) + (td.seconds / 3600.0)
def format_time(timedata):
return '%d:%02d' % (timedata.hour, timedata.minute)
def get_localtime():
_now = timezone.localtime()
# logger.debug("get_localtime() : %s" % (_now))
return _now
| _now = timezone.localtime()
_ret = _now.replace(day=1)
# logger.debug("get_thismonth_1st(): %s" % (_ret))
return _ret
def export_csv_task(datalist, add_header, new_line):
_s = ''
if six.PY2:
bufffer = six.BytesIO()
else:
bufffer = six.StringIO()
try:
if True:
_writer = csv.writer(
bufffer, lineterminator=new_line,
quotechar='"', quoting=csv.QUOTE_ALL)
if add_header:
_header = [
'date',
'project',
'code',
'job',
'task',
'user',
'tasktime',
'task_userdata1',
'task_userdata2',
'task_userdata3',
'task_userdata4',
'task_userdata5',
'comment',
]
_writer.writerow(_header)
for d in datalist:
_line = []
_date = d['taskdate'].isoformat()
_line.append(_date)
_line.append(d['project__name'])
if d['project__external_project__code']:
_line.append(d['project__external_project__code'])
else:
_line.append('')
_line.append(d['task__job__name'])
_line.append(d['task__name'])
_line.append(get_user_realname(d['user__first_name'], d['user__last_name'], ats_settings.ATS_IS_LASTNAME_FRONT))
_line.append(format_time(d['tasktime']))
_line.append(d['task__userdata1'])
_line.append(d['task__userdata2'])
_line.append(d['task__userdata3'])
_line.append(d['task__userdata4'])
_line.append(d['task__userdata5'])
_line.append(d['comment'])
if six.PY2:
for i in range(len(_line)):
_line[i] = _line[i].encode('utf8')
_writer.writerow(_line)
_s = bufffer.getvalue()
bufffer.close()
if six.PY3:
_s = _s.encode('utf8')
except Exception as e:
logger.error('fail export_csv_task().')
logger.error('EXCEPT: export_csv_task(). e=%s, msg1=%s,msg2=%s',
e, sys.exc_info()[1], sys.exc_info()[2])
return None
return _s | def get_thismonth_1st(): | random_line_split |
gulpfile.js | var gulp = require('gulp');
var exec = require('child_process').exec;
var mkdirs = require('mkdirs');
var browserify = require('gulp-browserify');
var rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');
var nodemon = require('gulp-nodemon')
function | (command) {
return function (cb) {
exec(command, function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
}
}
gulp.task('create-data-folder', function() {
mkdirs('./mongodb/data');
});
//https://stackoverflow.com/questions/28665395/using-gulp-to-manage-opening-and-closing-mongodb
gulp.task('start-mongo', runCommand('mongod --dbpath ./mongodb/data/'));
gulp.task('stop-mongo', runCommand('mongo --eval "use admin; db.shutdownServer();"'));
gulp.task('create-db', runCommand('mongo tauw --eval "db.getCollectionNames()"'));
gulp.task('import-data', runCommand('mongoimport --db tauw --collection sensors --drop --file ./sensorseed.json'));
gulp.task('import-data2', runCommand('mongoimport --db tauw --collection settings --drop --file ./settingsseed.json'));
gulp.task('drop-collection', runCommand('mongo tauw --eval "db.sensors.drop()"'));
gulp.task('import-data-live', runCommand('mongoimport --host "tauw-shard-00-00-rkjng.mongodb.net:27017,tauw-shard-00-01-rkjng.mongodb.net:27017,tauw-shard-00-02-rkjng.mongodb.net:27017" --authenticationDatabase admin --ssl --username jaimie2 --password tauw22 --db tauw --collection sensors --drop --jsonArray --file "./generated.json"'));
gulp.task('import-settings-live', runCommand('mongoimport --host "tauw-shard-00-00-rkjng.mongodb.net:27017,tauw-shard-00-01-rkjng.mongodb.net:27017,tauw-shard-00-02-rkjng.mongodb.net:27017" --authenticationDatabase admin --ssl --username jaimie2 --password tauw22 --db tauw --collection settings --drop --file "./settingsseed.json"'));
gulp.task('setup-db',['create-data-folder','start-mongo','create-db','import-data', 'import-data2']);
gulp.task('sass', function() {
return gulp.src('public/stylesheets/*.scss')
.pipe(sass())
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(gulp.dest('public/build/css'));
});
gulp.task('scripts', function() {
gulp.src('public/javascripts/main.js')
.pipe(browserify({
insertGlobals : true,
debug : !gulp.env.production
}))
.pipe(rename('build.js'))
.pipe(gulp.dest('public/build/js/'))
});
gulp.task('watch', function() {
gulp.watch('public/stylesheets/*.scss', ['sass']);
gulp.watch('public/javascripts/*.js', ['scripts']);
});
gulp.task('start', function () {
nodemon({
script: 'bin/www'
, ext: 'js html ejs'
, env: { 'NODE_ENV': 'development' }
})
})
gulp.task('start-live', function () {
nodemon({
script: 'bin/www'
, ext: 'js html ejs'
, env: { 'NODE_ENV': 'development' }
})
})
gulp.task('live',['start-live']);
gulp.task('default', ['sass','scripts','start-mongo', 'watch','start']);
| runCommand | identifier_name |
gulpfile.js | var gulp = require('gulp');
var exec = require('child_process').exec;
var mkdirs = require('mkdirs');
var browserify = require('gulp-browserify');
var rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');
var nodemon = require('gulp-nodemon')
function runCommand(command) {
return function (cb) {
exec(command, function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
}
}
gulp.task('create-data-folder', function() {
mkdirs('./mongodb/data');
});
//https://stackoverflow.com/questions/28665395/using-gulp-to-manage-opening-and-closing-mongodb
gulp.task('start-mongo', runCommand('mongod --dbpath ./mongodb/data/'));
gulp.task('stop-mongo', runCommand('mongo --eval "use admin; db.shutdownServer();"'));
gulp.task('create-db', runCommand('mongo tauw --eval "db.getCollectionNames()"'));
gulp.task('import-data', runCommand('mongoimport --db tauw --collection sensors --drop --file ./sensorseed.json'));
gulp.task('import-data2', runCommand('mongoimport --db tauw --collection settings --drop --file ./settingsseed.json'));
gulp.task('drop-collection', runCommand('mongo tauw --eval "db.sensors.drop()"'));
gulp.task('import-data-live', runCommand('mongoimport --host "tauw-shard-00-00-rkjng.mongodb.net:27017,tauw-shard-00-01-rkjng.mongodb.net:27017,tauw-shard-00-02-rkjng.mongodb.net:27017" --authenticationDatabase admin --ssl --username jaimie2 --password tauw22 --db tauw --collection sensors --drop --jsonArray --file "./generated.json"'));
gulp.task('import-settings-live', runCommand('mongoimport --host "tauw-shard-00-00-rkjng.mongodb.net:27017,tauw-shard-00-01-rkjng.mongodb.net:27017,tauw-shard-00-02-rkjng.mongodb.net:27017" --authenticationDatabase admin --ssl --username jaimie2 --password tauw22 --db tauw --collection settings --drop --file "./settingsseed.json"'));
gulp.task('setup-db',['create-data-folder','start-mongo','create-db','import-data', 'import-data2']);
gulp.task('sass', function() {
return gulp.src('public/stylesheets/*.scss')
.pipe(sass())
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(gulp.dest('public/build/css'));
});
gulp.task('scripts', function() {
gulp.src('public/javascripts/main.js')
.pipe(browserify({
insertGlobals : true,
debug : !gulp.env.production
}))
.pipe(rename('build.js'))
.pipe(gulp.dest('public/build/js/'))
});
gulp.task('watch', function() {
gulp.watch('public/stylesheets/*.scss', ['sass']);
gulp.watch('public/javascripts/*.js', ['scripts']);
});
| , env: { 'NODE_ENV': 'development' }
})
})
gulp.task('start-live', function () {
nodemon({
script: 'bin/www'
, ext: 'js html ejs'
, env: { 'NODE_ENV': 'development' }
})
})
gulp.task('live',['start-live']);
gulp.task('default', ['sass','scripts','start-mongo', 'watch','start']); | gulp.task('start', function () {
nodemon({
script: 'bin/www'
, ext: 'js html ejs' | random_line_split |
gulpfile.js | var gulp = require('gulp');
var exec = require('child_process').exec;
var mkdirs = require('mkdirs');
var browserify = require('gulp-browserify');
var rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');
var nodemon = require('gulp-nodemon')
function runCommand(command) |
gulp.task('create-data-folder', function() {
mkdirs('./mongodb/data');
});
//https://stackoverflow.com/questions/28665395/using-gulp-to-manage-opening-and-closing-mongodb
gulp.task('start-mongo', runCommand('mongod --dbpath ./mongodb/data/'));
gulp.task('stop-mongo', runCommand('mongo --eval "use admin; db.shutdownServer();"'));
gulp.task('create-db', runCommand('mongo tauw --eval "db.getCollectionNames()"'));
gulp.task('import-data', runCommand('mongoimport --db tauw --collection sensors --drop --file ./sensorseed.json'));
gulp.task('import-data2', runCommand('mongoimport --db tauw --collection settings --drop --file ./settingsseed.json'));
gulp.task('drop-collection', runCommand('mongo tauw --eval "db.sensors.drop()"'));
gulp.task('import-data-live', runCommand('mongoimport --host "tauw-shard-00-00-rkjng.mongodb.net:27017,tauw-shard-00-01-rkjng.mongodb.net:27017,tauw-shard-00-02-rkjng.mongodb.net:27017" --authenticationDatabase admin --ssl --username jaimie2 --password tauw22 --db tauw --collection sensors --drop --jsonArray --file "./generated.json"'));
gulp.task('import-settings-live', runCommand('mongoimport --host "tauw-shard-00-00-rkjng.mongodb.net:27017,tauw-shard-00-01-rkjng.mongodb.net:27017,tauw-shard-00-02-rkjng.mongodb.net:27017" --authenticationDatabase admin --ssl --username jaimie2 --password tauw22 --db tauw --collection settings --drop --file "./settingsseed.json"'));
gulp.task('setup-db',['create-data-folder','start-mongo','create-db','import-data', 'import-data2']);
gulp.task('sass', function() {
return gulp.src('public/stylesheets/*.scss')
.pipe(sass())
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(gulp.dest('public/build/css'));
});
gulp.task('scripts', function() {
gulp.src('public/javascripts/main.js')
.pipe(browserify({
insertGlobals : true,
debug : !gulp.env.production
}))
.pipe(rename('build.js'))
.pipe(gulp.dest('public/build/js/'))
});
gulp.task('watch', function() {
gulp.watch('public/stylesheets/*.scss', ['sass']);
gulp.watch('public/javascripts/*.js', ['scripts']);
});
gulp.task('start', function () {
nodemon({
script: 'bin/www'
, ext: 'js html ejs'
, env: { 'NODE_ENV': 'development' }
})
})
gulp.task('start-live', function () {
nodemon({
script: 'bin/www'
, ext: 'js html ejs'
, env: { 'NODE_ENV': 'development' }
})
})
gulp.task('live',['start-live']);
gulp.task('default', ['sass','scripts','start-mongo', 'watch','start']);
| {
return function (cb) {
exec(command, function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
}
} | identifier_body |
as_bytes.rs | // Copyright 2016 blake2-rfc Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use core::mem;
use core::slice;
pub unsafe trait Safe {}
pub trait AsBytes {
fn as_bytes(&self) -> &[u8];
fn as_mut_bytes(&mut self) -> &mut [u8];
}
impl<T: Safe> AsBytes for [T] {
#[inline]
fn as_bytes(&self) -> &[u8] {
unsafe {
slice::from_raw_parts(self.as_ptr() as *const u8,
self.len() * mem::size_of::<T>())
}
}
#[inline]
fn as_mut_bytes(&mut self) -> &mut [u8] {
unsafe {
slice::from_raw_parts_mut(self.as_mut_ptr() as *mut u8,
self.len() * mem::size_of::<T>())
}
} |
unsafe impl Safe for u8 {}
unsafe impl Safe for u16 {}
unsafe impl Safe for u32 {}
unsafe impl Safe for u64 {}
unsafe impl Safe for i8 {}
unsafe impl Safe for i16 {}
unsafe impl Safe for i32 {}
unsafe impl Safe for i64 {} | } | random_line_split |
as_bytes.rs | // Copyright 2016 blake2-rfc Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use core::mem;
use core::slice;
pub unsafe trait Safe {}
pub trait AsBytes {
fn as_bytes(&self) -> &[u8];
fn as_mut_bytes(&mut self) -> &mut [u8];
}
impl<T: Safe> AsBytes for [T] {
#[inline]
fn as_bytes(&self) -> &[u8] |
#[inline]
fn as_mut_bytes(&mut self) -> &mut [u8] {
unsafe {
slice::from_raw_parts_mut(self.as_mut_ptr() as *mut u8,
self.len() * mem::size_of::<T>())
}
}
}
unsafe impl Safe for u8 {}
unsafe impl Safe for u16 {}
unsafe impl Safe for u32 {}
unsafe impl Safe for u64 {}
unsafe impl Safe for i8 {}
unsafe impl Safe for i16 {}
unsafe impl Safe for i32 {}
unsafe impl Safe for i64 {}
| {
unsafe {
slice::from_raw_parts(self.as_ptr() as *const u8,
self.len() * mem::size_of::<T>())
}
} | identifier_body |
as_bytes.rs | // Copyright 2016 blake2-rfc Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use core::mem;
use core::slice;
pub unsafe trait Safe {}
pub trait AsBytes {
fn as_bytes(&self) -> &[u8];
fn as_mut_bytes(&mut self) -> &mut [u8];
}
impl<T: Safe> AsBytes for [T] {
#[inline]
fn as_bytes(&self) -> &[u8] {
unsafe {
slice::from_raw_parts(self.as_ptr() as *const u8,
self.len() * mem::size_of::<T>())
}
}
#[inline]
fn | (&mut self) -> &mut [u8] {
unsafe {
slice::from_raw_parts_mut(self.as_mut_ptr() as *mut u8,
self.len() * mem::size_of::<T>())
}
}
}
unsafe impl Safe for u8 {}
unsafe impl Safe for u16 {}
unsafe impl Safe for u32 {}
unsafe impl Safe for u64 {}
unsafe impl Safe for i8 {}
unsafe impl Safe for i16 {}
unsafe impl Safe for i32 {}
unsafe impl Safe for i64 {}
| as_mut_bytes | identifier_name |
test_hoursbalance_model.py | import datetime
import pytz
from django.utils import timezone
from django.contrib.auth.models import User
from django.test import TestCase
from gerencex.core.models import HoursBalance, Timing, Office
from gerencex.core.time_calculations import DateData
class HoursBalanceModelTest(TestCase):
@classmethod
def | (cls):
cls.user = User.objects.create_user('testuser', 'test@user.com', 'senha123')
def test_balances(self):
r1 = HoursBalance.objects.create(
date=datetime.date(2016, 8, 18),
user=self.user,
credit=datetime.timedelta(hours=6).seconds,
debit=datetime.timedelta(hours=7).seconds,
)
# Test creation
self.assertTrue(HoursBalance.objects.exists())
# First balance is calculated without a previous balance (see the
# total_balance_handler function at signals.py)
self.assertEqual(r1.balance, int(datetime.timedelta(hours=-1).total_seconds()))
# Second balance takes the first balance into account (see the
# total_balance_handler function at signals.py)
r2 = HoursBalance.objects.create(
date=datetime.date(2016, 8, 19),
user=self.user,
credit=datetime.timedelta(hours=6).seconds,
debit=datetime.timedelta(hours=7).seconds,
)
self.assertEqual(r2.balance, int(datetime.timedelta(hours=-2).total_seconds()))
# Change in first credit or debit must change the second balance (see the
# next_balance_handler function at signals.py)
r1.credit = datetime.timedelta(hours=7).seconds
r1.save()
r2 = HoursBalance.objects.get(pk=2)
self.assertEqual(r2.balance, int(datetime.timedelta(hours=-1).total_seconds()))
class CreditTriggerTest(TestCase):
"""
The user credit is always registered at HourBalance via signal, when a checkout occurs.
See the 'credit_calculation' function, at signals.py
"""
@classmethod
def setUpTestData(cls):
Office.objects.create(name='Nenhuma lotação',
initials='NL',
regular_work_hours=datetime.timedelta(hours=6))
User.objects.create_user('testuser', 'test@user.com', 'senha123')
cls.user = User.objects.get(username='testuser')
def test_credit_triggers(self):
# Let's record a check in...
t1 = Timing.objects.create(
user=self.user,
date_time=timezone.make_aware(datetime.datetime(2016, 10, 3, 12, 0, 0, 0)),
checkin=True
)
# ...and a checkout
t2 = Timing.objects.create(
user=self.user,
date_time=timezone.make_aware(datetime.datetime(2016, 10, 3, 13, 0, 0, 0)),
checkin=False
)
# Let's record a balance line at HoursBalance
date = datetime.date(2016, 10, 3)
new_credit = DateData(self.user, date).credit().seconds
new_debit = DateData(self.user, date).debit().seconds
HoursBalance.objects.create(
date=date,
user=self.user,
credit=new_credit,
debit=new_debit
)
# Let's change t2 (checkout record)
t2.date_time += datetime.timedelta(hours=1)
t2.save()
# The balance must have been recalculated via django signal (signals.py)
checkout_tolerance = self.user.userdetail.office.checkout_tolerance
checkin_tolerance = self.user.userdetail.office.checkin_tolerance
tolerance = checkout_tolerance + checkin_tolerance
reference = datetime.timedelta(hours=2).seconds + tolerance.seconds
line = HoursBalance.objects.first()
credit = line.credit
self.assertEqual(reference, credit)
# Let's change t1 (checkin record)
t1.date_time += datetime.timedelta(hours=1)
t1.save()
# The balance must have been recalculated via signal
modified_reference = datetime.timedelta(hours=1).seconds + tolerance.seconds
modified_balance_line = HoursBalance.objects.first()
modified_credit = modified_balance_line.credit
self.assertEqual(modified_reference, modified_credit)
# TODO: Escrever o teste depois que já houver view para produzir o balanço da divisão e do usuário
class RestdayDebitTriggerTest(TestCase):
"""
When a we record a Restday whose date is prior to the date of the Balance, the balances must
be recalculated for all users.
"""
@classmethod
def setUpTestData(cls):
Office.objects.create(name='Diacomp 1', initials='diacomp1')
Office.objects.create(name='Diacomp 2', initials='diacomp2')
cls.diacomp1 = Office.objects.get(initials='diacomp1')
cls.diacomp2 = Office.objects.get(initials='diacomp2')
cls.diacomp1.hours_control_start_date = datetime.date(2016, 9, 1)
cls.diacomp1.save()
cls.diacomp2.hours_control_start_date = datetime.date(2016, 10, 1)
cls.diacomp1.save()
User.objects.create_user('testuser1', 'test1@user.com', 'senha123')
User.objects.create_user('testuser2', 'test2@user.com', 'senha123')
cls.user1 = User.objects.get(username='testuser')
cls.user2 = User.objects.get(username='testuser')
# def test_debit_trigger(self):
def activate_timezone():
return timezone.activate(pytz.timezone('America/Sao_Paulo'))
| setUpTestData | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.