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
manual_flatten.rs
use super::utils::make_iterator_snippet; use super::MANUAL_FLATTEN; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::higher; use clippy_utils::visitors::is_local_used; use clippy_utils::{is_lang_ctor, path_to_local_id}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir::LangItem...
if !is_local_used(cx, if_then, pat_hir_id); then { let if_let_type = if some_ctor { "Some" } else { "Ok" }; // Prepare the error message let msg = format!("unnecessary `if let` since only the `{}` variant of the iterator element is used", if_let_ty...
let ok_ctor = is_lang_ctor(cx, qpath, ResultOk); if some_ctor || ok_ctor; // Ensure epxr in `if let` is not used afterwards
random_line_split
manual_flatten.rs
use super::utils::make_iterator_snippet; use super::MANUAL_FLATTEN; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::higher; use clippy_utils::visitors::is_local_used; use clippy_utils::{is_lang_ctor, path_to_local_id}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir::LangItem...
<'tcx>( cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, arg: &'tcx Expr<'_>, body: &'tcx Expr<'_>, span: Span, ) { if let ExprKind::Block(block, _) = body.kind { // Ensure the `if let` statement is the only expression or statement in the for-loop let inner_expr = if block.stmts.len()...
check
identifier_name
manual_flatten.rs
use super::utils::make_iterator_snippet; use super::MANUAL_FLATTEN; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::higher; use clippy_utils::visitors::is_local_used; use clippy_utils::{is_lang_ctor, path_to_local_id}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir::LangItem...
{ if let ExprKind::Block(block, _) = body.kind { // Ensure the `if let` statement is the only expression or statement in the for-loop let inner_expr = if block.stmts.len() == 1 && block.expr.is_none() { let match_stmt = &block.stmts[0]; if let StmtKind::Semi(inner_expr) = mat...
identifier_body
repl.rs
extern crate readline; use std::process; use storage; use jobs; use cluster; pub fn start() { loop { match readline::readline(">>> ") { Ok(input) => { let input = input.replace("\n", ""); if input.len() > 0 { readline::add_history(input.as_re...
storage.list(); } else if "exit" == input || "quit" == input { process::exit(0); } } }, Err(e) => { println!("{}", e); ...
} else if "storage" == input { let storage = storage::bootstrap();
random_line_split
repl.rs
extern crate readline; use std::process; use storage; use jobs; use cluster; pub fn start()
{ loop { match readline::readline(">>> ") { Ok(input) => { let input = input.replace("\n", ""); if input.len() > 0 { readline::add_history(input.as_ref()); println!("{:?}", input); if "help" == input { ...
identifier_body
repl.rs
extern crate readline; use std::process; use storage; use jobs; use cluster; pub fn start() { loop { match readline::readline(">>> ") { Ok(input) => { let input = input.replace("\n", ""); if input.len() > 0 { readline::add_history(input.as_re...
} } }
{ println!("{}", e); //panic!("{}", e); }
conditional_block
repl.rs
extern crate readline; use std::process; use storage; use jobs; use cluster; pub fn
() { loop { match readline::readline(">>> ") { Ok(input) => { let input = input.replace("\n", ""); if input.len() > 0 { readline::add_history(input.as_ref()); println!("{:?}", input); if "help" == input {...
start
identifier_name
utils.py
# -*- coding: utf-8 -*- #--------------------------------------------------------------------# # This file is part of Py-notify. # # # # Copyright (C) 2006, 2007, 2008 Paul Pogonyshev. # # ...
@raises ValueError: if either C{class_name} or C{identifier} is not valid from Python’s point of view. """ if not (is_valid_identifier (class_name) and is_valid_identifier (identifier)): raise ValueError ("'class_name' and 'identifier' must be valid Python identifiers") ...
@param identifier: name of an attribute of that class. @type identifier: C{basestring} @rtype: C{str}
random_line_split
utils.py
# -*- coding: utf-8 -*- #--------------------------------------------------------------------# # This file is part of Py-notify. # # # # Copyright (C) 2006, 2007, 2008 Paul Pogonyshev. # # ...
def raise_not_implemented_exception (object = None, function_name = None): """ Raise C{NotImplementedError} for a method invoked with C{object} as C{self}. The function determines object class and method declaration class(es) itself and that’s the whole point of it. It should be called like thi...
ng' as_string = _AsString ()
identifier_body
utils.py
# -*- coding: utf-8 -*- #--------------------------------------------------------------------# # This file is part of Py-notify. # # # # Copyright (C) 2006, 2007, 2008 Paul Pogonyshev. # # ...
name def __setattr__(self, name, value): raise TypeError ("'as_string' attributes cannot be set") def __delattr__(self, name): raise TypeError ("'as_string' attributes cannot be deleted") def __repr__(self): return 'notify.utils.as_string' as_string = _AsString () def raise_...
: return
identifier_name
utils.py
# -*- coding: utf-8 -*- #--------------------------------------------------------------------# # This file is part of Py-notify. # # # # Copyright (C) 2006, 2007, 2008 Paul Pogonyshev. # # ...
ef __repr__(self): return '%s (%s)' % (type (self).__name__, super (frozendict, self).__repr__()) frozendict.EMPTY = frozendict ({ }) # Force hash to be precomputed. hash (frozendict.EMPTY) class DummyReference (object): """ Simple class that is interface-compatible with C{weakref.ReferenceType}....
hasattr (dict, 'iteritems'): for key, value in self.iteritems (): _hash ^= hash (key) ^ hash (value) else: for key, value in self.items (): _hash ^= hash (key) ^ hash (value) self.__hash = _hash return _hash ...
conditional_block
testcase.py
# Copyright 2012 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditi...
(self, suite, path, flags=None, dependency=None): self.suite = suite # TestSuite object self.path = path # string, e.g. 'div-mod', 'test-api/foo' self.flags = flags or [] # list of strings, flags specific to this test self.dependency = dependency # |path| for testcase that must be run ...
__init__
identifier_name
testcase.py
# Copyright 2012 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditi...
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIA...
random_line_split
testcase.py
# Copyright 2012 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditi...
@staticmethod def UnpackTask(task): """Creates a new TestCase object based on packed task data.""" # For the order of the fields, refer to PackTask() above. test = TestCase(str(task[0]), task[1], task[2], task[3]) test.outcomes = set(task[4]) test.id = task[5] test.run = 1 return test ...
""" Extracts those parts of this object that are required to run the test and returns them as a JSON serializable object. """ assert self.id is not None return [self.suitename(), self.path, self.flags, self.dependency, list(self.outcomes or []), self.id]
identifier_body
home.service.ts
import { Injectable } from "@angular/core"; import { Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { HomeModel } from "./home.model"; import { LogServiceProvider } from '../../providers/log-service/log-service'; import { Constants } from "../../app/app.contants"; @Injectable() export clas...
{ constructor(public http: Http, public log: LogServiceProvider) {} // getData(): Promise<HomeModel> { // return this.http.get(Constants.URL + '/api/homes') // .toPromise() // .then(response => response.json() as HomeModel) // .catch(this.handleError); // } getData(): Promise<HomeModel> { ...
HomeService
identifier_name
home.service.ts
import { Injectable } from "@angular/core"; import { Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { HomeModel } from "./home.model"; import { LogServiceProvider } from '../../providers/log-service/log-service'; import { Constants } from "../../app/app.contants"; @Injectable() export clas...
// getData(): Promise<HomeModel> { // return this.http.get(Constants.URL + '/api/homes') // .toPromise() // .then(response => response.json() as HomeModel) // .catch(this.handleError); // } getData(): Promise<HomeModel> { return this.http.get(Constants.URL + '/api/dataofcategories') ...
{}
identifier_body
home.service.ts
import { Injectable } from "@angular/core"; import { Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { HomeModel } from "./home.model"; import { LogServiceProvider } from '../../providers/log-service/log-service'; import { Constants } from "../../app/app.contants"; @Injectable() export clas...
this.log.errorService('An error occurred', error); // for demo purposes only return Promise.reject(error.message || error); } }
private handleError(error: any): Promise<any> {
random_line_split
ptx.rs
#![crate_name = "ptx"] #![feature(convert, slice_chars, vec_push_all)] /* * This file is part of the uutils coreutils package. * * (c) Dorota Kapturkiewicz <dokaptur@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ exte...
else { (false, HashSet::new()) }; let (i, iset): (bool, HashSet<String>) = if matches.opt_present("i") { (true, read_word_filter_file(matches, "i")) } else { (false, HashSet::new()) }; if matches.opt_presen...
{ (true, read_word_filter_file(matches, "o")) }
conditional_block
ptx.rs
#![crate_name = "ptx"] #![feature(convert, slice_chars, vec_push_all)] /* * This file is part of the uutils coreutils package. * * (c) Dorota Kapturkiewicz <dokaptur@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ exte...
{ Dumb, Roff, Tex, } #[derive(Debug)] struct Config { format : OutFormat, gnu_ext : bool, auto_ref : bool, input_ref : bool, right_ref : bool, ignore_case : bool, macro_name : String, trunc_str : String, context_regex : String, line_width : usize, gap_size : u...
OutFormat
identifier_name
ptx.rs
#![crate_name = "ptx"] #![feature(convert, slice_chars, vec_push_all)] /* * This file is part of the uutils coreutils package. * * (c) Dorota Kapturkiewicz <dokaptur@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ exte...
#[derive(Debug)] struct WordFilter { only_specified: bool, ignore_specified: bool, only_set: HashSet<String>, ignore_set: HashSet<String>, word_regex: String, } impl WordFilter { fn new(matches: &Matches, config: &Config) -> WordFilter { let (o, oset): (bool, HashSet<String>) = ...
{ let filename = matches.opt_str(option).expect("parsing options failed!"); let reader = BufReader::new(crash_if_err!(1, File::open(filename))); let mut words: HashSet<String> = HashSet::new(); for word in reader.lines() { words.insert(crash_if_err!(1, word)); } words }
identifier_body
ptx.rs
#![crate_name = "ptx"] #![feature(convert, slice_chars, vec_push_all)] /* * This file is part of the uutils coreutils package. * * (c) Dorota Kapturkiewicz <dokaptur@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ exte...
crash!(1, "-S not implemented yet"); } config.auto_ref = matches.opt_present("A"); config.input_ref = matches.opt_present("r"); config.right_ref &= matches.opt_present("R"); config.ignore_case = matches.opt_present("f"); if matches.opt_present("M") { config.macro_name = ...
crash!(1, "GNU extensions not implemented yet"); } if matches.opt_present("S") {
random_line_split
data_to_json.py
#!/usr/bin/env python """ Extract minor planet orbital elements and discovery dates to json. Orbital elements are extracted from the file MPCORB.DAT: https://minorplanetcenter.net/iau/MPCORB/MPCORB.DAT Discovery dates are extracted from the file NumberedMPs.txt: https://minorplanetcenter.net/iau/lists/NumberedMPs.txt ...
nr = int(nr) # Skip if discovery date is missing if nr not in mpcs_disc: print 'Skipping MPC #%d (no discovery date found)' % (nr) continue # Extract the orbital elements _, _, _, epoch, M, w, W, i, e, n, a, _ = line.split(None, 11) mpc = (mpcs_...
continue
conditional_block
data_to_json.py
#!/usr/bin/env python """ Extract minor planet orbital elements and discovery dates to json. Orbital elements are extracted from the file MPCORB.DAT: https://minorplanetcenter.net/iau/MPCORB/MPCORB.DAT Discovery dates are extracted from the file NumberedMPs.txt: https://minorplanetcenter.net/iau/lists/NumberedMPs.txt ...
if __name__ == '__main__': main(sys.argv[1:])
parser = argparse.ArgumentParser(description='Parse orbital and discovery data to json.') parser.add_argument('amount', metavar='N', type=int, nargs='?', help='maximum number of results') parser.add_argument('-c', '--compact', action='store_true', dest='compact', help='output as compact json format') args =...
identifier_body
data_to_json.py
#!/usr/bin/env python """ Extract minor planet orbital elements and discovery dates to json. Orbital elements are extracted from the file MPCORB.DAT: https://minorplanetcenter.net/iau/MPCORB/MPCORB.DAT Discovery dates are extracted from the file NumberedMPs.txt: https://minorplanetcenter.net/iau/lists/NumberedMPs.txt ...
y = int(str(int(pd[0], 36)) + pd[1:3]) m = int(pd[3], 36) d = int(pd[4], 36) return datetime(y, m, d) # Packed to Julian date def pd2jd(pd): dt = pd2dt(pd) return dt2jd(dt) def main(argv): # Parse argumanets parser = argparse.ArgumentParser(description='Parse orbital and discovery data...
return dt.days + (dt.seconds + dt.microseconds / 1000000) / 86400 + 2451544.5 # Packed date to Datetime def pd2dt(pd):
random_line_split
data_to_json.py
#!/usr/bin/env python """ Extract minor planet orbital elements and discovery dates to json. Orbital elements are extracted from the file MPCORB.DAT: https://minorplanetcenter.net/iau/MPCORB/MPCORB.DAT Discovery dates are extracted from the file NumberedMPs.txt: https://minorplanetcenter.net/iau/lists/NumberedMPs.txt ...
(pd): y = int(str(int(pd[0], 36)) + pd[1:3]) m = int(pd[3], 36) d = int(pd[4], 36) return datetime(y, m, d) # Packed to Julian date def pd2jd(pd): dt = pd2dt(pd) return dt2jd(dt) def main(argv): # Parse argumanets parser = argparse.ArgumentParser(description='Parse orbital and discover...
pd2dt
identifier_name
d3d8trace.py
########################################################################## # # Copyright 2008-2009 VMware, Inc. # All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software withou...
(DllTracer): def dump_arg_instance(self, function, arg): # Dump shaders as strings if function.name in ('CreateVertexShader', 'CreatePixelShader') and arg.name == 'pFunction': print ' DumpShader(trace::localWriter, %s);' % (arg.name) return DllTracer.dump_arg_ins...
D3D8Tracer
identifier_name
d3d8trace.py
########################################################################## # # Copyright 2008-2009 VMware, Inc. # All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software withou...
DllTracer.dump_arg_instance(self, function, arg) if __name__ == '__main__': print '#include <windows.h>' print '#include <d3d8.h>' print '#include "d3dshader.hpp"' print print '#include "trace_writer.hpp"' print '#include "os.hpp"' print tracer = D3D8Tracer('d3d8.dll') tr...
print ' DumpShader(trace::localWriter, %s);' % (arg.name) return
conditional_block
d3d8trace.py
########################################################################## # # Copyright 2008-2009 VMware, Inc. # All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software withou...
if __name__ == '__main__': print '#include <windows.h>' print '#include <d3d8.h>' print '#include "d3dshader.hpp"' print print '#include "trace_writer.hpp"' print '#include "os.hpp"' print tracer = D3D8Tracer('d3d8.dll') tracer.trace_api(d3d8)
if function.name in ('CreateVertexShader', 'CreatePixelShader') and arg.name == 'pFunction': print ' DumpShader(trace::localWriter, %s);' % (arg.name) return DllTracer.dump_arg_instance(self, function, arg)
identifier_body
d3d8trace.py
########################################################################## # # Copyright 2008-2009 VMware, Inc. # All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software withou...
# # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOS...
# furnished to do so, subject to the following conditions:
random_line_split
parser.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/. */ //! The context within which CSS code is parsed. #![deny(missing_docs)] use cssparser::{Parser, SourcePosition, ...
} /// Parse a non-empty space-separated or comma-separated list of objects parsed by parse_one pub fn parse_space_or_comma_separated<F, T>(input: &mut Parser, mut parse_one: F) -> Result<Vec<T>, ()> where F: FnMut(&mut Parser) -> Result<T, ()> { let first = parse_one(input)?; let mut vec = vec...
{ input.parse_comma_separated(|input| T::parse(context, input)) }
identifier_body
parser.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/. */ //! The context within which CSS code is parsed. #![deny(missing_docs)] use cssparser::{Parser, SourcePosition, ...
else { break } } Ok(vec) } impl Parse for UnicodeRange { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> { UnicodeRange::parse(input) } }
{ vec.push(val) }
conditional_block
parser.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/. */ //! The context within which CSS code is parsed. #![deny(missing_docs)] use cssparser::{Parser, SourcePosition, ...
impl ParserContextExtraData { /// Construct from a GeckoParserExtraData /// /// GeckoParserExtraData must live longer than this call pub unsafe fn new(data: *const ::gecko_bindings::structs::GeckoParserExtraData) -> Self { // the to_safe calls are safe since we trust that we have references to ...
} #[cfg(feature = "gecko")]
random_line_split
parser.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/. */ //! The context within which CSS code is parsed. #![deny(missing_docs)] use cssparser::{Parser, SourcePosition, ...
{ /// The base URI. pub base: Option<GeckoArcURI>, /// The referrer URI. pub referrer: Option<GeckoArcURI>, /// The principal that loaded this stylesheet. pub principal: Option<GeckoArcPrincipal>, } #[cfg(not(feature = "gecko"))] impl Default for ParserContextExtraData { fn default() -> Se...
ParserContextExtraData
identifier_name
helper_arabic_ligature_exceptions.py
from __future__ import print_function from glyphNameFormatter.tools import camelCase doNotProcessAsLigatureRanges = [ (0xfc5e, 0xfc63), (0xfe70, 0xfe74), #(0xfc5e, 0xfc61), (0xfcf2, 0xfcf4), (0xfe76, 0xfe80), ] def process(self): # Specifically: do not add suffixes to these ligatures, ...
return False if __name__ == "__main__": from glyphNameFormatter import GlyphName print("\ndoNotProcessAsLigatureRanges", doNotProcessAsLigatureRanges) odd = 0xfe76 for a, b in doNotProcessAsLigatureRanges: for u in range(a,b+1): try: g = GlyphName(uniNumber=u...
if a <= self.uniNumber <= b: self.replace('TAIL FRAGMENT', "kashida Fina") self.replace('INITIAL FORM', "init") self.replace('MEDIAL FORM', "medi") self.replace('FINAL FORM', "fina") self.replace('ISOLATED FORM', "isol") self.replace('WITH SUPERSCR...
conditional_block
helper_arabic_ligature_exceptions.py
from __future__ import print_function from glyphNameFormatter.tools import camelCase doNotProcessAsLigatureRanges = [ (0xfc5e, 0xfc63), (0xfe70, 0xfe74), #(0xfc5e, 0xfc61), (0xfcf2, 0xfcf4), (0xfe76, 0xfe80), ] def
(self): # Specifically: do not add suffixes to these ligatures, # they're really arabic marks for a, b in doNotProcessAsLigatureRanges: if a <= self.uniNumber <= b: self.replace('TAIL FRAGMENT', "kashida Fina") self.replace('INITIAL FORM', "init") self.replace('M...
process
identifier_name
helper_arabic_ligature_exceptions.py
from __future__ import print_function from glyphNameFormatter.tools import camelCase doNotProcessAsLigatureRanges = [ (0xfc5e, 0xfc63), (0xfe70, 0xfe74), #(0xfc5e, 0xfc61), (0xfcf2, 0xfcf4), (0xfe76, 0xfe80), ] def process(self): # Specifically: do not add suffixes to these ligatures, ...
return False if __name__ == "__main__": from glyphNameFormatter import GlyphName print("\ndoNotProcessAsLigatureRanges", doNotProcessAsLigatureRanges) odd = 0xfe76 for a, b in doNotProcessAsLigatureRanges: for u in range(a,b+1): try: g = GlyphName(uniNumber=u) ...
self.lower() self.camelCase() return True
random_line_split
helper_arabic_ligature_exceptions.py
from __future__ import print_function from glyphNameFormatter.tools import camelCase doNotProcessAsLigatureRanges = [ (0xfc5e, 0xfc63), (0xfe70, 0xfe74), #(0xfc5e, 0xfc61), (0xfcf2, 0xfcf4), (0xfe76, 0xfe80), ] def process(self): # Specifically: do not add suffixes to these ligatures, ...
if __name__ == "__main__": from glyphNameFormatter import GlyphName print("\ndoNotProcessAsLigatureRanges", doNotProcessAsLigatureRanges) odd = 0xfe76 for a, b in doNotProcessAsLigatureRanges: for u in range(a,b+1): try: g = GlyphName(uniNumber=u) ...
for a, b in doNotProcessAsLigatureRanges: if a <= self.uniNumber <= b: self.replace('TAIL FRAGMENT', "kashida Fina") self.replace('INITIAL FORM', "init") self.replace('MEDIAL FORM', "medi") self.replace('FINAL FORM', "fina") self.replace('ISOLATED FORM...
identifier_body
compress.rs
//! An example of offloading work to a thread pool instead of doing work on the //! main event loop. //! //! In this example the server will act as a form of echo server except that //! it'll echo back gzip-compressed data. Each connected client will have the //! data written streamed back as the compressed version is ...
/// The main workhorse of this example. This'll compress all data read from /// `socket` on the `pool` provided, writing it back out to `socket` as it's /// available. fn compress(socket: TcpStream, pool: &CpuPool) -> Box<Future<Item = (u64, u64), Error = io::Error> + Send> { use tokio_io::io; // The gene...
Ok(()) }); core.run(server).unwrap(); }
random_line_split
compress.rs
//! An example of offloading work to a thread pool instead of doing work on the //! main event loop. //! //! In this example the server will act as a form of echo server except that //! it'll echo back gzip-compressed data. Each connected client will have the //! data written streamed back as the compressed version is ...
(socket: TcpStream, pool: &CpuPool) -> Box<Future<Item = (u64, u64), Error = io::Error> + Send> { use tokio_io::io; // The general interface that `CpuPool` provides is that we'll *spawn a // future* onto it. All execution of the future will occur on the `CpuPool` // and we'll get back a handle repr...
compress
identifier_name
compress.rs
//! An example of offloading work to a thread pool instead of doing work on the //! main event loop. //! //! In this example the server will act as a form of echo server except that //! it'll echo back gzip-compressed data. Each connected client will have the //! data written streamed back as the compressed version is ...
} impl<T: AsyncWrite> AsyncWrite for Count<T> { fn shutdown(&mut self) -> Poll<(), io::Error> { self.io.shutdown() } }
{ self.io.flush() }
identifier_body
reducer.js
/** * External dependencies */ import { expect } from 'chai'; /** * Internal dependencies */ import { SELECTED_SITE_SET, SERIALIZE, DESERIALIZE } from 'state/action-types'; import reducer, { selectedSiteId } from '../reducer'; describe( 'reducer', () => { it( 'should include expected keys in return value', ()...
it( 'should refuse to restore any persisted state', () => { const state = reducer( { selectedSiteId: 2916284 }, { type: DESERIALIZE } ); expect( state ).to.eql( {} ); } ); describe( '#selectedSiteId()', () => { it( 'should default to null', () => { const state = selectedSiteId( undefined, {} ); e...
expect( state ).to.eql( {} ); } );
random_line_split
RewardsProvider.ts
/*
* The MIT License (MIT) * Copyright (c) 2017 Heat Ledger Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, c...
random_line_split
RewardsProvider.ts
/* * The MIT License (MIT) * Copyright (c) 2017 Heat Ledger Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use...
public createProvider(): IPaginatedDataProvider { return new RewardsProvider(this.heat, this.$q); } } class RewardsProvider implements IPaginatedDataProvider { constructor(private heat: HeatService, private $q: angular.IQService) {} /* The number of items available */ public getPaginated...
{}
identifier_body
RewardsProvider.ts
/* * The MIT License (MIT) * Copyright (c) 2017 Heat Ledger Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use...
(private heat: HeatService, private $q: angular.IQService) {} public createProvider(): IPaginatedDataProvider { return new RewardsProvider(this.heat, this.$q); } } class RewardsProvider implements IPaginatedDataProvider { constructor(private heat: HeatService, private $q: angular.IQService) {}...
constructor
identifier_name
make_bb_spectrum_plot.py
import ROOT from math import pi, sqrt, pow, exp import scipy.integrate import numpy from array import array alpha = 7.2973e-3 m_e = 0.51099892 Z_Xe = 54 Q = 2.4578 def F(Z, KE): E = KE + m_e W = E/m_e Z0 = Z + 2 if W <= 1: W = 1 + 1e-4 if W > 2.2: a = -8.46e-2 + 2.48e-2*Z0 + 2....
def normalize(y, eps, f): return [a*f for a in y] N = 1000 min_E = 0.0 max_E = 1.2 E_scaled = array('d', numpy.linspace(min_E, max_E, N, False)) Es = array('d', (E*Q for E in E_scaled)) eps = (max_E - min_E)/N bb0n = [0.5/eps if abs(E-Q)<eps else 0 for E in Es] bb2n = [SumSpectrum(E, 5) for E in Es] bb0n_sme...
N = len(x) mu = numpy.mean(x) s = res*mu gauss = [1.0/(s*sqrt(2*pi))*exp(-0.5*((a-mu)/s)**2) for a in x] convolution = numpy.convolve(y, gauss,'same') return convolution
identifier_body
make_bb_spectrum_plot.py
import ROOT from math import pi, sqrt, pow, exp import scipy.integrate import numpy from array import array alpha = 7.2973e-3 m_e = 0.51099892 Z_Xe = 54 Q = 2.4578 def F(Z, KE): E = KE + m_e W = E/m_e Z0 = Z + 2 if W <= 1: W = 1 + 1e-4 if W > 2.2: a = -8.46e-2 + 2.48e-2*Z0 + 2....
bb0nX_graphs = [] for bb0nXn in bb0nX: bb0nX_int = scipy.integrate.simps(bb0nXn, None, eps) bb0nX_norm = array('d', normalize(bb0nXn, eps, 1/bb0nX_int)) g_bb0nX = ROOT.TGraph(N, E_scaled, bb0nX_norm) bb0nX_graphs.append(g_bb0nX) min_E = 0.9 max_E = 1.1 E_scaled_z = array('d', numpy.linspace(min_E, ma...
bb0nX.append([SumSpectrum(E, i) for E in Es])
conditional_block
make_bb_spectrum_plot.py
import ROOT from math import pi, sqrt, pow, exp import scipy.integrate import numpy from array import array alpha = 7.2973e-3 m_e = 0.51099892 Z_Xe = 54 Q = 2.4578 def F(Z, KE): E = KE + m_e W = E/m_e Z0 = Z + 2 if W <= 1: W = 1 + 1e-4 if W > 2.2: a = -8.46e-2 + 2.48e-2*Z0 + 2....
if K < 0: return 0 elif K > Q: return 0 a = -K/m_e b = K/m_e x = scipy.integrate.quad(D, a, b, (K/m_e, i))[0] if x < 0: return 0 else: return x def gauss_conv(x, y, res): N = len(x) mu = numpy.mean(x) s = res*mu gauss = [1.0/(s*sqrt(2*p...
return p1*E1*F(Z, T1*m_e)*p2*E2*F(Z, T1*m_e)*pow(T0 - K, i) def SumSpectrum(K, i):
random_line_split
make_bb_spectrum_plot.py
import ROOT from math import pi, sqrt, pow, exp import scipy.integrate import numpy from array import array alpha = 7.2973e-3 m_e = 0.51099892 Z_Xe = 54 Q = 2.4578 def F(Z, KE): E = KE + m_e W = E/m_e Z0 = Z + 2 if W <= 1: W = 1 + 1e-4 if W > 2.2: a = -8.46e-2 + 2.48e-2*Z0 + 2....
(x, y, res): N = len(x) mu = numpy.mean(x) s = res*mu gauss = [1.0/(s*sqrt(2*pi))*exp(-0.5*((a-mu)/s)**2) for a in x] convolution = numpy.convolve(y, gauss,'same') return convolution def normalize(y, eps, f): return [a*f for a in y] N = 1000 min_E = 0.0 max_E = 1.2 E_scaled = array...
gauss_conv
identifier_name
hero.js
/** * Created by kaicui on 17/8/22. * 表示战场上的一个英雄 * * 注意: * 1、hero被添加到一个team之后,可能会被注入一些属性,比如team属性 */ const oop = require("local-libs").oop; const event = require("local-libs").event; const Levelable = require("../../level/levelable"); const {SkillType} = require("../../skill/skill"); const {getRaceCamp} = requi...
s.DEF).getVal()}], M_ATK:[${this.getAttr(HeroDeriveAttributes.M_ATK).getVal()}], M_DEF:[${this.getAttr(HeroDeriveAttributes.M_DEF).getVal()}], ` } }, /** * 将英雄绑定到玩家对象,开始英雄生命周期 * @param player */ ...
CRI:[${this.getAttr(HeroDeriveAttributes.CRI).getVal()}], HIT:[${this.getAttr(HeroDeriveAttributes.HIT).getVal()}], FLEE:[${this.getAttr(HeroDeriveAttributes.FLEE).getVal()}], ATK:[${this.getAttr(HeroDeriveAttributes.ATK).getVal()}], DEF:[${this.getAttr(H...
conditional_block
hero.js
/** * Created by kaicui on 17/8/22. * 表示战场上的一个英雄 * * 注意: * 1、hero被添加到一个team之后,可能会被注入一些属性,比如team属性 */ const oop = require("local-libs").oop; const event = require("local-libs").event; const Levelable = require("../../level/levelable"); const {SkillType} = require("../../skill/skill"); const {getRaceCamp} = requi...
/** * 接收一个属性集合修改请求(注意,这里的修改,是一次性修改,而不是modify) * @param from:修改来源effect对象 * @param remark:本次改动的备注,用于配合数据展示一些备注信息 * @param mutation:key:attrName value:changeNum (+代表增加 -代表减少) */ takeMutation:function ({from,mutation,remark}) { var self = this; ...
self.emit(HeroEvents.AFTER_ACTION,skillToRelease); },
random_line_split
test_autocomplete_widget.py
from django import forms from django.contrib.admin.widgets import AutocompleteSelect from django.forms import ModelChoiceField from django.test import TestCase, override_settings from django.utils import translation from .models import Album, Band class AlbumForm(forms.ModelForm): class Meta: model = Alb...
def test_render_options_not_required_field(self): """Empty option isn't present if the field isn't required.""" form = RequiredBandForm() output = form.as_table() self.assertNotIn(self.empty_option, output) def test_media(self): rel = Album._meta.get_field('band').remo...
"""Empty option is present if the field isn't required.""" form = NotRequiredBandForm() output = form.as_table() self.assertIn(self.empty_option, output)
identifier_body
test_autocomplete_widget.py
from django import forms from django.contrib.admin.widgets import AutocompleteSelect from django.forms import ModelChoiceField from django.test import TestCase, override_settings from django.utils import translation from .models import Album, Band class AlbumForm(forms.ModelForm): class Meta: model = Alb...
(self): form = NotRequiredBandForm() attrs = form['band'].field.widget.build_attrs({}) self.assertJSONEqual(attrs['data-allow-clear'], True) def test_build_attrs_required_field(self): form = RequiredBandForm() attrs = form['band'].field.widget.build_attrs({}) self.as...
test_build_attrs_not_required_field
identifier_name
test_autocomplete_widget.py
from django import forms from django.contrib.admin.widgets import AutocompleteSelect from django.forms import ModelChoiceField from django.test import TestCase, override_settings from django.utils import translation from .models import Album, Band class AlbumForm(forms.ModelForm): class Meta: model = Alb...
with translation.override(lang): self.assertEqual(AutocompleteSelect(rel).media._js, expected_files)
expected_files = base_files
conditional_block
test_autocomplete_widget.py
from django import forms from django.contrib.admin.widgets import AutocompleteSelect from django.forms import ModelChoiceField from django.test import TestCase, override_settings from django.utils import translation from .models import Album, Band class AlbumForm(forms.ModelForm): class Meta: model = Alb...
form = RequiredBandForm() attrs = form['band'].field.widget.build_attrs({}) self.assertJSONEqual(attrs['data-allow-clear'], False) def test_get_url(self): rel = Album._meta.get_field('band').remote_field w = AutocompleteSelect(rel) url = w.get_url() self.asse...
form = NotRequiredBandForm() attrs = form['band'].field.widget.build_attrs({}) self.assertJSONEqual(attrs['data-allow-clear'], True) def test_build_attrs_required_field(self):
random_line_split
testimonial-list.component.ts
import {Component, OnInit} from '@angular/core'; import {TestimonialService} from "./testimonial.service"; import{TestimonialModel, TestimonialResponse} from "./testimonial.model"; @Component({ selector: 'testimonial-list', templateUrl: './testimonial-list.html' }) export class TestimonialComponent implements...
objListResponse:TestimonialResponse; error:any; showForm:boolean = false; testimonialId:string; /* Pagination */ perPage:number = 10; currentPage:number = 1; totalPage:number = 1; first:number = 0; bindSort:boolean = false; preIndex:number = 0; /* End Pagination */ n...
random_line_split
testimonial-list.component.ts
import {Component, OnInit} from '@angular/core'; import {TestimonialService} from "./testimonial.service"; import{TestimonialModel, TestimonialResponse} from "./testimonial.model"; @Component({ selector: 'testimonial-list', templateUrl: './testimonial-list.html' }) export class TestimonialComponent implements...
bindList(objRes:TestimonialResponse) { this.objListResponse = objRes; this.preIndex = (this.perPage * (this.currentPage - 1)); if (objRes.dataList.length > 0) { let totalPage = objRes.totalItems / this.perPage; this.totalPage = totalPage > 1 ? Math.ceil(totalPage) ...
{ swal("Alert !", objResponse.message, "info"); }
identifier_body
testimonial-list.component.ts
import {Component, OnInit} from '@angular/core'; import {TestimonialService} from "./testimonial.service"; import{TestimonialModel, TestimonialResponse} from "./testimonial.model"; @Component({ selector: 'testimonial-list', templateUrl: './testimonial-list.html' }) export class TestimonialComponent implements...
(objResponse:any) { swal("Alert !", objResponse.message, "info"); } bindList(objRes:TestimonialResponse) { this.objListResponse = objRes; this.preIndex = (this.perPage * (this.currentPage - 1)); if (objRes.dataList.length > 0) { let totalPage = objRes.totalItems / th...
errorMessage
identifier_name
dir_info.rs
use std::env; use std::path::Path; struct DirInfo { size: u64, depth: u32 } const EMPTY: DirInfo = DirInfo {size: 0, depth: 0}; fn main() { let arg = env::args_os().nth(1).expect("Please, provide a file as argument"); let path = Path::new(&arg); if path.is_dir() { let info = dir_info(path...
{ match std::fs::read_dir(path) { Err(_) => EMPTY, Ok(entries) => entries.fold(EMPTY, |info, entry| update_info(info, &entry.unwrap().path())) } }
identifier_body
dir_info.rs
use std::env; use std::path::Path; struct DirInfo { size: u64, depth: u32 } const EMPTY: DirInfo = DirInfo {size: 0, depth: 0}; fn main() { let arg = env::args_os().nth(1).expect("Please, provide a file as argument"); let path = Path::new(&arg); if path.is_dir() { let info = dir_info(path...
(path: &Path) -> DirInfo { if path.is_file() { file_info(path) } else if path.is_dir() { dir_info(path) } else { EMPTY } } fn file_info(path: &Path) -> DirInfo { let metadata = path.metadata().ok().expect("Cannot get file metadata"); DirInfo {size: metadata.len(), depth:...
dir_entry_info
identifier_name
dir_info.rs
use std::env; use std::path::Path; struct DirInfo { size: u64, depth: u32 } const EMPTY: DirInfo = DirInfo {size: 0, depth: 0}; fn main() { let arg = env::args_os().nth(1).expect("Please, provide a file as argument"); let path = Path::new(&arg); if path.is_dir() { let info = dir_info(path...
else if path.is_dir() { dir_info(path) } else { EMPTY } } fn file_info(path: &Path) -> DirInfo { let metadata = path.metadata().ok().expect("Cannot get file metadata"); DirInfo {size: metadata.len(), depth: 0} } fn dir_info(path: &Path) -> DirInfo { match std::fs::read_dir(path) ...
{ file_info(path) }
conditional_block
dir_info.rs
use std::env; use std::path::Path; struct DirInfo { size: u64, depth: u32 } const EMPTY: DirInfo = DirInfo {size: 0, depth: 0}; fn main() { let arg = env::args_os().nth(1).expect("Please, provide a file as argument"); let path = Path::new(&arg); if path.is_dir() { let info = dir_info(path...
|info, entry| update_info(info, &entry.unwrap().path())) } }
entries.fold(EMPTY,
random_line_split
settings.py
""" Django settings for sample_project project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...
'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'pt-br' TIME_ZONE = 'America/Sao_Paulo' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, Jav...
# Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': {
random_line_split
find_class_methods.py
#!/usr/bin/python import sys import logging #logging.basicConfig(level = logging.DEBUG)
from gi.repository import Vips, GObject # Search for all VipsOperation which don't have an input image object ... these # should be class methods and need to have their names pasted into Vips.py # This is slow :-( so we don't do this dynamically vips_type_image = GObject.GType.from_name("VipsImage") vips_type_operat...
random_line_split
find_class_methods.py
#!/usr/bin/python import sys import logging #logging.basicConfig(level = logging.DEBUG) from gi.repository import Vips, GObject # Search for all VipsOperation which don't have an input image object ... these # should be class methods and need to have their names pasted into Vips.py # This is slow :-( so we don't d...
(cls): if not cls.is_abstract(): op = Vips.Operation.new(cls.name) found = False for prop in op.props: flags = op.get_argument_flags(prop.name) if not flags & Vips.ArgumentFlags.INPUT: continue if not flags & Vips.ArgumentFlags.REQUIRED: ...
find_class_methods
identifier_name
find_class_methods.py
#!/usr/bin/python import sys import logging #logging.basicConfig(level = logging.DEBUG) from gi.repository import Vips, GObject # Search for all VipsOperation which don't have an input image object ... these # should be class methods and need to have their names pasted into Vips.py # This is slow :-( so we don't d...
print 'found class methods:' find_class_methods(vips_type_operation)
if not cls.is_abstract(): op = Vips.Operation.new(cls.name) found = False for prop in op.props: flags = op.get_argument_flags(prop.name) if not flags & Vips.ArgumentFlags.INPUT: continue if not flags & Vips.ArgumentFlags.REQUIRED: ...
identifier_body
find_class_methods.py
#!/usr/bin/python import sys import logging #logging.basicConfig(level = logging.DEBUG) from gi.repository import Vips, GObject # Search for all VipsOperation which don't have an input image object ... these # should be class methods and need to have their names pasted into Vips.py # This is slow :-( so we don't d...
if not found: gtype = Vips.type_find("VipsOperation", cls.name) nickname = Vips.nickname_find(gtype) print ' "%s",' % nickname if len(cls.children) > 0: for child in cls.children: # not easy to get at the deprecated flag in an abtract type? ...
flags = op.get_argument_flags(prop.name) if not flags & Vips.ArgumentFlags.INPUT: continue if not flags & Vips.ArgumentFlags.REQUIRED: continue if GObject.type_is_a(vips_type_image, prop.value_type): found = True break
conditional_block
test-concurrent-load.js
/** * Copyright 2017 The AMP HTML 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 require...
(loadingStrategy) { const element = createElementWithAttributes(env.win.document, 'amp-ad', { 'data-loading-strategy': loadingStrategy, }); allowConsoleError(() => { expect(() => getAmpAdRenderOutsideViewport(element)).to.throw(); }); } }); describe('incrementLoadingAds'...
expectGetAmpAdRenderOutsideViewportThrow
identifier_name
test-concurrent-load.js
/** * Copyright 2017 The AMP HTML 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 require...
}); describe('incrementLoadingAds', () => { let win; let clock; beforeEach(() => { win = env.win; clock = lolex.install({ target: win, toFake: ['Date', 'setTimeout', 'clearTimeout']}); installTimerService(win); }); afterEach(() => { clock.uninstall(); });...
{ const element = createElementWithAttributes(env.win.document, 'amp-ad', { 'data-loading-strategy': loadingStrategy, }); allowConsoleError(() => { expect(() => getAmpAdRenderOutsideViewport(element)).to.throw(); }); }
identifier_body
test-concurrent-load.js
/** * Copyright 2017 The AMP HTML 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 require...
import * as lolex from 'lolex'; import {createElementWithAttributes} from '../../../../src/dom'; import { getAmpAdRenderOutsideViewport, incrementLoadingAds, is3pThrottled, waitFor3pThrottle, } from '../concurrent-load'; import {installTimerService} from '../../../../src/service/timer-impl'; import {macroTask}...
* See the License for the specific language governing permissions and * limitations under the License. */
random_line_split
snmp.py
# -*- coding: utf-8 -*- # # This file is part of Glances. # # Copyright (C) 2015 Nicolargo <nicolas@nicolargo.com> # # Glances is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
def __bulk_result__(self, errorIndication, errorStatus, errorIndex, varBindTable): ret = [] if not errorIndication or not errorStatus: for varBindTableRow in varBindTable: ret.append(self.__buid_result(varBindTableRow)) return ret def getbulk_by_oid(self, n...
"""SNMP simple request (list of OID). One request per OID list. * oid: oid list > Return a dict """ if self.version == '3': errorIndication, errorStatus, errorIndex, varBinds = self.cmdGen.getCmd( cmdgen.UsmUserData(self.user, self.auth), ...
identifier_body
snmp.py
# -*- coding: utf-8 -*- # # This file is part of Glances. # # Copyright (C) 2015 Nicolargo <nicolas@nicolargo.com> # # Glances is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
except ImportError: logger.critical("PySNMP library not found. To install it: pip install pysnmp") sys.exit(2) class GlancesSNMPClient(object): """SNMP client class (based on pysnmp library).""" def __init__(self, host='localhost', port=161, version='2c', community='public', user='p...
from pysnmp.entity.rfc3413.oneliner import cmdgen
random_line_split
snmp.py
# -*- coding: utf-8 -*- # # This file is part of Glances. # # Copyright (C) 2015 Nicolargo <nicolas@nicolargo.com> # # Glances is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
return ret def __get_result__(self, errorIndication, errorStatus, errorIndex, varBinds): """Put results in table.""" ret = {} if not errorIndication or not errorStatus: ret = self.__buid_result(varBinds) return ret def get_by_oid(self, *oid): """SNM...
if str(val) == '': ret[name.prettyPrint()] = '' else: ret[name.prettyPrint()] = val.prettyPrint() # In Python 3, prettyPrint() return 'b'linux'' instead of 'linux' if ret[name.prettyPrint()].startswith('b\''): ret[name.prett...
conditional_block
snmp.py
# -*- coding: utf-8 -*- # # This file is part of Glances. # # Copyright (C) 2015 Nicolargo <nicolas@nicolargo.com> # # Glances is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
(self, *oid): """SNMP simple request (list of OID). One request per OID list. * oid: oid list > Return a dict """ if self.version == '3': errorIndication, errorStatus, errorIndex, varBinds = self.cmdGen.getCmd( cmdgen.UsmUserData(self.user, s...
get_by_oid
identifier_name
shootout-fasta.rs
// Copyright 2012-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-MI...
fn main() { if os::getenv("RUST_BENCH").is_some() { let mut file = BufferedWriter::new(File::create(&Path::new("./shootout-fasta.data"))); run(&mut file); } else { run(&mut BufferedWriter::new(io::stdout())); } }
{ let args = os::args(); let n = if os::getenv("RUST_BENCH").is_some() { 25000000 } else if args.len() <= 1u { 1000 } else { from_str(args[1]).unwrap() }; let rng = &mut MyRandom::new(); let alu = "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG\ GAGGCCGAG...
identifier_body
shootout-fasta.rs
// Copyright 2012-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-MI...
writer.flush(); } fn main() { if os::getenv("RUST_BENCH").is_some() { let mut file = BufferedWriter::new(File::create(&Path::new("./shootout-fasta.data"))); run(&mut file); } else { run(&mut BufferedWriter::new(io::stdout())); } }
AAGen::new(rng, homosapiens), n * 5);
random_line_split
shootout-fasta.rs
// Copyright 2012-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-MI...
else if args.len() <= 1u { 1000 } else { from_str(args[1]).unwrap() }; let rng = &mut MyRandom::new(); let alu = "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG\ GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA\ CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT\ ACAAAAAT...
{ 25000000 }
conditional_block
shootout-fasta.rs
// Copyright 2012-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-MI...
(&mut self) -> u32 { self.last = (self.last * 3877 + 29573) % IM; self.last } } struct AAGen<'a> { rng: &'a mut MyRandom, data: ~[(u32, u8)] } impl<'a> AAGen<'a> { fn new<'b>(rng: &'b mut MyRandom, aa: &[(char, f32)]) -> AAGen<'b> { let mut cum = 0.; let data = aa.iter()...
gen
identifier_name
__init__.py
""" ICS Ops Common Library """ import os from os.path import dirname
import boto __version__ = "0.0.3.3" __release__ = "alpha" CONFIG = "opslib.ini" LOG_NAME = "opslib" AWS_ACCESS_KEY_NAME = "aws_access_key_id" AWS_SECRET_KEY_NAME = "aws_secret_access_key" def init_config(filepath=None, enable_boto=True, enable_botocore=False): # Default credential file will be located at curren...
from os.path import realpath from os.path import join as pathjoin
random_line_split
__init__.py
""" ICS Ops Common Library """ import os from os.path import dirname from os.path import realpath from os.path import join as pathjoin import boto __version__ = "0.0.3.3" __release__ = "alpha" CONFIG = "opslib.ini" LOG_NAME = "opslib" AWS_ACCESS_KEY_NAME = "aws_access_key_id" AWS_SECRET_KEY_NAME = "aws_secret_acces...
(filepath=None, enable_boto=True, enable_botocore=False): # Default credential file will be located at current folder if filepath is None or not os.path.exists(filepath): pwdpath = dirname(realpath(__file__)) filepath = pathjoin(pwdpath, CONFIG) if enable_boto: # Initialize credenti...
init_config
identifier_name
__init__.py
""" ICS Ops Common Library """ import os from os.path import dirname from os.path import realpath from os.path import join as pathjoin import boto __version__ = "0.0.3.3" __release__ = "alpha" CONFIG = "opslib.ini" LOG_NAME = "opslib" AWS_ACCESS_KEY_NAME = "aws_access_key_id" AWS_SECRET_KEY_NAME = "aws_secret_acces...
botocore.credentials.get_credentials = get_credentials if access_key and secret_key: return access_key, secret_key def init_logging(name=LOG_NAME, logfile=None, console=False, loglevel="INFO", enable_boto_log=False): global logger from opslib.icslog ...
return botocore.credentials.Credentials(access_key, secret_key)
identifier_body
__init__.py
""" ICS Ops Common Library """ import os from os.path import dirname from os.path import realpath from os.path import join as pathjoin import boto __version__ = "0.0.3.3" __release__ = "alpha" CONFIG = "opslib.ini" LOG_NAME = "opslib" AWS_ACCESS_KEY_NAME = "aws_access_key_id" AWS_SECRET_KEY_NAME = "aws_secret_acces...
if enable_botocore: # Initialize credentials for botocore import botocore.credentials if access_key and secret_key: def get_credentials(session, metadata=None): return botocore.credentials.Credentials(access_key, secret_key) botocore.credentials.get...
boto.config.remove_section('Credentials')
conditional_block
app.ts
import "reflect-metadata"; import {createConnection, ConnectionOptions} from "../../src/index"; import {Post} from "./entity/Post"; import {Author} from "./entity/Author"; import {Category} from "./entity/Category"; const options: ConnectionOptions = { driver: { type: "mysql", host: "localhost", ...
entities: [Post, Author, Category] }; createConnection(options).then(connection => { let postRepository = connection.getRepository(Post); let author = new Author(); author.name = "Umed"; let category1 = new Category(); category1.name = "Category #1"; let category2 = new Category...
random_line_split
models.py
from __future__ import unicode_literals from functools import partial from future.utils import with_metaclass from django import VERSION from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db.models import Model, Field from django.db.models.signals import class_prepared...
(): from django.contrib.auth.models import User return User # Emulate Django 1.7's exception-raising get_registered_model # when running under earlier versions if VERSION >= (1, 7): from django.apps import apps get_model = apps.get_model get_registered_model = apps.get_registered_model els...
get_user_model
identifier_name
models.py
from __future__ import unicode_literals from functools import partial from future.utils import with_metaclass from django import VERSION from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db.models import Model, Field from django.db.models.signals import class_prepared...
def upload_to(field_path, default): """ Used as the ``upload_to`` arg for file fields - allows for custom handlers to be implemented on a per field basis defined by the ``UPLOAD_TO_HANDLERS`` setting. """ from mezzanine.conf import settings for k, v in settings.UPLOAD_TO_HANDLERS.items():...
""" Used in methods of abstract models to find the super-most concrete (non abstract) model in the inheritance chain that inherits from the given abstract model. This is so the methods in the abstract model can query data consistently across the correct concrete model. Consider the following:: ...
identifier_body
models.py
from __future__ import unicode_literals from functools import partial from future.utils import with_metaclass from django import VERSION from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db.models import Model, Field from django.db.models.signals import class_prepared...
else: def get_user_model(): from django.contrib.auth.models import User return User # Emulate Django 1.7's exception-raising get_registered_model # when running under earlier versions if VERSION >= (1, 7): from django.apps import apps get_model = apps.get_model get_registered_model = ...
from django.contrib.auth import get_user_model
conditional_block
models.py
from __future__ import unicode_literals from functools import partial from future.utils import with_metaclass from django import VERSION from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db.models import Model, Field from django.db.models.signals import class_prepared...
"an inner Meta class with the " "``mixin_for`` attribute defined, " "with a value that is a valid model.") # Copy fields and methods onto the model being mixed into, and # return it as th...
raise TypeError except (TypeError, KeyError, AttributeError): raise ImproperlyConfigured("The ModelMixin class '%s' requires "
random_line_split
test_optimization.py
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
assert not pytest.main([__file__])
conditional_block
test_optimization.py
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
def f_opt(x): x = x x = 0 x = x x = 0 x = x * 2 x = 2 * x x = 6 x = 1 + x x = x x = x + 1 x = x x = x + 2 x = 2 + x x = 5 x = 1 - x x = -x x = x - 1 x = x x = x - 2 x = 2 - x x = -1 x = 1 / x x = 0 / x x = x x = x / ...
x = 1 * x x = 0 * x x = x * 1 x = x * 0 x = x * 2 x = 2 * x x = 2 * 3 x = 1 + x x = 0 + x x = x + 1 x = x + 0 x = x + 2 x = 2 + x x = 2 + 3 x = 1 - x x = 0 - x x = x - 1 x = x - 0 x = x - 2 x = 2 - x x = 2 - 3 x = 1 / x x = 0 / x ...
identifier_body
test_optimization.py
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
return x node = quoting.parse_function(f) node = optimization.optimize(node) assert isinstance(node.body[0].body[0], gast.Return) def test_constant_folding(): def f(x): x = 1 * x x = 0 * x x = x * 1 x = x * 0 x = x * 2 x = 2 * x x = 2 * 3 x = 1 + x x = 0 + x x = x ...
z = h(y)
random_line_split
test_optimization.py
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
(x): y = g(x) z = h(y) return x node = quoting.parse_function(f) node = optimization.optimize(node) assert isinstance(node.body[0].body[0], gast.Return) def test_constant_folding(): def f(x): x = 1 * x x = 0 * x x = x * 1 x = x * 0 x = x * 2 x = 2 * x x = 2 * 3 x =...
f
identifier_name
accelerator.py
import numpy as _np import lnls as _lnls import pyaccel as _pyaccel from . import lattice as _lattice default_cavity_on = False default_radiation_on = False default_vchamber_on = False def create_accelerator(optics_mode=_lattice.default_optics_mode, energy=_lattice.energy):
accelerator_data = dict() accelerator_data['lattice_version'] = 'BO_V06_01' accelerator_data['global_coupling'] = 0.0002 # expected corrected value accelerator_data['pressure_profile'] = _np.array([[0, 496.8], [1.5e-8]*2]) # [s [m], p [mbar]]o 496.78745
lattice = _lattice.create_lattice(optics_mode=optics_mode, energy=energy) accelerator = _pyaccel.accelerator.Accelerator( lattice=lattice, energy=energy, harmonic_number=_lattice.harmonic_number, cavity_on=default_cavity_on, radiation_on=default_radiation_on, vchamber...
identifier_body
accelerator.py
import numpy as _np import lnls as _lnls import pyaccel as _pyaccel from . import lattice as _lattice default_cavity_on = False default_radiation_on = False default_vchamber_on = False def
(optics_mode=_lattice.default_optics_mode, energy=_lattice.energy): lattice = _lattice.create_lattice(optics_mode=optics_mode, energy=energy) accelerator = _pyaccel.accelerator.Accelerator( lattice=lattice, energy=energy, harmonic_number=_lattice.harmonic_number, cavity_on=defaul...
create_accelerator
identifier_name
accelerator.py
import numpy as _np import lnls as _lnls import pyaccel as _pyaccel from . import lattice as _lattice
default_cavity_on = False default_radiation_on = False default_vchamber_on = False def create_accelerator(optics_mode=_lattice.default_optics_mode, energy=_lattice.energy): lattice = _lattice.create_lattice(optics_mode=optics_mode, energy=energy) accelerator = _pyaccel.accelerator.Accelerator( latti...
random_line_split
player.rs
extern crate serde_redis; #[derive(Debug, Deserialize, Serialize, Clone)] pub struct Player { #[serde(skip_serializing)] pub addr: String, pub name: Option<String>, pub state: PlayerState } impl Player { pub fn new(addr: String, name: Option<String>) -> Player { Player { addr: ...
pub fn format_hand_key(addr: &str, game_id: &str) -> String { format!("HAND:{}:{}", addr, game_id) } pub fn state_key(&self) -> String { Player::format_state_key(&self.addr) } pub fn hand_key(&self, game_id: &str) -> String { Player::format_hand_key(&self.addr, game_id) ...
pub fn format_state_key(addr: &str) -> String { format!("STATE:{}", addr) }
random_line_split
player.rs
extern crate serde_redis; #[derive(Debug, Deserialize, Serialize, Clone)] pub struct Player { #[serde(skip_serializing)] pub addr: String, pub name: Option<String>, pub state: PlayerState } impl Player { pub fn new(addr: String, name: Option<String>) -> Player { Player { addr: ...
(&self, game_id: &str) -> String { Player::format_hand_key(&self.addr, game_id) } } // States #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(tag = "type")] pub enum PlayerState { Watching, Playing, Judging, TimeOut, Banned, } // Transitions
hand_key
identifier_name
index.d.ts
// Type definitions for react-hammerjs 1.0 // Project: https://github.com/JedWatson/react-hammerjs#readme // Definitions by: Jason Unger <https://github.com/jsonunger> // Cecchi MacNaughton <https://github.com/cecchi> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Versi...
action?: HammerListener; onDoubleTap?: HammerListener; onPan?: HammerListener; onPanCancel?: HammerListener; onPanEnd?: HammerListener; onPanStart?: HammerListener; onPinch?: HammerListener; onPinchCancel?: HammerListener; onPinchEnd?: HammerListen...
random_line_split
BuyTshirt.spec.ts
import { browser } from 'protractor'; import { MenuContentPage } from '../src/page'; import { OrderResumePage } from '../src/page'; import { ProductDetailPage } from '../src/page'; import { ProductAddedModalPage } from '../src/page';
import { SummaryStepPage } from '../src/page'; import { SignInStepPage } from '../src/page'; import { AddressStepPage } from '../src/page'; import { ShippingStepPage } from '../src/page'; import { PaymentStepPage } from '../src/page'; import { BankPaymentPage } from '../src/page'; import { ProductListPage } from '../sr...
random_line_split
product.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Pexego Sistemas Informáticos All Rights Reserved # $Jesús Ventosinos Mayor <jesus@pexego.es>$ # # This program is free software: you can redistribute it and/or modify # it under the ...
odels.Model): _inherit = 'product.product' is_outlet = fields.Boolean('Is outlet', compute='_is_outlet') normal_product_id = fields.Many2one('product.product', 'normal product') outlet_product_ids = fields.One2many('product.product', 'normal_product_id', ...
oduct_product(m
identifier_name
product.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Pexego Sistemas Informáticos All Rights Reserved # $Jesús Ventosinos Mayor <jesus@pexego.es>$ # # This program is free software: you can redistribute it and/or modify # it under the ...
else: self.is_outlet = False @api.model def cron_update_outlet_price(self): outlet_categ_ids = [] outlet_categ_ids.append(self.env.ref('product_outlet.product_category_o1').id) outlet_categ_ids.append(self.env.ref('product_outlet.product_category_o2').id) outl...
lf.is_outlet = True
conditional_block
product.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Pexego Sistemas Informáticos All Rights Reserved
# 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...
# $Jesús Ventosinos Mayor <jesus@pexego.es>$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published
random_line_split