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 |
|---|---|---|---|---|
has-phoneme.ts | import { contains, map, without } from 'ramda';
import { sample } from '../../sample';
import { ExerciseTypes } from '../exercises';
import { AbstractExerciseGroup } from './abstract-exercise-group.interface';
export class HasPhoneme extends AbstractExerciseGroup {
protected generateExercises() | sound: `exercises_hoeren_sie_den_laut_${version}`
}),
...this.getExplanationVideos(this.newLetter.toLowerCase()),
...map(word => {
return this.createExercise(ExerciseTypes.HasPhoneme, {
type: 'HasPhoneme',
word,
phoneme: this.newLetter
});
},... | {
if (!this.newLetter) {
return [];
}
const numberOfOldWords: number = 6;
const oldWords = sample(
without(this.newVocabulary, this.vocabulary),
numberOfOldWords
);
const words = sample(
[...oldWords, ...this.newVocabulary],
this.newVocabulary.length + numberOfOldWo... | identifier_body |
has-phoneme.ts | import { contains, map, without } from 'ramda';
import { sample } from '../../sample';
import { ExerciseTypes } from '../exercises';
import { AbstractExerciseGroup } from './abstract-exercise-group.interface';
export class | extends AbstractExerciseGroup {
protected generateExercises() {
if (!this.newLetter) {
return [];
}
const numberOfOldWords: number = 6;
const oldWords = sample(
without(this.newVocabulary, this.vocabulary),
numberOfOldWords
);
const words = sample(
[...oldWords, ...thi... | HasPhoneme | identifier_name |
has-phoneme.ts | import { contains, map, without } from 'ramda';
import { sample } from '../../sample';
import { ExerciseTypes } from '../exercises';
import { AbstractExerciseGroup } from './abstract-exercise-group.interface';
export class HasPhoneme extends AbstractExerciseGroup {
protected generateExercises() {
if (!this.newLe... |
return [];
}
}
|
return [
this.createExercise(ExerciseTypes.InfoScreen, {
type: 'TutorialVideo',
video: `explanation_has_phoneme_${letter}_w_phoneme`
}),
this.createExercise(ExerciseTypes.InfoScreen, {
type: 'TutorialVideo',
video: `explanation_has_phoneme_${letter}... | conditional_block |
has-phoneme.ts | import { contains, map, without } from 'ramda';
import { sample } from '../../sample';
import { ExerciseTypes } from '../exercises';
import { AbstractExerciseGroup } from './abstract-exercise-group.interface';
export class HasPhoneme extends AbstractExerciseGroup { | protected generateExercises() {
if (!this.newLetter) {
return [];
}
const numberOfOldWords: number = 6;
const oldWords = sample(
without(this.newVocabulary, this.vocabulary),
numberOfOldWords
);
const words = sample(
[...oldWords, ...this.newVocabulary],
this.newV... | random_line_split | |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); | *
* 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 and
* limitations under 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 | random_line_split |
expr-match-panic.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let r = match true { true => { true } false => { panic!() } };
assert_eq!(r, true);
}
fn test_box() {
let r = match true { true => { vec!(10) } false => { panic!() } };
assert_eq!(r[0], 10);
}
pub fn main() { test_simple(); test_box(); }
| test_simple | identifier_name |
expr-match-panic.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | false => { panic!() } };
assert_eq!(r, true);
}
fn test_box() {
let r = match true { true => { vec!(10) } false => { panic!() } };
assert_eq!(r[0], 10);
}
pub fn main() { test_simple(); test_box(); }
| { true } | conditional_block |
expr-match-panic.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
pub fn main() { test_simple(); test_box(); } | let r = match true { true => { vec!(10) } false => { panic!() } };
assert_eq!(r[0], 10); | random_line_split |
expr-match-panic.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() { test_simple(); test_box(); }
| {
let r = match true { true => { vec!(10) } false => { panic!() } };
assert_eq!(r[0], 10);
} | identifier_body |
last-use-in-cap-clause.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | { a: ~int }
fn foo() -> @fn() -> int {
let k = ~22;
let _u = A {a: k.clone()};
let result: @fn() -> int = || 22;
result
}
pub fn main() {
assert!(foo()() == 22);
}
| A | identifier_name |
AdobeReaderUpdatesURLProvider.py | #!/usr/bin/python
#
# Copyright 2014: wycomco GmbH (choules@wycomco.de)
# 2015: modifications by Tim Sutton
#
# 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... | AR_PROD = 'com_adobe_Reader'
AR_PROD_ARCH = 'univ'
class AdobeReaderUpdatesURLProvider(Processor):
"""Provides URL to the latest Adobe Reader release."""
description = __doc__
input_variables = {
"major_version": {
"required": False,
"description": ("Major version. Examples:... | AR_PROD_IDENTIFIER = '{PROD}'
AR_PROD_ARCH_IDENTIFIER = '{PROD_ARCH}' | random_line_split |
AdobeReaderUpdatesURLProvider.py | #!/usr/bin/python
#
# Copyright 2014: wycomco GmbH (choules@wycomco.de)
# 2015: modifications by Tim Sutton
#
# 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... | (self, major_version):
'''Returns download URL for Adobe Reader Updater DMG'''
request = urllib2.Request(
AR_UPDATER_BASE_URL + AR_MANIFEST_TEMPLATE % major_version)
try:
url_handle = urllib2.urlopen(request)
version_string = url_handle.read()
url... | get_reader_updater_pkg_url | identifier_name |
AdobeReaderUpdatesURLProvider.py | #!/usr/bin/python
#
# Copyright 2014: wycomco GmbH (choules@wycomco.de)
# 2015: modifications by Tim Sutton
#
# 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... | "description": "Version for this update.",
},
}
def get_reader_updater_pkg_url(self, major_version):
'''Returns download URL for Adobe Reader Updater DMG'''
request = urllib2.Request(
AR_UPDATER_BASE_URL + AR_MANIFEST_TEMPLATE % major_version)
try:
... | """Provides URL to the latest Adobe Reader release."""
description = __doc__
input_variables = {
"major_version": {
"required": False,
"description": ("Major version. Examples: '10', '11'. Defaults to "
"%s" % MAJOR_VERSION_DEFAULT)
},
... | identifier_body |
AdobeReaderUpdatesURLProvider.py | #!/usr/bin/python
#
# Copyright 2014: wycomco GmbH (choules@wycomco.de)
# 2015: modifications by Tim Sutton
#
# 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... | PROCESSOR = AdobeReaderUpdatesURLProvider()
PROCESSOR.execute_shell() | conditional_block | |
functions_64.js | var searchData=
[ | ]; | ['decompile',['Decompile',['../classreranker_1_1_candidate.html#aeb149e5da4251f1854eadbf50230342c',1,'reranker::Candidate']]],
['decompilefeatures',['DecompileFeatures',['../classreranker_1_1_candidate_set.html#acf9fb683cb0435f29188de9218941bca',1,'reranker::CandidateSet']]],
['defined',['Defined',['../classreran... | random_line_split |
line.ts | /// <reference path='../../../typings/tsd.d.ts' />
namespace Charts {
'use strict';
import IChartDataPoint = Charts.IChartDataPoint;
export function createLineChart(svg: any,
timeScale: any,
yScale: any,
chartData: IChartDataPoint[],
height?: number,
interpolation?: string) | // add new ones
pathMetric.enter().append('path')
.attr('class', 'metricLine')
.transition()
.attr('d', metricChartLine);
// remove old ones
pathMetric.exit().remove();
}
}
| {
let metricChartLine = d3.svg.line()
.interpolate(interpolation)
.defined((d: any) => {
return !isEmptyDataPoint(d);
})
.x((d: any) => {
return timeScale(d.timestamp);
})
.y((d: any) => {
return isRawMetric(d) ? yScale(d.value) : yScale(d.avg);
});... | identifier_body |
line.ts | /// <reference path='../../../typings/tsd.d.ts' />
namespace Charts {
'use strict';
import IChartDataPoint = Charts.IChartDataPoint;
export function | (svg: any,
timeScale: any,
yScale: any,
chartData: IChartDataPoint[],
height?: number,
interpolation?: string) {
let metricChartLine = d3.svg.line()
.interpolate(interpolation)
.defined((d: any) => {
return !isEmptyDataPoint(d);
})
.x((d: any) => {
return... | createLineChart | identifier_name |
line.ts | /// <reference path='../../../typings/tsd.d.ts' />
namespace Charts {
'use strict';
import IChartDataPoint = Charts.IChartDataPoint;
export function createLineChart(svg: any,
timeScale: any,
yScale: any,
chartData: IChartDataPoint[],
height?: number,
interpolation?: string) {
let metri... | }
} | random_line_split | |
__init__.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | (FlaskForm):
submit_publish = SubmitField("Publish entry")
class VulnerabilityDeleteForm(FlaskForm):
delete_entry = IntegerField("Delete entry", [validators.DataRequired()])
submit = SubmitField()
class UserProfileForm(BaseForm):
full_name = StringField(
"Name",
description=(
... | VulnerabilityProposalPublish | identifier_name |
__init__.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
class VulnerabilityProposalAssign(FlaskForm):
submit_assign = SubmitField("Take review")
class VulnerabilityProposalUnassign(FlaskForm):
submit_unassign = SubmitField("Unassign from this review")
class VulnerabilityProposalPublish(FlaskForm):
submit_publish = SubmitField("Publish entry")
class Vuln... | submit_approve = SubmitField("Approve proposal") | identifier_body |
__init__.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
class ModelFieldList(FieldList):
def __init__(self, *args, **kwargs):
self.model = kwargs.pop("model", None)
super().__init__(*args, **kwargs)
if not self.model:
raise ValueError("ModelFieldList requires model to be set")
def populate_obj(self, obj, name):
if not ... | if isinstance(field, HiddenField):
continue
yield field | conditional_block |
__init__.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
class VulnerabilityProposalPublish(FlaskForm):
submit_publish = SubmitField("Publish entry")
class VulnerabilityDeleteForm(FlaskForm):
delete_entry = IntegerField("Delete entry", [validators.DataRequired()])
submit = SubmitField()
class UserProfileForm(BaseForm):
full_name = StringField(
"... | class VulnerabilityProposalUnassign(FlaskForm):
submit_unassign = SubmitField("Unassign from this review") | random_line_split |
editor_subscribe_label_deleted.py | """
.. module:: editor_subscribe_label_deleted
The **Editor Subscribe Label Deleted** Model.
PostgreSQL Definition
---------------------
The :code:`editor_subscribe_label_deleted` table is defined in the MusicBrainz Server as:
.. code-block:: sql
CREATE TABLE editor_subscribe_label_deleted
(
editor... | :
db_table = 'editor_subscribe_label_deleted'
| Meta | identifier_name |
editor_subscribe_label_deleted.py |
PostgreSQL Definition
---------------------
The :code:`editor_subscribe_label_deleted` table is defined in the MusicBrainz Server as:
.. code-block:: sql
CREATE TABLE editor_subscribe_label_deleted
(
editor INTEGER NOT NULL, -- PK, references editor.id
gid UUID NOT NULL, -- PK, references de... | """
.. module:: editor_subscribe_label_deleted
The **Editor Subscribe Label Deleted** Model. | random_line_split | |
editor_subscribe_label_deleted.py | """
.. module:: editor_subscribe_label_deleted
The **Editor Subscribe Label Deleted** Model.
PostgreSQL Definition
---------------------
The :code:`editor_subscribe_label_deleted` table is defined in the MusicBrainz Server as:
.. code-block:: sql
CREATE TABLE editor_subscribe_label_deleted
(
editor... | """
Not all parameters are listed here, only those that present some interest
in their Django implementation.
:param editor: references :class:`.editor`
:param gid: references :class:`.deleted_entity`
:param deleted_by: references :class:`.edit`
"""
editor = models.OneToOneField('editor', ... | identifier_body | |
agent.rs | #![allow(non_snake_case)]
use std::collections::HashMap;
use request::Handler;
use serde_json;
use error::ConsulResult;
use std::error::Error;
use super::{Service, RegisterService, TtlHealthCheck};
/// Agent can be used to query the Agent endpoints
pub struct Agent{
handler: Handler
}
/// AgentMember represent... | (&self, health_check: TtlHealthCheck) -> ConsulResult<()> {
let json_str = serde_json::to_string(&health_check)
.map_err(|e| e.description().to_owned())?;
if let Err(e) = self.handler.put("check/register", json_str, Some("application/json")) {
Err(format!("Consul: Error register... | register_ttl_check | identifier_name |
agent.rs | #![allow(non_snake_case)]
use std::collections::HashMap;
use request::Handler;
use serde_json;
use error::ConsulResult;
use std::error::Error;
use super::{Service, RegisterService, TtlHealthCheck};
/// Agent can be used to query the Agent endpoints
pub struct Agent{
handler: Handler
}
/// AgentMember represent... |
else {
Ok(())
}
}
pub fn register_ttl_check(&self, health_check: TtlHealthCheck) -> ConsulResult<()> {
let json_str = serde_json::to_string(&health_check)
.map_err(|e| e.description().to_owned())?;
if let Err(e) = self.handler.put("check/register", json... | {
Err(format!("Consul: Error registering a service. Err:{}", e))
} | conditional_block |
agent.rs | #![allow(non_snake_case)]
use std::collections::HashMap;
use request::Handler;
use serde_json;
use error::ConsulResult;
use std::error::Error;
use super::{Service, RegisterService, TtlHealthCheck};
/// Agent can be used to query the Agent endpoints
pub struct Agent{
handler: Handler
}
/// AgentMember represent... |
}
| {
let result = self.handler.get("self")?;
let json_data = serde_json::from_str(&result)
.map_err(|e| e.description().to_owned())?;
Ok(super::get_string(&json_data, &["Config", "AdvertiseAddr"]))
} | identifier_body |
agent.rs | #![allow(non_snake_case)]
use std::collections::HashMap;
use request::Handler;
use serde_json;
use error::ConsulResult;
use std::error::Error;
|
/// Agent can be used to query the Agent endpoints
pub struct Agent{
handler: Handler
}
/// AgentMember represents a cluster member known to the agent
#[derive(Serialize, Deserialize)]
pub struct AgentMember {
Name: String,
Addr: String,
Port: u16,
Tags: HashMap<String, String>,
Status: usize,
ProtocolMin: ... | use super::{Service, RegisterService, TtlHealthCheck}; | random_line_split |
main.rs | // Copyright (C) 2015, Alberto Corona <alberto@0x1a.us>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
#![crate_type = "bin"]
#![crate_name = "rm"]
#![feature(path_ext)]
static VERS: &'static str = "0.1.0";
static PROG: &'s... |
}
}
fn print_usage(opts: Options) {
print!("Usage: rm [OPTION...] FILE...\n\
Remove FILE(s) {}\n\
Examples:
rm -r dir\tDeletes `dir` and all of its contents", opts.usage(""));
}
fn main() {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optflag("v"... | {
rm_dir(path, recurse, verbose);
} | conditional_block |
main.rs | // Copyright (C) 2015, Alberto Corona <alberto@0x1a.us>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
#![crate_type = "bin"]
#![crate_name = "rm"]
#![feature(path_ext)]
static VERS: &'static str = "0.1.0";
static PROG: &'s... |
fn rm_dir(dir: &PathBuf, recurse: bool, verbose: bool) {
if recurse {
match fs::remove_dir_all(dir) {
Ok(_) => {
if verbose {
println!("Removed: '{}'", dir.display());
}
},
Err(e) => {
util::err(PROG, S... | {
match fs::remove_file(file) {
Ok(_) => {
if verbose {
println!("Removed: '{}'", file.display());
}
},
Err(e) => {
util::err(PROG, Status::Error, e.to_string());
panic!();
}
};
} | identifier_body |
main.rs | // Copyright (C) 2015, Alberto Corona <alberto@0x1a.us>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
#![crate_type = "bin"]
#![crate_name = "rm"]
#![feature(path_ext)]
static VERS: &'static str = "0.1.0";
static PROG: &'s... | for item in matches.free.iter() {
rm_target(&PathBuf::from(&item), recurse, verb);
}
} else if matches.free.is_empty() {
util::prog_try(PROG);
}
} | } else if matches.opt_present("version") {
util::copyright(PROG, VERS, "2015", vec!["Alberto Corona"]);
} else if !matches.free.is_empty() { | random_line_split |
main.rs | // Copyright (C) 2015, Alberto Corona <alberto@0x1a.us>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
#![crate_type = "bin"]
#![crate_name = "rm"]
#![feature(path_ext)]
static VERS: &'static str = "0.1.0";
static PROG: &'s... | (file: &PathBuf, verbose: bool) {
match fs::remove_file(file) {
Ok(_) => {
if verbose {
println!("Removed: '{}'", file.display());
}
},
Err(e) => {
util::err(PROG, Status::Error, e.to_string());
panic!();
}
};
}
fn... | rm_file | identifier_name |
index.js | 'use strict';
var path = require('path'),
util = require('util'), | ngUtil = require('../../utils/componentUtil'),
ScriptBase = require('../../script-base.js');
var Generator = module.exports = function Generator() {
ScriptBase.apply(this, arguments);
};
util.inherits(Generator, ScriptBase);
Generator.prototype.prompting = function askFor() {
var self = this;
var d... | lodash = require ('lodash'), | random_line_split |
post.js | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company, L.P.
import path from 'path';
import fecha from 'fecha';
import lunr from 'lunr';
import GithubPostDAO from '../persistance/GithubPostDAO';
import PostDAO from '../persistance/PostDAO';
export function loadPosts () {
return new PostDAO().ge... |
return archive;
}
export function buildSearchIndex (posts) {
const index = lunr(function () {
this.field('title', {boost: 10});
this.field('author', {boost: 2});
this.field('content', {boost: 5});
this.field('tags');
this.ref('id');
});
posts.forEach((post) => index.add(post));
return... | {
archive[monthLabel] = postsByMonth[monthLabel];
} | conditional_block |
post.js | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company, L.P.
import path from 'path';
import fecha from 'fecha';
import lunr from 'lunr';
import GithubPostDAO from '../persistance/GithubPostDAO';
import PostDAO from '../persistance/PostDAO';
export function loadPosts () {
return new PostDAO().ge... |
export function getImageAsBase64 (imagePath) {
const postPath = imagePath.split('server/posts/')[1];
const postFolderGroup = postPath.split('/images/');
const postFolderName = postFolderGroup[0];
const imageName = decodeURI(postFolderGroup[1]);
return new GithubPostDAO(postFolderName).getImageAsBase64(image... | {
const postFolderName = getPostFolderName(id);
return new GithubPostDAO(postFolderName).getPending();
} | identifier_body |
post.js | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company, L.P.
import path from 'path';
import fecha from 'fecha';
import lunr from 'lunr';
import GithubPostDAO from '../persistance/GithubPostDAO';
import PostDAO from '../persistance/PostDAO';
export function loadPosts () {
return new PostDAO().ge... | (id) {
const postFolderName = getPostFolderName(id);
if (process.env.BLOG_PERSISTANCE === 'github') {
return new GithubPostDAO(postFolderName).delete();
} else {
return new PostDAO(postFolderName).delete(
path.resolve(path.join(__dirname, '../../'))
);
}
}
export function getAllPosts () {
... | deletePost | identifier_name |
pksig_ps03.py | """
Identity Based Signature
| From: "David Pointcheval and Olivier Sanders. Short Randomizable Signatures"
| Published in: 2015
| Available from: https://eprint.iacr.org/2015/525.pdf
* type: signature (identity-based)
* setting: bilinear groups (asymmetric)
:Authors: Lovesh Harchandani
:Date: ... |
sig = ps.unblind_signature(t, sig)
result = ps.verify(pk, sig, *messages)
assert result, "INVALID signature!"
if debug:
print("Successful Verification!!!")
rand_sig = ps.randomize_sig(sig)
assert sig != rand_sig
if debug:
print("Randomized Signature: ", rand_sig)
res... | print("Signature: ", sig) | conditional_block |
pksig_ps03.py | """
Identity Based Signature
| From: "David Pointcheval and Olivier Sanders. Short Randomizable Signatures"
| Published in: 2015
| Available from: https://eprint.iacr.org/2015/525.pdf
* type: signature (identity-based)
* setting: bilinear groups (asymmetric)
:Authors: Lovesh Harchandani
:Date: ... | ():
grp = PairingGroup('MNT224')
ps = PS01(grp)
messages = ['Hi there', 'Not there', 'Some message ................', 'Dont know .............']
(pk, sk) = ps.keygen(len(messages))
if debug:
print("Keygen...")
print("pk :=", pk)
print("sk :=", sk)
t, commitment = ps.com... | main | identifier_name |
pksig_ps03.py | """
Identity Based Signature
| From: "David Pointcheval and Olivier Sanders. Short Randomizable Signatures"
| Published in: 2015
| Available from: https://eprint.iacr.org/2015/525.pdf
* type: signature (identity-based)
* setting: bilinear groups (asymmetric)
:Authors: Lovesh Harchandani
:Date: ... |
def commitment(self, pk, *messages):
t = group.random(ZR)
return t, (pk['g1'] ** t) * self.product([y1 ** group.hash(m, ZR) for (y1, m) in zip(pk['Y1'], messages)])
def sign(self, sk, pk, commitment):
u = group.random(ZR)
return pk['g1'] ** u, (sk['X1'] * commitment) ** u
... | x = group.random(ZR)
g1 = group.random(G1)
sk = {'x': x, 'X1': g1 ** x}
g2 = group.random(G2)
ys = [group.random(ZR) for _ in range(num_messages)]
X2 = g2 ** x
y1s = [g1 ** y for y in ys]
y2s = [g2 ** y for y in ys]
pk = {'X2': X2, 'Y2': y2s, 'Y1': y1s, 'g... | identifier_body |
pksig_ps03.py | """
Identity Based Signature
| From: "David Pointcheval and Olivier Sanders. Short Randomizable Signatures"
| Published in: 2015
| Available from: https://eprint.iacr.org/2015/525.pdf
* type: signature (identity-based)
* setting: bilinear groups (asymmetric)
:Authors: Lovesh Harchandani
:Date: ... | global group
group = groupObj
@staticmethod
def keygen(num_messages=1):
x = group.random(ZR)
g1 = group.random(G1)
sk = {'x': x, 'X1': g1 ** x}
g2 = group.random(G2)
ys = [group.random(ZR) for _ in range(num_messages)]
X2 = g2 ** x
y1s = [... | Signatures over committed messages, section 6.1 of the paper
"""
def __init__(self, groupObj): | random_line_split |
fork.ts | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
import type { ComponentMeta } from 'core/component/interface';
/**
* Creates a new meta object from the specified
* @param base
*/
export function forkMeta(... | const
key = keys[i],
v = p[key];
if (v != null) {
o[key] = v.slice();
}
}
return meta;
}
| {
const
meta = Object.create(base);
meta.watchDependencies = new Map(meta.watchDependencies);
meta.params = Object.create(base.params);
meta.watchers = {};
meta.hooks = {};
for (let o = meta.hooks, p = base.hooks, keys = Object.keys(p), i = 0; i < keys.length; i++) {
const
key = keys[i],
v = p[key];
... | identifier_body |
fork.ts | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
import type { ComponentMeta } from 'core/component/interface';
/**
* Creates a new meta object from the specified
* @param base
*/
export function | (base: ComponentMeta): ComponentMeta {
const
meta = Object.create(base);
meta.watchDependencies = new Map(meta.watchDependencies);
meta.params = Object.create(base.params);
meta.watchers = {};
meta.hooks = {};
for (let o = meta.hooks, p = base.hooks, keys = Object.keys(p), i = 0; i < keys.length; i++) {
con... | forkMeta | identifier_name |
fork.ts | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
import type { ComponentMeta } from 'core/component/interface';
/**
* Creates a new meta object from the specified
* @param base
*/
export function forkMeta(... | v = p[key];
if (v != null) {
o[key] = v.slice();
}
}
for (let o = meta.watchers, p = base.watchers, keys = Object.keys(p), i = 0; i < keys.length; i++) {
const
key = keys[i],
v = p[key];
if (v != null) {
o[key] = v.slice();
}
}
return meta;
} | key = keys[i], | random_line_split |
fork.ts | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
import type { ComponentMeta } from 'core/component/interface';
/**
* Creates a new meta object from the specified
* @param base
*/
export function forkMeta(... |
for (let o = meta.watchers, p = base.watchers, keys = Object.keys(p), i = 0; i < keys.length; i++) {
const
key = keys[i],
v = p[key];
if (v != null) {
o[key] = v.slice();
}
}
return meta;
}
| {
const
key = keys[i],
v = p[key];
if (v != null) {
o[key] = v.slice();
}
} | conditional_block |
DbConfig.ts | import NoSqlProvider = require('nosqlprovider');
import DbModels = require('./DbModels');
// The actual value is just a string, but the type system can extract this extra info.
type DBStore<Name extends string, ObjectType, KeyFormat> = string & { name?: Name, objectType?: ObjectType, keyFormat?: KeyFormat };
type DBI... | noteSearchTerms: 'noteItems_searchTerms' as DBIndex<typeof Stores.noteItems, string>,
};
export const _databaseName = 'db';
export const _dbSchemaVersion = 1;
export const _dbSchema: NoSqlProvider.DbSchema = {
version: _dbSchemaVersion,
lastUsableVersion: _dbSchemaVersion,
stores: [
{
... | export const Indexes = { | random_line_split |
draw.rs | use nannou::prelude::*;
fn main() |
fn view(app: &App, frame: Frame) {
// Begin drawing
let draw = app.draw();
// Clear the background to blue.
draw.background().color(CORNFLOWERBLUE);
// Draw a purple triangle in the top left half of the window.
let win = app.window_rect();
draw.tri()
.points(win.bottom_left(), wi... | {
nannou::sketch(view).run()
} | identifier_body |
draw.rs | use nannou::prelude::*;
fn main() {
nannou::sketch(view).run()
}
fn view(app: &App, frame: Frame) {
// Begin drawing
let draw = app.draw();
// Clear the background to blue.
draw.background().color(CORNFLOWERBLUE);
// Draw a purple triangle in the top left half of the window.
let win = ap... | draw.line()
.weight(10.0 + (t.sin() * 0.5 + 0.5) * 90.0)
.caps_round()
.color(PALEGOLDENROD)
.points(win.top_left() * t.sin(), win.bottom_right() * t.cos());
// Draw a quad that follows the inverse of the ellipse.
draw.quad()
.x_y(-app.mouse.x, app.mouse.y)
.... | .radius(win.w() * 0.125 * t.sin())
.color(RED);
// Draw a line! | random_line_split |
draw.rs | use nannou::prelude::*;
fn | () {
nannou::sketch(view).run()
}
fn view(app: &App, frame: Frame) {
// Begin drawing
let draw = app.draw();
// Clear the background to blue.
draw.background().color(CORNFLOWERBLUE);
// Draw a purple triangle in the top left half of the window.
let win = app.window_rect();
draw.tri()
... | main | identifier_name |
data-web-examples.js | /**
* @file
* This file is used by "npm test" to selftest the succss package.
* Selftests are made from http://succss.ifzenelse.net documentation website.
*
* @see selftests/run.sh, selftests/test.sh
*
*/
var baseUrl = 'succss.ifzenelse.net';
Succss.pages = {
'home': {
url:'succss.ifzenelse.net',
di... | casper.test.assertNotEquals(fs.size(capture.filePath), fs.size(capture.basePath), 'Base and update are different in size.');
}
}
}
Succss.viewports = {
'classic-wide': {
width: 1366,
height: 768
},
}
Succss.options = {
imagediff:false,
resemble:false,
diff:true,
exitOnError:false
}
Su... | if (!capture.options.good && !capture.page.good) {
casper.test.assertTruthy(fs.exists(capture.filePath), 'The updated capture was taken (' + capture.filePath + ').'); | random_line_split |
data-web-examples.js | /**
* @file
* This file is used by "npm test" to selftest the succss package.
* Selftests are made from http://succss.ifzenelse.net documentation website.
*
* @see selftests/run.sh, selftests/test.sh
*
*/
var baseUrl = 'succss.ifzenelse.net';
Succss.pages = {
'home': {
url:'succss.ifzenelse.net',
di... |
}
}
Succss.viewports = {
'classic-wide': {
width: 1366,
height: 768
},
}
Succss.options = {
imagediff:false,
resemble:false,
diff:true,
exitOnError:false
}
Succss.diff = function(imgBase, imgCheck, capture) {
if (capture.page.name == 'custom-resemble') {
try {
this.injectJs(capt... | {
casper.test.assertTruthy(fs.exists(capture.filePath), 'The updated capture was taken (' + capture.filePath + ').');
casper.test.assertNotEquals(fs.size(capture.filePath), fs.size(capture.basePath), 'Base and update are different in size.');
} | conditional_block |
drawer.tsx | import React from 'react'
import fade from 'src/components/fade'
import Link from './link'
import { connect } from 'react-redux'
import { Dispatch, Action } from 'redux'
import { toggleNav } from './actions'
import { IAppState } from 'src/app-reducer'
const styles = require('./drawer.scss')
interface IDrawerStateProps... |
@fade()
class Drawer extends React.Component<IDrawerStateProps & IDrawerDispatchProps, {}> {
public render(): JSX.Element {
return (
<div className={styles.navDrawer}>
<div className={styles.backgroundOverlay} onClick={this.handleClick} />
<div className={styles.navLinksContainer}>
... | }
interface IDrawerDispatchProps {
toggleNav: () => void,
} | random_line_split |
drawer.tsx | import React from 'react'
import fade from 'src/components/fade'
import Link from './link'
import { connect } from 'react-redux'
import { Dispatch, Action } from 'redux'
import { toggleNav } from './actions'
import { IAppState } from 'src/app-reducer'
const styles = require('./drawer.scss')
interface IDrawerStateProps... | extends React.Component<IDrawerStateProps & IDrawerDispatchProps, {}> {
public render(): JSX.Element {
return (
<div className={styles.navDrawer}>
<div className={styles.backgroundOverlay} onClick={this.handleClick} />
<div className={styles.navLinksContainer}>
<ul className={styl... | Drawer | identifier_name |
swagger_model.py | # -*- coding: utf-8 -*-
import contextlib
import logging
import os
import os.path
import yaml
from bravado_core.spec import is_yaml
from six.moves import urllib
from six.moves.urllib import parse as urlparse
from bravado.compat import json
from bravado.requests_client import RequestsClient
log = logging.getLogger(__... | (self, timeout=None):
with contextlib.closing(urllib.request.urlopen(self.get_path())) as fp:
content = fp.read()
return self.FileResponse(content)
def result(self, *args, **kwargs):
return self.wait(*args, **kwargs)
def cancel(self):
pass
def request(http_cli... | wait | identifier_name |
swagger_model.py | # -*- coding: utf-8 -*-
import contextlib
import logging
import os
import os.path
import yaml
from bravado_core.spec import is_yaml
from six.moves import urllib
from six.moves.urllib import parse as urlparse
from bravado.compat import json
from bravado.requests_client import RequestsClient
log = logging.getLogger(__... |
return data
# TODO: Adding the file scheme here just adds complexity to request()
# Is there a better way to handle this?
def load_file(spec_file, http_client=None):
"""Loads a spec file
:param spec_file: Path to swagger.json.
:param http_client: HTTP client interface.
:return: validated js... | if 'responses' in operation:
operation['responses'] = dict(
(str(code), response)
for code, response in iter(
operation['responses'].items()
)
) | conditional_block |
swagger_model.py | # -*- coding: utf-8 -*-
import contextlib
import logging
import os
import os.path
import yaml
from bravado_core.spec import is_yaml
from six.moves import urllib
from six.moves.urllib import parse as urlparse
from bravado.compat import json
from bravado.requests_client import RequestsClient
log = logging.getLogger(__... | return data
# TODO: Adding the file scheme here just adds complexity to request()
# Is there a better way to handle this?
def load_file(spec_file, http_client=None):
"""Loads a spec file
:param spec_file: Path to swagger.json.
:param http_client: HTTP client interface.
:return: validated jso... | """Load a YAML Swagger spec from the given string, transforming
integer response status codes to strings. This is to keep
compatibility with the existing YAML spec examples in
https://github.com/OAI/OpenAPI-Specification/tree/master/examples/v2.0/yaml
:param text: String from which to pa... | identifier_body |
swagger_model.py | # -*- coding: utf-8 -*-
import contextlib
import logging
import os
import os.path
import yaml
from bravado_core.spec import is_yaml
from six.moves import urllib
from six.moves.urllib import parse as urlparse
from bravado.compat import json
from bravado.requests_client import RequestsClient
log = logging.getLogger(__... | loader = Loader(http_client=http_client)
return loader.load_spec(spec_url, base_url=base_url) | :raise: IOError, URLError: On error reading api-docs.
"""
if http_client is None:
http_client = RequestsClient()
| random_line_split |
option-like-enum.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... | () {
let some_str: Option<&'static str> = Some("abc");
let none_str: Option<&'static str> = None;
let some: Option<&u32> = Some(unsafe { std::mem::transmute(0x12345678_usize) });
let none: Option<&u32> = None;
let full = MoreFields::Full(454545, unsafe { std::mem::transmute(0x87654321_usize) }, 9... | main | identifier_name |
option-like-enum.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... | let full = MoreFields::Full(454545, unsafe { std::mem::transmute(0x87654321_usize) }, 9988);
let empty = MoreFields::Empty;
let empty_gdb: &MoreFieldsRepr = unsafe { std::mem::transmute(&MoreFields::Empty) };
let droid = NamedFields::Droid {
id: 675675,
range: 10000001,
interna... | let some: Option<&u32> = Some(unsafe { std::mem::transmute(0x12345678_usize) });
let none: Option<&u32> = None;
| random_line_split |
option-like-enum.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... | {()} | identifier_body | |
validate.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from math import isinf, isnan
from warnings import warn
NOT_MASS_BALANCED_TERMS = {"SBO:0000627", # EXCHANGE |
def check_mass_balance(model):
unbalanced = {}
for reaction in model.reactions:
if reaction.annotation.get("SBO") not in NOT_MASS_BALANCED_TERMS:
balance = reaction.check_mass_balance()
if balance:
unbalanced[reaction] = balance
return unbalanced
# no long... | "SBO:0000628", # DEMAND
"SBO:0000629", # BIOMASS
"SBO:0000631", # PSEUDOREACTION
"SBO:0000632", # SINK
} | random_line_split |
validate.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from math import isinf, isnan
from warnings import warn
NOT_MASS_BALANCED_TERMS = {"SBO:0000627", # EXCHANGE
"SBO:0000628", # DEMAND
"SBO:0000629", # BIOMASS
"SBO:0000631... |
# no longer strictly necessary, done by optlang solver interfaces
def check_reaction_bounds(model):
warn("no longer necessary, done by optlang solver interfaces",
DeprecationWarning)
errors = []
for reaction in model.reactions:
if reaction.lower_bound > reaction.upper_bound:
... | unbalanced = {}
for reaction in model.reactions:
if reaction.annotation.get("SBO") not in NOT_MASS_BALANCED_TERMS:
balance = reaction.check_mass_balance()
if balance:
unbalanced[reaction] = balance
return unbalanced | identifier_body |
validate.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from math import isinf, isnan
from warnings import warn
NOT_MASS_BALANCED_TERMS = {"SBO:0000627", # EXCHANGE
"SBO:0000628", # DEMAND
"SBO:0000629", # BIOMASS
"SBO:0000631... |
return errors
| if met.formula is not None and len(met.formula) > 0:
if not met.formula.isalnum():
errors.append("Metabolite '%s' formula '%s' not alphanumeric" %
(met.id, met.formula)) | conditional_block |
validate.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from math import isinf, isnan
from warnings import warn
NOT_MASS_BALANCED_TERMS = {"SBO:0000627", # EXCHANGE
"SBO:0000628", # DEMAND
"SBO:0000629", # BIOMASS
"SBO:0000631... | (model):
unbalanced = {}
for reaction in model.reactions:
if reaction.annotation.get("SBO") not in NOT_MASS_BALANCED_TERMS:
balance = reaction.check_mass_balance()
if balance:
unbalanced[reaction] = balance
return unbalanced
# no longer strictly necessary, d... | check_mass_balance | identifier_name |
position.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 https://mozilla.org/MPL/2.0/. */
//! Generic types for CSS handling of specified and computed values of
//! [`position`](https://drafts.csswg.org/... | #[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
Parse,
SpecifiedValueInfo,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C, u8)]
pub enum GenericZIndex<I> {
/// An integer value.
Integer... | }
/// A generic value for the `z-index` property. | random_line_split |
position.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 https://mozilla.org/MPL/2.0/. */
//! Generic types for CSS handling of specified and computed values of
//! [`position`](https://drafts.csswg.org/... | <H, V> {
/// The horizontal component of position.
pub horizontal: H,
/// The vertical component of position.
pub vertical: V,
}
pub use self::GenericPosition as Position;
impl<H, V> Position<H, V> {
/// Returns a new position.
pub fn new(horizontal: H, vertical: V) -> Self {
Self {
... | GenericPosition | identifier_name |
event-valuechange.js | the user is likely
to be interacting with it.
@property POLL_INTERVAL
@type Number
@default 50
@static
**/
POLL_INTERVAL: 50,
/**
Timeout (in milliseconds) after which to stop polling when there hasn't been
any new activity (keypresses, mouse clicks, etc.) on an element.
... | else {
vcData.notifiers[Y.stamp(notifier)] = notifier;
return;
}
}
// Poll for changes to the node's value. We can't rely on keyboard
// events for this, since the value may change due to a mouse-initiated
// paste event, an IME input event, ... | {
VC._stopPolling(node, notifier); // restart polling, but avoid dupe polls
} | conditional_block |
event-valuechange.js | the user is likely
to be interacting with it.
@property POLL_INTERVAL
@type Number
@default 50
@static
**/
POLL_INTERVAL: 50,
/**
Timeout (in milliseconds) after which to stop polling when there hasn't been
any new activity (keypresses, mouse clicks, etc.) on an element.
... | /**
Restarts the inactivity timeout for the specified node.
@method _refreshTimeout
@param {Node} node Node to refresh.
@param {SyntheticEvent.Notifier} notifier
@protected
@static
**/
_refreshTimeout: function (node, notifier) {
// The node may have been destroyed, so check... |
VC._refreshTimeout(node);
}
},
| random_line_split |
DelegationStepsConfirmationDialog.tsx | import React, { Component } from 'react';
import { intlShape, FormattedMessage, FormattedHTMLMessage } from 'react-intl';
import vjf from 'mobx-react-form/lib/validators/VJF';
import classNames from 'classnames';
import { get } from 'lodash';
import { observer } from 'mobx-react';
import { Stepper } from 'react-polymor... | const { selectedWallet } = this.props;
const isHardwareWallet = get(selectedWallet, 'isHardwareWallet');
const { spendingPassword } = form.values();
this.props.onConfirm(spendingPassword, isHardwareWallet);
},
onError: () => {},
});
};
handleSubmitOnEnter = submitOnEn... | onSuccess: (form) => { | random_line_split |
semantic_version.rs | // Copyright 2015-2017 Parity Technologies (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 lat... | {
/// Major version - API/feature removals & breaking changes.
pub major: u8,
/// Minor version - API/feature additions.
pub minor: u8,
/// Tiny version - bug fixes.
pub tiny: u8,
}
impl SemanticVersion {
/// Create a new object.
pub fn new(major: u8, minor: u8, tiny: u8) -> SemanticVe... | SemanticVersion | identifier_name |
semantic_version.rs | // Copyright 2015-2017 Parity Technologies (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 lat... | // along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Semantic version formatting and comparing.
/// A version value with strict meaning. Use `as_u32` to convert to a simple integer.
///
/// # Example
/// ```
/// extern crate util;
/// use util::semantic_version::*;
///
/// fn main() {
/// assert_e... | // You should have received a copy of the GNU General Public License | random_line_split |
disableJsDiagnostics.ts | /* @internal */
namespace ts.codefix {
const fixName = "disableJsDiagnostics";
const fixId = "disableJsDiagnostics";
const errorCodes = mapDefined(Object.keys(Diagnostics) as readonly (keyof typeof Diagnostics)[], key => {
const diag = Diagnostics[key];
return diag.category === Diagnos... | } | random_line_split | |
disableJsDiagnostics.ts | /* @internal */
namespace ts.codefix {
const fixName = "disableJsDiagnostics";
const fixId = "disableJsDiagnostics";
const errorCodes = mapDefined(Object.keys(Diagnostics) as readonly (keyof typeof Diagnostics)[], key => {
const diag = Diagnostics[key];
return diag.category === Diagnos... |
});
},
});
function makeChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, position: number, seenLines?: Set<number>) {
const { line: lineNumber } = getLineAndCharacterOfPosition(sourceFile, position);
// Only need to add `// @ts-ignore` for a line on... | {
makeChange(changes, diag.file, diag.start, seenLines);
} | conditional_block |
disableJsDiagnostics.ts | /* @internal */
namespace ts.codefix {
const fixName = "disableJsDiagnostics";
const fixId = "disableJsDiagnostics";
const errorCodes = mapDefined(Object.keys(Diagnostics) as readonly (keyof typeof Diagnostics)[], key => {
const diag = Diagnostics[key];
return diag.category === Diagnos... |
}
| {
const { line: lineNumber } = getLineAndCharacterOfPosition(sourceFile, position);
// Only need to add `// @ts-ignore` for a line once.
if (!seenLines || tryAddToSet(seenLines, lineNumber)) {
changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore");
... | identifier_body |
disableJsDiagnostics.ts | /* @internal */
namespace ts.codefix {
const fixName = "disableJsDiagnostics";
const fixId = "disableJsDiagnostics";
const errorCodes = mapDefined(Object.keys(Diagnostics) as readonly (keyof typeof Diagnostics)[], key => {
const diag = Diagnostics[key];
return diag.category === Diagnos... | (changes: textChanges.ChangeTracker, sourceFile: SourceFile, position: number, seenLines?: Set<number>) {
const { line: lineNumber } = getLineAndCharacterOfPosition(sourceFile, position);
// Only need to add `// @ts-ignore` for a line once.
if (!seenLines || tryAddToSet(seenLines, lineNumber)... | makeChange | identifier_name |
Browsers.js | Ext.define('KitchenSink.store.Browsers', {
extend: 'Ext.data.Store',
alias: 'store.browsers',
fields: ['month', 'data1', 'data2', 'data3', 'data4', 'other'],
data: [
{ month: 'Jan', data1: 20, data2: 37, data3: 35, data4: 4, other: 4 },
{ month: 'Feb', data1: 20, data2: 37, data3: 36, d... | { month: 'Sep', data1: 16, data2: 32, data3: 44, data4: 4, other: 4 },
{ month: 'Oct', data1: 16, data2: 32, data3: 45, data4: 4, other: 3 },
{ month: 'Nov', data1: 15, data2: 31, data3: 46, data4: 4, other: 4 },
{ month: 'Dec', data1: 15, data2: 31, data3: 47, data4: 4, other: 3 }
]... | { month: 'Jul', data1: 16, data2: 34, data3: 43, data4: 4, other: 3 },
{ month: 'Aug', data1: 16, data2: 33, data3: 44, data4: 4, other: 3 }, | random_line_split |
icon-filter.pipe.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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 ... | implements PipeTransform {
public transform(icons: string[], filter: string): string[] {
if (filter) {
const iconsByMeta = searchIconsByMeta(filter);
return icons.filter(icon => iconsByMeta.indexOf(getPureIconName(icon)) >= 0);
} else {
return icons;
}
}
}
| IconFilterPipe | identifier_name |
icon-filter.pipe.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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 ... | @Pipe({
name: 'iconFilter',
})
export class IconFilterPipe implements PipeTransform {
public transform(icons: string[], filter: string): string[] {
if (filter) {
const iconsByMeta = searchIconsByMeta(filter);
return icons.filter(icon => iconsByMeta.indexOf(getPureIconName(icon)) >= 0);
} else {
... | */
import {Pipe, PipeTransform} from '@angular/core';
import {getPureIconName, searchIconsByMeta} from '../../icons';
| random_line_split |
icon-filter.pipe.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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 ... | else {
return icons;
}
}
}
| {
const iconsByMeta = searchIconsByMeta(filter);
return icons.filter(icon => iconsByMeta.indexOf(getPureIconName(icon)) >= 0);
} | conditional_block |
icon-filter.pipe.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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 ... |
}
| {
if (filter) {
const iconsByMeta = searchIconsByMeta(filter);
return icons.filter(icon => iconsByMeta.indexOf(getPureIconName(icon)) >= 0);
} else {
return icons;
}
} | identifier_body |
rows.rs | use crate::{
Dao,
Value,
};
use serde_derive::{
Deserialize,
Serialize,
};
use std::slice;
/// use this to store data retrieved from the database
/// This is also slimmer than Vec<Dao> when serialized
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct Rows {
pub columns: Vec<Stri... |
#[test]
fn dao() {
let columns = vec!["id".to_string(), "username".to_string()];
let data: Vec<Vec<Value>> = vec![vec![1.into(), "ivanceras".into()]];
let rows = Rows {
columns,
data,
count: None,
};
let mut dao = Dao::new();
... | {
let columns = vec!["id".to_string(), "username".to_string()];
let data: Vec<Vec<Value>> = vec![vec![1.into(), "ivanceras".into()], vec![
2.into(),
"lee".into(),
]];
let rows = Rows {
columns,
data,
count: None,
};
... | identifier_body |
rows.rs | use crate::{
Dao,
Value,
};
use serde_derive::{
Deserialize,
Serialize,
};
use std::slice;
/// use this to store data retrieved from the database
/// This is also slimmer than Vec<Dao> when serialized
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct Rows {
pub columns: Vec<Stri... |
}
Some(dao)
} else {
None
}
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
impl<'a> ExactSizeIterator for Iter<'a> {}
#[cfg(test)]
mod test {
use super::*;
... | {
dao.insert_value(column, value);
} | conditional_block |
rows.rs | use crate::{
Dao,
Value,
};
use serde_derive::{
Deserialize,
Serialize,
};
use std::slice;
/// use this to store data retrieved from the database
/// This is also slimmer than Vec<Dao> when serialized
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct Rows {
pub columns: Vec<Stri... | (&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
impl<'a> ExactSizeIterator for Iter<'a> {}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn iteration_count() {
let columns = vec!["id".to_string(), "username".to_string()];
let data: Vec<Vec<Value>> = vec![vec![1.into(), "ivan... | size_hint | identifier_name |
rows.rs | use crate::{
Dao,
Value,
};
use serde_derive::{
Deserialize,
Serialize,
};
use std::slice;
/// use this to store data retrieved from the database
/// This is also slimmer than Vec<Dao> when serialized
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct Rows {
pub columns: Vec<Stri... |
pub fn new(columns: Vec<String>) -> Self {
Rows {
columns,
data: vec![],
count: None,
}
}
pub fn push(&mut self, row: Vec<Value>) { self.data.push(row) }
/// Returns an iterator over the `Row`s.
pub fn iter(&self) -> Iter {
Iter {
... | impl Rows {
pub fn empty() -> Self { Rows::new(vec![]) } | random_line_split |
test_fileinput.py | input import FileInput, hook_encoded
# The fileinput module has 2 interfaces: the FileInput class which does
# all the work, and a few functions (input, etc.) that use a global _state
# variable. We only test the FileInput class, since the other functions
# only provide a thin facade over FileInput.
# Write lines (a... | finally:
remove_tempfiles(t1, t2, t3, t4)
def test_files_that_dont_end_with_newline(self):
t1 = t2 = None
try:
t1 = writeTmp(1, ["A\nB\nC"])
t2 = writeTmp(2, ["D\nE\nF"])
fi = FileInput(files=(t1, t2))
lines = list(fi)
... | t1 = t2 = t3 = t4 = None
try:
t1 = writeTmp(1, [""])
t2 = writeTmp(2, [""])
t3 = writeTmp(3, ["The only line there is.\n"])
t4 = writeTmp(4, [""])
fi = FileInput(files=(t1, t2, t3, t4))
line = fi.readline()
self.assertEqual(lin... | identifier_body |
test_fileinput.py | input import FileInput, hook_encoded
# The fileinput module has 2 interfaces: the FileInput class which does
# all the work, and a few functions (input, etc.) that use a global _state
# variable. We only test the FileInput class, since the other functions
# only provide a thin facade over FileInput.
# Write lines (a... | (self):
t1 = t2 = t3 = t4 = None
try:
t1 = writeTmp(1, [""])
t2 = writeTmp(2, [""])
t3 = writeTmp(3, ["The only line there is.\n"])
t4 = writeTmp(4, [""])
fi = FileInput(files=(t1, t2, t3, t4))
line = fi.readline()
self... | test_zero_byte_files | identifier_name |
test_fileinput.py | input import FileInput, hook_encoded
# The fileinput module has 2 interfaces: the FileInput class which does
# all the work, and a few functions (input, etc.) that use a global _state
# variable. We only test the FileInput class, since the other functions
# only provide a thin facade over FileInput.
# Write lines (a... |
fi.close()
finally:
sys.stdout = savestdout
fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
for line in fi:
self.assertEqual(line[-1], '\n')
m = pat.match(line[:-1])
self.assertNotEqual(m, None)
self.assertEqual(int(m.g... | line = line[:-1].upper()
print(line) | conditional_block |
test_fileinput.py | input import FileInput, hook_encoded
# The fileinput module has 2 interfaces: the FileInput class which does
# all the work, and a few functions (input, etc.) that use a global _state
# variable. We only test the FileInput class, since the other functions
# only provide a thin facade over FileInput.
# Write lines (a... | sys.stdin = savestdin
if verbose:
print('%s. Boundary conditions (bs=%s)' % (start+4, bs))
fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
self.assertEqual(fi.lineno(), 0)
self.assertEqual(fi.filename(), None)
fi.nextfile()
self.assertEqual(fi.... | finally: | random_line_split |
query14.rs | use timely::order::TotalOrder;
use timely::dataflow::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::operators::*;
use differential_dataflow::operators::arrange::ArrangeBySelf;
use differential_dataflow::difference::DiffPair;
use differential_dataflow::lattice::Lattice;
us... | {
let arrangements = arrangements.in_scope(scope, experiment);
experiment
.lineitem(scope)
.explode(|l|
if create_date(1995,9,1) <= l.ship_date && l.ship_date < create_date(1995,10,1) {
Some((l.part_key, (l.extended_price * (100 - l.discount) / 100) as isize ))
... | identifier_body | |
query14.rs | use differential_dataflow::operators::*;
use differential_dataflow::operators::arrange::ArrangeBySelf;
use differential_dataflow::difference::DiffPair;
use differential_dataflow::lattice::Lattice;
use {Arrangements, Experiment, Collections};
use ::types::create_date;
// -- $ID$
// -- TPC-H/TPC-R Promotion Effect Quer... | use timely::order::TotalOrder;
use timely::dataflow::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
| random_line_split | |
query14.rs | use timely::order::TotalOrder;
use timely::dataflow::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::operators::*;
use differential_dataflow::operators::arrange::ArrangeBySelf;
use differential_dataflow::difference::DiffPair;
use differential_dataflow::lattice::Lattice;
us... |
)
.arrange_by_self()
.join_core(&arrangements.part, |_pk,&(),p| Some(DiffPair::new(1, if starts_with(&p.typ.as_bytes(), b"PROMO") { 1 } else { 0 })))
.explode(|dp| Some(((),dp)))
.count_total()
.probe_with(probe);
} | { None } | conditional_block |
query14.rs | use timely::order::TotalOrder;
use timely::dataflow::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::operators::*;
use differential_dataflow::operators::arrange::ArrangeBySelf;
use differential_dataflow::difference::DiffPair;
use differential_dataflow::lattice::Lattice;
us... | (source: &[u8], query: &[u8]) -> bool {
source.len() >= query.len() && &source[..query.len()] == query
}
pub fn query<G: Scope>(collections: &mut Collections<G>, probe: &mut ProbeHandle<G::Timestamp>)
where G::Timestamp: Lattice+TotalOrder+Ord {
let lineitems =
collections
.lineitems()
.ex... | starts_with | identifier_name |
config_loader.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2017 Joshua Charles Campbell
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your o... |
def restify_class(self, o):
if isclass(o):
d = {}
for k, v in getmembers(o):
if '__' not in k:
d[k] = self.restify_class(v)
return d
else:
assert (isinstance(o, dict),
isinstance(o, float),
... | return self._config[attr] | identifier_body |
config_loader.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
| # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty o... | # Copyright (C) 2017 Joshua Charles Campbell
# This program is free software; you can redistribute it and/or | random_line_split |
config_loader.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2017 Joshua Charles Campbell
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your o... |
return d
else:
assert (isinstance(o, dict),
isinstance(o, float),
isinstance(o, list),
isinstance(o, int),
isinstance(o, string_types)
), o
return o
def restify(self)... | if '__' not in k:
d[k] = self.restify_class(v) | conditional_block |
config_loader.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2017 Joshua Charles Campbell
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your o... | (self):
d = {}
for k, v in self._config.items():
if '__' not in k:
x = self.restify_class(v)
d[k] = x
return d
| restify | identifier_name |
IPaddValidity_hex_bin.py | #!/usr/bin/env python
import fileinput
class NotValidIP(Exception):
pass
class NotValidIPLength(Exception):
|
while True:
try:
ip_addr = input("Enter a network IP address: ")
ip_addr_split = ip_addr.split('.')
len1 = len(ip_addr_split)
ip_addr_split = ip_addr_split[:3]
ip_addr_split.append('0')
i=0
for element in ip_addr_split:
ip_addr_split[i] = int(ele... | pass | identifier_body |
IPaddValidity_hex_bin.py | #!/usr/bin/env python
import fileinput
class NotValidIP(Exception):
pass
class | (Exception):
pass
while True:
try:
ip_addr = input("Enter a network IP address: ")
ip_addr_split = ip_addr.split('.')
len1 = len(ip_addr_split)
ip_addr_split = ip_addr_split[:3]
ip_addr_split.append('0')
i=0
for element in ip_addr_split:
ip_ad... | NotValidIPLength | identifier_name |
IPaddValidity_hex_bin.py | #!/usr/bin/env python
import fileinput
class NotValidIP(Exception):
pass
class NotValidIPLength(Exception):
pass
while True:
try:
ip_addr = input("Enter a network IP address: ")
ip_addr_split = ip_addr.split('.')
len1 = len(ip_addr_split)
ip_addr_split = ip_addr_split[:3]
... | print('%20s %20s %20s' % (a, b, c)) | random_line_split | |
IPaddValidity_hex_bin.py | #!/usr/bin/env python
import fileinput
class NotValidIP(Exception):
pass
class NotValidIPLength(Exception):
pass
while True:
try:
ip_addr = input("Enter a network IP address: ")
ip_addr_split = ip_addr.split('.')
len1 = len(ip_addr_split)
ip_addr_split = ip_addr_split[:3]
... |
if (len1!=3 and len1!=4):
raise NotValidIPLength
print("The network IP address now is: %s" % ip_addr_split)
break
except ValueError:
print('Not a good value')
except NotValidIP:
print('this is not a valid IP address')
except NotValidIPLength:
prin... | if (element > 255 or element < 0):
raise NotValidIP | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.