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 |
|---|---|---|---|---|
speaker.py | import pygame
import logging
from tools.action import Action
class Speaker(Action):
def __init__(self, id, params):
super(Speaker, self).__init__(id, params)
try:
self.path_to_audio = params["path_to_audio"]
self.repetitions = int(params["repetitions"])
except ValueError as ve: # if repetitions can't be... |
pygame.mixer.quit()
logging.debug("Speaker: Finished playing audio")
def execute(self):
if not self.corrupted:
self.play_audio()
else:
logging.error("Speaker: Wasn't able to play sound because of an initialization error")
def cleanup(self):
logging.debug("Speaker: No cleanup necessary at the mome... | pygame.mixer.music.rewind()
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
continue | conditional_block |
speaker.py | import pygame
import logging
from tools.action import Action
class | (Action):
def __init__(self, id, params):
super(Speaker, self).__init__(id, params)
try:
self.path_to_audio = params["path_to_audio"]
self.repetitions = int(params["repetitions"])
except ValueError as ve: # if repetitions can't be parsed as int
logging.error("Speaker: Wasn't able to initialize the devi... | Speaker | identifier_name |
speaker.py | import pygame
import logging
from tools.action import Action
class Speaker(Action):
def __init__(self, id, params):
super(Speaker, self).__init__(id, params)
try:
self.path_to_audio = params["path_to_audio"]
self.repetitions = int(params["repetitions"])
except ValueError as ve: # if repetitions can't be... | logging.debug("Speaker: No cleanup necessary at the moment") | else:
logging.error("Speaker: Wasn't able to play sound because of an initialization error")
def cleanup(self): | random_line_split |
ns_t_array.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/. */
//! Rust helpers for Gecko's nsTArray.
use gecko_bindings::bindings;
use gecko_bindings::structs::{nsTArray, nsTA... | cap,
mem::size_of::<T>(),
)
}
}
}
/// Clears the array storage without calling the destructor on the values.
#[inline]
pub unsafe fn clear(&mut self) {
if self.len() != 0 {
bindings::Gecko_ClearPODTArray(
... | bindings::Gecko_EnsureTArrayCapacity(
self as *mut nsTArray<T> as *mut _, | random_line_split |
ns_t_array.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/. */
//! Rust helpers for Gecko's nsTArray.
use gecko_bindings::bindings;
use gecko_bindings::structs::{nsTArray, nsTA... |
/// Resize and set the length of the array to `len`.
///
/// unsafe because this may leave the array with uninitialized elements.
///
/// This will not call constructors. If you need that, either manually add
/// bindings or run the typed `EnsureCapacity` call on the gecko side.
pub unsaf... | {
unsafe { self.clear() }
} | identifier_body |
ns_t_array.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/. */
//! Rust helpers for Gecko's nsTArray.
use gecko_bindings::bindings;
use gecko_bindings::structs::{nsTArray, nsTA... | (&mut self, len: u32)
where
T: Copy,
{
self.ensure_capacity(len as usize);
let header = self.header_mut();
header.mLength = len;
}
/// Collects the given iterator into this array.
///
/// Not unsafe because we won't leave uninitialized elements in the array.
... | set_len_pod | identifier_name |
ns_t_array.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/. */
//! Rust helpers for Gecko's nsTArray.
use gecko_bindings::bindings;
use gecko_bindings::structs::{nsTArray, nsTA... |
}
/// Clears a POD array. This is safe since copy types are memcopyable.
#[inline]
pub fn clear_pod(&mut self)
where
T: Copy,
{
unsafe { self.clear() }
}
/// Resize and set the length of the array to `len`.
///
/// unsafe because this may leave the array with u... | {
bindings::Gecko_ClearPODTArray(
self as *mut nsTArray<T> as *mut _,
mem::size_of::<T>(),
mem::align_of::<T>(),
);
} | conditional_block |
credentials.rs | #[macro_use]
extern crate accord;
use accord::{Accord, Result as AccordResult};
use accord::validators::{length, contains, not_contain_any};
struct Credentials {
pub email: String,
pub password: String,
}
impl Accord for Credentials {
#[cfg(not(feature = "inclusive_range"))]
fn validate(&self) -> Acc... | (&self) -> AccordResult {
rules!{
"email" => self.email => [length(5..=64), contains("@"), contains(".")],
"password" => self.password => [not_contain_any(&["1234", "admin", "password"])]
}
}
}
#[test]
fn main() {
let a = Credentials {
email: "test@test.test".to_... | validate | identifier_name |
credentials.rs | #[macro_use]
extern crate accord;
use accord::{Accord, Result as AccordResult};
use accord::validators::{length, contains, not_contain_any};
struct Credentials {
pub email: String,
pub password: String,
}
impl Accord for Credentials {
#[cfg(not(feature = "inclusive_range"))]
fn validate(&self) -> Acc... |
}
#[test]
fn main() {
let a = Credentials {
email: "test@test.test".to_string(),
password: "lfdsfsfsfghdgdljddsjfkdlsf".to_string(),
};
let b = Credentials {
email: "t".to_string(),
password: "admin1234password".to_string(),
};
assert!(a.validate().is_ok());
a... | {
rules!{
"email" => self.email => [length(5..=64), contains("@"), contains(".")],
"password" => self.password => [not_contain_any(&["1234", "admin", "password"])]
}
} | identifier_body |
credentials.rs | #[macro_use]
extern crate accord;
use accord::{Accord, Result as AccordResult}; | pub password: String,
}
impl Accord for Credentials {
#[cfg(not(feature = "inclusive_range"))]
fn validate(&self) -> AccordResult {
rules!{
"email" => self.email => [length(5, 64), contains("@"), contains(".")],
"password" => self.password => [not_contain_any(&["1234", "admi... | use accord::validators::{length, contains, not_contain_any};
struct Credentials {
pub email: String, | random_line_split |
industry.js | const industry = [
{
"name": "金融",
"children": [
{ "name": "银行" }, | { "name": "会计/审计" },
{ "name": "其它金融服务" }
]
},
{
"name": "专业服务",
"children": [
{ "name": "科研/教育" },
{ "name": "顾问/咨询服务" },
{ "name": "法律服务" },
{ "name": "医疗/保健" },
{ "name": "其它专业服务" }
]
},
{
"name": "政府",
"child... | { "name": "保险" },
{ "name": "证券公司" }, | random_line_split |
1D_intrusion.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# 1D_intrusion.py
#
# This script plots the cooling of a 1D intrusion with time
#
# dwhipp 09.13
#--- User-defined input values ------------------------------------------------#
Ti=700. # Intrusion tempe... | # Import libraries
import pylab,scipy,scipy.special
# Scale input values
l=l*1000. # km -> m
w=w*1000. # km -> m
t1=t1*365.25*24*3600
t2=t2*365.25*24*3600
t3=t3*365.25*24*3600
t4=... | #--- End user-defined input ---------------------------------------------------#
#--- DO NOT MODIFY ANYTHING BELOW THIS LINE -----------------------------------#
| random_line_split |
dataTables.foundation.js | /*! DataTables Foundation integration
* ©2011-2015 SpryMedia Ltd - datatables.net/license
*/
/**
* DataTables integration for Foundation. This requires Foundation 5 and
* DataTables 1.10 or newer.
*
* This file sets the defaults and adds options to DataTables to style its
* controls using Foundation. See http:/... |
return factory( $, root, root.document );
};
}
else {
// Browser
factory( jQuery, window, document );
}
}(function( $, window, document, undefined ) {
'use strict';
var DataTable = $.fn.dataTable;
$.extend( DataTable.ext.classes, {
sWrapper: "dataTables_wrapper dt-foundation",
sProcessing: "dataTabl... |
$ = require('datatables.net')(root, $).$;
}
| conditional_block |
dataTables.foundation.js | /*! DataTables Foundation integration
* ©2011-2015 SpryMedia Ltd - datatables.net/license
*/
/**
* DataTables integration for Foundation. This requires Foundation 5 and
* DataTables 1.10 or newer.
*
* This file sets the defaults and adds options to DataTables to style its
* controls using Foundation. See http:/... | return factory( $, root, root.document );
};
}
else {
// Browser
factory( jQuery, window, document );
}
}(function( $, window, document, undefined ) {
'use strict';
var DataTable = $.fn.dataTable;
$.extend( DataTable.ext.classes, {
sWrapper: "dataTables_wrapper dt-foundation",
sProcessing: "dataTable... | }
| random_line_split |
boluswizardpreview.js | prop === undefined) { return; }
var settings = prepareSettings(sbx);
if (bwp.highSnoozedByIOB(prop, settings, sbx)) {
sbx.notifications.requestSnooze({
level: levels.URGENT
, title: 'Snoozing high alarm since there is enough IOB'
, message: [sbx.propertyLine('bwp'), sbx.propertyL... | label: 'Recent carbs'
, value: prop.recentCarbs.carbs + 'g @ ' + moment(prop.recentCarbs.mills).format('LT')});
}
if (!prop.belowLowTarget) {
info.unshift({
label: '-BWP'
, value: 'Excess insulin equivalent ' + prop.bolusEstimateDisplay + 'U more than n... | {
if (prop && prop.errors) {
info.push({label: 'Notice', value: 'required info missing'});
_.each(prop.errors, function pushError (error) {
info.push({label: ' • ', value: error});
});
} else if (prop) {
info.push({label: 'Insulin on Board', value: prop.displayIOB + 'U'});
info.push({labe... | identifier_body |
boluswizardpreview.js | prop === undefined) { return; }
var settings = prepareSettings(sbx);
if (bwp.highSnoozedByIOB(prop, settings, sbx)) {
sbx.notifications.requestSnooze({
level: levels.URGENT
, title: 'Snoozing high alarm since there is enough IOB'
, message: [sbx.propertyLine('bwp'), sbx.propertyL... | var iob = results.iob = sbx.properties.iob.iob || 0;
results.effect = iob * profile.getSensitivity(sbx.time);
results.outcome = scaled - results.effect;
var delta = 0;
var recentCarbs = _.findLast(sbx.data.treatments, function eachTreatment (treatment) {
return treatment.mills <= sbx.time &&... |
var profile = sbx.data.profile; | random_line_split |
boluswizardpreview.js | prop === undefined) { return; }
var settings = prepareSettings(sbx);
if (bwp.highSnoozedByIOB(prop, settings, sbx)) {
sbx.notifications.requestSnooze({
level: levels.URGENT
, title: 'Snoozing high alarm since there is enough IOB'
, message: [sbx.propertyLine('bwp'), sbx.propertyL... | (sbx) {
var lastSGVEntry = sbx.lastSGVEntry();
return lastSGVEntry && lastSGVEntry.mgdl >= 39 && sbx.isCurrent(lastSGVEntry);
}
function profileFieldsMissing (sbx) {
return !sbx.data.profile.getSensitivity(sbx.time)
|| !sbx.data.profile.getHighBGTarget(sbx.time)
|| !sbx.data.profile.getLowBGTarget(sbx.t... | isSGVOk | identifier_name |
compiler.py | = {
'ASC': 'DESC',
'DESC': 'ASC'
}
SQL_SERVER_8_LIMIT_QUERY = \
"""SELECT *
FROM (
SELECT TOP %(limit)s *
FROM (
%(orig_sql)s
ORDER BY %(ord)s
) AS %(table)s
ORDER BY %(rev_ord)s
) AS %(table)s
ORDER BY %(ord)s"""
SQL_SERVER_8_NO_LIMIT_QUERY = \
"""SELECT *
FROM %(table)s
WHERE %(key)s NOT IN... | # going to be column names (so we can avoid the extra overhead).
qn = self.connection.ops.quote_name
opts = self.query.model._meta
returns_id = bool(self.return_id and
self.connection.features.can_return_id_from_insert)
if returns_id:
result... | class SQLInsertCompiler(compiler.SQLInsertCompiler, SQLCompiler):
def as_sql_legacy(self):
# We don't need quote_name_unless_alias() here, since these are all | random_line_split |
compiler.py | {
'ASC': 'DESC',
'DESC': 'ASC'
}
SQL_SERVER_8_LIMIT_QUERY = \
"""SELECT *
FROM (
SELECT TOP %(limit)s *
FROM (
%(orig_sql)s
ORDER BY %(ord)s
) AS %(table)s
ORDER BY %(rev_ord)s
) AS %(table)s
ORDER BY %(ord)s"""
SQL_SERVER_8_NO_LIMIT_QUERY = \
"""SELECT *
FROM %(table)s
WHERE %(key)s NOT IN (... | (self, row, fields=()):
index_start = len(self.query.extra_select.keys())
values = [self.query.convert_values(v, None, connection=self.connection) for v in row[:index_start]]
for value, field in map(None, row[index_start:], fields):
values.append(self.query.convert_values(value, fiel... | resolve_columns | identifier_name |
compiler.py | = {
'ASC': 'DESC',
'DESC': 'ASC'
}
SQL_SERVER_8_LIMIT_QUERY = \
"""SELECT *
FROM (
SELECT TOP %(limit)s *
FROM (
%(orig_sql)s
ORDER BY %(ord)s
) AS %(table)s
ORDER BY %(rev_ord)s
) AS %(table)s
ORDER BY %(ord)s"""
SQL_SERVER_8_NO_LIMIT_QUERY = \
"""SELECT *
FROM %(table)s
WHERE %(key)s NOT IN... | sql = ' '.join(result)
meta = self.query.get_meta()
if meta.has_auto_field:
# db_column is None if not explicitly specified by model field
auto_field_column = meta.auto_field.db_column or meta.auto_field.column
if auto_field_column in self.query.columns:
... | qn = self.connection.ops.quote_name
opts = self.query.model._meta
returns_id = bool(self.return_id and
self.connection.features.can_return_id_from_insert)
if returns_id:
result = ['SET NOCOUNT ON']
else:
result = []
result.appen... | identifier_body |
compiler.py | {
'ASC': 'DESC',
'DESC': 'ASC'
}
SQL_SERVER_8_LIMIT_QUERY = \
"""SELECT *
FROM (
SELECT TOP %(limit)s *
FROM (
%(orig_sql)s
ORDER BY %(ord)s
) AS %(table)s
ORDER BY %(rev_ord)s
) AS %(table)s
ORDER BY %(ord)s"""
SQL_SERVER_8_NO_LIMIT_QUERY = \
"""SELECT *
FROM %(table)s
WHERE %(key)s NOT IN (... |
select_re = re.compile('^SELECT[ ]+(DISTINCT\s)?')
query, params = super(SQLCompiler, self).as_sql(with_limits=False,
with_col_aliases=with_col_aliases)
m = select_re.match(query)
if with_limits and m != None:
num = Non... | return super(SQLCompiler, self).as_sql(with_limits=False,
with_col_aliases=with_col_aliases) | conditional_block |
trendDetail.component.ts | import { PlayService } from './../../service/playService';
import { Component } from '@angular/core';
import { NavController, NavParams, AlertController } from 'ionic-angular';
@Component({
selector: 'trend-detail',
templateUrl: './trendDetail.component.html',
styleUrls: ['./trendDetail.component.scss']
})
... | this.playSvr.getTrendData(item.id, this.limit).subscribe(
data => {
let result = data.json();
if (!result.error) {
this.trendData = result.data;
}
},
error => {
this.playSvr.errorHandler(error, (... | = `${item.text}开奖预测`;
this.getTrend(item);
}
}
getTrend(item) {
| conditional_block |
trendDetail.component.ts | import { PlayService } from './../../service/playService';
import { Component } from '@angular/core';
import { NavController, NavParams, AlertController } from 'ionic-angular';
@Component({
selector: 'trend-detail',
templateUrl: './trendDetail.component.html',
styleUrls: ['./trendDetail.component.scss']
})
... | (
public nav: NavController,
private navParams: NavParams,
private playSvr: PlayService,
private alertCtrl: AlertController
) { }
title: string = "";
private limit = 500;
trendData;
ionViewWillEnter() {
let item = this.navParams.get("playType");
if (!... | constructor | identifier_name |
trendDetail.component.ts | import { PlayService } from './../../service/playService';
import { Component } from '@angular/core';
import { NavController, NavParams, AlertController } from 'ionic-angular';
@Component({
selector: 'trend-detail',
templateUrl: './trendDetail.component.html',
styleUrls: ['./trendDetail.component.scss']
})
... | });
alert.present();
} else {
this.title = `${item.text}开奖预测`;
this.getTrend(item);
}
}
getTrend(item) {
this.playSvr.getTrendData(item.id, this.limit).subscribe(
data => {
let result = data.json();
... | ] | random_line_split |
question.js | /*
* Copyright 2012-2015 MarkLogic Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law... | var content = spec.answerId ?
_.find(
doc.answers, { 'id': spec.answerId }
) :
doc;
contentContributorId = content.owner.id;
spec.voteChange = spec.operation === 'upvotes' ? 1 : -1;
notAlreadyVoted(content, spec.contributor);
spe... | var contentContributorId; | random_line_split |
p13.rs | use std::collections::BTreeMap;
use rand::{Rng, weak_rng};
use serialize::json::{Json, ToJson};
use ssl::symm::{self, encrypt, decrypt};
fn parse_querystr(input: &str) -> Result<Json, ()> {
let mut obj = BTreeMap::new();
for pair in input.split('&') {
let mut items = pair.split('=');
match (it... |
};
}
Ok(Json::Object(obj))
}
#[test]
fn test_parse_queryst() {
let json = parse_querystr("foo=bar&baz=wanker@foobar.com").unwrap();
let obj = json.as_object().unwrap();
assert_eq!(obj["foo"], "bar".to_json());
assert_eq!(obj["baz"], "wanker@foobar.com".to_json());
}
fn profile_for(ema... | {
return Err(());
} | conditional_block |
p13.rs | use std::collections::BTreeMap;
use rand::{Rng, weak_rng};
use serialize::json::{Json, ToJson};
use ssl::symm::{self, encrypt, decrypt};
fn parse_querystr(input: &str) -> Result<Json, ()> {
let mut obj = BTreeMap::new();
for pair in input.split('&') {
let mut items = pair.split('=');
match (it... | let mut rng = weak_rng();
let mut key = [0_u8; 16];
rng.fill_bytes(&mut key);
// 0123456789012345|0123456789012345|0123456789012345|012345678912345
// email=AAAAAAAAAA|adminPPPPPPPPPPP|AAA&uid=10&role=|userPPPPPPPPPPP
// ^^^^^^^^^^|^^^^^^^^^^^^^^^^|^^^
// input
... | let blocksize = 16; | random_line_split |
p13.rs | use std::collections::BTreeMap;
use rand::{Rng, weak_rng};
use serialize::json::{Json, ToJson};
use ssl::symm::{self, encrypt, decrypt};
fn parse_querystr(input: &str) -> Result<Json, ()> {
let mut obj = BTreeMap::new();
for pair in input.split('&') {
let mut items = pair.split('=');
match (it... | (key: &[u8], input: &str) -> Vec<u8> {
let plaintext = profile_for(input);
let data = plaintext.as_bytes();
encrypt(symm::Cipher::aes_128_ecb(), key, None, data).unwrap()
}
fn decryption_oracle(key: &[u8], data: &[u8]) -> Json {
let plaintext = decrypt(symm::Cipher::aes_128_ecb(), key, None, data).unwr... | encryption_oracle | identifier_name |
p13.rs | use std::collections::BTreeMap;
use rand::{Rng, weak_rng};
use serialize::json::{Json, ToJson};
use ssl::symm::{self, encrypt, decrypt};
fn parse_querystr(input: &str) -> Result<Json, ()> |
#[test]
fn test_parse_queryst() {
let json = parse_querystr("foo=bar&baz=wanker@foobar.com").unwrap();
let obj = json.as_object().unwrap();
assert_eq!(obj["foo"], "bar".to_json());
assert_eq!(obj["baz"], "wanker@foobar.com".to_json());
}
fn profile_for(email: &str) -> String {
let email_clean = e... | {
let mut obj = BTreeMap::new();
for pair in input.split('&') {
let mut items = pair.split('=');
match (items.next(), items.next(), items.next()) {
(Some(key), Some(val), None) => {
obj.insert(key.to_string(), Json::String(val.to_string()));
},
... | identifier_body |
package.py | 1a41b9a177ab7f70d')
version('5.24.1', sha256='e6c185c9b09bdb3f1b13f678999050c639859a7ef39c8cad418448075f5918af')
version('5.22.4', sha256='ba9ef57c2b709f2dad9c5f6acf3111d9dfac309c484801e0152edbca89ed61fa')
version('5.22.3', sha256='1b351fb4df7e62ec3c8b2a9f516103595b2601291f659fef1bbe3917e8410083')
versi... | make() | identifier_body | |
package.py | bf3d25571ff1ee94186177c2cdef87867fd6a14aa5a84f0b1fb7bf798f42f964')
version('5.30.0', sha256='851213c754d98ccff042caa40ba7a796b2cee88c5325f121be5cbb61bbf975f2')
# End of life releases
version('5.28.0', sha256='7e929f64d4cb0e9d1159d4a59fc89394e27fa1f7004d0836ca0d514685406ea8')
version('5.26.2', sha256='5... | # On a lustre filesystem, patch may fail when files
# aren't writeable so make pp.c user writeable
# before patching. This should probably walk the
# source and make everything writeable in the future.
def do_stage(self, mirror_only=False):
# Do Spack's regular stage
super(Perl, self... | variants += '+cpanm'
else:
variants += '~cpanm'
return variants
| random_line_split |
package.py | 6='81ad196385aa168cb8bd785031850e808c583ed18a7901d33e02d4f70ada83c2')
version('5.22.1', sha256='2b475d0849d54c4250e9cba4241b7b7291cffb45dfd083b677ca7b5d38118f27')
version('5.22.0', sha256='0c690807f5426bbd1db038e833a917ff00b988bf03cbf2447fa9ffdb34a2ab3c')
version('5.20.3', sha256='3524e3a76b71650ab2f794fd68... | setup_dependent_build_environment | identifier_name | |
package.py | '+shared'
else:
variants += '~shared'
match = re.search(r'-Duse.?threads', output)
if match:
variants += '+threads'
else:
variants += '~threads'
path = os.path.dirname(exe)
... | path = os.path.join(self.prefix.bin, '{0}{1}'.format(
self.spec.name, ver))
if os.path.exists(path):
return Executable(path) | conditional_block | |
fr.js | /*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
| armenian: 'Numération arménienne',
bulletedTitle: 'Propriétés de la liste à puces',
circle: 'Cercle',
decimal: 'Décimal (1, 2, 3, etc.)',
decimalLeadingZero: 'Décimal précédé par un 0 (01, 02, 03, etc.)',
disc: 'Disque',
georgian: 'Numération géorgienne (an, ban, gan, etc.)',
lowerAlpha: 'Alphabétique mi... | CKEDITOR.plugins.setLang( 'liststyle', 'fr', {
| random_line_split |
tokenizer.rs | /*
* Copyright 2006 Kenta Cho. Some rights reserved.
*/
use std::io::prelude::*;
use std::fs::File;
fn readFile(fileName : &string, separator : &string) -> string {
let mut file = File::open(fileName.unwrap());
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let mut... | () {
}
/*
/*
* Tokenizer.
*/
public class Tokenizer {
private:
public static string[] readFile(string fileName, string separator) {
string[] result;
auto file = new File(fileName, FileMode.In);
char[][] lines = splitLines(file);
foreach(line; lines) {
char[][] spl =... | main | identifier_name |
tokenizer.rs | /*
* Copyright 2006 Kenta Cho. Some rights reserved.
*/
use std::io::prelude::*;
use std::fs::File;
| file.read_to_string(&mut contents).unwrap();
let mut result : Vec[String];
// Returns amount of bytes read and append the result to the buffer
let result = file.read_to_end(&mut contents).unwrap();
for line in result.lines() {
for s in line.split(separator) {
result.push(s.trim());
}
}
... | fn readFile(fileName : &string, separator : &string) -> string {
let mut file = File::open(fileName.unwrap());
let mut contents = String::new();
| random_line_split |
tokenizer.rs | /*
* Copyright 2006 Kenta Cho. Some rights reserved.
*/
use std::io::prelude::*;
use std::fs::File;
fn readFile(fileName : &string, separator : &string) -> string |
fn main() {
}
/*
/*
* Tokenizer.
*/
public class Tokenizer {
private:
public static string[] readFile(string fileName, string separator) {
string[] result;
auto file = new File(fileName, FileMode.In);
char[][] lines = splitLines(file);
foreach(line; lines) {
cha... | {
let mut file = File::open(fileName.unwrap());
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let mut result : Vec[String];
// Returns amount of bytes read and append the result to the buffer
let result = file.read_to_end(&mut contents).unwrap();
for line in resul... | identifier_body |
show_payments.js | import React from 'react';
import Snackbar from 'material-ui/Snackbar';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/IconMenu';
import RaisedButton from 'material-ui/RaisedButton';
import Paper from 'material-ui/Paper';
import Menu from 'material-ui/Menu';
imp... | () {
}
handleClick(){
return true;
}
render() {
/* console.log("render mostrar pagos");*/
let guests = this.props.guests;
let payments = this.props.payments;
let guest_payment = new Array();
for(let i = 0; i < guests.length; i++) {
gu... | handleShowPayments | identifier_name |
show_payments.js | import React from 'react';
import Snackbar from 'material-ui/Snackbar';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/IconMenu'; | import Paper from 'material-ui/Paper';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
import AppBar from 'material-ui/AppBar';
import Divider from 'material-ui/Divider';
import TextField from 'material-ui/TextField';
import SelectField from 'material-ui/SelectField';
import {Table, Ta... | import RaisedButton from 'material-ui/RaisedButton'; | random_line_split |
show_payments.js | import React from 'react';
import Snackbar from 'material-ui/Snackbar';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/IconMenu';
import RaisedButton from 'material-ui/RaisedButton';
import Paper from 'material-ui/Paper';
import Menu from 'material-ui/Menu';
imp... | const actions = [
<FlatButton
label="Cancelar"
primary={true}
onTouchTap={null}
/>,
<FlatButton
label="Aceptar"
primary={true}
onTouchTap={null}
/>,
];
... | {
/* console.log("render mostrar pagos");*/
let guests = this.props.guests;
let payments = this.props.payments;
let guest_payment = new Array();
for(let i = 0; i < guests.length; i++) {
guest_payment[guests[i].cedula] = 0;
}
for(let i = 0; i < ... | identifier_body |
show_payments.js | import React from 'react';
import Snackbar from 'material-ui/Snackbar';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/IconMenu';
import RaisedButton from 'material-ui/RaisedButton';
import Paper from 'material-ui/Paper';
import Menu from 'material-ui/Menu';
imp... |
}
}
};
const actions = [
<FlatButton
label="Cancelar"
primary={true}
onTouchTap={null}
/>,
<FlatButton
label="Aceptar"
primary={true}
onTouc... | {
guest_payment[guests[i].cedula] += payments[j].valor;
} | conditional_block |
ka.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... |
export default [
'ka',
[['a', 'p'], ['AM', 'PM'], u],
[['AM', 'PM'], u, u],
[
['კ', 'ო', 'ს', 'ო', 'ხ', 'პ', 'შ'],
['კვი', 'ორშ', 'სამ', 'ოთხ', 'ხუთ', 'პარ', 'შაბ'],
[
'კვირა', 'ორშაბათი', 'სამშაბათი',
'ოთხშაბათი', 'ხუთშაბათი', 'პარასკევი',
'შაბათი'
],
['კვ', 'ორ', 'სმ', ... | {
if (n === 1) return 1;
return 5;
} | identifier_body |
ka.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... | 'ka',
[['a', 'p'], ['AM', 'PM'], u],
[['AM', 'PM'], u, u],
[
['კ', 'ო', 'ს', 'ო', 'ხ', 'პ', 'შ'],
['კვი', 'ორშ', 'სამ', 'ოთხ', 'ხუთ', 'პარ', 'შაბ'],
[
'კვირა', 'ორშაბათი', 'სამშაბათი',
'ოთხშაბათი', 'ხუთშაბათი', 'პარასკევი',
'შაბათი'
],
['კვ', 'ორ', 'სმ', 'ოთ', 'ხთ', 'პრ', '... | if (n === 1) return 1;
return 5;
}
export default [ | random_line_split |
ka.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... | (n: number): number {
if (n === 1) return 1;
return 5;
}
export default [
'ka',
[['a', 'p'], ['AM', 'PM'], u],
[['AM', 'PM'], u, u],
[
['კ', 'ო', 'ს', 'ო', 'ხ', 'პ', 'შ'],
['კვი', 'ორშ', 'სამ', 'ოთხ', 'ხუთ', 'პარ', 'შაბ'],
[
'კვირა', 'ორშაბათი', 'სამშაბათი',
'ოთხშაბათი', 'ხუთშაბათი'... | plural | identifier_name |
__main__.py | """
radish
~~~~~~
The root from red to green. BDD tooling for Python.
:copyright: (c) 2019 by Timo Furrer <tuxtimo@gmail.com>
:license: MIT, see LICENSE for more details.
"""
from collections import namedtuple
from pathlib import Path
import click
import colorful as cf
import radish.loader as loader
from radish.__... |
return expanded_matcher_configs
@click.command()
@click.version_option()
@click.help_option("--help", "-h")
@click.option(
"--debug",
"-d",
"enable_debug_mode",
is_flag=True,
help="Enable debug mode for radish-test itself",
callback=enable_radish_debug_mode_click_hook,
)
@click.option(
... | expanded_matcher_configs.append(matcher_config_file_location) | conditional_block |
__main__.py | """
radish
~~~~~~
The root from red to green. BDD tooling for Python.
:copyright: (c) 2019 by Timo Furrer <tuxtimo@gmail.com>
:license: MIT, see LICENSE for more details.
"""
from collections import namedtuple
from pathlib import Path
import click
import colorful as cf
import radish.loader as loader
from radish.__... |
@click.command()
@click.version_option()
@click.help_option("--help", "-h")
@click.option(
"--debug",
"-d",
"enable_debug_mode",
is_flag=True,
help="Enable debug mode for radish-test itself",
callback=enable_radish_debug_mode_click_hook,
)
@click.option(
"--basedir",
"-b",
"basedi... | """Expand the given matcher configuration files
Expanding directories recursively for YAML files.
"""
expanded_matcher_configs = []
for matcher_config_file_location in (Path(f) for f in matcher_configs):
if matcher_config_file_location.is_dir():
expanded_matcher_configs.extend(
... | identifier_body |
__main__.py | """
radish
~~~~~~
The root from red to green. BDD tooling for Python.
:copyright: (c) 2019 by Timo Furrer <tuxtimo@gmail.com>
:license: MIT, see LICENSE for more details.
"""
from collections import namedtuple
from pathlib import Path
import click
import colorful as cf
import radish.loader as loader
from radish.__... | """
expanded_matcher_configs = []
for matcher_config_file_location in (Path(f) for f in matcher_configs):
if matcher_config_file_location.is_dir():
expanded_matcher_configs.extend(
list(matcher_config_file_location.glob("**/*.yml"))
)
else:
... | """Expand the given matcher configuration files
Expanding directories recursively for YAML files. | random_line_split |
__main__.py | """
radish
~~~~~~
The root from red to green. BDD tooling for Python.
:copyright: (c) 2019 by Timo Furrer <tuxtimo@gmail.com>
:license: MIT, see LICENSE for more details.
"""
from collections import namedtuple
from pathlib import Path
import click
import colorful as cf
import radish.loader as loader
from radish.__... | (**kwargs):
"""radish - The root from red to green. BDD tooling for Python.
radish-test can be used to perform tests for the Steps
implemented in a radish base directory.
Use the `MATCHER_CONFIGS` to pass configuration
files containing the Step matchers.
"""
config = Config(kwargs)
# ... | cli | identifier_name |
connection.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... |
/// Creates a new peer connection.
pub fn peer(id: ServerId, addr: SocketAddr) -> Result<Connection> {
let stream = try!(TcpStream::connect(&addr));
Ok(Connection {
kind: ConnectionKind::Peer(id),
addr: addr,
stream: Some(MessageStream::new(stream, ... | {
let addr = try!(socket.peer_addr());
Ok(Connection {
kind: ConnectionKind::Unknown,
addr: addr,
stream: Some(MessageStream::new(socket, ReaderOptions::new())),
backoff: Backoff::with_duration_range(50, 10000),
})
} | identifier_body |
connection.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... | use std::rc::Rc;
fn poll_opt() -> PollOpt {
PollOpt::edge() | PollOpt::oneshot()
}
/// The type of a connection.
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum ConnectionKind {
/// A peer in the cluster.
Peer(ServerId),
/// A client which is asking the Raft cluster to do things.
Clien... | use state_machine::StateMachine;
use std::fmt;
use std::net::SocketAddr; | random_line_split |
connection.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... | (&self) -> &SocketAddr {
&self.addr
}
pub fn set_addr(&mut self, addr: SocketAddr) {
self.addr = addr;
}
/// Returns the connection's stream.
/// Must only be called while the connection is active.
fn stream(&self) -> &MessageStream<TcpStream, HeapAllocator, Rc<Builder<HeapAllo... | addr | identifier_name |
deploy_snapshots.py | # Copyright (c) 2014 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... | (action.Action):
def run(self, storage_info=None, identity_info=None, **kwargs):
storage_info = copy.deepcopy(storage_info)
deploy_info = copy.deepcopy(storage_info)
deploy_info.update(identity_info)
storage_info.update(identity_info)
volume_resource = self.cloud.resources[u... | DeployVolSnapshots | identifier_name |
deploy_snapshots.py | # Copyright (c) 2014 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... |
else:
one_volume_info = {
'one_volume_info': {
utl.VOLUMES_TYPE: {
vol_id: vol
}
}
}
act_transport_vol_data = \
task_tran... | if volume_resource.config.storage.host:
act_delete_redundant_snap = \
rbd_util.RbdUtil(cloud=self.cloud,
config_migrate=self.cfg.migrate,
host=vol_info[utl.HOST_DST])
... | conditional_block |
deploy_snapshots.py | # Copyright (c) 2014 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... | class DeployVolSnapshots(action.Action):
def run(self, storage_info=None, identity_info=None, **kwargs):
storage_info = copy.deepcopy(storage_info)
deploy_info = copy.deepcopy(storage_info)
deploy_info.update(identity_info)
storage_info.update(identity_info)
volume_resource ... | OLD_ID = 'old_id'
| random_line_split |
deploy_snapshots.py | # Copyright (c) 2014 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... | ssh_ceph_to_ceph.SSHCephToCeph,
1)
else:
snap_num = snapshots_list.index(snap)
snap['prev_snapname'] = \
snapshots_list[snap_num - 1]['name']
... | storage_info = copy.deepcopy(storage_info)
deploy_info = copy.deepcopy(storage_info)
deploy_info.update(identity_info)
storage_info.update(identity_info)
volume_resource = self.cloud.resources[utl.STORAGE_RESOURCE]
for vol_id, vol in deploy_info[utl.VOLUMES_TYPE].iteritems():
... | identifier_body |
karma.conf.js | // Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
... | // 'app/bower_components/angular-route/angular-route.js',
// 'app/bower_components/angular-animate/angular-animate.js',
// 'app/bower_components/ng-table/ng-table.js',
// 'app/bower_components/select2/select2.js',
// 'app/bower_components/angular-ui-select2/src/select2.js',
// 'app/scripts... | 'app/bower_components/angular-mocks/angular-mocks.js',
// 'app/bower_components/jquery/jquery.js',
// 'app/bower_components/angular-bootstrap/ui-bootstrap.js',
// 'app/bower_components/angular-resource/angular-resource.js', | random_line_split |
bgp_netconf.py | #!/usr/bin/env python
# ----------------------------------------------------------------
# Copyright 2016 Cisco Systems
#
# 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.apac... |
if __name__ == "__main__":
init_logging()
provider = NetconfServiceProvider(address='127.0.0.1', username='admin', password='admin', protocol='ssh', port=12022)
netconf_service = NetconfService()
bgp_run(netconf_service, provider)
# run_multiple_routing_bgp(netconf_service, provider)
exit()
| import logging
logger = logging.getLogger("ydk")
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
formatter = logging.Formatter(("%(asctime)s - %(name)s - "
"%(levelname)s - %(message)s"))
handler.setFormatter(formatter)
logger.addHandler(handler... | identifier_body |
bgp_netconf.py | #!/usr/bin/env python
# ----------------------------------------------------------------
# Copyright 2016 Cisco Systems
#
# 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.apac... | init_logging()
provider = NetconfServiceProvider(address='127.0.0.1', username='admin', password='admin', protocol='ssh', port=12022)
netconf_service = NetconfService()
bgp_run(netconf_service, provider)
# run_multiple_routing_bgp(netconf_service, provider)
exit() | conditional_block | |
bgp_netconf.py | #!/usr/bin/env python
# ----------------------------------------------------------------
# Copyright 2016 Cisco Systems
#
# 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.apac... | (netconf_service, session):
crud = CRUDService()
codec = CodecService()
codec_provider = CodecServiceProvider()
crud.delete(session, bgp())
crud.delete(session, RoutingPolicy())
multi_cfg = _get_bgp_routing_multiple_object()
multi_payload_expected = codec.encode(codec_provider, multi_cfg)
... | run_multiple_routing_bgp | identifier_name |
bgp_netconf.py | #!/usr/bin/env python
# ----------------------------------------------------------------
# Copyright 2016 Cisco Systems
#
# 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.apac... | logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
formatter = logging.Formatter(("%(asctime)s - %(name)s - "
"%(levelname)s - %(message)s"))
handler.setFormatter(formatter)
logger.addHandler(handler)
if __name__ == "__main__":
init_logging()
... |
def init_logging():
import logging
logger = logging.getLogger("ydk") | random_line_split |
mod.rs | use std::rc::Rc;
use std::vec::Vec;
pub mod database;
pub mod parser; // bytes -> events
pub mod builder; // events -> DOM
pub mod generator; // DOM -> bytes
pub mod templates;
pub mod midlevel; // events -> events+DOM
#[derive(Debug,Eq,PartialEq,Clone,Copy)]
pub enum Type {
Master,
Unsigned,
Signed,
... | (c: database::Class, d:i64 ) -> Element { Element { class: c, content: ElementContent::MatroskaDate(d)}}
pub fn el<T>(c: database::Class, d:T) -> Element where T:IntoIterator<Item=Element> {
let mut v = vec![];
for i in d {
v.push ( Rc::new(i) );
}
Element { class: c, content: ElementCont... | el_date | identifier_name |
mod.rs | use std::rc::Rc;
use std::vec::Vec;
pub mod database;
pub mod parser; // bytes -> events
pub mod builder; // events -> DOM
pub mod generator; // DOM -> bytes
pub mod templates;
pub mod midlevel; // events -> events+DOM
#[derive(Debug,Eq,PartialEq,Clone,Copy)]
pub enum Type {
Master,
Unsigned,
Signed,
... | .to_string();
Element { class: EBML, content: Master(vec![
Rc::new(Element {class: EBMLVersion, content: Unsigned(1)}),
Rc::new(Element {class: EBMLReadVersion, content: Unsigned(1)}),
Rc::new(Element {class: EBMLMaxIDLength, content: Unsigned(4)}),
Rc::new(Element {class: ... | { "matroska"} | conditional_block |
mod.rs | use std::rc::Rc;
use std::vec::Vec;
pub mod database;
pub mod parser; // bytes -> events
pub mod builder; // events -> DOM
pub mod generator; // DOM -> bytes
pub mod templates;
pub mod midlevel; // events -> events+DOM
#[derive(Debug,Eq,PartialEq,Clone,Copy)]
pub enum Type {
Master,
Unsigned,
Signed,
... | {
use self::database::Class::*;
use self::ElementContent::{Unsigned,Text,Master};
let doctype = if webm { "webm" } else { "matroska"}.to_string();
Element { class: EBML, content: Master(vec![
Rc::new(Element {class: EBMLVersion, content: Unsigned(1)}),
Rc::new(Element {class: EBML... | identifier_body | |
mod.rs | use std::rc::Rc;
use std::vec::Vec;
pub mod database;
pub mod parser; // bytes -> events
pub mod builder; // events -> DOM
pub mod generator; // DOM -> bytes
pub mod templates;
pub mod midlevel; // events -> events+DOM
#[derive(Debug,Eq,PartialEq,Clone,Copy)]
pub enum Type {
Master,
Unsigned,
Signed,
... | }
#[derive(PartialEq,Debug,PartialOrd,Clone)]
#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
pub struct Element {
pub class : database::Class,
pub content : ElementContent,
}
// Cosy constructors
pub fn el_bin (c: database::Class, d:Vec<u8>) -> Element { Element { class: c, ... | Float(f64),
MatroskaDate(i64), // Nanoseconds since 20010101_000000_UTC
Unknown(u64, Rc<Vec<u8>>) | random_line_split |
mixins.py | # copyright 2003-2013 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of astroid.
#
# astroid is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
#... |
raise NotFoundError(asname)
| if name == '*':
return asname
if not _asname:
name = name.split('.', 1)[0]
_asname = name
if asname == _asname:
return name | conditional_block |
mixins.py | # copyright 2003-2013 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of astroid.
#
# astroid is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
#... |
def do_import_module(self, modname):
"""return the ast for a module whose name is <modname> imported by <self>
"""
# handle special case where we are on a package node importing a module
# using the same name as the package, which may end in an infinite loop
# on relative i... | return name | identifier_body |
mixins.py | # copyright 2003-2013 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of astroid.
#
# astroid is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
#... |
from .exceptions import (AstroidBuildingException, InferenceError,
NotFoundError)
class BlockRangeMixIn(object):
"""override block range """
def set_line_info(self, lastchild):
self.fromlineno = self.lineno
self.tolineno = lastchild.tolineno
self.... | # You should have received a copy of the GNU Lesser General Public License along
# with astroid. If not, see <http://www.gnu.org/licenses/>.
"""This module contains some mixins for the different nodes.
""" | random_line_split |
mixins.py | # copyright 2003-2013 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of astroid.
#
# astroid is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
#... | (FilterStmtsMixin):
"""MixIn for From and Import Nodes"""
def _infer_name(self, frame, name):
return name
def do_import_module(self, modname):
"""return the ast for a module whose name is <modname> imported by <self>
"""
# handle special case where we are on a package node ... | FromImportMixIn | identifier_name |
index.js | var should = require("should");
it("should be able to load JSON files without loader", function() {
var someJson = require("./some.json");
someJson.should.have.property("it", "works");
someJson.should.have.property("number", 42);
});
it("should also work when the json extension is omitted", function() {
var someJ... | it("should still be possible to manually apply the json-loader for compatibility reasons", function() {
var someJson = require("json-loader!./some.json");
someJson.should.have.property("it", "works");
someJson.should.have.property("number", 42);
});
it("should still be possible to use a custom loader", function() {... | someJson.should.have.property("number", 42);
});
| random_line_split |
membership.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use anyhow::Result;
use async_trait::async_trait;
use std::panic::RefUnwindSafe;
use std::sync::Arc;
use crate::MononokeIdentitySet;
pub ... | struct AllowlistChecker {
allowlist: MononokeIdentitySet,
}
#[async_trait]
impl MembershipChecker for AllowlistChecker {
async fn is_member(&self, identities: &MononokeIdentitySet) -> Result<bool> {
Ok(!self.allowlist.is_disjoint(identities))
}
} | random_line_split | |
membership.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use anyhow::Result;
use async_trait::async_trait;
use std::panic::RefUnwindSafe;
use std::sync::Arc;
use crate::MononokeIdentitySet;
pub ... |
}
struct NeverMember {}
#[async_trait]
impl MembershipChecker for NeverMember {
async fn is_member(&self, _identities: &MononokeIdentitySet) -> Result<bool> {
Ok(false)
}
}
struct AllowlistChecker {
allowlist: MononokeIdentitySet,
}
#[async_trait]
impl MembershipChecker for AllowlistChecker {
... | {
Ok(true)
} | identifier_body |
membership.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use anyhow::Result;
use async_trait::async_trait;
use std::panic::RefUnwindSafe;
use std::sync::Arc;
use crate::MononokeIdentitySet;
pub ... | () -> BoxMembershipChecker {
Box::new(AlwaysMember {})
}
pub fn never_member() -> BoxMembershipChecker {
Box::new(NeverMember {})
}
pub fn allowlist_checker(allowlist: MononokeIdentitySet) -> BoxMembershipChecker {
Box::new(AllowlistChecker { allowlist })
}
}
struct Always... | always_member | identifier_name |
all_6.js | var searchData=
[
['failure',['FAILURE',['../aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921aa5571864412c8275a2e18a931fddcaa6',1,'aws_iot_error.h']]], | ['fpactioncallback_5ft',['fpActionCallback_t',['../aws__iot__shadow__interface_8h.html#ab20a49b955606347ac9d18aef0e421c2',1,'aws_iot_shadow_interface.h']]],
['func_5fentry',['FUNC_ENTRY',['../aws__iot__log_8h.html#a602d2c17a648437184ad780bf897ddae',1,'aws_iot_log.h']]]
]; | random_line_split | |
tabs.component.ts | import { Component, OnInit, ContentChildren, Input, AfterViewInit, QueryList, EventEmitter, Output } from '@angular/core';
import { Tab } from './tab'
import { TabpanelComponent } from './tabpanel.component'
@Component({
selector: 'tabs',
template: `
<ul class="nav nav-tabs" role="tablist" style="marg... | }else{
data.active = false
}
})
}
} | if(data.key == tab.key){
data.active = true | random_line_split |
tabs.component.ts | import { Component, OnInit, ContentChildren, Input, AfterViewInit, QueryList, EventEmitter, Output } from '@angular/core';
import { Tab } from './tab'
import { TabpanelComponent } from './tabpanel.component'
@Component({
selector: 'tabs',
template: `
<ul class="nav nav-tabs" role="tablist" style="marg... | () { }
ngOnInit() {
}
ngAfterContentInit() {
this.panes.forEach(data=>{
if(data.tab.active == true){
this.curTab = data.tab
}
this.tabs.push(data.tab)
});
}
tabClick(tab:Tab){
let reverse:boolean = tab === this.curTab?f... | constructor | identifier_name |
tabs.component.ts | import { Component, OnInit, ContentChildren, Input, AfterViewInit, QueryList, EventEmitter, Output } from '@angular/core';
import { Tab } from './tab'
import { TabpanelComponent } from './tabpanel.component'
@Component({
selector: 'tabs',
template: `
<ul class="nav nav-tabs" role="tablist" style="marg... |
ngOnInit() {
}
ngAfterContentInit() {
this.panes.forEach(data=>{
if(data.tab.active == true){
this.curTab = data.tab
}
this.tabs.push(data.tab)
});
}
tabClick(tab:Tab){
let reverse:boolean = tab === this.curTab?false:t... | { } | identifier_body |
tabs.component.ts | import { Component, OnInit, ContentChildren, Input, AfterViewInit, QueryList, EventEmitter, Output } from '@angular/core';
import { Tab } from './tab'
import { TabpanelComponent } from './tabpanel.component'
@Component({
selector: 'tabs',
template: `
<ul class="nav nav-tabs" role="tablist" style="marg... |
this.activeTab(tab)
}
private activeTab(tab:Tab){
this.tabs.forEach(data=>{
if(data.key == tab.key){
data.active = true
}else{
data.active = false
}
})
}
} | {
this.curTab = tab
this.tabclick.emit(tab)
} | conditional_block |
BaseballGame.js | // Source : https://leetcode.com/problems/baseball-game
// Author : Dean Shi
// Date : 2017-09-24
/***************************************************************************************
*
* You're now a baseball game point recorder
*
* Given a list of strings, each string can be one of the 4 following types
... | * Example 2
* Input: ["5","-2","4","C","D","9
* Output: 27
* Explanation
* Round 1: You could get 5 points. The sum is: 5
* Round 2: You could get -2 points. The sum is: 3
* Round 3: You could get 4 points. The sum is: 7
* Operation 1: The round 3's data is invalid. The sum is: 3
* Round 4: You could get -4 po... | * Round 4: You could get 5 + 10 = 15 points. The sum is: 30
* | random_line_split |
header_footer_shim.tsx | /*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... |
const footerMountPoint = document.getElementById("app-footer");
if (footerMountPoint) {
m.mount(footerMountPoint, {
view() {
return <SiteFooter {...footerData}/>;
}
});
} else {
throw Error("Could not find footer mount point");
}
});
});
| {
throw Error("Could not find menu mount point");
} | conditional_block |
header_footer_shim.tsx | /*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | () {
return <SiteFooter {...footerData}/>;
}
});
} else {
throw Error("Could not find footer mount point");
}
});
});
| view | identifier_name |
header_footer_shim.tsx | /*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | return <SiteFooter {...footerData}/>;
}
});
} else {
throw Error("Could not find footer mount point");
}
});
}); | view() { | random_line_split |
header_footer_shim.tsx | /*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... |
});
} else {
throw Error("Could not find menu mount point");
}
const footerMountPoint = document.getElementById("app-footer");
if (footerMountPoint) {
m.mount(footerMountPoint, {
view() {
return <SiteFooter {...footerData}/>;
}
});
} else {
... | {
return <SiteHeader {...headerData}/>;
} | identifier_body |
searchIndexing.ts | import { getClient } from '../../utils/search/algolia'
import { unTokeniseMarkdown } from '../../utils/search/markdown'
import { interpretExerciseMarkdown } from '../../utils/pocketLisp'
import { SaveObjectResponse } from '@algolia/client-search'
import { ExerciseDoc, ExerciseState } from 'shared/exercise/types'
import... |
export async function removeExerciseIndex(id: string, store?: StoreType): Promise<void> {
if (!store) {
await removeExerciseIndex(id, 'admin')
await removeExerciseIndex(id, 'summary')
} else {
await getExerciseIndex(store).deleteObjects([id])
}
return
}
export async function clearPublicExerciseIn... | {
const data = await getIndexData(exercise, classifications)
const promises = [getExerciseIndex('admin').saveObject({ objectID: id, ...data })]
if (exercise.state === ExerciseState.Public) {
promises.push(getExerciseIndex('summary').saveObject({ objectID: id, ...data }))
}
return await Promise.all(promise... | identifier_body |
searchIndexing.ts | import { getClient } from '../../utils/search/algolia'
import { unTokeniseMarkdown } from '../../utils/search/markdown' | type StoreType = 'summary' | 'admin'
const getExerciseIndex = (store: StoreType) => getClient().initIndex(`exercise-${store}`)
export async function indexExercise(
id: string,
exercise: ExerciseDoc,
classifications: ClassificationSummaryDoc,
): Promise<SaveObjectResponse[]> {
const data = await getIndexData(e... | import { interpretExerciseMarkdown } from '../../utils/pocketLisp'
import { SaveObjectResponse } from '@algolia/client-search'
import { ExerciseDoc, ExerciseState } from 'shared/exercise/types'
import { ClassificationSummaryDoc } from '../../../shared/classification/type'
| random_line_split |
searchIndexing.ts | import { getClient } from '../../utils/search/algolia'
import { unTokeniseMarkdown } from '../../utils/search/markdown'
import { interpretExerciseMarkdown } from '../../utils/pocketLisp'
import { SaveObjectResponse } from '@algolia/client-search'
import { ExerciseDoc, ExerciseState } from 'shared/exercise/types'
import... |
return
}
export async function clearPublicExerciseIndexes(): Promise<void> {
await getExerciseIndex('admin').clearObjects()
await getExerciseIndex('summary').clearObjects()
return
}
const getIndexData = async (exercise: ExerciseDoc, classifications: ClassificationSummaryDoc) => {
const classificationLabels... | {
await getExerciseIndex(store).deleteObjects([id])
} | conditional_block |
searchIndexing.ts | import { getClient } from '../../utils/search/algolia'
import { unTokeniseMarkdown } from '../../utils/search/markdown'
import { interpretExerciseMarkdown } from '../../utils/pocketLisp'
import { SaveObjectResponse } from '@algolia/client-search'
import { ExerciseDoc, ExerciseState } from 'shared/exercise/types'
import... | (
id: string,
exercise: ExerciseDoc,
classifications: ClassificationSummaryDoc,
): Promise<SaveObjectResponse[]> {
const data = await getIndexData(exercise, classifications)
const promises = [getExerciseIndex('admin').saveObject({ objectID: id, ...data })]
if (exercise.state === ExerciseState.Public) {
... | indexExercise | identifier_name |
issue-36023.rs | // Copyright 2016 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 ... |
}
#[inline(never)]
fn env_var(s: &str) -> Result<String, VarError> {
Err(VarError::NotPresent)
}
pub enum VarError {
NotPresent,
NotUnicode(String),
}
| { panic!() } | conditional_block |
issue-36023.rs | // Copyright 2016 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 ... | (s: &str) -> Result<String, VarError> {
Err(VarError::NotPresent)
}
pub enum VarError {
NotPresent,
NotUnicode(String),
}
| env_var | identifier_name |
issue-36023.rs | // Copyright 2016 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 ... | use std::ops::Deref;
fn main() {
if env_var("FOOBAR").as_ref().map(Deref::deref).ok() == Some("yes") {
panic!()
}
let env_home: Result<String, ()> = Ok("foo-bar-baz".to_string());
let env_home = env_home.as_ref().map(Deref::deref).ok();
if env_home == Some("") { panic!() }
}
#[inline(nev... | // run-pass
#![allow(unused_variables)] | random_line_split |
classlognotify_1_1_condicion.js | var classlognotify_1_1_condicion =
[
[ "Condicion", "classlognotify_1_1_condicion.html#a7fa2c60cf042b82ef04a446c8b223a02", null ],
[ "evaluar", "classlognotify_1_1_condicion.html#a1eb83a1cf9cc215fe5eaaab6f6fab971", null ], | ]; | [ "regex_", "classlognotify_1_1_condicion.html#aa9df9f3969295db87c0fc14a380947dd", null ],
[ "signo_", "classlognotify_1_1_condicion.html#ac69675f54d9e6a179bbfa71d371d78ca", null ] | random_line_split |
updateView.py | *
import appView
import glib
import gtk
import pango
import utils
class UpdateItem(DownloadItem):
'''Application item.'''
MAX_CHARS = 50
VERSION_MAX_CHARS = 30
APP_LEFT_PADDING_X = 5
STAR_PADDING_X = 2
NORMAL_PADDING_X = 2
VOTE_PADDING_X = 3
VOTE_PADDING_Y = 1
VERSION_LABEL_WI... | )
appSize = appSizeLabel.getLabel()
appSize.set_size_request(self.SIZE_LABEL_WIDTH, -1)
appSize.set_alignment(1.0, 0.5)
self.appAdditionBox.pack_start(appSize, False, False, self.APP_RIGHT_PADDING_X)
# Add ignore button.
(ignoreLabel, ignoreE... | '''Init normal status.'''
pkg = self.appInfo.pkg
# Clean right box first.
utils.containerRemoveAll(self.appAdditionBox)
# Add application vote information.
self.appVoteView = VoteView(
self.appInfo, PAGE_UPGRADE,
self.sendVoteCallback)
... | identifier_body |
updateView.py | , 0.5, 0.0, 0.0)
self.checkAlign.set_padding(checkPaddingY, checkPaddingY, checkPaddingLeft, checkPaddingRight)
self.checkAlign.add(self.checkButton)
self.itemBox.pack_start(self.checkAlign, False, False)
self.appBasicView = AppBasicView(self.appInfo, 300 + APP_BASIC_WIDTH_ADJUS... | self.itemDict[pkgName].checkButton.set_active(False) | conditional_block | |
updateView.py | *
import appView
import glib
import gtk
import pango
import utils
class UpdateItem(DownloadItem):
'''Application item.'''
MAX_CHARS = 50
VERSION_MAX_CHARS = 30
APP_LEFT_PADDING_X = 5
STAR_PADDING_X = 2
NORMAL_PADDING_X = 2
VOTE_PADDING_X = 3
VOTE_PADDING_Y = 1
VERSION_LABEL_WI... | (self, repoCache, switchStatus, downloadQueue,
entryDetailCallback, sendVoteCallback, fetchVoteCallback, addIgnorePkgCallback):
'''Init for application view.'''
appNum = repoCache.getUpgradableNum()
appView.AppView.__init__(self, appNum, PAGE_UPGRADE)
# Init.
... | __init__ | identifier_name |
updateView.py | *
import appView
import glib
import gtk
import pango
import utils
class UpdateItem(DownloadItem):
'''Application item.'''
MAX_CHARS = 50
VERSION_MAX_CHARS = 30
APP_LEFT_PADDING_X = 5
STAR_PADDING_X = 2
NORMAL_PADDING_X = 2
VOTE_PADDING_X = 3
VOTE_PADDING_Y = 1
VERSION_LABEL_WI... | (appButton, appButtonAlign) = newActionButton(
"update", 0.5, 0.5, "cell", False, __("Action Update"), BUTTON_FONT_SIZE_SMALL, "buttonFont")
appButton.connect("button-release-event", lambda widget, event: self.switchToDownloading())
actionButtonBox.pack_start(appButtonAlign)
... | # Add action button.
(actionButtonBox, actionButtonAlign) = createActionButton()
self.appAdditionBox.pack_start(actionButtonAlign, False, False)
| random_line_split |
test_docker.py | import unittest
import json
import time
from celery import current_app
from django.conf import settings
from django.utils import timezone
from ep.models import DPMeasurements, DeviceParameter
from ep.tasks import send_msg
from django.test import TestCase, modify_settings, override_settings
from ep.tests.static_fac... |
class LocalTaskTest(TestCase):
def test_messaging(self):
print(settings.IODICUS_MESSAGING_HOST)
print(settings.BROKER_URL)
self.assertTrue(send_msg.delay(json.dumps({'test': 1})))
# @override_settings(INFLUXDB_HOST='52.49.171.8')
class InfluxDBTest(TestCase):
@classmethod
def setU... | print(settings.IODICUS_MESSAGING_HOST)
# print(settings.BROKER_URL)
self.assertTrue(send_msg.delay(json.dumps({'test': 1}))) | random_line_split |
test_docker.py | import unittest
import json
import time
from celery import current_app
from django.conf import settings
from django.utils import timezone
from ep.models import DPMeasurements, DeviceParameter
from ep.tasks import send_msg
from django.test import TestCase, modify_settings, override_settings
from ep.tests.static_fac... |
# @override_settings(INFLUXDB_HOST='52.49.171.8')
class InfluxDBTest(TestCase):
@classmethod
def setUpTestData(cls):
SiteFactory.create(name=secure_site_name)
# @unittest.skip
def test_simple_add(self):
print(settings.INFLUXDB_HOST)
m = DPMeasurements(device_parameter=DeviceP... | def test_messaging(self):
print(settings.IODICUS_MESSAGING_HOST)
print(settings.BROKER_URL)
self.assertTrue(send_msg.delay(json.dumps({'test': 1}))) | identifier_body |
test_docker.py | import unittest
import json
import time
from celery import current_app
from django.conf import settings
from django.utils import timezone
from ep.models import DPMeasurements, DeviceParameter
from ep.tasks import send_msg
from django.test import TestCase, modify_settings, override_settings
from ep.tests.static_fac... | (TestCase):
def test_messaging(self):
print(settings.IODICUS_MESSAGING_HOST)
# print(settings.BROKER_URL)
self.assertTrue(send_msg.delay(json.dumps({'test': 1})))
class LocalTaskTest(TestCase):
def test_messaging(self):
print(settings.IODICUS_MESSAGING_HOST)
print(settin... | TaskTest | identifier_name |
test_docker.py | import unittest
import json
import time
from celery import current_app
from django.conf import settings
from django.utils import timezone
from ep.models import DPMeasurements, DeviceParameter
from ep.tasks import send_msg
from django.test import TestCase, modify_settings, override_settings
from ep.tests.static_fac... | unittest.main() | conditional_block | |
ImageButton.js |
/**
* 上午9:16
* 2017年6月28日
* Author : 罗浩 (Luo Hao)
* GitHub : https://github.com/RoJoHub
* Blog : http://blog.csdn.net/mandmg
*/
import React, { PureComponent } from 'react';
import { View, Text, Image, TouchableOpacity, ViewPropTypes } from 'react-native'
import PropTypes from 'prop-types'
export default cla... | let { onPress, disabled, containStyle, activeOpacity, source } = this.props
return (
<TouchableOpacity
style={containStyle}
onPress={onPress}
disabled={disabled}
activeOpacity={activeOpacity}>
<Image source={source} style={containStyle} />
</TouchableOpacity>
... | ops)
}
render() {
| identifier_body |
ImageButton.js |
/**
* 上午9:16
* 2017年6月28日
* Author : 罗浩 (Luo Hao)
* GitHub : https://github.com/RoJoHub
* Blog : http://blog.csdn.net/mandmg
*/
import React, { PureComponent } from 'react';
import { View, Text, Image, TouchableOpacity, ViewPropTypes } from 'react-native'
import PropTypes from 'prop-types'
export default cla... | super(props)
}
render() {
let { onPress, disabled, containStyle, activeOpacity, source } = this.props
return (
<TouchableOpacity
style={containStyle}
onPress={onPress}
disabled={disabled}
activeOpacity={activeOpacity}>
<Image source={source} style={containStyle}... | ops) {
| identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.