file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
pystone.py
, 10/84 pg. 1013. Translated from ADA to C by Rick Richardson. Every method to preserve ADA-likeness has been used, at the expense of C-ness. Translated from C to Python by Guido van Rossum. Version History: Version 1.1 corrects two bug...
(PtrParOut): global IntGlob if PtrGlb is not None: PtrParOut = PtrGlb.PtrComp else: IntGlob = 100 PtrGlb.IntComp = Proc7(10, IntGlob) return PtrParOut def Proc4(): global Char2Glob BoolLoc = Char1Glob == 'A' BoolLoc = BoolLoc or BoolGlob Char2Glob = 'B' def Proc5(...
Proc3
identifier_name
pystone.py
. 1013. Translated from ADA to C by Rick Richardson. Every method to preserve ADA-likeness has been used, at the expense of C-ness. Translated from C to Python by Guido van Rossum. Version History: Version 1.1 corrects two bugs in versi...
EnumLoc = EnumParIn if EnumLoc == Ident3: return TRUE return FALSE
identifier_body
pystone.py
is rather inefficient and not true to the intention of the original benchmark (where a pointer comparison to None is intended; the != operator attempts to find a method __cmp__ to do value comparison of the record). Version 1.1 runs 5-10 ...
import sys def error(msg): print(msg, end=' ', file=sys.stderr) print("usage: %s [number_of_loops]" % sys.argv[0], file=sys.stderr) sys.exit(100) nargs = len(sys.argv) - 1 if nargs > 1: error("%d arguments are too many;" % nargs) elif nargs == 1: try: loops = int(...
conditional_block
test.rs
#[macro_use] extern crate smelter; #[derive(PartialEq, Debug, Builder, Default)] struct Point { x: u32, #[smelter(field_name="y_axis")] y: u32, } #[derive(PartialEq, Debug, Builder, Default)] struct Container<T> where T: PartialEq + Default { item: T, } #[test] fn can_generate_builder_methods()...
<T> where T: PartialEq + Default { item: T, #[smelter(field_name = "id")] item_id: u64, } #[test] fn can_generate_container_with_prefix() { let container: ContainerWith<u32> = ContainerWith::default() .with_item(1u32) ...
ContainerWith
identifier_name
test.rs
#[macro_use] extern crate smelter; #[derive(PartialEq, Debug, Builder, Default)] struct Point { x: u32, #[smelter(field_name="y_axis")] y: u32, } #[derive(PartialEq, Debug, Builder, Default)] struct Container<T> where T: PartialEq + Default { item: T, } #[test] fn can_generate_builder_methods()...
} #[derive(PartialEq, Builder, Default, Debug, Clone)] #[smelter(prefix="with_")] pub struct User { pub uid: u64, pub email: String, pub alias: String, pub friends: Vec<User>, } #[test] fn can_derive_collection() { let mut u1 = User::default(); let u2 = User::default() .with_em...
assert_eq!(with_lifetime, expected);
random_line_split
settings.py
from celery.schedules import crontab import djcelery from django.conf.global_settings import EMAIL_BACKEND import os, sys, logging import subprocess ############################### # MISC # ############################## ROOT_PATH = os.path.dirname(__file__) def to_absolute_path(path): re...
EXTRA_PATHS = [ 'lib', ] for path in EXTRA_PATHS: path = to_absolute_path(path) if path not in sys.path: sys.path.append(path) PROXY_SERVER = "PROXY_SERVER" IGNORE_HTTPS = False ############################### # CAMPAIGN SETTINGS # ############################## MAX_PAYMENT_RETRIES =...
DONATION_DEBUG = True #So we don't have to rely on django's debug. BLOCK_FB_POSTS = True #ROOT_PATH = os.path.dirname(__file__)
random_line_split
settings.py
from celery.schedules import crontab import djcelery from django.conf.global_settings import EMAIL_BACKEND import os, sys, logging import subprocess ############################### # MISC # ############################## ROOT_PATH = os.path.dirname(__file__) def
(path): return os.path.realpath(os.path.join(ROOT_PATH, path)) DEBUG = True TEMPLATE_DEBUG = DEBUG DONATION_DEBUG = True #So we don't have to rely on django's debug. BLOCK_FB_POSTS = True #ROOT_PATH = os.path.dirname(__file__) EXTRA_PATHS = [ 'lib', ] for path in EXTRA_PATHS: path = to_absolute_path(pat...
to_absolute_path
identifier_name
settings.py
from celery.schedules import crontab import djcelery from django.conf.global_settings import EMAIL_BACKEND import os, sys, logging import subprocess ############################### # MISC # ############################## ROOT_PATH = os.path.dirname(__file__) def to_absolute_path(path):
DEBUG = True TEMPLATE_DEBUG = DEBUG DONATION_DEBUG = True #So we don't have to rely on django's debug. BLOCK_FB_POSTS = True #ROOT_PATH = os.path.dirname(__file__) EXTRA_PATHS = [ 'lib', ] for path in EXTRA_PATHS: path = to_absolute_path(path) if path not in sys.path: sys.path.append(path) PRO...
return os.path.realpath(os.path.join(ROOT_PATH, path))
identifier_body
settings.py
from celery.schedules import crontab import djcelery from django.conf.global_settings import EMAIL_BACKEND import os, sys, logging import subprocess ############################### # MISC # ############################## ROOT_PATH = os.path.dirname(__file__) def to_absolute_path(path): re...
PROXY_SERVER = "PROXY_SERVER" IGNORE_HTTPS = False ############################### # CAMPAIGN SETTINGS # ############################## MAX_PAYMENT_RETRIES = 1 PAYMENT_RETRY_SCHEDULE = [1, 3, 7] JUMOEIN = "" ############################### # ADMIN SETTINGS # ############################## ...
sys.path.append(path)
conditional_block
rhel_release.rs
use regex::Regex; use std::fs::File; use std::io::Error; use std::io::prelude::*; use utils; pub struct RHELRelease { pub distro: Option<String>, pub version: Option<String> } fn read_file(filename: &str) -> Result<String, Error> { let mut file = File::open(filename)?; let mut contents = String::new()...
, None => None }; RHELRelease { distro: distro, version: version } }
{ match m.get(1) { Some(version) => { Some(version.as_str().to_owned()) }, None => None } }
conditional_block
rhel_release.rs
use regex::Regex; use std::fs::File; use std::io::Error; use std::io::prelude::*; use utils; pub struct RHELRelease { pub distro: Option<String>, pub version: Option<String> } fn read_file(filename: &str) -> Result<String, Error> { let mut file = File::open(filename)?; let mut contents = String::new()...
} } } pub fn parse(file: String) -> RHELRelease { let distrib_regex = Regex::new(r"(\w+) Linux release").unwrap(); let version_regex = Regex::new(r"release\s([\w\.]+)").unwrap(); let distro = match distrib_regex.captures_iter(&file).next() { Some(m) => { match m.get(1) { ...
None
random_line_split
rhel_release.rs
use regex::Regex; use std::fs::File; use std::io::Error; use std::io::prelude::*; use utils; pub struct RHELRelease { pub distro: Option<String>, pub version: Option<String> } fn read_file(filename: &str) -> Result<String, Error> { let mut file = File::open(filename)?; let mut contents = String::new()...
pub fn parse(file: String) -> RHELRelease { let distrib_regex = Regex::new(r"(\w+) Linux release").unwrap(); let version_regex = Regex::new(r"release\s([\w\.]+)").unwrap(); let distro = match distrib_regex.captures_iter(&file).next() { Some(m) => { match m.get(1) { Som...
{ if utils::file_exists("/etc/redhat-release") { if let Ok(release) = read_file("/etc/redhat-release") { Some(parse(release)) } else { None } } else { if let Ok(release) = read_file("/etc/centos-release") { Some(parse(release)) } else {...
identifier_body
rhel_release.rs
use regex::Regex; use std::fs::File; use std::io::Error; use std::io::prelude::*; use utils; pub struct RHELRelease { pub distro: Option<String>, pub version: Option<String> } fn read_file(filename: &str) -> Result<String, Error> { let mut file = File::open(filename)?; let mut contents = String::new()...
() -> Option<RHELRelease> { if utils::file_exists("/etc/redhat-release") { if let Ok(release) = read_file("/etc/redhat-release") { Some(parse(release)) } else { None } } else { if let Ok(release) = read_file("/etc/centos-release") { Some(parse(...
retrieve
identifier_name
components.py
#################################################################################################### # # GroupedPurchaseOrder - A Django Application. # Copyright (C) 2014 Fabrice Salvaire # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public Lic...
#################################################################################################### def render_modal_icon_button(icon, *args, **kwargs): attrs = {'data-toggle':'modal', 'data-target':join_text(args)} return render_button(None, icon=icon, attrs=attrs, **kwargs) ##############################...
return render_button(None, icon=icon, **kwargs)
identifier_body
components.py
#################################################################################################### # # GroupedPurchaseOrder - A Django Application. # Copyright (C) 2014 Fabrice Salvaire # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public Lic...
else: tag = 'button' if title: attrs['title'] = escape(_(title)) icon_content = render_icon(icon) if icon else '' if content: content = join_text((icon_content, escape(_(content))), separator=' ') else: content = icon_content return render_tag(tag, mark_safe(c...
try: # current_app = context['request'].resolver_match.namespace # viewname=viewname, args=view_args, kwargs=view_kwargs, current_app=current_app url = reverse(href) except NoReverseMatch: url = href attrs['href'] = url tag = 'a'
conditional_block
components.py
#################################################################################################### # # GroupedPurchaseOrder - A Django Application. # Copyright (C) 2014 Fabrice Salvaire # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public Lic...
(content, icon=None, style='default', size='', href='', title='', button_class='', attrs=None): """Render a button with content """ # <button type="button" class="btn btn-default">Default</button> # <button type="button" class="btn btn-primary">Primary</button> # <button type="button" class="...
render_button
identifier_name
components.py
#################################################################################################### # # GroupedPurchaseOrder - A Django Application. # Copyright (C) 2014 Fabrice Salvaire # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public Lic...
from .html import join_text, merge_new_words, render_tag #################################################################################################### # # Notes: # - How to concate in {% %} ? #deleteModal{{ supplier.pk }} # - url 'suppliers.update' supplier.pk # ##############################################...
####################################################################################################
random_line_split
base.py
from __future__ import unicode_literals from os.path import abspath, basename, dirname, join, normpath from sys import path import markdown """Common settings and globals.""" # PATH CONFIGURATION # Absolute filesystem path to the Django project directory: DJANGO_ROOT = dirname(dirname(abspath(__file__))) # Absolut...
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = [] # END SITE CONFIGURATION # FIXTURE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS FIXTURE_DIRS = ( normpath(join(SITE_ROOT, 'fixtures')), ) # END FIXTURE CONFIGURATION # ...
# Hosts/domain names that are valid for this site
random_line_split
constant-in-match-pattern.rs
// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() { match 1 { CONSTANT => {} _ => {} }; // if let 3 = CONSTANT {} match (Struct { a: 2, b: 2 }) { STRUCT => {} _ => {} }; // if let STRUCT = STRUCT {} match TupleStruct(3) { TUPLE_STRUCT => {} _ => {} }; // if let TupleStruct(4) ...
main
identifier_name
constant-in-match-pattern.rs
// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
struct Struct { a: isize, b: usize, } const STRUCT: Struct = Struct { a: 1, b: 2 }; struct TupleStruct(u32); const TUPLE_STRUCT: TupleStruct = TupleStruct(4); enum Enum { Variant1(char), Variant2 { a: u8 }, Variant3 } const VARIANT1: Enum = Enum::Variant1('v'); const VARIANT2: Enum = Enum::Varian...
// debug locations to 'constant' patterns in match expressions. const CONSTANT: u64 = 3;
random_line_split
object-css-parser.js
/* MIT License Copyright (c) 2016 Christian Rafael JS Object to CSS String Parser christian@paradix.com.br */ function parseCSS( object_css )
{ function parseClass( _class, properties ) { return String().concat( _class, " { ", parseProperties( properties ), " } " ); } function parseProperties( properties ) { var css_properties = String(); for (var prop in properties) { css_properties = css_properties.concat( ...
identifier_body
object-css-parser.js
/* MIT License Copyright (c) 2016 Christian Rafael JS Object to CSS String Parser christian@paradix.com.br */ function parseCSS( object_css ) { function
( _class, properties ) { return String().concat( _class, " { ", parseProperties( properties ), " } " ); } function parseProperties( properties ) { var css_properties = String(); for (var prop in properties) { css_properties = css_properties.concat( typeof prop...
parseClass
identifier_name
object-css-parser.js
/* MIT License Copyright (c) 2016 Christian Rafael JS Object to CSS String Parser christian@paradix.com.br */ function parseCSS( object_css ) { function parseClass( _class, properties ) { return String().concat( _class, " { ", parseProperties( properties ), " } " ); } function parse...
return css_str; }
}
random_line_split
feature_compute2.py
''' Computes feature representations ''' from __future__ import division, print_function from hscom import __common__ (print, print_, print_on, print_off, rrr, profile) = __common__.init(__name__, '[fc2]') # scientific import numpy as np # python from os.path import join # hotspotter from hscom import helpers as util ...
desc_list = desc_list.tolist() kpts_list = kpts_list.tolist() print('[fc2] Loaded kpts_list and desc_list from big cache') return kpts_list, desc_list @profile def sequential_feat_load(feat_cfg, feat_fpath_list): kpts_list = [] desc_list = [] # Debug loading (seems to use lots of memory)...
return None
conditional_block
feature_compute2.py
''' Computes feature representations ''' from __future__ import division, print_function from hscom import __common__ (print, print_, print_on, print_off, rrr, profile) = __common__.init(__name__, '[fc2]') # scientific import numpy as np # python from os.path import join # hotspotter from hscom import helpers as util ...
(cache_dir, uid, ext, kpts_list, desc_list): print('[fc2] Caching desc_list and kpts_list') io.smart_save(kpts_list, cache_dir, 'kpts_list', uid, ext) io.smart_save(desc_list, cache_dir, 'desc_list', uid, ext) @profile def bigcache_feat_load(cache_dir, uid, ext): #io.debug_smart_load(cache_dir, fname=...
bigcache_feat_save
identifier_name
feature_compute2.py
''' Computes feature representations ''' from __future__ import division, print_function from hscom import __common__ (print, print_, print_on, print_off, rrr, profile) = __common__.init(__name__, '[fc2]') # scientific import numpy as np # python from os.path import join # hotspotter from hscom import helpers as util ...
desc_list.append(desc) mark_progress(count) end_progress() print('[fc2] Finished load of individual kpts and desc') except MemoryError: print('\n------------') print('[fc2] Out of memory') print('[fc2] Trying to read: %r' % feat_path) print('[f...
kpts_list = [] desc_list = [] # Debug loading (seems to use lots of memory) print('\n') try: nFeats = len(feat_fpath_list) prog_label = '[fc2] Loading feature: ' mark_progress, end_progress = util.progress_func(nFeats, prog_label) for count, feat_path in enumerate(feat_fp...
identifier_body
feature_compute2.py
''' Computes feature representations ''' from __future__ import division, print_function from hscom import __common__ (print, print_, print_on, print_off, rrr, profile) = __common__.init(__name__, '[fc2]') # scientific import numpy as np # python from os.path import join # hotspotter from hscom import helpers as util ...
print('[fc2] Loaded kpts_list and desc_list from big cache') return kpts_list, desc_list @profile def sequential_feat_load(feat_cfg, feat_fpath_list): kpts_list = [] desc_list = [] # Debug loading (seems to use lots of memory) print('\n') try: nFeats = len(feat_fpath_list) ...
random_line_split
hr_payroll_pay_commission.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Original Module by SIESA (<http://www.siesacr.com>) # Refactored by CLEARCORP S.A. (<http://clearcorp.co.cr>) # # This program is free software: you can redis...
return True _columns = { 'commission_id': fields.many2one('sale.commission.commission', string='Commission'), 'invoice_id': fields.related('commission_id', 'invoice_id', type='many2one', obj='account.invoice', string='Invoice', readonly=True), 'input_id': fields.many2on...
if payment.amount_paid <= 0.0: return False
conditional_block
hr_payroll_pay_commission.py
# -*- coding: utf-8 -*- ############################################################################## #
# OpenERP, Open Source Management Solution # Original Module by SIESA (<http://www.siesacr.com>) # Refactored by CLEARCORP S.A. (<http://clearcorp.co.cr>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # publish...
random_line_split
hr_payroll_pay_commission.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Original Module by SIESA (<http://www.siesacr.com>) # Refactored by CLEARCORP S.A. (<http://clearcorp.co.cr>) # # This program is free software: you can redis...
_columns = { 'commission_id': fields.many2one('sale.commission.commission', string='Commission'), 'invoice_id': fields.related('commission_id', 'invoice_id', type='many2one', obj='account.invoice', string='Invoice', readonly=True), 'input_id': fields.many2one('hr.payslip.input'...
for payment in self.browse(cr, uid, ids, context=context): if payment.amount_paid <= 0.0: return False return True
identifier_body
hr_payroll_pay_commission.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Original Module by SIESA (<http://www.siesacr.com>) # Refactored by CLEARCORP S.A. (<http://clearcorp.co.cr>) # # This program is free software: you can redis...
(osv.Model): """Commissions Payroll Payment""" _name = 'hr.payroll.pay.commission.payment' _description = __doc__ def _check_amount_paid(self, cr, uid, ids, context=None): for payment in self.browse(cr, uid, ids, context=context): if payment.amount_paid <= 0.0: ret...
Payment
identifier_name
bounds.rs
use core::{usize, u8, u16, u32, u64}; use core::{isize, i8, i16, i32, i64}; use core::{f32, f64}; use core::num::Wrapping; /// Numbers which have upper and lower bounds pub trait Bounded { // FIXME (#5527): These should be associated constants /// returns the smallest finite number this type can represent ...
() { macro_rules! test_wrapping_bounded { ($($t:ty)+) => { $( assert_eq!(Wrapping::<$t>::min_value().0, <$t>::min_value()); assert_eq!(Wrapping::<$t>::max_value().0, <$t>::max_value()); )+ }; } test_wrapping_bounded!(usize u8 u16 u32 u...
wrapping_bounded
identifier_name
bounds.rs
use core::{usize, u8, u16, u32, u64}; use core::{isize, i8, i16, i32, i64}; use core::{f32, f64}; use core::num::Wrapping; /// Numbers which have upper and lower bounds pub trait Bounded { // FIXME (#5527): These should be associated constants /// returns the smallest finite number this type can represent ...
bounded_impl!(u32, u32::MIN, u32::MAX); bounded_impl!(u64, u64::MIN, u64::MAX); bounded_impl!(isize, isize::MIN, isize::MAX); bounded_impl!(i8, i8::MIN, i8::MAX); bounded_impl!(i16, i16::MIN, i16::MAX); bounded_impl!(i32, i32::MIN, i32::MAX); bounded_impl!(i64, i64::MIN, i64::MAX); impl<T: B...
random_line_split
bounds.rs
use core::{usize, u8, u16, u32, u64}; use core::{isize, i8, i16, i32, i64}; use core::{f32, f64}; use core::num::Wrapping; /// Numbers which have upper and lower bounds pub trait Bounded { // FIXME (#5527): These should be associated constants /// returns the smallest finite number this type can represent ...
fn max_value() -> Self { Wrapping(T::max_value()) } } bounded_impl!(f32, f32::MIN, f32::MAX); macro_rules! for_each_tuple_ { ( $m:ident !! ) => ( $m! { } ); ( $m:ident !! $h:ident, $($t:ident,)* ) => ( $m! { $h $($t)* } for_each_tuple_! { $m !! $($t,)* } ); } macro_rules! ...
{ Wrapping(T::min_value()) }
identifier_body
plotmetadata.py
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>Dialog</class> <widget class="QDialog" name="Dialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y>
<height>300</height> </rect> </property> <property name="windowTitle"> <string>Dialog</string> </property> <widget class="QDialogButtonBox" name="buttonBox"> <property name="geometry"> <rect> <x>30</x> <y>240</y> <width>341</width> <height>32</height> </rect> </proper...
<width>400</width>
random_line_split
panic.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { // macro_rules! panic { // () => ( // panic!("explicit panic") // ); // ($msg:expr) => ({ // static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!()); // ::core::pani...
#[test] #[should_panic] fn panic_test2() { panic!("Hello, World!"); // panicked at 'Hello, World!' } #[test] #[should_panic] fn panic_test3() { panic!("{}, {}!", "Hello", "World"); // panicked at 'Hello, World!' } #[test] #[should_panic] fn panic_test4() { let arg1: &'...
{ panic!(); // panicked at 'explicit panic' }
identifier_body
panic.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { // macro_rules! panic { // () => ( // panic!("explicit panic") // ); // ($msg:expr) => ({ // static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!()); // ::core::pani...
() { let arg1: &'static str = "Hello"; let arg2: &'static str = "World"; panic!("{}, {}!", arg1, arg2); // panicked at 'Hello, World!' } #[test] #[should_panic] fn panic_test5() { let arg1: usize = 68; let arg2: usize = 500; panic!("arg1 = [{}], arg2 = [{}]", arg1, arg2); // panicked at 'arg1 =...
panic_test4
identifier_name
panic.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { // macro_rules! panic { // () => ( // panic!("explicit panic") // ); // ($msg:expr) => ({ // static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!()); // ::core::pani...
// } #[test] #[should_panic] fn panic_test1() { panic!(); // panicked at 'explicit panic' } #[test] #[should_panic] fn panic_test2() { panic!("Hello, World!"); // panicked at 'Hello, World!' } #[test] #[should_panic] fn panic_test3() { panic!("{}, {}!", "Hello", "Wo...
random_line_split
test.js
var VueSession=require('../dist/vue-session'); var assert=require('assert'); var localstorage={ setItem:function (key,value) { this[key]=value; }, getItem:function (key) { return this[key]; }, removeItem:function (key) { delete this[key]; } }; var session=new VueSession.Session(10000,'test',lo...
it('session maxAge should eq "10000"',function () { assert.equal(session.__maxAge__,10000); }); it('session prefix should eq "test"',function () { assert.equal(session.__prefix__,'test'); }); it('session signedin should eq "false"',function () { assert.equal(session.signedin,...
describe('Session',function () { describe('new Session',function () {
random_line_split
utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from .corner import _quantile from ..models.priors import TopHat as Uniform __all__ = ["get_best", "best_sample", "get_simple_prior", "sample_prior", "sample_posterior", "boxplot", "violinplot", "step"] def get_simple_prior(prior, xlim, nu...
if span is None: span = [0.999999426697 for i in range(ndim)] for i, _ in enumerate(span): try: xmin, xmax = span[i] except(TypeError): q = [0.5 - 0.5 * span[i], 0.5 + 0.5 * span[i]] xmin, xmax = _quantile(data[i], q) good = (data[i] > xmin)...
color = ndim * [color]
conditional_block
utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from .corner import _quantile from ..models.priors import TopHat as Uniform __all__ = ["get_best", "best_sample", "get_simple_prior", "sample_prior", "sample_posterior", "boxplot", "violinplot", "step"] def get_simple_prior(prior, xlim, nu...
(res, **kwargs): """Get the maximum a posteriori parameters and their names :param res: A ``results`` dictionary with the keys 'lnprobability', 'chain', and 'theta_labels' :returns theta_names: List of strings giving the names of the parameters, of length ``ndim`` :returns bes...
get_best
identifier_name
utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from .corner import _quantile from ..models.priors import TopHat as Uniform __all__ = ["get_best", "best_sample", "get_simple_prior", "sample_prior", "sample_posterior", "boxplot", "violinplot", "step"] def get_simple_prior(prior, xlim, nu...
Samples from the prior :returns labels: list of strings The names of the free parameters. """ labels = model.free_params chain = np.zeros([nsample, model.ndim]) #chain = [] for l in labels: prior = model.config_dict[l]["prior"] if isinstance(prior, Uniform): ...
random_line_split
utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from .corner import _quantile from ..models.priors import TopHat as Uniform __all__ = ["get_best", "best_sample", "get_simple_prior", "sample_prior", "sample_posterior", "boxplot", "violinplot", "step"] def get_simple_prior(prior, xlim, nu...
pc.set_facecolor(color[i]) pc.set_alpha(alpha) def boxplot(data, pos, widths=0.1, weights=None, ax=None, q=[0.16, 0.84], **box_kwargs): from matplotlib.patches import Rectangle from matplotlib.collections import PatchCollection ndim = len(data) widths = np.ones(ndim) * n...
ndim = len(data) clipped_data = [] if type(color) is str: color = ndim * [color] if span is None: span = [0.999999426697 for i in range(ndim)] for i, _ in enumerate(span): try: xmin, xmax = span[i] except(TypeError): q = [0.5 - 0.5 * span[i], 0....
identifier_body
google_api.py
#!/usr/bin/env python """Read the Google Weather API and emit data in the usual format. Write a sample every 5 minutes on stdout, log on stderr. """ import sys import time from urllib import quote_plus from urllib2 import urlopen from datetime import datetime, timedelta from xml.etree import cElementTree as ET impor...
if __name__ == '__main__': sys.exit(main())
ts = datetime.now() try: et = ET.parse(urlopen(url)) value = float(et.getroot() .find('weather') .find('current_conditions') .find('temp_c') .attrib['data']) except Exception, e: logger.error("error readi...
conditional_block
google_api.py
#!/usr/bin/env python """Read the Google Weather API and emit data in the usual format. Write a sample every 5 minutes on stdout, log on stderr. """ import sys import time from urllib import quote_plus from urllib2 import urlopen from datetime import datetime, timedelta from xml.etree import cElementTree as ET impor...
if __name__ == '__main__': sys.exit(main())
location = sys.argv[1] url = ("http://www.google.com/ig/api?weather=" + quote_plus(location)) while 1: ts = datetime.now() try: et = ET.parse(urlopen(url)) value = float(et.getroot() .find('weather') .find('current_conditions') ...
identifier_body
google_api.py
#!/usr/bin/env python """Read the Google Weather API and emit data in the usual format. Write a sample every 5 minutes on stdout, log on stderr. """ import sys import time from urllib import quote_plus from urllib2 import urlopen from datetime import datetime, timedelta from xml.etree import cElementTree as ET impor...
(): location = sys.argv[1] url = ("http://www.google.com/ig/api?weather=" + quote_plus(location)) while 1: ts = datetime.now() try: et = ET.parse(urlopen(url)) value = float(et.getroot() .find('weather') .find('current_conditio...
main
identifier_name
google_api.py
#!/usr/bin/env python """Read the Google Weather API and emit data in the usual format. Write a sample every 5 minutes on stdout, log on stderr. """
from urllib import quote_plus from urllib2 import urlopen from datetime import datetime, timedelta from xml.etree import cElementTree as ET import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger() def main(): location = sys.argv[1] url = ("http://www.google.com/ig/api?weather=" ...
import sys import time
random_line_split
staticFriction.js
var Example = Example || {}; Example.staticFriction = function() { var Engine = Matter.Engine, Render = Matter.Render, Runner = Matter.Runner, Body = Matter.Body, Composites = Matter.Composites, Events = Matter.Events, MouseConstraint = Matter.MouseConstraint, ...
element: document.body, engine: engine, options: { width: Math.min(document.documentElement.clientWidth, 800), height: Math.min(document.documentElement.clientHeight, 600), showVelocity: true } }); Render.run(render); // create runner ...
var engine = Engine.create(), world = engine.world; // create renderer var render = Render.create({
random_line_split
staticFriction.js
var Example = Example || {}; Example.staticFriction = function() { var Engine = Matter.Engine, Render = Matter.Render, Runner = Matter.Runner, Body = Matter.Body, Composites = Matter.Composites, Events = Matter.Events, MouseConstraint = Matter.MouseConstraint, ...
var px = 400 + 100 * Math.sin(counter); // body is static so must manually update velocity for friction to work Body.setVelocity(body, { x: px - body.position.x, y: 0 }); Body.setPosition(body, { x: px, y: body.position.y }); }); // add mouse control var mouse = Mouse.cre...
{ return; }
conditional_block
worker.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::{Arc, Mutex}; use futures_channel::oneshot::Sender; use futures_util::{FutureExt as _, SinkExt as _, TryFutureExt as _, TryStreamExt as _}; use grpc_proto::testing::control::{ ClientArgs, ClientStatus, CoreRequest, CoreResponse, Ser...
resp.set_cores(cpu_count as i32); ctx.spawn( sink.success(resp) .map_err(|e| error!("failed to report cpu count: {:?}", e)) .map(|_| ()), ) } fn quit_worker(&mut self, ctx: RpcContext, _: Void, sink: crate::grpc::UnarySink<Void>) { let...
fn core_count(&mut self, ctx: RpcContext, _: CoreRequest, sink: UnarySink<CoreResponse>) { let cpu_count = util::cpu_num_cores(); let mut resp = CoreResponse::default();
random_line_split
worker.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::{Arc, Mutex}; use futures_channel::oneshot::Sender; use futures_util::{FutureExt as _, SinkExt as _, TryFutureExt as _, TryStreamExt as _}; use grpc_proto::testing::control::{ ClientArgs, ClientStatus, CoreRequest, CoreResponse, Ser...
{ shutdown_notifier: Arc<Mutex<Option<Sender<()>>>>, } impl Worker { pub fn new(sender: Sender<()>) -> Worker { Worker { shutdown_notifier: Arc::new(Mutex::new(Some(sender))), } } } impl WorkerService for Worker { fn run_server( &mut self, ctx: RpcContext, ...
Worker
identifier_name
worker.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::{Arc, Mutex}; use futures_channel::oneshot::Sender; use futures_util::{FutureExt as _, SinkExt as _, TryFutureExt as _, TryStreamExt as _}; use grpc_proto::testing::control::{ ClientArgs, ClientStatus, CoreRequest, CoreResponse, Ser...
fn quit_worker(&mut self, ctx: RpcContext, _: Void, sink: crate::grpc::UnarySink<Void>) { let notifier = self.shutdown_notifier.lock().unwrap().take(); if let Some(notifier) = notifier { let _ = notifier.send(()); } ctx.spawn( sink.success(Void::default()) ...
{ let cpu_count = util::cpu_num_cores(); let mut resp = CoreResponse::default(); resp.set_cores(cpu_count as i32); ctx.spawn( sink.success(resp) .map_err(|e| error!("failed to report cpu count: {:?}", e)) .map(|_| ()), ) }
identifier_body
worker.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::{Arc, Mutex}; use futures_channel::oneshot::Sender; use futures_util::{FutureExt as _, SinkExt as _, TryFutureExt as _, TryStreamExt as _}; use grpc_proto::testing::control::{ ClientArgs, ClientStatus, CoreRequest, CoreResponse, Ser...
ctx.spawn( sink.success(Void::default()) .map_err(|e| error!("failed to report quick worker: {:?}", e)) .map(|_| ()), ); } }
{ let _ = notifier.send(()); }
conditional_block
main.rs
extern crate serial; use std::env; use std::io; use std::time::Duration; use std::process::exit; use std::thread::sleep; use std::io::prelude::*; use serial::prelude::*; fn
() { let args: Vec<String> = env::args().skip(1).collect(); if args.len() != 1 { writeln!(io::stderr(), "Program takes exactly one argument. (The serial port)").unwrap(); exit(1); } let level = read_level(&mut io::stdin()); let mut port = serial::open(&args[0]).unwrap(); let mu...
main
identifier_name
main.rs
extern crate serial; use std::env; use std::io; use std::time::Duration; use std::process::exit; use std::thread::sleep; use std::io::prelude::*; use serial::prelude::*; fn main() { let args: Vec<String> = env::args().skip(1).collect(); if args.len() != 1 { writeln!(io::stderr(), "Program takes exac...
else { println!("Failed."); } for b in port.bytes() { print!("{}", std::char::from_u32(b.unwrap() as u32).unwrap()); } } // Reads level and prepares it to be sent fn read_level(input: &mut Read) -> String { let mut buf = String::new(); input.read_to_string(&mut buf).unwrap(); ...
{ println!("Finished."); }
conditional_block
main.rs
extern crate serial; use std::env; use std::io; use std::time::Duration; use std::process::exit; use std::thread::sleep; use std::io::prelude::*; use serial::prelude::*; fn main()
} port.set_timeout(Duration::from_millis(10000)).unwrap(); println!("Level: {} {} {}", level.as_bytes()[0], level.as_bytes()[1], level.split_at(2).1); println!("Uploading..."); if send_level(&mut port, &level) { println!("Finished."); } else { println!("Failed."); } fo...
{ let args: Vec<String> = env::args().skip(1).collect(); if args.len() != 1 { writeln!(io::stderr(), "Program takes exactly one argument. (The serial port)").unwrap(); exit(1); } let level = read_level(&mut io::stdin()); let mut port = serial::open(&args[0]).unwrap(); let mut s...
identifier_body
main.rs
extern crate serial; use std::env; use std::io; use std::time::Duration; use std::process::exit;
use std::io::prelude::*; use serial::prelude::*; fn main() { let args: Vec<String> = env::args().skip(1).collect(); if args.len() != 1 { writeln!(io::stderr(), "Program takes exactly one argument. (The serial port)").unwrap(); exit(1); } let level = read_level(&mut io::stdin()); ...
use std::thread::sleep;
random_line_split
__init__.py
import re class CommandError(Exception): pass class BaseCommand(): """ Base command, this will accept and handle some generic features of all commands. Like error handling, argument retrieving / checking """ def __init__(self, args): """ Initialize the class """ ...
return context
expressions = { 'options': r'--(.*)', 'values': r'<(.*)>', } for group, expression in expressions.items(): matches = re.search(expression, key) if matches: context[matches.group(1).replace('-', '_')] = value
conditional_block
__init__.py
import re class CommandError(Exception): pass class BaseCommand(): """ Base command, this will accept and handle some generic features of all commands. Like error handling, argument retrieving / checking """ def __init__(self, args): """ Initialize the class """ ...
return context
random_line_split
__init__.py
import re class CommandError(Exception): pass class BaseCommand(): """ Base command, this will accept and handle some generic features of all commands. Like error handling, argument retrieving / checking """ def __init__(self, args): """ Initialize the class """ ...
""" Convert all options and values into a context usable by the template parser """ context = dict(options={}, values={}) for key, value in self.args().items(): expressions = { 'options': r'--(.*)', 'values': r'<(.*)>', } ...
identifier_body
__init__.py
import re class CommandError(Exception): pass class
(): """ Base command, this will accept and handle some generic features of all commands. Like error handling, argument retrieving / checking """ def __init__(self, args): """ Initialize the class """ self._args = args def arg(self, key): """ Retr...
BaseCommand
identifier_name
hu.js
//! moment.js locale configuration //! locale : hungarian (hu) //! author : Adam Brunner : https://github.com/adambrunner import moment from '../moment'; var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' '); function translate(number, withoutSuffix, key, isFuture) { var num...
ture ? '' : '[múlt] ') + '[' + weekEndings[this.day()] + '] LT[-kor]'; } export default moment.defineLocale('hu', { months : 'január_február_március_április_május_június_július_augusztus_szeptember_október_november_december'.split('_'), monthsShort : 'jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec'.split('...
isFu
identifier_name
hu.js
//! moment.js locale configuration //! locale : hungarian (hu) //! author : Adam Brunner : https://github.com/adambrunner import moment from '../moment'; var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' '); function translate(number, withoutSuffix, key, isFuture) { var num...
'DU'; } }, calendar : { sameDay : '[ma] LT[-kor]', nextDay : '[holnap] LT[-kor]', nextWeek : function () { return week.call(this, true); }, lastDay : '[tegnap] LT[-kor]', lastWeek : function () { return week.call(this, false); ...
} else { return isLower === true ? 'du' :
conditional_block
hu.js
//! moment.js locale configuration //! locale : hungarian (hu) //! author : Adam Brunner : https://github.com/adambrunner import moment from '../moment'; var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' '); function translate(number, withoutSuffix, key, isFuture) { var num...
Locale('hu', { months : 'január_február_március_április_május_június_július_augusztus_szeptember_október_november_december'.split('_'), monthsShort : 'jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec'.split('_'), weekdays : 'vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat'.split('_'), weekdaysShor...
'[múlt] ') + '[' + weekEndings[this.day()] + '] LT[-kor]'; } export default moment.define
identifier_body
hu.js
//! moment.js locale configuration //! locale : hungarian (hu) //! author : Adam Brunner : https://github.com/adambrunner import moment from '../moment'; var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' '); function translate(number, withoutSuffix, key, isFuture) { var num...
case 'h': return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'hh': return num + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'd': return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'dd': return num + (isFuture || withoutSuffix ...
case 'm': return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'mm': return num + (isFuture || withoutSuffix ? ' perc' : ' perce');
random_line_split
plugin.js
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview The "div" plugin. It wraps the selected block level elements with a 'div' element with specified styles and attributes. * */ (function() { CKEDITOR.p...
for ( i = 0 ; i < toRemove.length ; i++ ) toRemove[ i ].remove( true ); selection.selectBookmarks( bookmarks ); } } ); editor.ui.addButton( 'CreateDiv', { label : lang.toolbar, command :'creatediv' } ); if ( editor.addMenuItems ) { editor.addMenuItems( { ...
random_line_split
plugin.js
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview The "div" plugin. It wraps the selected block level elements with a 'div' element with specified styles and attributes. * */ (function() { CKEDITOR.p...
} CKEDITOR.dialog.add( 'creatediv', this.path + 'dialogs/div.js' ); CKEDITOR.dialog.add( 'editdiv', this.path + 'dialogs/div.js' ); } } ); })();
{ editor.contextMenu.addListener( function( element, selection ) { if ( !element || element.isReadOnly() ) return null; var elementPath = new CKEDITOR.dom.elementPath( element ), blockLimit = elementPath.blockLimit; if ( blockLimit && blockLimit.getAscendant( 'div', tru...
conditional_block
plugin.js
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview The "div" plugin. It wraps the selected block level elements with a 'div' element with specified styles and attributes. * */ (function() { CKEDITOR.p...
for ( var i = 0 ; i < ranges.length ; i++ ) { range = ranges[ i ]; if ( range.collapsed ) findDiv( selection.getStartElement() ); else { walker = new CKEDITOR.dom.walker( range ); walker.evaluator = findDiv; walker.lastForward(); } }...
{ var path = new CKEDITOR.dom.elementPath( node ), blockLimit = path.blockLimit, div = blockLimit.is( 'div' ) && blockLimit; if ( div && !div.data( 'cke-div-added' ) ) { toRemove.push( div ); div.data( 'cke-div-added' ); } }
identifier_body
plugin.js
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview The "div" plugin. It wraps the selected block level elements with a 'div' element with specified styles and attributes. * */ (function() { CKEDITOR.p...
( node ) { var path = new CKEDITOR.dom.elementPath( node ), blockLimit = path.blockLimit, div = blockLimit.is( 'div' ) && blockLimit; if ( div && !div.data( 'cke-div-added' ) ) { toRemove.push( div ); div.data( 'cke-div-added' ); } } for ( ...
findDiv
identifier_name
test.py
#!/usr/bin/env python # -*- coding: utf-8 -*-
import organizations try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') os.system('python setup.py bdist_wheel upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY...
import os import sys
random_line_split
test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import organizations try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish':
readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( author="Ben Lopatin", author_email="ben@wellfire.co", name='django-organizations', version=organizations.__version__, description='Group accounts for Django', long_description=readme ...
os.system('python setup.py sdist upload') os.system('python setup.py bdist_wheel upload') sys.exit()
conditional_block
test_lagrange_polynomials.py
import chaospy import numpy import pytest @pytest.fixture def samples(joint): return joint.sample(10, rule="sobol") @pytest.fixture def evaluations(model_solver, samples): return numpy.array([model_solver(sample) for sample in samples.T]) @pytest.fixture def expansion(samples): return chaospy.lagrange...
(evaluations, expansion): return chaospy.sum(evaluations.T*expansion, axis=-1).T def test_lagrange_mean(lagrange_approximation, joint, true_mean): assert numpy.allclose(chaospy.E(lagrange_approximation, joint), true_mean, rtol=1e-3) def test_lagrange_variance(lagrange_approximation, joint, true_variance): ...
lagrange_approximation
identifier_name
test_lagrange_polynomials.py
import chaospy import numpy import pytest @pytest.fixture def samples(joint): return joint.sample(10, rule="sobol") @pytest.fixture def evaluations(model_solver, samples): return numpy.array([model_solver(sample) for sample in samples.T]) @pytest.fixture def expansion(samples): return chaospy.lagrange...
def test_lagrange_mean(lagrange_approximation, joint, true_mean): assert numpy.allclose(chaospy.E(lagrange_approximation, joint), true_mean, rtol=1e-3) def test_lagrange_variance(lagrange_approximation, joint, true_variance): assert numpy.allclose(chaospy.Var(lagrange_approximation, joint), true_variance, ...
return chaospy.sum(evaluations.T*expansion, axis=-1).T
identifier_body
test_lagrange_polynomials.py
import chaospy import numpy import pytest @pytest.fixture def samples(joint): return joint.sample(10, rule="sobol")
@pytest.fixture def expansion(samples): return chaospy.lagrange_polynomial(samples) @pytest.fixture def lagrange_approximation(evaluations, expansion): return chaospy.sum(evaluations.T*expansion, axis=-1).T def test_lagrange_mean(lagrange_approximation, joint, true_mean): assert numpy.allclose(chaospy....
@pytest.fixture def evaluations(model_solver, samples): return numpy.array([model_solver(sample) for sample in samples.T])
random_line_split
room.ts
import {Loadable} from "./loadable"; import Game from "./game"; declare let game: Game; export class RoomExit extends Loadable { static EXIT = -999; static EXIT_SILENT = -998; // same as regular exit, but without the "ride off into the sunset" message public direction: string; public room_to: number; pub...
(direction: string, room_to: number, door_id: number = null): void { const new_exit = new RoomExit(); new_exit.direction = direction; new_exit.room_to = room_to; new_exit.door_id = door_id; this.exits.push(new_exit); } /** * Removes the exit in a given direction */ public removeExit(dir...
createExit
identifier_name
room.ts
import {Loadable} from "./loadable"; import Game from "./game"; declare let game: Game; export class RoomExit extends Loadable { static EXIT = -999; static EXIT_SILENT = -998; // same as regular exit, but without the "ride off into the sunset" message public direction: string; public room_to: number; pub...
}
{ str = str.toLowerCase(); const name = this.name.toLowerCase(); const desc = this.description.toLowerCase(); return (name.indexOf(str) !== -1 || desc.indexOf(str) !== -1); }
identifier_body
room.ts
import {Loadable} from "./loadable"; import Game from "./game"; declare let game: Game; export class RoomExit extends Loadable { static EXIT = -999; static EXIT_SILENT = -998; // same as regular exit, but without the "ride off into the sunset" message public direction: string; public room_to: number; pub...
* Creates a new exit from the room in a given direction */ public addExit(exit: RoomExit): void { this.exits.push(exit); } /** * Creates a new exit from the room in a given direction (shorthand version) */ public createExit(direction: string, room_to: number, door_id: number = null): void { ...
return good_exits[game.diceRoll(1, good_exits.length) - 1]; } } /**
random_line_split
room.ts
import {Loadable} from "./loadable"; import Game from "./game"; declare let game: Game; export class RoomExit extends Loadable { static EXIT = -999; static EXIT_SILENT = -998; // same as regular exit, but without the "ride off into the sunset" message public direction: string; public room_to: number; pub...
else { return good_exits[game.diceRoll(1, good_exits.length) - 1]; } } /** * Creates a new exit from the room in a given direction */ public addExit(exit: RoomExit): void { this.exits.push(exit); } /** * Creates a new exit from the room in a given direction (shorthand version) */ ...
{ return null; }
conditional_block
ttf.rs
//! Module for creating text textures. use common::color::Color4; use gl; use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888}; use sdl2_sys::surface::SDL_Surface; use sdl2_sys::surface; use std::ffi::CString; use std::path::Path; use yaglw::gl_context::GLContext; use yaglw::texture::Texture2D; #[allow(non_came...
<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> { self.render(gl, txt, Color4::of_rgba(0xFF, 0x00, 0x00, 0xFF)) } /// dark black #333 #[allow(dead_code)] pub fn dark<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> { self.render(gl, txt, Color4::of_rgba(0x33, 0x33, 0x33, 0xFF)) } ...
red
identifier_name
ttf.rs
//! Module for creating text textures. use common::color::Color4; use gl; use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888}; use sdl2_sys::surface::SDL_Surface; use sdl2_sys::surface; use std::ffi::CString; use std::path::Path; use yaglw::gl_context::GLContext; use yaglw::texture::Texture2D; #[allow(non_came...
impl Font { #[allow(missing_docs)] pub fn new(font: &Path, point_size: u32) -> Font { ensure_init(); let c_path = CString::new(font.to_str().unwrap().as_bytes()).unwrap(); let ptr = c_path.as_ptr() as *const i8; let p = unsafe { ffi::TTF_OpenFont(ptr, point_size as ffi::c_int) }; assert!(!p....
{ unsafe { if ffi::TTF_WasInit() == 0 { assert_eq!(ffi::TTF_Init(), 0); } } }
identifier_body
ttf.rs
//! Module for creating text textures. use common::color::Color4; use gl; use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888}; use sdl2_sys::surface::SDL_Surface; use sdl2_sys::surface; use std::ffi::CString; use std::path::Path; use yaglw::gl_context::GLContext; use yaglw::texture::Texture2D; #[allow(non_came...
/// dark black #333 #[allow(dead_code)] pub fn dark<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> { self.render(gl, txt, Color4::of_rgba(0x33, 0x33, 0x33, 0xFF)) } /// light black #555 #[allow(dead_code)] pub fn light<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> { self.r...
#[allow(dead_code)] pub fn red<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> { self.render(gl, txt, Color4::of_rgba(0xFF, 0x00, 0x00, 0xFF)) }
random_line_split
ttf.rs
//! Module for creating text textures. use common::color::Color4; use gl; use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888}; use sdl2_sys::surface::SDL_Surface; use sdl2_sys::surface; use std::ffi::CString; use std::path::Path; use yaglw::gl_context::GLContext; use yaglw::texture::Texture2D; #[allow(non_came...
} } impl Font { #[allow(missing_docs)] pub fn new(font: &Path, point_size: u32) -> Font { ensure_init(); let c_path = CString::new(font.to_str().unwrap().as_bytes()).unwrap(); let ptr = c_path.as_ptr() as *const i8; let p = unsafe { ffi::TTF_OpenFont(ptr, point_size as ffi::c_int) }; asser...
{ assert_eq!(ffi::TTF_Init(), 0); }
conditional_block
admin.py
.models import AutoField from django.forms import ValidationError, ModelForm from django.http import HttpResponseRedirect from django.shortcuts import redirect from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User as AuthUser from mezzanine.conf import settings from mezzan...
when clicked, dynamically reveals another fieldset. Also handles adding the ``_order`` field and its widget for models that subclass ``Orderable``. """ form = DynamicInlineAdminForm extra = 20 def __init__(self, *args, **kwargs): super(BaseDynamicInlineAdmin, self).__init__(*args, ...
class BaseDynamicInlineAdmin(object): """ Admin inline that uses JS to inject an "Add another" link which
random_line_split
admin.py
import AutoField from django.forms import ValidationError, ModelForm from django.http import HttpResponseRedirect from django.shortcuts import redirect from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User as AuthUser from mezzanine.conf import settings from mezzanine.cor...
(self, *args, **kwargs): super(BaseDynamicInlineAdmin, self).__init__(*args, **kwargs) if issubclass(self.model, Orderable): fields = self.fields if not fields: fields = self.model._meta.fields exclude = self.exclude or [] fields = ...
__init__
identifier_name
admin.py
import AutoField from django.forms import ValidationError, ModelForm from django.http import HttpResponseRedirect from django.shortcuts import redirect from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User as AuthUser from mezzanine.conf import settings from mezzanine.cor...
return response def add_view(self, *args, **kwargs): """ Redirect to the change view if the singleton instance exists. """ try: singleton = self.model.objects.get() except (self.model.DoesNotExist, self.model.MultipleObjectsReturned): kwargs....
return redirect("admin:index")
conditional_block
admin.py
import AutoField from django.forms import ValidationError, ModelForm from django.http import HttpResponseRedirect from django.shortcuts import redirect from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User as AuthUser from mezzanine.conf import settings from mezzanine.cor...
class OwnableAdmin(admin.ModelAdmin): """ Admin class for models that subclass the abstract ``Ownable`` model. Handles limiting the change list to objects owned by the logged in user, as well as setting the owner of newly created objects to the logged in user. Remember that this will include...
""" Stacked dynamic inlines won't work without grappelli installed, as the JavaScript in dynamic_inline.js isn't able to target each of the inlines to set the value of the order field. """ grappelli_name = getattr(settings, "PACKAGE_NAME_GRAPPELLI") if grappelli_n...
identifier_body
misconception-editor.component.ts
// Copyright 2021 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 ap...
implements OnInit { @Input() getIndex: string; @Input() isEditable: boolean; @Input() misconception; nameMemento: string; notesMemento: string; feedbackMemento: string; container: Container; skill: Skill; MAX_CHARS_IN_MISCONCEPTION_NAME: number; nameEditorIsOpen: boolean; notesEditorIsOpen: boole...
MisconceptionEditorComponent
identifier_name
misconception-editor.component.ts
// Copyright 2021 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 ap...
cancelEditName(): void { this.container.misconceptionName = this.nameMemento; this.nameMemento = null; this.nameEditorIsOpen = false; } cancelEditNotes(): void { this.container.misconceptionNotes = this.notesMemento; this.notesMemento = null; this.notesEditorIsOpen = false; } cance...
{ this.feedbackEditorIsOpen = false; var feedbackHasChanged = ( this.feedbackMemento !== this.container.misconceptionFeedback); if (feedbackHasChanged) { this.skillUpdateService.updateMisconceptionFeedback( this.skill, this.misconception.getId(), this.feedbackMemen...
identifier_body
misconception-editor.component.ts
// Copyright 2021 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 ap...
} openNotesEditor(): void { if (this.isEditable) { this.notesMemento = cloneDeep( this.container.misconceptionNotes); this.notesEditorIsOpen = true; } } openFeedbackEditor(): void { if (this.isEditable) { this.feedbackMemento = cloneDeep( this.container.misconcep...
{ this.nameMemento = cloneDeep( this.container.misconceptionName); this.nameEditorIsOpen = true; }
conditional_block
misconception-editor.component.ts
// Copyright 2021 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 ap...
} } cancelEditName(): void { this.container.misconceptionName = this.nameMemento; this.nameMemento = null; this.nameEditorIsOpen = false; } cancelEditNotes(): void { this.container.misconceptionNotes = this.notesMemento; this.notesMemento = null; this.notesEditorIsOpen = false; }...
this.misconception.getId(), this.feedbackMemento, this.container.misconceptionFeedback); this.feedbackMemento = null;
random_line_split
extE3.d.ts
/** * @hidden * @param a0 * @param a1 * @param a2 * @param a3 * @param a4 * @param a5 * @param a6 * @param a7 * @param b0 * @param b1 * @param b2
* @param b4 * @param b5 * @param b6 * @param b7 * @param index * @returns */ export declare function extE3(a0: number, a1: number, a2: number, a3: number, a4: number, a5: number, a6: number, a7: number, b0: number, b1: number, b2: number, b3: number, b4: number, b5: number, b6: number, b7: number, index: number)...
* @param b3
random_line_split
packed-tuple-struct-size.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ Bar = 1, Baz = 2 } #[packed] struct S3_Foo(u8, u16, Foo); #[packed] struct S7_Option(f32, u8, u16, Option<@f64>); pub fn main() { assert_eq!(mem::size_of::<S4>(), 4); assert_eq!(mem::size_of::<S5>(), 5); assert_eq!(mem::size_of::<S13_str>(), 13 + mem::size_of::<~str>()); ...
Foo
identifier_name
packed-tuple-struct-size.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
assert_eq!(mem::size_of::<S5>(), 5); assert_eq!(mem::size_of::<S13_str>(), 13 + mem::size_of::<~str>()); assert_eq!(mem::size_of::<S3_Foo>(), 3 + mem::size_of::<Foo>()); assert_eq!(mem::size_of::<S7_Option>(), 7 + mem::size_of::<Option<@f64>>()); }
#[packed] struct S7_Option(f32, u8, u16, Option<@f64>); pub fn main() { assert_eq!(mem::size_of::<S4>(), 4);
random_line_split
corks.py
import bottle from cork import Cork from utils import skeleton aaa = Cork('users', email_sender='c.emmery@outlook.com', smtp_url='smtp://smtp.magnet.ie') authorize = aaa.make_auth_decorator(fail_redirect='/login', role="user") def postd(): return bottle.request.forms def post_get(name, default=''):...
(): try: aaa.delete_role(post_get('role')) return dict(ok=True, msg='') except Exception as e: return dict(ok=False, msg=e.message) # Static pages @bottle.route('/login') def login_form(): """Serve login form""" return skeleton(bottle.template('login_form')) @bottle.route('/...
delete_role
identifier_name
corks.py
import bottle from cork import Cork from utils import skeleton aaa = Cork('users', email_sender='c.emmery@outlook.com', smtp_url='smtp://smtp.magnet.ie') authorize = aaa.make_auth_decorator(fail_redirect='/login', role="user") def postd(): return bottle.request.forms def post_get(name, default=''):...
@bottle.route('/validate_registration/:registration_code') def validate_registration(registration_code): """Validate registration, create user account""" aaa.validate_registration(registration_code) return 'Thanks. <a href="/login">Go to login</a>' @bottle.post('/change_password') def change_password()...
"""Send out registration email""" aaa.register(post_get('username'), post_get('password'), post_get('email_address')) return 'Please check your mailbox.'
identifier_body
corks.py
import bottle from cork import Cork from utils import skeleton aaa = Cork('users', email_sender='c.emmery@outlook.com', smtp_url='smtp://smtp.magnet.ie') authorize = aaa.make_auth_decorator(fail_redirect='/login', role="user") def postd(): return bottle.request.forms def post_get(name, default=''):...
aaa.logout(success_redirect='/login') @bottle.post('/register') def register(): """Send out registration email""" aaa.register(post_get('username'), post_get('password'), post_get('email_address')) return 'Please check your mailbox.' @bottle.route('/validate_registration/:registrati...
aaa.login(username, password, success_redirect='/', fail_redirect='/login') @bottle.route('/logout') def logout():
random_line_split
font.rs
/* 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/. */ /// Implementation of Quartz (CoreGraphics) fonts. extern mod core_foundation; extern mod core_graphics; extern m...
let characters: [UniChar, ..1] = [codepoint as UniChar]; let glyphs: [CGGlyph, ..1] = [0 as CGGlyph]; let count: CFIndex = 1; let result = self.ctfont.get_glyphs_for_characters(ptr::to_unsafe_ptr(&characters[0]), ptr::to_unsafe...
random_line_split
font.rs
/* 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/. */ /// Implementation of Quartz (CoreGraphics) fonts. extern mod core_foundation; extern mod core_graphics; extern m...
{ data: CFData, } // Noncopyable. impl Drop for FontTable { fn drop(&mut self) {} } impl FontTable { pub fn wrap(data: CFData) -> FontTable { FontTable { data: data } } } impl FontTableMethods for FontTable { fn with_buffer(&self, blk: |*u8, uint|) { blk(self.data.bytes().as_ptr(...
FontTable
identifier_name
lib.rs
// Copyrighttape Technologies 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...
pub extern crate bloomchain; pub type Bytes = Vec<u8>; pub mod block; pub mod block_number; pub mod block_receipts; pub mod context; pub mod db_indexes; pub mod errors; pub mod filter; pub mod header; pub mod log; pub mod log_blooms; pub mod receipt; pub mod reserved_addresses; pub mod state_proof; pub mod transactio...
extern crate lazy_static; #[macro_use] extern crate cita_logger as logger; extern crate cita_database as cita_db;
random_line_split
15.2.3.6-3-141-1.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyrigh...
runTestCase(testcase);
{ var obj = {}; try { String.prototype.value = "String"; var strObj = new String("abc"); Object.defineProperty(obj, "property", strObj); return obj.property === "String"; } finally { delete String.prototype.value; }...
identifier_body