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
observe.js
/** * Librerías Javascript * * @package Roraima * @author $Author$ <desarrollo@cidesa.com.ve> * @version SVN: $Id$ * * @copyright Copyright 2007, Cide S.A. * @license http://opensource.org/licenses/gpl-2.0.php GPLv2 */ //FUNCIONES JAVASCRIPT var form = null; var arreglo = null; var inicio...
) { if(!noActualizarInputs){ form = $('sf_admin_edit_form'); arreglo = Array(); if(form) arreglo = $$('input[type=text]', 'select','textarea'); // -> only text inputs var i = 0; arreglo.each(function(e,index){ if(!e.disabled && !e.readOnly) { e.tabindex = ...
ctualizarInputs(
identifier_name
heat_iterations.py
""" Illustration of the heat equation Solve the heat equation using finite differences and Forward Euler. Based on: https://commons.wikimedia.org/wiki/File:Heat_eqn.gif """ from __future__ import division, print_function import numpy as np from mayavi import mlab def step_function(N, scale, X, Y, shape="crescent")...
Z[right_eye < 0] = 0 Z = scale * Z return Z def data_gen(num): # Solve the heat equation with zero boundary conditions for cont in range(ntime_anim): Z[1:N-1, 1:N-1] = Z[1:N-1, 1:N-1] + dt*(Z[2:N, 1:N-1] + Z[0:N-2, 1:N-1] + Z[1:N-1, 0:N-2] + ...
random_line_split
heat_iterations.py
""" Illustration of the heat equation Solve the heat equation using finite differences and Forward Euler. Based on: https://commons.wikimedia.org/wiki/File:Heat_eqn.gif """ from __future__ import division, print_function import numpy as np from mayavi import mlab def step_function(N, scale, X, Y, shape="crescent")...
Z = scale * Z return Z def data_gen(num): # Solve the heat equation with zero boundary conditions for cont in range(ntime_anim): Z[1:N-1, 1:N-1] = Z[1:N-1, 1:N-1] + dt*(Z[2:N, 1:N-1] + Z[0:N-2, 1:N-1] + Z[1:N-1, 0:N-2] + Z[1:N-1, 2:N...
Z = np.ones_like(X) fac = 1.2 x_eye = 0.5 y_eye = 0.4 bicorn = fac**2*(Y + 0.3)**2*(1 - fac**2*X**2) -\ (fac**2*X**2 - 2*fac*(Y + 0.3) - 1)**2 left_eye = (X + x_eye)**2/0.1 + (Y - y_eye)**2/0.4 - 1 right_eye = (X - x_eye)**2/0.1 + (Y - y_eye)**2/0.4 - 1 ...
conditional_block
heat_iterations.py
""" Illustration of the heat equation Solve the heat equation using finite differences and Forward Euler. Based on: https://commons.wikimedia.org/wiki/File:Heat_eqn.gif """ from __future__ import division, print_function import numpy as np from mayavi import mlab def step_function(N, scale, X, Y, shape="crescent")...
if shape == "crescent": c = 2 d = -1 e = 1 f = 0.5 k = 1.2 shift = 10 Z = (c**2 - (X/e - d)**2 - (Y/f)**2)**2 + k*(c + d - X/e)**3 - shift Z = 1 - np.maximum(np.sign(Z), 0) if shape == "smiley": Z = np.ones_like(X) fac = 1.2 ...
"""Function that is 1 on a set and 0 outside of it""" shapes = ["crescent", "cylinder", "hexagon", "superquadric", "smiley"] if shape not in shapes: shape = "crescent" if shape == "cylinder": Z = np.ones_like(X) Z[X**2 + Y**2 < 0.5] = 0 Z[X**2 + Y**2 > 2] = 0 if shape ...
identifier_body
heat_iterations.py
""" Illustration of the heat equation Solve the heat equation using finite differences and Forward Euler. Based on: https://commons.wikimedia.org/wiki/File:Heat_eqn.gif """ from __future__ import division, print_function import numpy as np from mayavi import mlab def
(N, scale, X, Y, shape="crescent"): """Function that is 1 on a set and 0 outside of it""" shapes = ["crescent", "cylinder", "hexagon", "superquadric", "smiley"] if shape not in shapes: shape = "crescent" if shape == "cylinder": Z = np.ones_like(X) Z[X**2 + Y**2 < 0.5] = 0 ...
step_function
identifier_name
shootout-ackermann.rs
// Copyright 2012 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 ...
(m: int, n: int) -> int { if m == 0 { return n + 1 } else { if n == 0 { return ack(m - 1, 1); } else { return ack(m - 1, ack(m, n - 1)); } } } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { ~[~"",...
ack
identifier_name
shootout-ackermann.rs
// Copyright 2012 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 ...
{ let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { ~[~"", ~"12"] } else if args.len() <= 1u { ~[~"", ~"8"] } else { args }; let n = from_str::<int>(args[1]).unwrap(); printfln!("Ack(3,%d): %d\n", n, ack(3, n)); }
identifier_body
shootout-ackermann.rs
// Copyright 2012 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 ...
}; let n = from_str::<int>(args[1]).unwrap(); printfln!("Ack(3,%d): %d\n", n, ack(3, n)); }
random_line_split
shootout-ackermann.rs
// Copyright 2012 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 ...
else { args }; let n = from_str::<int>(args[1]).unwrap(); printfln!("Ack(3,%d): %d\n", n, ack(3, n)); }
{ ~[~"", ~"8"] }
conditional_block
move_error.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} debug!("found a new move from location"); grouped_errors.push(GroupedMoveErrors { move_from: error.move_from.clone(), move_to_places: move_to }) } } fn report_cannot_move_out_of<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, ...
{ debug!("appending move_to to list"); ge.move_to_places.extend(move_to.into_iter()); return }
conditional_block
move_error.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
move_to_places: Vec<MoveSpanAndPath> } fn report_move_errors<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, errors: &Vec<MoveError<'tcx>>) { let grouped_errors = group_errors_with_same_origin(errors); for error in grouped_errors.iter() { report_cannot_move_out_of(bccx, err...
} pub struct GroupedMoveErrors<'tcx> { move_from: mc::cmt<'tcx>,
random_line_split
move_error.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(move_from: mc::cmt<'tcx>, move_to: Option<MoveSpanAndPath>) -> MoveError<'tcx> { MoveError { move_from: move_from, move_to: move_to, } } } #[derive(Clone)] pub struct MoveSpanAndPath { pub span: codemap::Span, pub ...
with_move_info
identifier_name
move_error.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} pub struct MoveError<'tcx> { move_from: mc::cmt<'tcx>, move_to: Option<MoveSpanAndPath> } impl<'tcx> MoveError<'tcx> { pub fn with_move_info(move_from: mc::cmt<'tcx>, move_to: Option<MoveSpanAndPath>) -> MoveError<'tcx> { MoveError { ...
{ report_move_errors(bccx, &*self.errors.borrow()) }
identifier_body
fragment.rs
// Copyright 2017 Serde Developers // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except accordin...
macro_rules! quote_expr { ($($tt:tt)*) => { $crate::fragment::Fragment::Expr(quote!($($tt)*)) } } macro_rules! quote_block { ($($tt:tt)*) => { $crate::fragment::Fragment::Block(quote!($($tt)*)) } } /// Interpolate a fragment in place of an expression. This involves surrounding /// Bloc...
random_line_split
fragment.rs
// Copyright 2017 Serde Developers // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except accordin...
} } } /// Interpolate a fragment as the statements of a block. pub struct Stmts(pub Fragment); impl ToTokens for Stmts { fn to_tokens(&self, out: &mut Tokens) { match self.0 { Fragment::Expr(ref expr) => expr.to_tokens(out), Fragment::Block(ref block) => block.to_tokens...
{ token::Brace::default().surround(out, |out| block.to_tokens(out)); }
conditional_block
fragment.rs
// Copyright 2017 Serde Developers // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except accordin...
} impl AsRef<Tokens> for Fragment { fn as_ref(&self) -> &Tokens { match *self { Fragment::Expr(ref expr) => expr, Fragment::Block(ref block) => block, } } }
{ match self.0 { Fragment::Expr(ref expr) => { expr.to_tokens(out); <Token![,]>::default().to_tokens(out); } Fragment::Block(ref block) => { token::Brace::default().surround(out, |out| block.to_tokens(out)); } ...
identifier_body
fragment.rs
// Copyright 2017 Serde Developers // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except accordin...
(&self, out: &mut Tokens) { match self.0 { Fragment::Expr(ref expr) => expr.to_tokens(out), Fragment::Block(ref block) => { token::Brace::default().surround(out, |out| block.to_tokens(out)); } } } } /// Interpolate a fragment as the statements of ...
to_tokens
identifier_name
install.py
#!/usr/bin/python3 import sys import os def printUsage(): sys.exit('Usage: %s server|client' % sys.argv[0]) if ((len(sys.argv)!=2) or (sys.argv[1] != 'client') and (sys.argv[1] != 'server')):
print("Generating daemon script\n") fileContents = open('dyndns.sh').read( os.path.getsize('dyndns.sh') ) fileContents = fileContents.replace('{DYNDNS_PATH}', os.getcwd()) fileContents = fileContents.replace('{VERSION}', sys.argv[1]) fileContents = fileContents.replace('{USER}', os.getlogin()) print("Writing daemon ...
printUsage()
conditional_block
install.py
#!/usr/bin/python3 import sys import os def printUsage():
if ((len(sys.argv)!=2) or (sys.argv[1] != 'client') and (sys.argv[1] != 'server')): printUsage() print("Generating daemon script\n") fileContents = open('dyndns.sh').read( os.path.getsize('dyndns.sh') ) fileContents = fileContents.replace('{DYNDNS_PATH}', os.getcwd()) fileContents = fileContents.replace('{VERSION}...
sys.exit('Usage: %s server|client' % sys.argv[0])
identifier_body
install.py
#!/usr/bin/python3 import sys import os def
(): sys.exit('Usage: %s server|client' % sys.argv[0]) if ((len(sys.argv)!=2) or (sys.argv[1] != 'client') and (sys.argv[1] != 'server')): printUsage() print("Generating daemon script\n") fileContents = open('dyndns.sh').read( os.path.getsize('dyndns.sh') ) fileContents = fileContents.replace('{DYNDNS_PATH}', os.g...
printUsage
identifier_name
install.py
#!/usr/bin/python3 import sys import os def printUsage(): sys.exit('Usage: %s server|client' % sys.argv[0]) if ((len(sys.argv)!=2) or (sys.argv[1] != 'client') and (sys.argv[1] != 'server')): printUsage() print("Generating daemon script\n") fileContents = open('dyndns.sh').read( os.path.getsize('dyndns.sh') ) fi...
print('Changing permissions\n') os.chmod(daemonPath, 0o755) print('Installing the init script') os.system('update-rc.d dyndns defaults') print('done.\nYou can start the service by using:\nsudo service dyndns start')
daemon = open(daemonPath, 'w') daemon.write(fileContents) daemon.close()
random_line_split
singleton.rs
, u64)>, pub resolved_calls: MultiMap<Uuid, (Uuid, u64)>, // callee -> caller pub region: Option<Region>, pub project: Option<Project>, pub undo_stack: Vec<Action>, pub undo_stack_top: usize, pub layout_task: Option<future::BoxFuture<ControlFlowLayout, Error>>, } impl Panopticon { pub fn ...
let mut proj = Project::new("(none)".to_string(), region.clone()); let mut prog = Program::new("(none"); for f in self.functions.iter() { prog.insert(f.1.clone()); } proj.code.push(prog); proj.snapshot(&Path::new(&path))?; ...
} else if let Some(ref region) = self.region {
random_line_split
singleton.rs
, u64)>, pub resolved_calls: MultiMap<Uuid, (Uuid, u64)>, // callee -> caller pub region: Option<Region>, pub project: Option<Project>, pub undo_stack: Vec<Action>, pub undo_stack_top: usize, pub layout_task: Option<future::BoxFuture<ControlFlowLayout, Error>>, } impl Panopticon { pub fn ...
(&mut self, path: String) -> Result<()> { use std::path::Path; use panopticon_core::{CallTarget, Machine}; use panopticon_amd64 as amd64; use panopticon_avr as avr; use panopticon_analysis::pipeline; use futures::Stream; use std::ffi::CString; debug!("ope...
open_program
identifier_name
singleton.rs
mega103()), Machine::Ia32 => pipeline::<amd64::Amd64>(prog, reg.clone(), amd64::Mode::Protected), Machine::Amd64 => pipeline::<amd64::Amd64>(prog, reg.clone(), amd64::Mode::Long), }; self.region = Some(reg); thread::spawn( ...
{ match rv { &Rvalue::Constant { value, .. } => { // their addr let maybe_callee = self.by_entry.get(&value); if let Some(callee) = maybe_callee { ...
conditional_block
singleton.rs
_flow_layouts.insert(uuid, cfl); future::ok((nodes, edges)) } ) .boxed() } else { let cfl = &self.control_flow_layouts.get(uuid).unwrap(); let nodes = cfl.get_all_nodes(); let edges = cfl.get_all_edge...
{ use std::ffi::CString; use panopticon_glue::{CBasicBlockLine, CBasicBlockOperand}; debug!( "update_control_flow_nodes() func={}, addrs={:?}", uuid, addrs ); let ids = if let Some(ref mut cfl) = self.control_flow_layouts.get_mut(uuid) { ...
identifier_body
uart.rs
use Core; use Addon; use io; pub struct
{ /// The baud rate (bits/second) pub baud: u64, /// The number of CPU ticks in a single second (ticks/second) pub cpu_frequency: u64, /// Number of ticks between each bit. ticks_between_bits: u64, ticks_until_next_bit: u64, _tx: io::Port, _rx: io::Port, _processed_bits: Vec<...
Uart
identifier_name
uart.rs
use Core; use Addon; use io; pub struct Uart { /// The baud rate (bits/second) pub baud: u64, /// The number of CPU ticks in a single second (ticks/second) pub cpu_frequency: u64, /// Number of ticks between each bit. ticks_between_bits: u64, ticks_until_next_bit: u64, _tx: io::Port, ...
pub fn new(cpu_frequency: u64, baud: u64, tx: io::Port, rx: io::Port) -> Self { let ticks_between_bits = cpu_frequency / baud; Uart { cpu_frequency: cpu_frequency, baud: baud, _tx: tx, _rx: rx, ticks_between_bits: ticks_between_bits, // T...
random_line_split
uart.rs
use Core; use Addon; use io; pub struct Uart { /// The baud rate (bits/second) pub baud: u64, /// The number of CPU ticks in a single second (ticks/second) pub cpu_frequency: u64, /// Number of ticks between each bit. ticks_between_bits: u64, ticks_until_next_bit: u64, _tx: io::Port, ...
} }
{ self.process_bit(core); self.ticks_until_next_bit = self.ticks_between_bits; }
conditional_block
uart.rs
use Core; use Addon; use io; pub struct Uart { /// The baud rate (bits/second) pub baud: u64, /// The number of CPU ticks in a single second (ticks/second) pub cpu_frequency: u64, /// Number of ticks between each bit. ticks_between_bits: u64, ticks_until_next_bit: u64, _tx: io::Port, ...
fn process_bit(&mut self, _core: &mut Core) { println!("tick"); } } impl Addon for Uart { fn tick(&mut self, core: &mut Core) { self.ticks_until_next_bit -= 1; if self.ticks_until_next_bit == 0 { self.process_bit(core); self.ticks_until_next_bit = self.tic...
{ let ticks_between_bits = cpu_frequency / baud; Uart { cpu_frequency: cpu_frequency, baud: baud, _tx: tx, _rx: rx, ticks_between_bits: ticks_between_bits, // TODO: set this variable ticks_until_next_bit: ticks_between_bits, ...
identifier_body
webpack.config.js
// Example webpack configuration for React with live reloading in development // and asset fingerprinting in production. "use strict"; var path = require("path"); var webpack = require("webpack"); // Helpers are hardcoded to expect dev assets at http://localhost:3808/webpack/* var devServerPort = 3808; // set TARGET...
] }, resolve: { extensions: ["", ".js", ".jsx"] }, // Sourcemaps in both production & development devtool: "cheap-module-eval-source-map" }; if(!production) { config.devServer = { port: devServerPort }; // react-hot-loader configuration bits config.plugins ...
include: path.join(__dirname, "webpack") }
random_line_split
webpack.config.js
// Example webpack configuration for React with live reloading in development // and asset fingerprinting in production. "use strict"; var path = require("path"); var webpack = require("webpack"); // Helpers are hardcoded to expect dev assets at http://localhost:3808/webpack/* var devServerPort = 3808; // set TARGET...
module.exports = config;
{ config.devServer = { port: devServerPort }; // react-hot-loader configuration bits config.plugins = [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ]; Object.keys(config.entry).forEach(function(entryPoint) { config.entry[entryPoint] = [...
conditional_block
fixnss.py
#! /usr/bin/python # # Copyright (C) 2012,2014 Stefano Sanfilippo. # See LICENSE.txt in the main source package for more information # from __future__ import with_statement import sys # Ugly ugly trick to give us compatibility both with Py2 and Py3k try: import cStringIO as StringIO except ImportError: try: ...
buffer.write('Off\n') ready = steady = False if not overwrite: filename = filename.replace('.nss', '.new.nss') with open(filename, 'wt') as sourcefile: sourcefile.write(buffer.getvalue()) def main(): filenames = sys.argv[1:] if f...
"""Will append a `Off` flag into each `(Duplex|Simplex)` Link declaration. Needed because the old file format was updated to include Queue Visualization. Converted file will be saved to ${somename}.new.nss Args: filename: the name of the file to be converted. overwrite: will overwrite input...
identifier_body
fixnss.py
#! /usr/bin/python # # Copyright (C) 2012,2014 Stefano Sanfilippo. # See LICENSE.txt in the main source package for more information # from __future__ import with_statement import sys # Ugly ugly trick to give us compatibility both with Py2 and Py3k try: import cStringIO as StringIO except ImportError: try: ...
main()
conditional_block
fixnss.py
#! /usr/bin/python # # Copyright (C) 2012,2014 Stefano Sanfilippo. # See LICENSE.txt in the main source package for more information # from __future__ import with_statement import sys # Ugly ugly trick to give us compatibility both with Py2 and Py3k try: import cStringIO as StringIO except ImportError: try: ...
(): filenames = sys.argv[1:] if filenames: for filename in filenames: print ('Converting %s' % filename) fix(filename) else: print('Usage: %s file1.nss [file2.nss [...]]' % sys.argv[0]) sys.exit(0) if __name__ == '__main__': main()
main
identifier_name
fixnss.py
#! /usr/bin/python # # Copyright (C) 2012,2014 Stefano Sanfilippo. # See LICENSE.txt in the main source package for more information # from __future__ import with_statement import sys # Ugly ugly trick to give us compatibility both with Py2 and Py3k try: import cStringIO as StringIO except ImportError: try: ...
for filename in filenames: print ('Converting %s' % filename) fix(filename) else: print('Usage: %s file1.nss [file2.nss [...]]' % sys.argv[0]) sys.exit(0) if __name__ == '__main__': main()
def main(): filenames = sys.argv[1:] if filenames:
random_line_split
_conformal_layout.py
import numpy as np from ._layout import Layout from ._multivector import MultiVector class
(Layout): r""" A layout for a conformal algebra, which adds extra constants and helpers. Typically these should be constructed via :func:`clifford.conformalize`. .. versionadded:: 1.2.0 Attributes ---------- ep : MultiVector The first added basis element, :math:`e_{+}`, usually wi...
ConformalLayout
identifier_name
_conformal_layout.py
import numpy as np from ._layout import Layout from ._multivector import MultiVector class ConformalLayout(Layout): r""" A layout for a conformal algebra, which adds extra constants and helpers. Typically these should be constructed via :func:`clifford.conformalize`. .. versionadded:: 1.2.0 At...
en : MultiVector The first added basis element, :math:`e_{-}`, usually with :math:`e_{-}^2 = -1` eo : MultiVector The null basis vector at the origin, :math:`e_o = 0.5(e_{-} - e_{+})` einf : MultiVector The null vector at infinity, :math:`e_\infty = e_{-} + e_{+}` E0 : MultiVecto...
ep : MultiVector The first added basis element, :math:`e_{+}`, usually with :math:`e_{+}^2 = +1`
random_line_split
_conformal_layout.py
import numpy as np from ._layout import Layout from ._multivector import MultiVector class ConformalLayout(Layout): r""" A layout for a conformal algebra, which adds extra constants and helpers. Typically these should be constructed via :func:`clifford.conformalize`. .. versionadded:: 1.2.0 At...
@classmethod def _from_base_layout(cls, layout, added_sig=[1, -1], **kwargs) -> 'ConformalLayout': """ helper to implement :func:`clifford.conformalize` """ sig_c = list(layout.sig) + added_sig return cls( sig_c, ids=layout._basis_vector_ids.augmented_with(len(a...
super().__init__(*args, **kwargs) self._base_layout = layout ep, en = self.basis_vectors_lst[-2:] # setup null basis, and minkowski subspace bivector eo = .5 ^ (en - ep) einf = en + ep E0 = einf ^ eo I_base = self.pseudoScalar*E0 # helper properties ...
identifier_body
_conformal_layout.py
import numpy as np from ._layout import Layout from ._multivector import MultiVector class ConformalLayout(Layout): r""" A layout for a conformal algebra, which adds extra constants and helpers. Typically these should be constructed via :func:`clifford.conformalize`. .. versionadded:: 1.2.0 At...
except(AttributeError): # if x is a scalar it doesnt have layout but following # will still work pass # then up-project into a null vector return x + (.5 ^ ((x**2)*self.einf)) + self.eo def homo(self, x: MultiVector) -> MultiVector: """ homogeni...
old_val = x.value new_val = np.zeros(self.gaDims) new_val[:len(old_val)] = old_val x = self.MultiVector(value=new_val)
conditional_block
image_alt.py
#!/usr/bin/python # -*- coding: utf-8 -*- from holmes.validators.base import Validator
def get_without_alt_parsed_value(cls, value): result = [] for src, name in value: data = '<a href="%s" target="_blank">%s</a>' % (src, name) result.append(data) return {'images': ', '.join(result)} @classmethod def get_alt_too_big_parsed_value(cls, value): ...
from holmes.utils import _ class ImageAltValidator(Validator): @classmethod
random_line_split
image_alt.py
#!/usr/bin/python # -*- coding: utf-8 -*- from holmes.validators.base import Validator from holmes.utils import _ class ImageAltValidator(Validator): @classmethod def get_without_alt_parsed_value(cls, value): result = [] for src, name in value: data = '<a href="%s" target="_blank"...
@classmethod def get_violation_definitions(cls): return { 'invalid.images.alt': { 'title': _('Image(s) without alt attribute'), 'description': _( 'Images without alt text are not good for ' 'Search Engines. Images with...
result = [] for src, name, alt in value['images']: data = u'<a href="{}" alt="{}" target="_blank">{}</a>'.format( src, alt, name ) result.append(data) return { 'max_size': value['max_size'], 'images': ', '.join(result) ...
identifier_body
image_alt.py
#!/usr/bin/python # -*- coding: utf-8 -*- from holmes.validators.base import Validator from holmes.utils import _ class ImageAltValidator(Validator): @classmethod def get_without_alt_parsed_value(cls, value): result = [] for src, name in value:
return {'images': ', '.join(result)} @classmethod def get_alt_too_big_parsed_value(cls, value): result = [] for src, name, alt in value['images']: data = u'<a href="{}" alt="{}" target="_blank">{}</a>'.format( src, alt, name ) result...
data = '<a href="%s" target="_blank">%s</a>' % (src, name) result.append(data)
conditional_block
image_alt.py
#!/usr/bin/python # -*- coding: utf-8 -*- from holmes.validators.base import Validator from holmes.utils import _ class ImageAltValidator(Validator): @classmethod def get_without_alt_parsed_value(cls, value): result = [] for src, name in value: data = '<a href="%s" target="_blank"...
(cls, config): return { 'invalid.images.alt_too_big': { 'value': config.MAX_IMAGE_ALT_SIZE, 'description': config.get_description('MAX_IMAGE_ALT_SIZE') } } def validate(self): max_alt_size = self.get_violation_pref('invalid.images.alt_...
get_default_violations_values
identifier_name
index.js
// # Ruta Menú Principal /* Configuración de la ruta del menú principal (`/` y `/index`) */ "use strict"; /*UGR Transparente. Sitio Web de la Universidad de Granada de acceso a Datos Abiertos. Copyright (C) 2014 Jaime Torres Benavente, Óscar Zafra Megías Copyright (C) 2015 Mario Heredia Moreno, Germán Martínez Mal...
ports // * `index(req,res)`: callback para renderizar inicio exports.index = function(req, res) { if (enlaces.length === 0) leerEnlaces(); res.render('index', { seccion: config.archivosJson.index.nombre, enlaces: enlaces }); };
config.archivosJson.index.enlaces.length; for (var i = 0; i < l; i++) { var enlace = config.archivosJson.index.enlaces[i]; enlaces.push({ "nombre": enlace.nombre, "link": enlace.href, "id": enlace.id }); } } // ### Ex
identifier_body
index.js
// # Ruta Menú Principal /* Configuración de la ruta del menú principal (`/` y `/index`) */ "use strict"; /*UGR Transparente. Sitio Web de la Universidad de Granada de acceso a Datos Abiertos. Copyright (C) 2014 Jaime Torres Benavente, Óscar Zafra Megías Copyright (C) 2015 Mario Heredia Moreno, Germán Martínez Mal...
= config.archivosJson.index.enlaces.length; for (var i = 0; i < l; i++) { var enlace = config.archivosJson.index.enlaces[i]; enlaces.push({ "nombre": enlace.nombre, "link": enlace.href, "id": enlace.id }); } } // ### Exports // * `index(req,res)`: callback para renderizar inicio exports.index = funct...
() { var l
identifier_name
index.js
// # Ruta Menú Principal /* Configuración de la ruta del menú principal (`/` y `/index`) */ "use strict"; /*UGR Transparente. Sitio Web de la Universidad de Granada de acceso a Datos Abiertos. Copyright (C) 2014 Jaime Torres Benavente, Óscar Zafra Megías Copyright (C) 2015 Mario Heredia Moreno, Germán Martínez Mal...
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.*/ /...
(at your option) any later version. UGR Transparente is distributed in the hope that it will be useful,
random_line_split
default_writer.rs
extern crate rust_base58; use std::fs; use std::fs::File; use std::io::Write; use std::path::PathBuf; use serde_json; use errors::prelude::*; use utils::environment; use super::{WritableBlob, Writer, WriterType}; use self::rust_base58::ToBase58; #[allow(dead_code)] pub struct DefaultWriter { base_dir: PathBuf...
(id: i32) -> PathBuf { environment::tmp_file_path(&format!("def_storage_tmp_{}", id)) } pub struct DefaultWriterType {} impl DefaultWriterType { pub fn new() -> Self { DefaultWriterType {} } }
tmp_storage_file
identifier_name
default_writer.rs
extern crate rust_base58; use std::fs; use std::fs::File; use std::io::Write; use std::path::PathBuf; use serde_json; use errors::prelude::*; use utils::environment; use super::{WritableBlob, Writer, WriterType}; use self::rust_base58::ToBase58; #[allow(dead_code)] pub struct DefaultWriter { base_dir: PathBuf...
fs::remove_file(&tmp_storage_file(self.id)) .map_err(map_err_trace!())?; let res = path.to_str().unwrap().to_owned(); trace!("finalize <<< {}", res); Ok(res) } } fn tmp_storage_file(id: i32) -> PathBuf { environment::tmp_file_path(&format!("def_storage_tmp_{}", id...
.map_err(map_err_trace!(format!("path: {:?}", path)))?; fs::copy(&tmp_storage_file(self.id), &path) .map_err(map_err_trace!())?; //FIXME
random_line_split
default_writer.rs
extern crate rust_base58; use std::fs; use std::fs::File; use std::io::Write; use std::path::PathBuf; use serde_json; use errors::prelude::*; use utils::environment; use super::{WritableBlob, Writer, WriterType}; use self::rust_base58::ToBase58; #[allow(dead_code)] pub struct DefaultWriter { base_dir: PathBuf...
} impl WritableBlob for DefaultWriter { fn append(&mut self, bytes: &[u8]) -> IndyResult<usize> { trace!("append >>>"); let res = self.file.write(bytes) .map_err(map_err_trace!())?; trace!("append <<< {}", res); Ok(res) } fn finalize(&mut self, hash: &[u8]) -...
{ let path = PathBuf::from(&self.base_dir); fs::DirBuilder::new() .recursive(true) .create(tmp_storage_file(id).parent().unwrap())?; let file = File::create(tmp_storage_file(id)) .map_err(map_err_trace!())?; Ok(Box::new(DefaultWriter { b...
identifier_body
parser.py
in the configuration. Recursively searches through config files to find directives Directives should be in the form of a case insensitive regex currently .. todo:: arg should probably be a list .. todo:: arg search currently only supports direct matching. It does not handl...
parsed_in_current
identifier_name
parser.py
, match): """Uses augeas.get to get argument value and interprets result. This also converts all variables and parameters appropriately. """ value = self.aug.get(match) # No need to strip quotes for variables, as apache2ctl already does # this, but we do need to strip ...
random_line_split
parser.py
False) nvh_path = if_mod_path + "directive[1]" self.aug.set(nvh_path, directive) if len(args) == 1: self.aug.set(nvh_path + "/arg", args[0]) else: for i, arg in enumerate(args): self.aug.set("%s/arg[%d]" % (nvh_path, i + 1), arg) def _get_ifm...
split_arg[idx] = ("* [label()=~regexp('%s')]" % self.fnmatch_to_re(split))
conditional_block
parser.py
.partition("=") variables[parts[0]] = parts[2] self.variables = variables def _get_runtime_cfg(self): # pylint: disable=no-self-use """Get runtime configuration info. :returns: stdout from DUMP_RUN_CFG """ try: proc = subprocess.Popen( ...
"""Uses augeas.get to get argument value and interprets result. This also converts all variables and parameters appropriately. """ value = self.aug.get(match) # No need to strip quotes for variables, as apache2ctl already does # this, but we do need to strip quotes for all nor...
identifier_body
settings-dialog.component.ts
import {Component, Inject} from '@angular/core'; import {FormBuilder, FormGroup, Validators} from '@angular/forms'; import {MAT_DIALOG_DATA, MatDialogConfig, MatDialogRef} from '@angular/material'; import {Project} from '../../models/project'; export interface SettingsDialogData { project: Project; } enum MasterSe...
}
return Array.from(this.MASTER_SECTION_LABELS_MAP.keys()); }
random_line_split
settings-dialog.component.ts
import {Component, Inject} from '@angular/core'; import {FormBuilder, FormGroup, Validators} from '@angular/forms'; import {MAT_DIALOG_DATA, MatDialogConfig, MatDialogRef} from '@angular/material'; import {Project} from '../../models/project'; export interface SettingsDialogData { project: Project; } enum MasterSe...
masterSections(): MasterSection[] { return Array.from(this.MASTER_SECTION_LABELS_MAP.keys()); } }
{ this.selectedSection = section; }
identifier_body
settings-dialog.component.ts
import {Component, Inject} from '@angular/core'; import {FormBuilder, FormGroup, Validators} from '@angular/forms'; import {MAT_DIALOG_DATA, MatDialogConfig, MatDialogRef} from '@angular/material'; import {Project} from '../../models/project'; export interface SettingsDialogData { project: Project; } enum MasterSe...
{ selectedSection = MasterSection.GENERAL; readonly generalForm: FormGroup; readonly MasterSection = MasterSection; readonly MASTER_SECTION_LABELS_MAP = MASTER_SECTION_LABELS_MAP; constructor( private readonly dialogRef: MatDialogRef<SettingsDialogComponent>, @Inject(MAT_DIALOG_DATA) dialogData:...
SettingsDialogComponent
identifier_name
CustomEvent.js
(function () { describe('CustomEvent tests - future rule?', function () { context('ignores safe patterns', function () { context(null, function () { var good = 'var a = "CustomEvent";'; it(good, function () { chai.expect(ScanJS.scan(acorn.parse(good, {locations: true}), "/tests/"))...
}); }); }); context('detects dangerous patterns', function () { context(null, function () { var bad = 'obj.addEventListener("cat", function(e) { process(e.detail) }); var event = new CustomEvent("cat", {"detail":{"hazcheeseburger":true}}); obj.dispatchEvent(event);'; it.ski...
context(null, function () { var good = 'good.CustomEvent = "CustomEvent";'; it(good, function () { chai.expect(ScanJS.scan(acorn.parse(good, {locations: true}), "/tests/")).to.be.empty;
random_line_split
gpr1.rs
#[doc = "Register `GPR1` reader"] pub struct R(crate::R<GPR1_SPEC>); impl core::ops::Deref for R { type Target = crate::R<GPR1_SPEC>; #[inline(always)] fn
(&self) -> &Self::Target { &self.0 } } impl From<crate::R<GPR1_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<GPR1_SPEC>) -> Self { R(reader) } } #[doc = "Register `GPR1` writer"] pub struct W(crate::W<GPR1_SPEC>); impl core::ops::Deref for W { type Target = crate::W<GPR1_...
deref
identifier_name
gpr1.rs
#[doc = "Register `GPR1` reader"] pub struct R(crate::R<GPR1_SPEC>); impl core::ops::Deref for R { type Target = crate::R<GPR1_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<GPR1_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<GPR1_SP...
} #[doc = "Register `GPR1` writer"] pub struct W(crate::W<GPR1_SPEC>); impl core::ops::Deref for W { type Target = crate::W<GPR1_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self...
R(reader) }
random_line_split
gpr1.rs
#[doc = "Register `GPR1` reader"] pub struct R(crate::R<GPR1_SPEC>); impl core::ops::Deref for R { type Target = crate::R<GPR1_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<GPR1_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<GPR1_SP...
} impl R { #[doc = "Bits 0:31 - User Data"] #[inline(always)] pub fn dat(&self) -> DAT_R { DAT_R::new((self.bits & 0xffff_ffff) as u32) } } impl W { #[doc = "Bits 0:31 - User Data"] #[inline(always)] pub fn dat(&mut self) -> DAT_W { DAT_W { w: self } } #[doc = "Write...
{ self.w.bits = (self.w.bits & !0xffff_ffff) | (value as u32 & 0xffff_ffff); self.w }
identifier_body
grasp_demo.py
#!/usr/bin/env python import rospy import actionlib from play_motion_msgs.msg import PlayMotionAction, PlayMotionGoal from sensor_msgs.msg import JointState if __name__ == "__main__":
client.wait_for_result(rospy.Duration(5.0)) goal.motion_name = 'pregrasp_demo' goal.skip_planning = True client.send_goal(goal) client.wait_for_result(rospy.Duration(40.0)) goal.motion_name = 'grasp_demo' goal.skip_planning = True client.send_goal(goal) client.wait_for_result(rospy.Duration(80.0)) ...
rospy.init_node("grasp_demo") rospy.loginfo("Waiting for play_motion...") client = actionlib.SimpleActionClient("/play_motion", PlayMotionAction) client.wait_for_server() rospy.loginfo("...connected.") rospy.wait_for_message("/joint_states", JointState) rospy.sleep(3.0) rospy.loginfo("Grasping demo...")...
conditional_block
grasp_demo.py
#!/usr/bin/env python import rospy import actionlib from play_motion_msgs.msg import PlayMotionAction, PlayMotionGoal from sensor_msgs.msg import JointState if __name__ == "__main__": rospy.init_node("grasp_demo") rospy.loginfo("Waiting for play_motion...") client = actionlib.SimpleActionClient("/play_motion", ...
goal.motion_name = 'look_at_object_demo' goal.skip_planning = True client.send_goal(goal) client.wait_for_result(rospy.Duration(5.0)) goal.motion_name = 'pregrasp_demo' goal.skip_planning = True client.send_goal(goal) client.wait_for_result(rospy.Duration(40.0)) goal.motion_name = 'grasp_demo' go...
goal.skip_planning = True client.send_goal(goal) client.wait_for_result(rospy.Duration(15.0))
random_line_split
main.rs
/* Aurélien DESBRIÈRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations // HOF - Higher Order Functions in Rust fn is_odd(n: u32) -> bool { n % 2 == 1 } fn main() { println!("Find the sum of all the squared odd numbers under 1000"); let upper = 1000; // Imperative appr...
} else if is_odd(n_squared) { // Accumulate value, if it's odd acc += n_squared; } } println!("imperative style: {}", acc); // Functional approach let sum_of_squared_odd_numbers: u32 = (0..).map(|n| n * n) // All natural numbers squared .ta...
if n_squared >= upper { // Break loop if exceeded the upper limit break;
random_line_split
main.rs
/* Aurélien DESBRIÈRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations // HOF - Higher Order Functions in Rust fn is_odd(n: u32) -> bool { n % 2 == 1 } fn main() {
// Functional approach let sum_of_squared_odd_numbers: u32 = (0..).map(|n| n * n) // All natural numbers squared .take_while(|&n| n < upper) // Below upper limit .filter(|&n| is_odd(n)) // That are odd .fold(0, |sum, i| sum + i); // Sum them println!("functional s...
println!("Find the sum of all the squared odd numbers under 1000"); let upper = 1000; // Imperative approach // Declare accumulator varialbe let mut acc = 0; // Iterate: 0, 1, 2, ... to infinity for n in 0.. { // Square the number let n_squared = n * n; if n_squared...
identifier_body
main.rs
/* Aurélien DESBRIÈRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations // HOF - Higher Order Functions in Rust fn is_odd(n: u32) -> bool { n % 2 == 1 } fn ma
{ println!("Find the sum of all the squared odd numbers under 1000"); let upper = 1000; // Imperative approach // Declare accumulator varialbe let mut acc = 0; // Iterate: 0, 1, 2, ... to infinity for n in 0.. { // Square the number let n_squared = n * n; if n_squa...
in()
identifier_name
modules.rs
use parking_lot::RwLock; use std::sync::Arc; use crate::language::ty::SourceType; use crate::size::InstanceSize; use crate::utils::GrowableVec; use crate::vm::{ namespace_path, replace_type_param, Candidate, FctDefinitionId, Field, FieldDef, FileId, NamespaceId, TraitDefinitionId, VM, }; use crate::vtable::VT...
(&self, vm: &VM) -> String { namespace_path(vm, self.namespace_id, self.name) } } pub fn find_methods_in_module(vm: &VM, object_type: SourceType, name: Name) -> Vec<Candidate> { let mut ignores = HashSet::new(); let mut module_type = object_type; loop { let module_id = module_type.mod...
name
identifier_name
modules.rs
use parking_lot::RwLock; use std::sync::Arc; use crate::language::ty::SourceType; use crate::size::InstanceSize; use crate::utils::GrowableVec; use crate::vm::{ namespace_path, replace_type_param, Candidate, FctDefinitionId, Field, FieldDef, FileId, NamespaceId, TraitDefinitionId, VM, }; use crate::vtable::VT...
if !ignores.contains(&method.id) { return vec![Candidate { object_type: module_type.clone(), container_type_params: module_type.type_params(), fct_id: method.id, }]; } ...
{ ignores.insert(overrides); }
conditional_block
modules.rs
use parking_lot::RwLock; use std::sync::Arc; use crate::language::ty::SourceType; use crate::size::InstanceSize; use crate::utils::GrowableVec; use crate::vm::{ namespace_path, replace_type_param, Candidate, FctDefinitionId, Field, FieldDef, FileId, NamespaceId, TraitDefinitionId, VM, }; use crate::vtable::VT...
}]; } } } if let Some(parent_class) = module.parent_class.clone() { let type_list = module_type.type_params(); module_type = replace_type_param(vm, parent_class, &type_list, None); } else { break; } ...
container_type_params: module_type.type_params(), fct_id: method.id,
random_line_split
modules.rs
use parking_lot::RwLock; use std::sync::Arc; use crate::language::ty::SourceType; use crate::size::InstanceSize; use crate::utils::GrowableVec; use crate::vm::{ namespace_path, replace_type_param, Candidate, FctDefinitionId, Field, FieldDef, FileId, NamespaceId, TraitDefinitionId, VM, }; use crate::vtable::VT...
} pub fn find_methods_in_module(vm: &VM, object_type: SourceType, name: Name) -> Vec<Candidate> { let mut ignores = HashSet::new(); let mut module_type = object_type; loop { let module_id = module_type.module_id().expect("no module"); let module = vm.modules.idx(module_id); let m...
{ namespace_path(vm, self.namespace_id, self.name) }
identifier_body
instmsg.js
.parse(o.responseText); } catch (e) {return;} startPinging(); } function startPinging() { pingTimer=setInterval("ping()",15000); } function ping() { var id_receiver=userid; var name_receiver=username; var data="op=ping&id_receiver="+id_receiver+"&name_receiver="+name_receiver; var objAjax = YA...
var sentText=String(YAHOO.util.Dom.get(wChat+'_inputBox').value); if (sentText.length < 1) return true; YAHOO.util.Dom.get(wChat+'_inputBox').value=""; Stamp = new Date(); var h = String(Stamp.getHours()); var m = String(Stamp.getMinutes()); var s = String(Stamp.getSeconds()); var day = String...
} function sendLine(wChat) {
random_line_split
instmsg.js
.parse(o.responseText); } catch (e) {return;} startPinging(); } function startPinging() { pingTimer=setInterval("ping()",15000); } function ping() { var id_receiver=userid; var name_receiver=username; var data="op=ping&id_receiver="+id_receiver+"&name_receiver="+name_receiver; var objAjax = YA...
function startChat(id_sender,name_sender) { if (id_sender==userid) return 0; var wChat=id_sender; if (wObjList[wChat]==null) { clearInterval(pingTimer); pingTimer=setInterval("ping()",5000); chat_windows++; getChatContent(wChat,name_sender); } destroyWindow("wUsersList"); } f...
{ try { users = YAHOO.lang.JSON.parse(o.responseText); } catch (e) {return;} displayUsersList(users.list,true); }
identifier_body
instmsg.js
.util.Connect.asyncRequest('POST', 'ajax.server.php?mn=instmsg&'+data, { success: pingResponse }); } function pingResponse(o) { try { chatMsgs = YAHOO.lang.JSON.parse(o.responseText); } catch (e) {return;} for (var i=0;i<chatMsgs.content.length;i++) { var wChat=chatMsgs.content[i].id_sende...
getChatEmoticon
identifier_name
wsgi.py
# This file is part of the Anitya project. # Copyright (C) 2017 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later ...
application = create()
random_line_split
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ }
identifier_body
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}; let mut val = 0u32; for codepoint in s.get().chars().take(4) { let byte = if codepoint as u32 > 0xFF { cx.span_err(expr.span, "fourcc! literal character out of range 0-255"); 0u8 } else { codepoint as u8 }; val = if little { ...
{ cx.span_err(expr.span, "non-literal in fourcc!"); return MRExpr(cx.expr_lit(sp, ast::LitUint(0u64, ast::TyU32))); }
conditional_block
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// FIXME (10872): This is required to prevent an LLVM assert on Windows #[test] fn dummy_test() { }
ast::LitStr(InternedString::new("little"), ast::CookedStr)); contains(cx.cfg().as_slice(), meta) }
random_line_split
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ ident: ast::Ident, span: Span } fn parse_tts(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> (@ast::Expr, Option<Ident>) { let p = &mut parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts.iter() ...
Ident
identifier_name
slack.rs
use std::sync::{Arc, Mutex}; use log::{debug, error, info}; use serde_derive::{Deserialize, Serialize}; use crate::util; use crate::worker; use octobot_lib::errors::*; use octobot_lib::http_client::HTTPClient; use octobot_lib::metrics::Metrics; #[derive(Serialize, Clone, PartialEq, Eq, Debug)] pub struct SlackAttach...
} impl SlackAttachment { pub fn new(text: &str) -> SlackAttachment { SlackAttachment { text: text.to_string(), title: None, title_link: None, color: None, mrkdwn_in: None, } } } pub struct SlackAttachmentBuilder { attachment: Slac...
#[derive(Deserialize)] struct SlackResponse { ok: bool, error: Option<String>,
random_line_split
slack.rs
use std::sync::{Arc, Mutex}; use log::{debug, error, info}; use serde_derive::{Deserialize, Serialize}; use crate::util; use crate::worker; use octobot_lib::errors::*; use octobot_lib::http_client::HTTPClient; use octobot_lib::metrics::Metrics; #[derive(Serialize, Clone, PartialEq, Eq, Debug)] pub struct SlackAttach...
debug!("Sending message to #{}", channel); let res: Result<SlackResponse> = self.client.post("/chat.postMessage", &slack_msg).await; match res { Ok(r) => { if r.ok { info!("Successfully sent slack message to {}", channel) } else ...
{ info!("Skipping duplicate message to {}", channel); return; }
conditional_block
slack.rs
use std::sync::{Arc, Mutex}; use log::{debug, error, info}; use serde_derive::{Deserialize, Serialize}; use crate::util; use crate::worker; use octobot_lib::errors::*; use octobot_lib::http_client::HTTPClient; use octobot_lib::metrics::Metrics; #[derive(Serialize, Clone, PartialEq, Eq, Debug)] pub struct
{ pub text: String, pub title: Option<String>, pub title_link: Option<String>, pub color: Option<String>, pub mrkdwn_in: Option<Vec<String>>, } #[derive(Deserialize)] struct SlackResponse { ok: bool, error: Option<String>, } impl SlackAttachment { pub fn new(text: &str) -> SlackAttach...
SlackAttachment
identifier_name
utils.rs
use brotli; use byteorder::{BigEndian, ReadBytesExt}; use chrono::Local; use env_logger::Builder; use log::{LevelFilter, Record}; use rocket::http::{ContentType, Status}; use rocket::response::{self, Responder}; use rocket::{fairing, Data, Request, Response}; use serde_json; use std::env; use std::io::{self, BufRead, ...
for _ in vector.len()..=pos { vector.push(default); } vector[pos] = value; } /// Wraps a JSON value and implements a responder for it, with support for brotli compression. #[allow(dead_code)] pub struct CompressedJSON(pub serde_json::Value); impl Responder<'static> for CompressedJSON { fn resp...
pub fn insert_at<T: Copy>(vector: &mut Vec<T>, pos: usize, value: T, default: T) {
random_line_split
utils.rs
use brotli; use byteorder::{BigEndian, ReadBytesExt}; use chrono::Local; use env_logger::Builder; use log::{LevelFilter, Record}; use rocket::http::{ContentType, Status}; use rocket::response::{self, Responder}; use rocket::{fairing, Data, Request, Response}; use serde_json; use std::env; use std::io::{self, BufRead, ...
}
{ let uri = request.uri().path(); if !uri.starts_with("/api") && !uri.starts_with("/public") { info!("User request: {}", uri); } }
identifier_body
utils.rs
use brotli; use byteorder::{BigEndian, ReadBytesExt}; use chrono::Local; use env_logger::Builder; use log::{LevelFilter, Record}; use rocket::http::{ContentType, Status}; use rocket::response::{self, Responder}; use rocket::{fairing, Data, Request, Response}; use serde_json; use std::env; use std::io::{self, BufRead, ...
(&self, request: &mut Request, _: &Data) { let uri = request.uri().path(); if !uri.starts_with("/api") && !uri.starts_with("/public") { info!("User request: {}", uri); } } }
on_request
identifier_name
utils.rs
use brotli; use byteorder::{BigEndian, ReadBytesExt}; use chrono::Local; use env_logger::Builder; use log::{LevelFilter, Record}; use rocket::http::{ContentType, Status}; use rocket::response::{self, Responder}; use rocket::{fairing, Data, Request, Response}; use serde_json; use std::env; use std::io::{self, BufRead, ...
else { Ok(Response::build() .status(Status::Ok) .header(ContentType::JSON) .streamed_body(reader) .finalize()) } } } pub fn read_str<'a>(rdr: &'a mut Cursor<&[u8]>) -> Result<&'a str> { let len = (rdr.read_i16::<BigEndian>())....
{ Ok(Response::build() .status(Status::Ok) .header(ContentType::JSON) .raw_header("Content-Encoding", "br") .streamed_body(brotli::CompressorReader::new(reader, 4096, 3, 20)) .finalize()) }
conditional_block
command.rs
use std::fmt::{Debug, Formatter, Error}; use std::path::{PathBuf, Path}; use std::process::{Command, Output}; use std::{env, str}; pub struct TestCommand { cwd: PathBuf, args: Vec<String>, env_vars: Vec<(String, String)>, } impl TestCommand { pub fn new(cwd: &Path, subcommand: &str) -> Self { ...
() -> PathBuf { env::current_exe().unwrap() .parent().unwrap() .join("diesel") } impl Debug for CommandResult { fn fmt(&self, out: &mut Formatter) -> Result<(), Error> { write!(out, "stdout: {}\nstderr: {}", self.stdout(), self.stderr()) } }
path_to_diesel_cli
identifier_name
command.rs
use std::fmt::{Debug, Formatter, Error}; use std::path::{PathBuf, Path}; use std::process::{Command, Output}; use std::{env, str}; pub struct TestCommand { cwd: PathBuf, args: Vec<String>, env_vars: Vec<(String, String)>, } impl TestCommand { pub fn new(cwd: &Path, subcommand: &str) -> Self { ...
CommandResult { output: output, } } fn build_command(&self) -> Command { let mut command = Command::new(path_to_diesel_cli()); command.args(&self.args) .current_dir(&self.cwd); for &(ref k, ref v) in self.env_vars.iter() { command.env(...
let output = self.build_command().output().unwrap();
random_line_split
command.rs
use std::fmt::{Debug, Formatter, Error}; use std::path::{PathBuf, Path}; use std::process::{Command, Output}; use std::{env, str}; pub struct TestCommand { cwd: PathBuf, args: Vec<String>, env_vars: Vec<(String, String)>, } impl TestCommand { pub fn new(cwd: &Path, subcommand: &str) -> Self { ...
fn build_command(&self) -> Command { let mut command = Command::new(path_to_diesel_cli()); command.args(&self.args) .current_dir(&self.cwd); for &(ref k, ref v) in self.env_vars.iter() { command.env(&k, &v); } command } } pub struct CommandResul...
{ let output = self.build_command().output().unwrap(); CommandResult { output: output, } }
identifier_body
task.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const options_1 = require("./options"); class TslintFixTask { constructor(configOrPath, options) { if (options) { this._configOrPath = configOrPath; this._options = options; } else { ...
...path, ...config, }; return { name: options_1.TslintFixName, options }; } } exports.TslintFixTask = TslintFixTask;
random_line_split
task.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const options_1 = require("./options"); class
{ constructor(configOrPath, options) { if (options) { this._configOrPath = configOrPath; this._options = options; } else { this._options = configOrPath; this._configOrPath = null; } } toConfiguration() { const path = ty...
TslintFixTask
identifier_name
task.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const options_1 = require("./options"); class TslintFixTask { constructor(configOrPath, options) { if (options) { this._configOrPath = configOrPath; this._options = options; } else { ...
} exports.TslintFixTask = TslintFixTask;
{ const path = typeof this._configOrPath == 'string' ? { tslintPath: this._configOrPath } : {}; const config = typeof this._configOrPath == 'object' && this._configOrPath !== null ? { tslintConfig: this._configOrPath } : {}; const options = { ...this._options,...
identifier_body
task.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const options_1 = require("./options"); class TslintFixTask { constructor(configOrPath, options) { if (options) { this._configOrPath = configOrPath; this._options = options; } else
} toConfiguration() { const path = typeof this._configOrPath == 'string' ? { tslintPath: this._configOrPath } : {}; const config = typeof this._configOrPath == 'object' && this._configOrPath !== null ? { tslintConfig: this._configOrPath } : {}; const options = { ...
{ this._options = configOrPath; this._configOrPath = null; }
conditional_block
gulpfile.js
const gulp = require('gulp'); const plugins = require('gulp-load-plugins')(); const pngquant = require('imagemin-pngquant'); const browserSync = require('browser-sync'); const jsDir = [ './js/*.js', './js/render/*.js', './js/data/*.js', './js/admin/*.js' ]; gulp.task('css', () => { gul...
}); gulp.watch(jsDir, ['js-watch']); gulp.watch('./scss/*.scss', ['css-watch']); gulp.watch('./img/*.{png,jpg,svg,gif}', ['img-watch']); gulp.watch('./index.html').on('change', browserSync.reload); }); gulp.task('default', ['server']);
browserSync.init({ server: './'
random_line_split
layout_debug.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/. */ //! Supports writing a trace file created during each layout scope //! that can be viewed by an external tool to m...
} }); } } /// Generate a unique ID. This is used for items such as Fragment /// which are often reallocated but represent essentially the /// same data. pub fn generate_unique_debug_id() -> u16 { DEBUG_ID_COUNTER.fetch_add(1, Ordering::SeqCst) as u16 } /// Begin a layout debug trace. If t...
{}
conditional_block
layout_debug.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/. */ //! Supports writing a trace file created during each layout scope //! that can be viewed by an external tool to m...
let mut file = File::create("layout_trace.json").unwrap(); file.write_all(result.as_bytes()).unwrap(); }
let result = json::encode(&root_scope).unwrap();
random_line_split
layout_debug.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/. */ //! Supports writing a trace file created during each layout scope //! that can be viewed by an external tool to m...
() { let mut task_state = STATE_KEY.with(|ref r| r.borrow_mut().take().unwrap()); assert!(task_state.scope_stack.len() == 1); let mut root_scope = task_state.scope_stack.pop().unwrap(); root_scope.post = json::encode(&flow::base(&*task_state.flow_root)).unwrap(); let result = json::encode(&root_sco...
end_trace
identifier_name
install.py
# $Id$ # installer for pmon # Copyright 2014 Matthew Wall from setup import ExtensionInstaller def loader(): return ProcessMonitorInstaller() class
(ExtensionInstaller): def __init__(self): super(ProcessMonitorInstaller, self).__init__( version="0.2", name='pmon', description='Collect and display process memory usage.', author="Matthew Wall", author_email="mwall@users.sourceforge.net", ...
ProcessMonitorInstaller
identifier_name
install.py
# $Id$
# Copyright 2014 Matthew Wall from setup import ExtensionInstaller def loader(): return ProcessMonitorInstaller() class ProcessMonitorInstaller(ExtensionInstaller): def __init__(self): super(ProcessMonitorInstaller, self).__init__( version="0.2", name='pmon', descr...
# installer for pmon
random_line_split
install.py
# $Id$ # installer for pmon # Copyright 2014 Matthew Wall from setup import ExtensionInstaller def loader(): return ProcessMonitorInstaller() class ProcessMonitorInstaller(ExtensionInstaller):
'database_name': 'pmon.sdb', 'driver': 'weedb.sqlite'}}, 'StdReport': { 'pmon': { 'skin': 'pmon', 'HTML_ROOT': 'pmon'}}}, files=[('bin/user', ['bin/user/pmon.py']), ...
def __init__(self): super(ProcessMonitorInstaller, self).__init__( version="0.2", name='pmon', description='Collect and display process memory usage.', author="Matthew Wall", author_email="mwall@users.sourceforge.net", process_services='use...
identifier_body
cfcapp.py
# import time from flask import Flask, json, request from flask.app import setupmethod from threading import Thread class DaemonThread(Thread): def start(self): self.daemon = True super(DaemonThread, self).start() class WSConnection(object): def __init__(self, app, wsid, fid): self.app = app self.fid = fid ...
except: self.logger.debug('RX[%s] got bad JSON: %r' % (vhost, msg)) for handler in self.ws_rx_handlers: handler(vhost, conn, msg) if not self.ws_rx_handlers: self.logger.debug('RX[%s] %r' % (vhost, msg)) def ws_new_connection(self, wsid, fid): ''' New WS connection, track it. ''' ...
try: msg = json.loads(msg)
random_line_split
cfcapp.py
# import time from flask import Flask, json, request from flask.app import setupmethod from threading import Thread class DaemonThread(Thread): def start(self): self.daemon = True super(DaemonThread, self).start() class WSConnection(object): def __init__(self, app, wsid, fid): self.app = app self.fid = fid ...
# Important: do not trust "msg" here as it comes # unverified from browser-side code. Could be nasty junk. msg = here.get('msg', None) if msg[0] == '{' and msg[-1] == '}': # looks like json try: msg = json.loads(msg) except: self.logger.debug('RX[%s] got bad JSON: %r' % (vhost, ...
self.logger.warn('Existing/unexpected WSID') conn = self.ws_new_connection(wsid, fid)
conditional_block