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
main.py
# -*- coding: utf-8 -*- try: import simplejson as json except ImportError: import json import logging import werkzeug from openerp import http from openerp.http import request _logger = logging.getLogger(__name__) class
(http.Controller): _notify_url = '/payment/sips/ipn/' _return_url = '/payment/sips/dpn/' def _get_return_url(self, **post): """ Extract the return URL from the data coming from sips. """ return_url = post.pop('return_url', '') if not return_url: tx_obj = request.registry...
SipsController
identifier_name
main.py
# -*- coding: utf-8 -*- try: import simplejson as json except ImportError: import json import logging import werkzeug from openerp import http from openerp.http import request _logger = logging.getLogger(__name__) class SipsController(http.Controller): _notify_url = '/payment/sips/ipn/' _return_url...
return res @http.route([ '/payment/sips/ipn/'], type='http', auth='none', methods=['POST']) def sips_ipn(self, **post): """ Sips IPN. """ self.sips_validate_data(**post) return '' @http.route([ '/payment/sips/dpn'], type='http', auth="none", methods...
_logger.warning('Sips: data are corrupted')
conditional_block
main.py
# -*- coding: utf-8 -*- try: import simplejson as json except ImportError: import json import logging import werkzeug from openerp import http from openerp.http import request _logger = logging.getLogger(__name__) class SipsController(http.Controller): _notify_url = '/payment/sips/ipn/' _return_url...
'/payment/sips/dpn'], type='http', auth="none", methods=['POST']) def sips_dpn(self, **post): """ Sips DPN """ return_url = self._get_return_url(**post) self.sips_validate_data(**post) return werkzeug.utils.redirect(return_url)
@http.route([
random_line_split
prelude.rs
// Copyright 2018 Developers of the Rand project. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed /...
//! ``` //! use rand::prelude::*; //! # let mut r = StdRng::from_rng(thread_rng()).unwrap(); //! # let _: f32 = r.gen(); //! ``` #[doc(no_inline)] pub use crate::distributions::Distribution; #[cfg(feature = "small_rng")] #[doc(no_inline)] pub use crate::rngs::SmallRng; #[cfg(feature = "std_rng")] #[doc(no_inline)] pub...
//! common items. Unlike the standard prelude, the contents of this module must //! be imported manually: //!
random_line_split
whiteboarding.js
/* Introduction/rules/advice: -- You will have 15 minutes to solve a randomly-selected problem as well as you can. If you finish early, your interviewer may tweak the problem or ask related questions. After your 15 minutes, the interviewer and/or listeners will have 5 minutes to offer feedback on your presentation. ...
// Assuming each month has 31 days and begins on Sunday: function getDates(targetDayName) { var weekdayNum = weekdays.indexOf(targetDayName); var date = weekdayNum+1; var result = []; while (date <= 31) { result.push(date); date+=7; } return result; } // Now generalize: provide extra paramete...
random_line_split
whiteboarding.js
/* Introduction/rules/advice: -- You will have 15 minutes to solve a randomly-selected problem as well as you can. If you finish early, your interviewer may tweak the problem or ask related questions. After your 15 minutes, the interviewer and/or listeners will have 5 minutes to offer feedback on your presentation. ...
(arrA,arrB) { // Preserves originals, uses 2 counters var result = []; var a=0,b=0; while (a < arrA.length || b < arrB.length) { if (a >= arrA.length) result.push(arrB[b++]); else if (b >= arrB.length) result.push(arrA[a++]); else if (arrA[a] < arrB[b]) result.push(arrA[a++]); else ...
merge2
identifier_name
whiteboarding.js
/* Introduction/rules/advice: -- You will have 15 minutes to solve a randomly-selected problem as well as you can. If you finish early, your interviewer may tweak the problem or ask related questions. After your 15 minutes, the interviewer and/or listeners will have 5 minutes to offer feedback on your presentation. ...
// EASIER: Capitalize the first letter of any word, without exceptions // IMPROVEMENT: ?? // VARIANT: Given a paragraph string, capitalize all sentences correctly. //---4--- // Given a string of words, decide which word occurs most often. function mostFreqWord(str) { var words = str.split(' '); var counter =...
{ var words = str.split(' '); return words.map(titleizeWord).join(' '); }
identifier_body
test_create_embed.rs
#[macro_use] extern crate serde_json; extern crate serenity; use serde_json::Value; use serenity::model::{Embed, EmbedField, EmbedImage}; use serenity::utils::builder::CreateEmbed; use serenity::utils::Colour; #[test] fn
() { let embed = Embed { author: None, colour: Colour::new(0xFF0011), description: Some("This is a test description".to_owned()), fields: vec![ EmbedField { inline: false, name: "a".to_owned(), value: "b".to_owned(), ...
test_from_embed
identifier_name
test_create_embed.rs
#[macro_use] extern crate serde_json; extern crate serenity; use serde_json::Value; use serenity::model::{Embed, EmbedField, EmbedImage}; use serenity::utils::builder::CreateEmbed; use serenity::utils::Colour; #[test] fn test_from_embed() { let embed = Embed { author: None, colour: Colour::new(0xF...
}
random_line_split
test_create_embed.rs
#[macro_use] extern crate serde_json; extern crate serenity; use serde_json::Value; use serenity::model::{Embed, EmbedField, EmbedImage}; use serenity::utils::builder::CreateEmbed; use serenity::utils::Colour; #[test] fn test_from_embed()
{ let embed = Embed { author: None, colour: Colour::new(0xFF0011), description: Some("This is a test description".to_owned()), fields: vec![ EmbedField { inline: false, name: "a".to_owned(), value: "b".to_owned(), ...
identifier_body
eventTimeSpanFilterEnSpec.js
/* * This file is part of MystudiesMyteaching application. * * MystudiesMyteaching application is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any l...
module(function ($provide) { $provide.constant('StateService', { getStateFromDomain: function () { } }); $provide.constant('LanguageService', { getLocale: function () { return 'en'; } }); }); }); beforeEach(inject(function ($filter) { eventTimeSpanFilter = $filter('eventTimeSpan'); })); ...
random_line_split
pyunit_create_frame.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- from collections import defaultdict import random import sys sys.path.insert(1, "../../") import h2o from h2o.exceptions import H2OValueError from h2o.utils.compatibility import viewvalues from tests import pyunit_utils def create_frame_test(): """Test `h2o.create_fr...
(frame, freal, fenum, fint, fbin, ftime, fstring): # The server does not report columns as binary -- instead they are integer. fint += fbin fbin = 0 type_counts = defaultdict(int) for ft in viewvalues(frame.types): type_counts[ft] += 1 print("Created table wit...
assert_coltypes
identifier_name
pyunit_create_frame.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- from collections import defaultdict import random import sys sys.path.insert(1, "../../") import h2o from h2o.exceptions import H2OValueError from h2o.utils.compatibility import viewvalues from tests import pyunit_utils def create_frame_test(): """Test `h2o.create_fr...
f1 = h2o.create_frame(rows=10, cols=1000, real_fraction=1) assert_coltypes(f1, 1, 0, 0, 0, 0, 0) f2 = h2o.create_frame(rows=10, cols=1000, binary_fraction=0.5, time_fraction=0.5) assert_coltypes(f2, 0, 0, 0, 0.5, 0.5, 0) f3 = h2o.create_frame(rows=10, cols=1000, string_fraction=0.2, time_fractio...
fint += fbin fbin = 0 type_counts = defaultdict(int) for ft in viewvalues(frame.types): type_counts[ft] += 1 print("Created table with column counts: {%s}" % ", ".join("%s: %d" % t for t in type_counts.items())) for ct in ["real", "enum", "int", "time", "string"]: ...
identifier_body
pyunit_create_frame.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- from collections import defaultdict import random import sys sys.path.insert(1, "../../") import h2o from h2o.exceptions import H2OValueError from h2o.utils.compatibility import viewvalues from tests import pyunit_utils def create_frame_test(): """Test `h2o.create_fr...
for ft in viewvalues(frame.types): type_counts[ft] += 1 print("Created table with column counts: {%s}" % ", ".join("%s: %d" % t for t in type_counts.items())) for ct in ["real", "enum", "int", "time", "string"]: assert abs(type_counts[ct] - locals()["f" + ct] * frame.ncol...
random_line_split
pyunit_create_frame.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- from collections import defaultdict import random import sys sys.path.insert(1, "../../") import h2o from h2o.exceptions import H2OValueError from h2o.utils.compatibility import viewvalues from tests import pyunit_utils def create_frame_test(): """Test `h2o.create_fr...
create_frame_test()
conditional_block
mod.rs
#[cfg(test)] pub mod mocks; #[cfg(test)] mod spec_tests; use crate::{ cart::Cart, ppu::{control_register::IncrementAmount, write_latch::LatchState}, }; use std::cell::Cell; pub trait IVram: Default { fn write_ppu_addr(&self, latch_state: LatchState); fn write_ppu_data<C: Cart>(&mut self, val: u8, inc...
(&self, latch_state: LatchState) { // Addresses greater than 0x3fff are mirrored down match latch_state { LatchState::FirstWrite(val) => { // t: ..FEDCBA ........ = d: ..FEDCBA // t: .X...... ........ = 0 let t = self.t.get() & 0b1000_0000_1111...
write_ppu_addr
identifier_name
mod.rs
#[cfg(test)] pub mod mocks; #[cfg(test)] mod spec_tests; use crate::{ cart::Cart, ppu::{control_register::IncrementAmount, write_latch::LatchState}, }; use std::cell::Cell; pub trait IVram: Default { fn write_ppu_addr(&self, latch_state: LatchState); fn write_ppu_data<C: Cart>(&mut self, val: u8, inc...
IncrementAmount::One => self.address.set(self.address.get() + 1), IncrementAmount::ThirtyTwo => self.address.set(self.address.get() + 32), } val } fn ppu_data<C: Cart>(&self, cart: &C) -> u8 { let addr = self.address.get(); let val = self.read(addr, cart)...
} fn read_ppu_data<C: Cart>(&self, inc_amount: IncrementAmount, cart: &C) -> u8 { let val = self.ppu_data(cart); match inc_amount {
random_line_split
mod.rs
#[cfg(test)] pub mod mocks; #[cfg(test)] mod spec_tests; use crate::{ cart::Cart, ppu::{control_register::IncrementAmount, write_latch::LatchState}, }; use std::cell::Cell; pub trait IVram: Default { fn write_ppu_addr(&self, latch_state: LatchState); fn write_ppu_data<C: Cart>(&mut self, val: u8, inc...
fn fine_y_increment(&self) { let v = self.address.get(); let v = if v & 0x7000 != 0x7000 { // if fine Y < 7, increment fine Y v + 0x1000 } else { // if fine Y = 0... let v = v & !0x7000; // let y = coarse Y let mut y...
{ let v = self.address.get(); // The coarse X component of v needs to be incremented when the next tile is reached. Bits // 0-4 are incremented, with overflow toggling bit 10. This means that bits 0-4 count from 0 // to 31 across a single nametable, and bit 10 selects the current nameta...
identifier_body
RoomList.js
/* Copyright 2015 OpenMarket Ltd
http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions ...
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
random_line_split
file_operations.py
# -*- coding: utf-8 -*- import os import grp import tempfile from django.conf import settings from utilities import encoding import shutil import zipfile gid = None if (settings.USEPRAKTOMATTESTER): gid = grp.getgrnam('praktomat').gr_gid def makedirs(path): if os.path.exists(path):
else: (head, tail) = os.path.split(path) makedirs(head) os.mkdir(path) if (gid): os.chown(path, -1, gid) os.chmod(path, 0o770) def create_file(path, content, override=True, binary=False): """ """ dirname = os.path.dirname(path) if not os.path.exists...
return
conditional_block
file_operations.py
# -*- coding: utf-8 -*-
from django.conf import settings from utilities import encoding import shutil import zipfile gid = None if (settings.USEPRAKTOMATTESTER): gid = grp.getgrnam('praktomat').gr_gid def makedirs(path): if os.path.exists(path): return else: (head, tail) = os.path.split(path) makedirs(he...
import os import grp import tempfile
random_line_split
file_operations.py
# -*- coding: utf-8 -*- import os import grp import tempfile from django.conf import settings from utilities import encoding import shutil import zipfile gid = None if (settings.USEPRAKTOMATTESTER): gid = grp.getgrnam('praktomat').gr_gid def makedirs(path): if os.path.exists(path): return else: ...
(from_path, to_path, to_is_directory=False, override=True): """ """ if to_is_directory: to_path = os.path.join(to_path, os.path.basename(from_path)) with open(from_path, "rb") as fd: create_file(to_path, fd.read(), override=override, binary=True) def create_tempfolder(path): makedirs(p...
copy_file
identifier_name
file_operations.py
# -*- coding: utf-8 -*- import os import grp import tempfile from django.conf import settings from utilities import encoding import shutil import zipfile gid = None if (settings.USEPRAKTOMATTESTER): gid = grp.getgrnam('praktomat').gr_gid def makedirs(path): if os.path.exists(path): return else: ...
def unpack_zipfile_to(zipfilename, to_path, override_cb=None, file_cb=None): """ Extracts a zipfile to the given location, trying to safeguard against wrong paths The override_cb is called for every file that overwrites an existing file, with the name of the file in the archive as the parameter. ...
pass
identifier_body
external_reference.rs
use std::str::FromStr; use thiserror::Error; use crate::publications::reference_type; #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct ExternalReference(reference_type::ReferenceType, String); #[derive(Error, Debug)] pub enum ConversionError { #[error("No prefix for the reference id: `{0}`")] Missing...
(&self) -> String { format!("{}:{}", self.0.to_string(), self.0) } } impl FromStr for ExternalReference { type Err = ConversionError; fn from_str(raw: &str) -> Result<ExternalReference, Self::Err> { let parts: Vec<&str> = raw.split(":").collect(); if parts.len() == 1 { ...
to_string
identifier_name
external_reference.rs
use std::str::FromStr; use thiserror::Error; use crate::publications::reference_type; #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct ExternalReference(reference_type::ReferenceType, String); #[derive(Error, Debug)] pub enum ConversionError { #[error("No prefix for the reference id: `{0}`")] Missing...
pub fn to_string(&self) -> String { format!("{}:{}", self.0.to_string(), self.0) } } impl FromStr for ExternalReference { type Err = ConversionError; fn from_str(raw: &str) -> Result<ExternalReference, Self::Err> { let parts: Vec<&str> = raw.split(":").collect(); if parts.len...
{ &self.1 }
identifier_body
external_reference.rs
use std::str::FromStr; use thiserror::Error; use crate::publications::reference_type; #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct ExternalReference(reference_type::ReferenceType, String); #[derive(Error, Debug)] pub enum ConversionError { #[error("No prefix for the reference id: `{0}`")] Missing...
if parts.len() > 2 { return Err(Self::Err::InvalidFormat(raw.to_string())); } let ref_type: reference_type::ReferenceType = parts[0].parse()?; Ok(ExternalReference(ref_type, parts[1].to_string())) } } impl From<ExternalReference> for String { fn from(raw: ExternalR...
return Err(Self::Err::MissingPrefix(raw.to_string())); }
random_line_split
external_reference.rs
use std::str::FromStr; use thiserror::Error; use crate::publications::reference_type; #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct ExternalReference(reference_type::ReferenceType, String); #[derive(Error, Debug)] pub enum ConversionError { #[error("No prefix for the reference id: `{0}`")] Missing...
let ref_type: reference_type::ReferenceType = parts[0].parse()?; Ok(ExternalReference(ref_type, parts[1].to_string())) } } impl From<ExternalReference> for String { fn from(raw: ExternalReference) -> String { format!("{}:{}", raw.0, raw.1) } }
{ return Err(Self::Err::InvalidFormat(raw.to_string())); }
conditional_block
Obj.py
# -*- coding:utf-8 -*- # # Import OBJ files # # External dependencies import os import numpy as np import MeshToolkit as mtk # Import a mesh from a OBJ / SMF file def
( filename ) : # Initialisation vertices = [] faces = [] normals = [] colors = [] texcoords = [] material = "" # Read each line in the file for line in open( filename, "r" ) : # Empty line / Comment if line.isspace() or line.startswith( '#' ) : continue # Split values in the line values = line.split() ...
ReadObj
identifier_name
Obj.py
# -*- coding:utf-8 -*- # # Import OBJ files # # External dependencies import os import numpy as np import MeshToolkit as mtk # Import a mesh from a OBJ / SMF file def ReadObj( filename ) : # Initialisation vertices = [] faces = [] normals = [] colors = [] texcoords = [] material = "" # Read each line in the ...
# Vertex if values[0] == 'v' : vertices.append( list( map( float, values[1:4] ) ) ) # Face (index starts at 1) elif values[0] == 'f' : faces.append( list( map( int, [ (v.split('/'))[0] for v in values[1:4] ] ) ) ) # Normal elif values[0] == 'vn' : normals.append( list( map( float, values[1:4] ) ) )...
random_line_split
Obj.py
# -*- coding:utf-8 -*- # # Import OBJ files # # External dependencies import os import numpy as np import MeshToolkit as mtk # Import a mesh from a OBJ / SMF file def ReadObj( filename ) : # Initialisation vertices = [] faces = [] normals = [] colors = [] texcoords = [] material = "" # Read each line in the ...
# Color elif values[0] == 'c' : colors.append( list( map( float, values[1:4] ) ) ) # Texture elif values[0] == 'vt' : texcoords.append( list( map( float, values[1:3] ) ) ) # Texture filename elif values[0] == 'mtllib' : material = values[1] # Remap face indices faces = np.array( faces ) - 1 # R...
normals.append( list( map( float, values[1:4] ) ) )
conditional_block
Obj.py
# -*- coding:utf-8 -*- # # Import OBJ files # # External dependencies import os import numpy as np import MeshToolkit as mtk # Import a mesh from a OBJ / SMF file def ReadObj( filename ) : # Initialisation
vertices = [] faces = [] normals = [] colors = [] texcoords = [] material = "" # Read each line in the file for line in open( filename, "r" ) : # Empty line / Comment if line.isspace() or line.startswith( '#' ) : continue # Split values in the line values = line.split() # Vertex if values[0] == 'v' :...
identifier_body
main.rs
use std::collections::{HashMap}; use std::io::{self, BufRead}; use lazy_regex::regex; use regex::Regex; type H = HashMap<Header, Vec<(String, String, String)>>; #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum Header { Versioned { package: String, version: String }, Missing { package: String }, } fn main()...
for (header, packages) in tests { for (package, version, component) in packages { printer(" ", &package, false, &version, &component, &header); } } if !benches.is_empty() { println!("\nBENCHMARKS\n"); } for (header, packages) in benches { for (package...
{ println!("\nTESTS\n"); }
conditional_block
main.rs
use std::collections::{HashMap}; use std::io::{self, BufRead}; use lazy_regex::regex; use regex::Regex; type H = HashMap<Header, Vec<(String, String, String)>>; #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum Header { Versioned { package: String, version: String }, Missing { package: String }, } fn main()...
fn is_reg_match(s: &str, r: &Regex) -> bool { r.captures(s).is_some() }
{ (*h.entry(header).or_insert_with(Vec::new)).push(( package.to_owned(), version.to_owned(), component.to_owned(), )); }
identifier_body
main.rs
use std::collections::{HashMap}; use std::io::{self, BufRead}; use lazy_regex::regex; use regex::Regex; type H = HashMap<Header, Vec<(String, String, String)>>; #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum Header { Versioned { package: String, version: String }, Missing { package: String }, } fn main()...
} for (header, packages) in benches { for (package, version, component) in packages { printer(" ", &package, false, &version, &component, &header); } } } fn printer( indent: &str, package: &str, lt0: bool, version: &str, component: &str, header: &Heade...
} if !benches.is_empty() { println!("\nBENCHMARKS\n");
random_line_split
main.rs
use std::collections::{HashMap}; use std::io::{self, BufRead}; use lazy_regex::regex; use regex::Regex; type H = HashMap<Header, Vec<(String, String, String)>>; #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum Header { Versioned { package: String, version: String }, Missing { package: String }, } fn main()...
(h: &mut H, header: Header, package: &str, version: &str, component: &str) { (*h.entry(header).or_insert_with(Vec::new)).push(( package.to_owned(), version.to_owned(), component.to_owned(), )); } fn is_reg_match(s: &str, r: &Regex) -> bool { r.captures(s).is_some() }
insert
identifier_name
issue-23485.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 ...
{ value: i32 } impl Iterator for Counter { type Item = Token; fn next(&mut self) -> Option<Token> { let x = self.value; self.value += 1; Some(Token { value: x }) } } fn main() { let mut x: Box<Iterator<Item=Token>> = Box::new(Counter { value: 22 }); assert_eq!(x.next(...
Token
identifier_name
issue-23485.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 ...
} fn main() { let mut x: Box<Iterator<Item=Token>> = Box::new(Counter { value: 22 }); assert_eq!(x.next().unwrap().value, 22); }
{ let x = self.value; self.value += 1; Some(Token { value: x }) }
identifier_body
issue-23485.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 ...
self.value += 1; Some(Token { value: x }) } } fn main() { let mut x: Box<Iterator<Item=Token>> = Box::new(Counter { value: 22 }); assert_eq!(x.next().unwrap().value, 22); }
type Item = Token; fn next(&mut self) -> Option<Token> { let x = self.value;
random_line_split
InPlaceEdit.js
YUI.add("inputex-inplaceedit", function(Y){ var lang = Y.Lang;//, Event = YAHOO.util.Event, Dom = YAHOO.util.Dom, CSS_PREFIX = 'inputEx-InPlaceEdit-'; /** * Meta field providing in place editing (the editor appears when you click on the formatted value). * @class inputEx.InPlaceEdit * @extends inputEx.Field *...
this.disabled = true; inputEx.sn(this.formattedContainer, {className: 'inputEx-InPlaceEdit-visu-disable'}); }, /** * Display the editor */ openEditor: function() { if(this.disabled) return; var value = this.getValue(); this.editorContainer.style.display = ''; this.f...
* Override disable to Disable openEditor */ disable: function(){
random_line_split
queue.rs
use collections::vec::Vec; /// A FIFO Queue pub struct Queue<T> { /// The queue as a vector pub vec: Vec<T>, } impl<T> Queue<T> { /// Create new queue pub fn new() -> Self { Queue { vec: Vec::new() } }
/// Push element to queue pub fn push(&mut self, value: T) { self.vec.push(value); } /// Pop the last element pub fn pop(&mut self) -> Option<T> { if !self.vec.is_empty() { Some(self.vec.remove(0)) } else { None } } /// Get the length...
random_line_split
queue.rs
use collections::vec::Vec; /// A FIFO Queue pub struct Queue<T> { /// The queue as a vector pub vec: Vec<T>, } impl<T> Queue<T> { /// Create new queue pub fn new() -> Self { Queue { vec: Vec::new() } } /// Push element to queue pub fn
(&mut self, value: T) { self.vec.push(value); } /// Pop the last element pub fn pop(&mut self) -> Option<T> { if !self.vec.is_empty() { Some(self.vec.remove(0)) } else { None } } /// Get the length of the queue pub fn len(&self) -> usize ...
push
identifier_name
queue.rs
use collections::vec::Vec; /// A FIFO Queue pub struct Queue<T> { /// The queue as a vector pub vec: Vec<T>, } impl<T> Queue<T> { /// Create new queue pub fn new() -> Self { Queue { vec: Vec::new() } } /// Push element to queue pub fn push(&mut self, value: T) { self.vec.p...
} /// Get the length of the queue pub fn len(&self) -> usize { self.vec.len() } } impl<T> Clone for Queue<T> where T: Clone { fn clone(&self) -> Self { Queue { vec: self.vec.clone() } } }
{ None }
conditional_block
queue.rs
use collections::vec::Vec; /// A FIFO Queue pub struct Queue<T> { /// The queue as a vector pub vec: Vec<T>, } impl<T> Queue<T> { /// Create new queue pub fn new() -> Self
/// Push element to queue pub fn push(&mut self, value: T) { self.vec.push(value); } /// Pop the last element pub fn pop(&mut self) -> Option<T> { if !self.vec.is_empty() { Some(self.vec.remove(0)) } else { None } } /// Get the leng...
{ Queue { vec: Vec::new() } }
identifier_body
getFile.py
#!/usr/bin/env python # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Licen...
from _cffi_backend import callback # noqa F401 class GetFilePrinterProcessor(PyProcessor): # noqa F405 def __init__(self, minifi, flow): PyProcessor.__init__(self, minifi, flow) # noqa F405 self._callback = None def _onTriggerCallback(self): def onTrigger(session, context): ...
import ctypes # noqa F401 import sys
random_line_split
getFile.py
#!/usr/bin/env python # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Licen...
return CALLBACK(onTrigger) # noqa F405 parser = ArgumentParser() parser.add_argument("-s", "--dll", dest="dll_file", help="DLL filename", metavar="FILE") parser.add_argument("-n", "--nifi", dest="nifi_instance", help="NiFi Instance") parser.add_argument("-i", "--inp...
print("transfer to relationship " + target_relationship + " failed")
conditional_block
getFile.py
#!/usr/bin/env python # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Licen...
(self, minifi, flow): PyProcessor.__init__(self, minifi, flow) # noqa F405 self._callback = None def _onTriggerCallback(self): def onTrigger(session, context): flow_file = self.get(session, context) if flow_file: if flow_file.add_attribute("python_te...
__init__
identifier_name
getFile.py
#!/usr/bin/env python # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Licen...
parser = ArgumentParser() parser.add_argument("-s", "--dll", dest="dll_file", help="DLL filename", metavar="FILE") parser.add_argument("-n", "--nifi", dest="nifi_instance", help="NiFi Instance") parser.add_argument("-i", "--input", dest="input_port", help...
def __init__(self, minifi, flow): PyProcessor.__init__(self, minifi, flow) # noqa F405 self._callback = None def _onTriggerCallback(self): def onTrigger(session, context): flow_file = self.get(session, context) if flow_file: if flow_file.add_attribut...
identifier_body
fortranfile.py
# Copyright 2008-2010 Neil Martinsen-Burrell # # 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, copy, modify, merge, publ...
length of the following data in bytes, then the data itself, then the same integer as before. Examples -------- To use the default endian and precision settings, one can just do:: >>> f = FortranFile('filename') >>> x = f.readReals() One can read arrays with varying precisions:: >>> f = FortranFile('file...
the Fortran runtime as a sequence of records. Each record consists of an integer (of the default size [usually 32 or 64 bits]) giving the
random_line_split
fortranfile.py
# Copyright 2008-2010 Neil Martinsen-Burrell # # 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, copy, modify, merge, publ...
def writeReals(self, reals, prec='f'): """Write an array of floats in given precision Parameters ---------- reals : array Data to write prec` : string Character code for the precision to use in writing """ if prec not in self._real_p...
"""Read in an array of real numbers. Parameters ---------- prec : character, optional Specify the precision of the array using character codes from Python's struct module. Possible values are 'd' and 'f'. """ _numpy_precisio...
identifier_body
fortranfile.py
# Copyright 2008-2010 Neil Martinsen-Burrell # # 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, copy, modify, merge, publ...
(self,c): """Set endian to big (c='>') or little (c='<') or native (c='=') :Parameters: `c` : string The endian-ness to use when reading from this file. """ if c in '<>@=': if c == '@': c = '=' self._endian = c else: ...
_set_endian
identifier_name
fortranfile.py
# Copyright 2008-2010 Neil Martinsen-Burrell # # 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, copy, modify, merge, publ...
else: raise ValueError('Cannot set header precision') def _get_header_prec(self): return self._header_prec HEADER_PREC = property(fset=_set_header_prec, fget=_get_header_prec, doc="Possible header precisions are 'h', 'i', 'l', 'q...
self._header_prec = prec
conditional_block
hashmap.rs
#[macro_use] extern crate log; extern crate rusty_raft; extern crate rand; extern crate rustc_serialize; extern crate env_logger; use rand::{thread_rng, Rng}; use rusty_raft::server::{start_server, ServerHandle}; use rusty_raft::client::{RaftConnection}; use rusty_raft::client::state_machine::{ StateMachine, RaftS...
raft_db.add_server(*id, info.get(id).cloned().unwrap().addr).unwrap(); } Cluster { servers: servers, cluster: info.clone(), client: raft_db } } fn add_server(&mut self, id: u64, addr: SocketAddr) { if self.cluster.contains_key(&id) { println!("Server {} is alrea...
{ continue; }
conditional_block
hashmap.rs
#[macro_use] extern crate log; extern crate rusty_raft; extern crate rand; extern crate rustc_serialize; extern crate env_logger; use rand::{thread_rng, Rng}; use rusty_raft::server::{start_server, ServerHandle}; use rusty_raft::client::{RaftConnection}; use rusty_raft::client::state_machine::{ StateMachine, RaftS...
// TODO (sydli): make this function less shit fn process_command(&mut self, words: Vec<String>) -> bool { if words.len() == 0 { return true; } let ref cmd = words[0]; if *cmd == String::from("get") { if words.len() <= 1 { return false; } words.get(1).ma...
{ json::encode(&Put {key:key, value:value}) .map_err(serialize_error) .and_then(|buffer| self.raft.command(&buffer.as_bytes())) }
identifier_body
hashmap.rs
#[macro_use] extern crate log; extern crate rusty_raft; extern crate rand; extern crate rustc_serialize; extern crate env_logger; use rand::{thread_rng, Rng}; use rusty_raft::server::{start_server, ServerHandle}; use rusty_raft::client::{RaftConnection}; use rusty_raft::client::state_machine::{ StateMachine, RaftS...
<T: Debug>(error: T) -> RaftError { RaftError::ClientError( format!("Couldn't serialize object. Error: {:?}", error)) } fn deserialize_error <T: Debug>(error: T) -> RaftError { RaftError::ClientError( format!("Couldn't deserialize buffer. Error: {:?}", error)) } fn key_error(k...
serialize_error
identifier_name
hashmap.rs
#[macro_use] extern crate log; extern crate rusty_raft; extern crate rand; extern crate rustc_serialize; extern crate env_logger; use rand::{thread_rng, Rng}; use rusty_raft::server::{start_server, ServerHandle}; use rusty_raft::client::{RaftConnection}; use rusty_raft::client::state_machine::{ StateMachine, RaftS...
} impl StateMachine for RaftHashMap { fn command (&mut self, buffer: &[u8]) ->Result<(), RaftError> { str::from_utf8(buffer) .map_err(deserialize_error) .and_then(|string| json::decode(&string) .map_err(deserialize_error)) .map(|put: P...
fn key_error(key: &String) -> RaftError { RaftError::ClientError(format!("Couldn't find key {}", key))
random_line_split
iframe-messaging-client.js
/** * Copyright 2016 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...
* Map messageType keys to observables to be fired when messages of that * type are received. * @private {!Object} */ this.observableFor_ = map(); this.setupEventListener_(); } /** * Make an event listening request to the host window. * * @param {string} requestType The type of ...
this.hostWindow_ = win.parent; /** @private {?string} */ this.sentinel_ = null; /**
random_line_split
iframe-messaging-client.js
/** * Copyright 2016 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...
/** * Send a postMessage to Host Window * @param {string} type The type of message to send. * @param {JsonObject=} opt_payload The payload of message to send. */ sendMessage(type, opt_payload) { this.hostWindow_.postMessage/*OK*/( serializeMessage( type, dev().assertString(t...
{ // NOTE : no validation done here. any callback can be register // for any callback, and then if that message is received, this // class *will execute* that callback return this.getOrCreateObservableFor_(messageType).add(callback); }
identifier_body
iframe-messaging-client.js
/** * Copyright 2016 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...
{ /** * @param {!Window} win A window object. */ constructor(win) { /** @private {!Window} */ this.win_ = win; /** @private {?string} */ this.rtvVersion_ = getMode().rtvVersion || null; /** @private {!Window} */ this.hostWindow_ = win.parent; /** @private {?string} */ this.s...
IframeMessagingClient
identifier_name
iframe-messaging-client.js
/** * Copyright 2016 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...
this.fireObservable_(message['type'], message); }); } /** * @param {!Window} win */ setHostWindow(win) { this.hostWindow_ = win; } /** * @param {string} sentinel */ setSentinel(sentinel) { this.sentinel_ = sentinel; } /** * @param {string} messageType * @return {...
{ return; }
conditional_block
manifest.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or
// Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along w...
// (at your option) any later version.
random_line_split
manifest.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
(manifest: &Manifest) -> Result<String, String> { serde_json::to_string_pretty(manifest).map_err(|e| format!("{:?}", e)) }
serialize_manifest
identifier_name
manifest.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
pub fn serialize_manifest(manifest: &Manifest) -> Result<String, String> { serde_json::to_string_pretty(manifest).map_err(|e| format!("{:?}", e)) }
{ serde_json::from_str::<Manifest>(&manifest).map_err(|e| format!("{:?}", e)) // TODO [todr] Manifest validation (especialy: id (used as path)) }
identifier_body
graphviz.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 ...
} impl<'a, 'tcx> dot::GraphWalk<'a, Node<'a>, Edge<'a>> for DataflowLabeller<'a, 'tcx> { fn nodes(&self) -> dot::Nodes<'a, Node<'a>> { self.inner.nodes() } fn edges(&self) -> dot::Edges<'a, Edge<'a>> { self.inner.edges() } fn source(&self, edge: &Edge<'a>) -> Node<'a> { self.inner.source(edge) } fn ta...
{ self.inner.edge_label(e) }
identifier_body
graphviz.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 ...
(&self, e: EntryOrExit, cfgidx: CFGIndex) -> String { let dfcx = &self.analysis_data.move_data.dfcx_assign; let assign_index_to_path = |assign_index| { let move_data = &self.analysis_data.move_data.move_data; let assignments = move_data.var_assignments.borrow(); let a...
dataflow_assigns_for
identifier_name
graphviz.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 ...
fn dataflow_for_variant(&self, e: EntryOrExit, n: &Node, v: Variant) -> String { let cfgidx = n.val0(); match v { Loans => self.dataflow_loans_for(e, cfgidx), Moves => self.dataflow_moves_for(e, cfgidx), Assigns => self.dataflow_assigns_for(e, cfgidx), ...
} sets }
random_line_split
character-details-achievements.ts
// Services import { Component, Inject, Input, OnInit, OnChanges, AfterViewInit } from 'angular2/core'; import { CharacterService } from '../../../../service/character-service'; import { AchievementModel } from '../../../../model/achievement'; // Sub components import { NgFor } from 'angular2/common'; import { Sortabl...
}
}
random_line_split
character-details-achievements.ts
// Services import { Component, Inject, Input, OnInit, OnChanges, AfterViewInit } from 'angular2/core'; import { CharacterService } from '../../../../service/character-service'; import { AchievementModel } from '../../../../model/achievement'; // Sub components import { NgFor } from 'angular2/common'; import { Sortabl...
ngOnChanges (changes : {}) : any { // This is needed so that on character change all items are removed and then readded from scratch this.achievements = []; setTimeout(() => { this.characterService.getAchievementsForCharacter(this.characterId) .subscribe((achi...
{ this.listener = (event : Event) => { let cards : NodeListOf<Element> = document.getElementsByClassName('character-details-achievement-card'); for (let i : number = 0; i < cards.length; i++) { let cardElement : HTMLElement = <HTMLElement>cards.item(i); ca...
identifier_body
character-details-achievements.ts
// Services import { Component, Inject, Input, OnInit, OnChanges, AfterViewInit } from 'angular2/core'; import { CharacterService } from '../../../../service/character-service'; import { AchievementModel } from '../../../../model/achievement'; // Sub components import { NgFor } from 'angular2/common'; import { Sortabl...
(changes : {}) : any { // This is needed so that on character change all items are removed and then readded from scratch this.achievements = []; setTimeout(() => { this.characterService.getAchievementsForCharacter(this.characterId) .subscribe((achievements : Achiev...
ngOnChanges
identifier_name
character-details-achievements.ts
// Services import { Component, Inject, Input, OnInit, OnChanges, AfterViewInit } from 'angular2/core'; import { CharacterService } from '../../../../service/character-service'; import { AchievementModel } from '../../../../model/achievement'; // Sub components import { NgFor } from 'angular2/common'; import { Sortabl...
setTimeout(() => { window.removeEventListener('click', this.listener); }, 0); }; } ngOnChanges (changes : {}) : any { // This is needed so that on character change all items are removed and then readded from scratch this.achievements = []; ...
{ let cardElement : HTMLElement = <HTMLElement>cards.item(i); cardElement.classList.remove('is-active'); }
conditional_block
dynamic.rs
// SPDX-License-Identifier: Apache-2.0 use std::env; use std::fs::File; use std::io::{self, Error, ErrorKind, Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use super::common; //================================================ // Validation //================================================ /// Extracts the...
else { Err(Error::new(ErrorKind::InvalidData, "invalid ELF header")) } } /// Extracts the magic number from the PE header in a shared library. fn parse_pe_header(path: &Path) -> io::Result<u16> { let mut file = File::open(path)?; // Extract the header offset. let mut buffer = [0; 4]; let ...
{ Ok(buffer[4]) }
conditional_block
dynamic.rs
// SPDX-License-Identifier: Apache-2.0 use std::env; use std::fs::File; use std::io::{self, Error, ErrorKind, Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use super::common; //================================================ // Validation //================================================ /// Extracts the...
/// Checks that a `libclang` shared library matches the target platform. fn validate_library(path: &Path) -> Result<(), String> { if cfg!(any(target_os = "linux", target_os = "freebsd")) { let class = parse_elf_header(path).map_err(|e| e.to_string())?; if cfg!(target_pointer_width = "32") && class ...
Ok(u16::from_le_bytes(buffer)) }
random_line_split
dynamic.rs
// SPDX-License-Identifier: Apache-2.0 use std::env; use std::fs::File; use std::io::{self, Error, ErrorKind, Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use super::common; //================================================ // Validation //================================================ /// Extracts the...
(filename: &str) -> Vec<u32> { let version = if let Some(version) = filename.strip_prefix("libclang.so.") { version } else if filename.starts_with("libclang-") { &filename[9..filename.len() - 3] } else { return vec![]; }; version.split('.').map(|s| s.parse().unwrap_or(0)).co...
parse_version
identifier_name
dynamic.rs
// SPDX-License-Identifier: Apache-2.0 use std::env; use std::fs::File; use std::io::{self, Error, ErrorKind, Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use super::common; //================================================ // Validation //================================================ /// Extracts the...
/// Finds the "best" `libclang` shared library and returns the directory and /// filename of that library. pub fn find(runtime: bool) -> Result<(PathBuf, String), String> { search_libclang_directories(runtime)? .iter() // We want to find the `libclang` shared library with the highest // ve...
{ let mut files = vec![format!( "{}clang{}", env::consts::DLL_PREFIX, env::consts::DLL_SUFFIX )]; if cfg!(target_os = "linux") { // Some Linux distributions don't create a `libclang.so` symlink, so we // need to look for versioned files (e.g., `libclang-3.9.so`). ...
identifier_body
application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative pat...
status){ $('[id^="switch-pc-"]').each(function(){ if(status === 'on'){ $(this).prop('checked', true); $('.date-time').fadeIn('slow'); } else { $(this).prop('checked', false); $('.date-time').fadeOut('slow'); } }); }; function verifyStatus(element){ if($(element).is(':checked')...
hangeAllComputers(
identifier_name
application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative pat...
type: 'PUT', data: { status: status, datetime: $('#date-time-' + computer_id).val() }, complete: function() { setTimeout(function() { semaphore = false; }, wait_ajax_complete); } }); } }); $('#onoffswitch-class').change(function(e){ ...
if(validateDateTimePicker(this, status)) { $.ajax({ url: '/computers/' + computer_id + '/change_status',
random_line_split
application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative pat...
function changeAllComputers(status){ $('[id^="switch-pc-"]').each(function(){ if(status === 'on'){ $(this).prop('checked', true); $('.date-time').fadeIn('slow'); } else { $(this).prop('checked', false); $('.date-time').fadeOut('slow'); } }); }; function verifyStatus(element){ ...
return $(element).parent().find('.date-time').val() !== '__/__/____ __:__'; }
identifier_body
chmod.rs
#![crate_name = "uu_chmod"] /* * This file is part of the uutils coreutils package. * * (c) Alex Lyon <arcterus@mail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #[cfg(unix)] extern crate libc; extern crate walker; #[mac...
fn sanitize_input(args: &mut Vec<String>) -> Option<String> { for i in 0..args.len() { let first = args[i].chars().nth(0).unwrap(); if first != '-' { continue; } if let Some(second) = args[i].chars().nth(1) { match second { 'r' | 'w' | 'x' | ...
{ let syntax = format!( "[OPTION]... MODE[,MODE]... FILE... {0} [OPTION]... OCTAL-MODE FILE... {0} [OPTION]... --reference=RFILE FILE...", NAME ); let mut opts = new_coreopts!(&syntax, SUMMARY, LONG_HELP); opts.optflag("c", "changes", "like verbose but report only when a change is made...
identifier_body
chmod.rs
#![crate_name = "uu_chmod"] /* * This file is part of the uutils coreutils package. * * (c) Alex Lyon <arcterus@mail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #[cfg(unix)] extern crate libc; extern crate walker; #[mac...
{ changes: bool, quiet: bool, verbose: bool, preserve_root: bool, recursive: bool, fmode: Option<u32>, cmode: Option<String>, } impl Chmoder { fn chmod(&self, files: Vec<String>) -> Result<(), i32> { let mut r = Ok(()); for filename in &files { let filename...
Chmoder
identifier_name
chmod.rs
#![crate_name = "uu_chmod"] /* * This file is part of the uutils coreutils package. * * (c) Alex Lyon <arcterus@mail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #[cfg(unix)] extern crate libc; extern crate walker; #[mac...
match chmoder.chmod(matches.free) { Ok(()) => {} Err(e) => return e, } } 0 } fn sanitize_input(args: &mut Vec<String>) -> Option<String> { for i in 0..args.len() { let first = args[i].chars().nth(0).unwrap(); if first != '-' { continue; ...
fmode: fmode, cmode: cmode, };
random_line_split
chmod.rs
#![crate_name = "uu_chmod"] /* * This file is part of the uutils coreutils package. * * (c) Alex Lyon <arcterus@mail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #[cfg(unix)] extern crate libc; extern crate walker; #[mac...
0 } fn sanitize_input(args: &mut Vec<String>) -> Option<String> { for i in 0..args.len() { let first = args[i].chars().nth(0).unwrap(); if first != '-' { continue; } if let Some(second) = args[i].chars().nth(1) { match second { 'r' | 'w'...
{ let changes = matches.opt_present("changes"); let quiet = matches.opt_present("quiet"); let verbose = matches.opt_present("verbose"); let preserve_root = matches.opt_present("preserve-root"); let recursive = matches.opt_present("recursive"); let fmode = matches ...
conditional_block
__init__.py
# Copyright (C) 2014 Dustin Spicuzza # # 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, or (at your option) # any later version. # # This program is distributed in the hope that...
return if data.use_disk: return track.get_tag_disk(tagname) if tagname == '__grouptagger': return list(self.get_track_groups(track)) return track.get_tag_raw(tagname, join=True) def generat...
if extra == 0: return int(ret) else: return int(ret) - (int(ret) % extra)
conditional_block
__init__.py
# Copyright (C) 2014 Dustin Spicuzza # # 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, or (at your option) # any later version. # # This program is distributed in the hope that...
(self, track, tagname, extra): data = tag_data.get(tagname) if data is not None: if data.type == 'int': ret = track.get_tag_raw(tagname, join=True) if ret is not None: if extra == 0: return int(ret)...
get_tag
identifier_name
__init__.py
# Copyright (C) 2014 Dustin Spicuzza # # 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, or (at your option) # any later version. # # This program is distributed in the hope that...
:param kwargs: Named parameters to substitute in template ''' # read the template file with open(tmpl, 'rb') as fp: contents = fp.read() try: contents = contents % kwargs except: raise RuntimeError("Format string e...
random_line_split
__init__.py
# Copyright (C) 2014 Dustin Spicuzza # # 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, or (at your option) # any later version. # # This program is distributed in the hope that...
# # Menu functions # def on_analyze_playlist(self, widget, name, parent, context): if self.dialog is None: self.dialog = AnalyzerDialog(self, context['selected-playlist']) def on_analyze_playlists(self, widget, name, parent, context): ...
if self._get_track_groups is None: if 'grouptagger' not in self.exaile.plugins.enabled_plugins: raise ValueError("GroupTagger plugin must be loaded to use the GroupTagger tag") self._get_track_groups = self.exaile.plugins.enabled_plugins['grouptagger'].get_track...
identifier_body
CheckerBase.py
#! /usr/bin/env python3 import contextlib import threading import mwparserfromhell import ws.ArchWiki.lang as lang from ws.utils import LazyProperty from ws.parser_helpers.title import canonicalize from ws.parser_helpers.wikicode import get_parent_wikicode, get_adjacent_node __all__ = ["get_edit_summary_tracker", "...
def localize_flag(wikicode, node, template_name): """ If a ``node`` in ``wikicode`` is followed by a template with the same base name as ``template_name``, this function changes the adjacent template's name to ``template_name``. :param wikicode: a :py:class:`mwparserfromhell.wikicode.Wikicode` o...
@contextlib.contextmanager def checker(summary): text = str(wikicode) try: yield finally: if text != str(wikicode): summary_parts.append(summary) return checker
identifier_body
CheckerBase.py
#! /usr/bin/env python3 import contextlib import threading import mwparserfromhell import ws.ArchWiki.lang as lang from ws.utils import LazyProperty from ws.parser_helpers.title import canonicalize from ws.parser_helpers.wikicode import get_parent_wikicode, get_adjacent_node __all__ = ["get_edit_summary_tracker", "...
(summary): text = str(wikicode) try: yield finally: if text != str(wikicode): summary_parts.append(summary) return checker def localize_flag(wikicode, node, template_name): """ If a ``node`` in ``wikicode`` is followed by a template with the ...
checker
identifier_name
CheckerBase.py
#! /usr/bin/env python3 import contextlib import threading import mwparserfromhell import ws.ArchWiki.lang as lang from ws.utils import LazyProperty from ws.parser_helpers.title import canonicalize from ws.parser_helpers.wikicode import get_parent_wikicode, get_adjacent_node __all__ = ["get_edit_summary_tracker", "...
:param node: a :py:class:`mwparserfromhell.nodes.Node` object :param str template_name: the name of the template flag, potentially including a language name """ parent = get_parent_wikicode(wikicode, node) adjacent = get_adjacent_node(parent, node, ignore_whitespace=Tru...
If a ``node`` in ``wikicode`` is followed by a template with the same base name as ``template_name``, this function changes the adjacent template's name to ``template_name``. :param wikicode: a :py:class:`mwparserfromhell.wikicode.Wikicode` object
random_line_split
CheckerBase.py
#! /usr/bin/env python3 import contextlib import threading import mwparserfromhell import ws.ArchWiki.lang as lang from ws.utils import LazyProperty from ws.parser_helpers.title import canonicalize from ws.parser_helpers.wikicode import get_parent_wikicode, get_adjacent_node __all__ = ["get_edit_summary_tracker", "...
# fall back to English return template def handle_node(self, src_title, wikicode, node, summary_parts): raise NotImplementedError("the handle_node method was not implemented in the derived class")
return localized
conditional_block
gdb-pretty-struct-and-enums.rs
// Copyright 2013-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-MI...
// gdb-command: print regular_struct // gdb-check:$1 = RegularStruct = {the_first_field = 101, the_second_field = 102.5, the_third_field = false, the_fourth_field = "I'm so pretty, oh so pretty..."} // gdb-command: print tuple // gdb-check:$2 = {true, 103, "blub"} // gdb-command: print tuple_struct // gdb-check:$3 =...
// gdb-command: run
random_line_split
gdb-pretty-struct-and-enums.rs
// Copyright 2013-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-MI...
{ CStyleEnumVar1, CStyleEnumVar2, CStyleEnumVar3, } enum MixedEnum { MixedEnumCStyleVar, MixedEnumTupleVar(u32, u16, bool), MixedEnumStructVar { field1: f64, field2: i32 } } struct NestedStruct { regular_struct: RegularStruct, tuple_struct: TupleStruct, empty_struct: EmptyStruct, ...
CStyleEnum
identifier_name
radixRule.ts
/* * Copyright 2013 Palantir Technologies, 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 l...
(node: TypeScript.InvocationExpressionSyntax): void { var expression = node.expression; if (expression.isToken() && expression.kind() === TypeScript.SyntaxKind.IdentifierName) { var firstToken = expression.firstToken(); var arguments = node.argumentList.arguments; if ...
visitInvocationExpression
identifier_name
radixRule.ts
/* * Copyright 2013 Palantir Technologies, 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 l...
/// <reference path='../../lib/tslint.d.ts' /> export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "missing radix parameter"; public apply(syntaxTree: TypeScript.SyntaxTree): Lint.RuleFailure[] { return this.applyWithWalker(new RadixWalker(syntaxTree, this.getOptions())...
* distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
random_line_split
radixRule.ts
/* * Copyright 2013 Palantir Technologies, 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 l...
} class RadixWalker extends Lint.RuleWalker { public visitInvocationExpression(node: TypeScript.InvocationExpressionSyntax): void { var expression = node.expression; if (expression.isToken() && expression.kind() === TypeScript.SyntaxKind.IdentifierName) { var firstToken = expression.fi...
{ return this.applyWithWalker(new RadixWalker(syntaxTree, this.getOptions())); }
identifier_body
radixRule.ts
/* * Copyright 2013 Palantir Technologies, 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 l...
super.visitInvocationExpression(node); } }
{ var firstToken = expression.firstToken(); var arguments = node.argumentList.arguments; if (firstToken.text() === "parseInt" && arguments.childCount() < 2) { var position = this.position() + node.leadingTriviaWidth(); this.addFailure(this.createFailur...
conditional_block
catalog.js
var SELECT_LAYER_TEXT = "Choose the layers you want to add.", catalogFamilies; function catalog() { if ($("#catalog").is(":visible")) { $("#maps").show(); $("#catalog").slideUp(); } else{ $("#maps").hide(); $("input[layer_name]:checked").each(function(){ $...
function getMedinaWMS(json){ var url = medinaCatalogWMS + "?SERVICE=WMS&Request=GetCapabilities"; var req_url = url.replace("?","&"); var server_base_url = url.substring(0,url.indexOf("?")); catalogFamilies = json.families; $.ajax({ url: 'proxy_noheaders.php?url='+req_url, dataType: ...
{ var html = ""; if (f.hasOwnProperty("children")){ var html2 = ""; f.children.sort(sortByName); for (var i=0;i<f.children.length;i++){ html2 += getFamilyHTML(f.children[i]); } html += "<li class='close' toggleable>" + "<ul cla...
identifier_body
catalog.js
var SELECT_LAYER_TEXT = "Choose the layers you want to add.", catalogFamilies; function catalog() { if ($("#catalog").is(":visible")) { $("#maps").show(); $("#catalog").slideUp(); } else{ $("#maps").hide(); $("input[layer_name]:checked").each(function(){ $...
() { $.getJSON("json/families.json",function(json){ getMedinaWMS(json); }); } function openCloseFamilyCatalog(e){ e.stopPropagation(); if ($(this).hasClass("close")) { $(this).removeClass("close").addClass("open"); $(this).find(">.family_header li.ico_open_close > img").a...
loadMedinaCatalog
identifier_name
catalog.js
var SELECT_LAYER_TEXT = "Choose the layers you want to add.", catalogFamilies; function catalog() { if ($("#catalog").is(":visible")) { $("#maps").show(); $("#catalog").slideUp(); } else{ $("#maps").hide(); $("input[layer_name]:checked").each(function(){ $...
bbox = !$(this).attr("layer_bbox") ? null : $(this).attr("layer_bbox"); Split.addLayer(server,name,title,false,type,panel,bbox); }); // hide catalog catalog(); }
server = !$(this).attr("layer_server") ? medinaCatalogWMS : $(this).attr("layer_server"),
random_line_split
bswap16.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::bswap16; // pub fn bswap16(x: u16) -> u16; macro_rules! bswap16_test { ($value:expr, $reverse:expr) => ({ let x: u16 = $value; let result: u16 = unsafe { bswap16(x) }; assert_eq!(result, ...
}
{ bswap16_test!(0x0000, 0x0000); bswap16_test!(0x0001, 0x0100); bswap16_test!(0x0002, 0x0200); bswap16_test!(0x0004, 0x0400); bswap16_test!(0x0008, 0x0800); bswap16_test!(0x0010, 0x1000); bswap16_test!(0x0020, 0x2000); bswap16_test!(0x0040, 0x4000); bswap16_test!(0x0080, 0x8000); bswap16_test!(0x0100, 0x0001)...
identifier_body
bswap16.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::bswap16; // pub fn bswap16(x: u16) -> u16; macro_rules! bswap16_test { ($value:expr, $reverse:expr) => ({ let x: u16 = $value; let result: u16 = unsafe { bswap16(x) }; assert_eq!(result, ...
() { bswap16_test!(0x0000, 0x0000); bswap16_test!(0x0001, 0x0100); bswap16_test!(0x0002, 0x0200); bswap16_test!(0x0004, 0x0400); bswap16_test!(0x0008, 0x0800); bswap16_test!(0x0010, 0x1000); bswap16_test!(0x0020, 0x2000); bswap16_test!(0x0040, 0x4000); bswap16_test!(0x0080, 0x8000); bswap16_test!(0x0100, 0x00...
bswap16_test1
identifier_name
bswap16.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::bswap16; // pub fn bswap16(x: u16) -> u16; macro_rules! bswap16_test { ($value:expr, $reverse:expr) => ({ let x: u16 = $value; let result: u16 = unsafe { bswap16(x) }; assert_eq!(result, ...
}
}
random_line_split