file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
decode.rs | use std::{iter, fs, path};
use image::ImageFormat;
use criterion::{Criterion, criterion_group, criterion_main};
#[derive(Clone, Copy)]
struct BenchDef {
dir: &'static [&'static str],
files: &'static [&'static str],
format: ImageFormat,
}
fn | (c: &mut Criterion) {
const BENCH_DEFS: &'static [BenchDef] = &[
BenchDef {
dir: &["bmp", "images"],
files: &[
"Core_1_Bit.bmp",
"Core_4_Bit.bmp",
"Core_8_Bit.bmp",
"rgb16.bmp",
"rgb24.bmp",
... | load_all | identifier_name |
decode.rs | use std::{iter, fs, path};
use image::ImageFormat;
use criterion::{Criterion, criterion_group, criterion_main};
#[derive(Clone, Copy)]
struct BenchDef {
dir: &'static [&'static str],
files: &'static [&'static str],
format: ImageFormat,
}
fn load_all(c: &mut Criterion) {
const BENCH_DEFS: &'static [Be... | format: ImageFormat::Ico,
},
BenchDef {
dir: &["jpg", "progressive"],
files: &[
"3.jpg",
"cat.jpg",
"test.jpg",
],
format: ImageFormat::Jpeg,
},
// TODO: pnm
// TODO: png
... | random_line_split | |
FixtureSearchHeader.tsx | import React from 'react';
import styled from 'styled-components';
import { IconButton32 } from '../../shared/buttons';
import { blue, grey160, grey32, white10 } from '../../shared/colors';
import { ChevronLeftIcon, SearchIcon } from '../../shared/icons';
import { KeyBox } from '../../shared/KeyBox';
type Props = {
... | const Container = styled.div`
display: flex;
flex-direction: row;
align-items: center;
height: 40px;
margin: 0 1px 0 0;
background: ${grey32};
`;
const SearchButton = styled.button`
flex: 1;
height: 32px;
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
bo... | {
return (
<Container>
<SearchButton onClick={onOpen}>
<SearchIconContainer>
<SearchIcon />
</SearchIconContainer>
<SearchLabel>Search fixtures</SearchLabel>
<KeyBox value={'⌘'} bgColor={white10} textColor={grey160} size={20} />
<KeyBox value={'P'} bgColor={... | identifier_body |
FixtureSearchHeader.tsx | import React from 'react';
import styled from 'styled-components';
import { IconButton32 } from '../../shared/buttons';
import { blue, grey160, grey32, white10 } from '../../shared/colors';
import { ChevronLeftIcon, SearchIcon } from '../../shared/icons';
import { KeyBox } from '../../shared/KeyBox';
type Props = {
... | ({
validFixtureSelected,
onOpen,
onCloseNav,
}: Props) {
return (
<Container>
<SearchButton onClick={onOpen}>
<SearchIconContainer>
<SearchIcon />
</SearchIconContainer>
<SearchLabel>Search fixtures</SearchLabel>
<KeyBox value={'⌘'} bgColor={white10} textColor... | FixtureSearchHeader | identifier_name |
FixtureSearchHeader.tsx | import React from 'react';
import styled from 'styled-components';
import { IconButton32 } from '../../shared/buttons';
import { blue, grey160, grey32, white10 } from '../../shared/colors';
import { ChevronLeftIcon, SearchIcon } from '../../shared/icons';
import { KeyBox } from '../../shared/KeyBox';
type Props = {
... | padding: 0 4px;
`; | text-overflow: ellipsis;
text-align: left;
`;
const NavButtonContainer = styled.div` | random_line_split |
index.d.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 | * @description
* This module provides a set of common Pipes.
*/
import { AsyncPipe } from './async_pipe';
import { LowerCasePipe, TitleCasePipe, UpperCasePipe } from './case_conversion_pipes';
import { DatePipe } from './date_pipe';
import { I18nPluralPipe } from './i18n_plural_pipe';
import { I18nSelectPipe } from ... | */
/**
* @module | random_line_split |
walker.js | 'use strict';
const fs = require('fs'),
Emitter = require('events').EventEmitter,
emitter = new Emitter(),
eventState = require('event-state'),
dirTree = (path, cb) => {
const buildBranch = (path, branch) => {
fs.readdir(path, (err, files) => {
if (err) {
... | state.add(newEvents);
}
// Check each file descriptor to see if it's a directory.
files.forEach(file => {
const filePath = path + '/' + file;
fs.stat(filePath, (err, stats) => {
... | });
} else {
// Add events to the DSM for the directory's children | random_line_split |
walker.js | 'use strict';
const fs = require('fs'),
Emitter = require('events').EventEmitter,
emitter = new Emitter(),
eventState = require('event-state'),
dirTree = (path, cb) => {
const buildBranch = (path, branch) => {
fs.readdir(path, (err, files) => {
if (err) {
... |
//Once we've read the directory, we can raise the event for the parent
// directory and let it's children take care of themselves.
emitter.emit(path, true);
});
};
let tree = {},
state;
return buildBranch(path, tree);
... | {
const newEvents = files.map(file => {
return path + '/' + file;
});
if (!state) {
// If this is the first iteration,
// initialize the dynamic state machine (DSM).
... | conditional_block |
callback.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/. */
//! Base classes to work with IDL callbacks.
use dom::bindings::error::{Error, Fallible};
use dom::bindings::glob... |
}
Ok(callable.ptr)
}
}
/// Wraps the reflector for `p` into the compartment of `cx`.
pub fn wrap_call_this_object<T: Reflectable>(cx: *mut JSContext,
p: &T,
rval: MutableHandleObject) {
rval.set(p.reflect... | {
return Err(Error::Type(format!("The value of the {} property is not callable",
name)));
} | conditional_block |
callback.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/. */
//! Base classes to work with IDL callbacks.
use dom::bindings::error::{Error, Fallible};
use dom::bindings::glob... | let cx = global.r().get_cx();
unsafe {
JS_BeginRequest(cx);
}
let exception_compartment = unsafe {
GetGlobalForObjectCrossCompartment(callback.callback())
};
CallSetup {
exception_compartment: RootedObject::new_with_addr(cx,
... | pub fn new<T: CallbackContainer>(callback: &T, handling: ExceptionHandling) -> CallSetup {
let global = global_root_from_object(callback.callback()); | random_line_split |
callback.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/. */
//! Base classes to work with IDL callbacks.
use dom::bindings::error::{Error, Fallible};
use dom::bindings::glob... | <T: CallbackContainer>(callback: &T, handling: ExceptionHandling) -> CallSetup {
let global = global_root_from_object(callback.callback());
let cx = global.r().get_cx();
unsafe {
JS_BeginRequest(cx);
}
let exception_compartment = unsafe {
GetGlobalForObje... | new | identifier_name |
badfiles.py | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, François-Xavier Thomas.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limi... |
def commands(self):
bad_command = Subcommand('bad',
help=u'check for corrupt or missing files')
bad_command.func = self.check_bad
return [bad_command] | ui.print_(u"{}: ok".format(ui.colorize('text_success', dpath))) | random_line_split |
badfiles.py | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, François-Xavier Thomas.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limi... | BeetsPlugin):
def run_command(self, cmd):
self._log.debug(u"running command: {}",
displayable_path(list2cmdline(cmd)))
try:
output = check_output(cmd, stderr=STDOUT)
errors = 0
status = 0
except CalledProcessError as e:
... | adFiles( | identifier_name |
badfiles.py | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, François-Xavier Thomas.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limi... |
def check_mp3val(self, path):
status, errors, output = self.run_command(["mp3val", path])
if status == 0:
output = [line for line in output if line.startswith("WARNING:")]
errors = len(output)
return status, errors, output
def check_flac(self, path):
ret... | elf._log.debug(u"running command: {}",
displayable_path(list2cmdline(cmd)))
try:
output = check_output(cmd, stderr=STDOUT)
errors = 0
status = 0
except CalledProcessError as e:
output = e.output
errors = 1
st... | identifier_body |
badfiles.py | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, François-Xavier Thomas.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limi... | elif errors > 0:
ui.print_(u"{}: checker found {} errors or warnings"
.format(ui.colorize('text_warning', dpath), errors))
for line in output:
ui.print_(u" {}".format(displayable_path(line)))
else:
ui.... | i.print_(" {}".format(displayable_path(line)))
| conditional_block |
TypeaheadInputMulti.stories.tsx | /* eslint-disable sort-keys,import/no-extraneous-dependencies */
import React, { ChangeEvent, useState } from 'react';
import { Story, Meta } from '@storybook/react';
import Token from '../Token';
import TypeaheadInputMulti, {
TypeaheadInputMultiProps,
} from './TypeaheadInputMulti';
import options from '../../tes... | Valid.args = {
...defaultProps,
className: 'focus',
isValid: true,
};
export const Invalid = Template.bind({});
Invalid.args = {
...defaultProps,
className: 'focus',
isInvalid: true,
};
export const WithHint = Template.bind({});
WithHint.args = {
...defaultProps,
hintText: 'california',
value: 'cali... | };
export const Valid = Template.bind({}); | random_line_split |
vec.rs | use super::{AssertionFailure, Spec};
pub trait VecAssertions {
fn has_length(&mut self, expected: usize);
fn is_empty(&mut self);
}
impl<'s, T> VecAssertions for Spec<'s, Vec<T>> {
/// Asserts that the length of the subject vector is equal to the provided length. The subject
/// type must be of `Vec`.... |
}
}
#[cfg(test)]
mod tests {
use super::super::prelude::*;
#[test]
fn should_not_panic_if_vec_length_matches_expected() {
let test_vec = vec![1, 2, 3];
assert_that(&test_vec).has_length(3);
}
#[test]
#[should_panic(expected = "\n\texpected: vec to have length <1>\n\t but... | {
AssertionFailure::from_spec(self)
.with_expected(format!("an empty vec"))
.with_actual(format!("a vec with length <{:?}>", subject.len()))
.fail();
} | conditional_block |
vec.rs | use super::{AssertionFailure, Spec};
pub trait VecAssertions {
fn has_length(&mut self, expected: usize);
fn is_empty(&mut self);
}
impl<'s, T> VecAssertions for Spec<'s, Vec<T>> {
/// Asserts that the length of the subject vector is equal to the provided length. The subject
/// type must be of `Vec`.... | fn has_length(&mut self, expected: usize) {
let length = self.subject.len();
if length != expected {
AssertionFailure::from_spec(self)
.with_expected(format!("vec to have length <{}>", expected))
.with_actual(format!("<{}>", length))
.fail(... | random_line_split | |
vec.rs | use super::{AssertionFailure, Spec};
pub trait VecAssertions {
fn has_length(&mut self, expected: usize);
fn is_empty(&mut self);
}
impl<'s, T> VecAssertions for Spec<'s, Vec<T>> {
/// Asserts that the length of the subject vector is equal to the provided length. The subject
/// type must be of `Vec`.... |
#[test]
fn should_not_panic_if_vec_was_expected_to_be_empty_and_is() {
let test_vec: Vec<u8> = vec![];
assert_that(&test_vec).is_empty();
}
#[test]
#[should_panic(expected = "\n\texpected: an empty vec\
\n\t but was: a vec with length <1>")]
fn should_panic_... | {
let test_vec = vec![1, 2, 3];
assert_that(&test_vec).has_length(1);
} | identifier_body |
vec.rs | use super::{AssertionFailure, Spec};
pub trait VecAssertions {
fn has_length(&mut self, expected: usize);
fn is_empty(&mut self);
}
impl<'s, T> VecAssertions for Spec<'s, Vec<T>> {
/// Asserts that the length of the subject vector is equal to the provided length. The subject
/// type must be of `Vec`.... | () {
let test_vec = vec![1, 2, 3];
assert_that(&test_vec).has_length(3);
}
#[test]
#[should_panic(expected = "\n\texpected: vec to have length <1>\n\t but was: <3>")]
fn should_panic_if_vec_length_does_not_match_expected() {
let test_vec = vec![1, 2, 3];
assert_that(&tes... | should_not_panic_if_vec_length_matches_expected | identifier_name |
parser.js | const pug = require("pug");
const pugRuntimeWrap = require("pug-runtime/wrap");
const path = require("path");
const YAML = require("js-yaml");
const getCodeBlock = require("pug-code-block");
const detectIndent = require("detect-indent");
const rebaseIndent = require("rebase-indent");
const pugdocArguments = require(".... |
if (meta.afterEach && typeof x.afterEach === "undefined") {
x.example = `${x.example}\n${meta.afterEach}`;
}
// merge example/examples with parent examples
meta.examples[i] = getExamples(x).reduce(
(acc, val) => acc.concat(val),
[]
);
// ... | {
x.example = `${meta.beforeEach}\n${x.example}`;
} | conditional_block |
parser.js | const pug = require("pug");
const pugRuntimeWrap = require("pug-runtime/wrap");
const path = require("path");
const YAML = require("js-yaml");
const getCodeBlock = require("pug-code-block");
const detectIndent = require("detect-indent");
const rebaseIndent = require("rebase-indent");
const pugdocArguments = require(".... | (meta) {
let examples = [];
if (meta.example) {
examples = examples.concat(meta.example);
}
if (meta.examples) {
examples = examples.concat(meta.examples);
}
return examples;
}
/**
* Compile Pug
*/
function compilePug(src, meta, filename, locals) {
let newSrc = [src];
// add example calls
... | getExamples | identifier_name |
parser.js | const pug = require("pug");
const pugRuntimeWrap = require("pug-runtime/wrap");
const path = require("path");
const YAML = require("js-yaml");
const getCodeBlock = require("pug-code-block");
const detectIndent = require("detect-indent");
const rebaseIndent = require("rebase-indent");
const pugdocArguments = require(".... |
/**
* Returns all pugdocDocuments for the given code
*
* @param templateSrc {string}
* @param filename {string}
*/
function getPugdocDocuments(templateSrc, filename, locals) {
return extractPugdocBlocks(templateSrc).map(function (pugdocBlock) {
const meta = parsePugdocComment(pugdocBlock.comment);
con... | {
return (
templateSrc
.split("\n")
// Walk through every line and look for a pugdoc comment
.map(function (line, lineIndex) {
// If the line does not contain a pugdoc comment skip it
if (!line.match(DOC_REGEX)) {
return undefined;
}
// If the line cont... | identifier_body |
parser.js | const pug = require("pug");
const pugRuntimeWrap = require("pug-runtime/wrap");
const path = require("path");
const YAML = require("js-yaml");
const getCodeBlock = require("pug-code-block");
const detectIndent = require("detect-indent");
const rebaseIndent = require("rebase-indent");
const pugdocArguments = require(".... | /**
* Extract pug attributes from comment block
*/
function parsePugdocComment(comment) {
// remove first line (@pugdoc)
if (comment.indexOf("\n") === -1) {
return {};
}
comment = comment.substr(comment.indexOf("\n"));
comment = pugdocArguments.escapeArgumentsYAML(comment, "arguments");
comment = pu... | });
}
| random_line_split |
theodolite.module.ts | import { NgModule } from '@angular/core';
import { TheodoliteComponent } from './theodolite/theodolite.component';
import { MarkdownSlideComponent } from './slide/markdown/markdownSlide.component';
import { CodeSlideComponent } from './slide/code/codeSlide.component';
import { PresentationComponent } from './presentati... | () {
}
} | constructor | identifier_name |
theodolite.module.ts | import { NgModule } from '@angular/core';
import { TheodoliteComponent } from './theodolite/theodolite.component';
import { MarkdownSlideComponent } from './slide/markdown/markdownSlide.component';
import { CodeSlideComponent } from './slide/code/codeSlide.component';
import { PresentationComponent } from './presentati... |
} | {
} | identifier_body |
theodolite.module.ts | import { NgModule } from '@angular/core';
import { TheodoliteComponent } from './theodolite/theodolite.component'; | import { BrowserModule } from '@angular/platform-browser';
import { ControlsComponent } from './controls/controls.component';
import { AboutComponent } from './about/about.component';
import { ModalComponent } from './modal/modal.component';
import { SlideComponent } from './slide/slide.component';
import { DefaultValu... | import { MarkdownSlideComponent } from './slide/markdown/markdownSlide.component';
import { CodeSlideComponent } from './slide/code/codeSlide.component';
import { PresentationComponent } from './presentation/presentation.component';
import { MarkdownService } from './markdown/markdown.service';
import { ParseService } ... | random_line_split |
Problem_37.py | __author__ = 'Meemaw'
import math
def | (stevilo):
if stevilo == 1:
return 0
meja = int(math.sqrt(stevilo)+1)
if(stevilo > 2 and stevilo % 2 == 0):
return 0
for i in range(3,meja,2):
if stevilo % i == 0:
return 0
return 1
def izLeve(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(st... | isPrime | identifier_name |
Problem_37.py | __author__ = 'Meemaw'
import math
def isPrime(stevilo):
if stevilo == 1:
|
meja = int(math.sqrt(stevilo)+1)
if(stevilo > 2 and stevilo % 2 == 0):
return 0
for i in range(3,meja,2):
if stevilo % i == 0:
return 0
return 1
def izLeve(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[i:]))) != 1:
return False
... | return 0 | conditional_block |
Problem_37.py | __author__ = 'Meemaw'
import math
def isPrime(stevilo):
|
def izLeve(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[i:]))) != 1:
return False
return True
def izDesne(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[0:len(stevilo)-i]))) != 1:
return False
return True
numOfPrimes = 0
vsot... | if stevilo == 1:
return 0
meja = int(math.sqrt(stevilo)+1)
if(stevilo > 2 and stevilo % 2 == 0):
return 0
for i in range(3,meja,2):
if stevilo % i == 0:
return 0
return 1 | identifier_body |
Problem_37.py | __author__ = 'Meemaw'
import math
def isPrime(stevilo):
if stevilo == 1:
return 0 | if stevilo % i == 0:
return 0
return 1
def izLeve(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[i:]))) != 1:
return False
return True
def izDesne(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[0:len(stevilo)-i]))) != 1:
... | meja = int(math.sqrt(stevilo)+1)
if(stevilo > 2 and stevilo % 2 == 0):
return 0
for i in range(3,meja,2): | random_line_split |
make_single_pages.py | import os
import internetarchive
folder = 'pages'
def | (book, item, filepattern, start, steps, finish):
if not os.path.exists(os.getcwd() + os.sep + folder + os.sep + book):
os.makedirs(os.getcwd() + os.sep + folder + os.sep + book)
session = internetarchive.ArchiveSession()
re_item = session.get_item(item)
list_of_pages = range(start, finish + ste... | from_IA | identifier_name |
make_single_pages.py | import os
import internetarchive
folder = 'pages'
def from_IA(book, item, filepattern, start, steps, finish):
if not os.path.exists(os.getcwd() + os.sep + folder + os.sep + book):
os.makedirs(os.getcwd() + os.sep + folder + os.sep + book)
session = internetarchive.ArchiveSession()
re_item = sess... | make_single_pages() | conditional_block | |
make_single_pages.py | import os
import internetarchive
folder = 'pages'
def from_IA(book, item, filepattern, start, steps, finish):
|
def make_single_pages():
if not os.path.exists(os.getcwd() + os.sep + folder):
os.makedirs(os.getcwd() + os.sep + folder)
from_IA(book='I,1', item='PWRE01-02', filepattern='Pauly-Wissowa_I1_{0:04d}.png', start=1, steps=2, finish=1439)
from_IA(book='I,2', item='PWRE01-02', filepattern='Pauly-Wisso... | if not os.path.exists(os.getcwd() + os.sep + folder + os.sep + book):
os.makedirs(os.getcwd() + os.sep + folder + os.sep + book)
session = internetarchive.ArchiveSession()
re_item = session.get_item(item)
list_of_pages = range(start, finish + steps, steps)
for idx, i in enumerate(list_of_pages)... | identifier_body |
make_single_pages.py | import os
import internetarchive
folder = 'pages'
def from_IA(book, item, filepattern, start, steps, finish):
if not os.path.exists(os.getcwd() + os.sep + folder + os.sep + book):
os.makedirs(os.getcwd() + os.sep + folder + os.sep + book)
session = internetarchive.ArchiveSession()
re_item = sess... | except:
print('{} is not an item'.format(filepattern.format(i)))
def make_single_pages():
if not os.path.exists(os.getcwd() + os.sep + folder):
os.makedirs(os.getcwd() + os.sep + folder)
from_IA(book='I,1', item='PWRE01-02', filepattern='Pauly-Wissowa_I1_{0:04d}.png', start... | try:
re_file = re_item.get_file(filepattern.format(i))
re_file.download(file_on_harddisk, silent=True) | random_line_split |
dragon.rs | // Copyright 2015 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 ... | (d: &Decoded, buf: &mut [u8], limit: i16) -> (/*#digits*/ usize, /*exp*/ i16) {
assert!(d.mant > 0);
assert!(d.minus > 0);
assert!(d.plus > 0);
assert!(d.mant.checked_add(d.plus).is_some());
assert!(d.mant.checked_sub(d.minus).is_some());
// estimate `k_0` from original inputs satisfying `10^(k... | format_exact | identifier_name |
dragon.rs | // Copyright 2015 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 ... | static POW10TO64: [Digit; 7] = [0, 0, 0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03];
static POW10TO128: [Digit; 14] =
[0, 0, 0, 0, 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08,
0xbccdb0da, 0xa6337f19, 0xe91f2603, 0x24e];
static POW10TO256: [Digit; 27] =
[0, 0, 0, 0, 0, 0... | static POW10TO32: [Digit; 4] = [0, 0x85acef81, 0x2d6d415b, 0x4ee]; | random_line_split |
dragon.rs | // Copyright 2015 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 ... |
/// The exact and fixed mode implementation for Dragon.
pub fn format_exact(d: &Decoded, buf: &mut [u8], limit: i16) -> (/*#digits*/ usize, /*exp*/ i16) {
assert!(d.mant > 0);
assert!(d.minus > 0);
assert!(d.plus > 0);
assert!(d.mant.checked_add(d.plus).is_some());
assert!(d.mant.checked_sub(d.min... | {
// the number `v` to format is known to be:
// - equal to `mant * 2^exp`;
// - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and
// - followed by `(mant + 2 * plus) * 2^exp` in the original type.
//
// obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-o... | identifier_body |
dragon.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else {
buf.len()
};
if len > 0 {
// cache `(2, 4, 8) * scale` for digit generation.
// (this can be expensive, so do not calculate them when the buffer is empty.)
let mut scale2 = scale.clone(); scale2.mul_pow2(1);
let mut scale4 = scale.clone(); scale4.mul_pow2(2);
... | {
(k - limit) as usize
} | conditional_block |
table-errors.d.ts | * found in the LICENSE file at https://angular.io/license
*/
/**
* Returns an error to be thrown when attempting to find an unexisting column.
* @param id Id whose lookup failed.
* @docs-private
*/
export declare function getTableUnknownColumnError(id: string): Error;
/**
* Returns an error to be thrown when two... | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be | random_line_split | |
scalar.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use collections::HashMap;
use std::usize;
use test::{black_box, Bencher};
use tipb::ScalarFuncSig;
fn get_scalar_args_with_match(sig: ScalarFuncSig) -> (usize, usize) {
// Only select some functions to benchmark
let (min_args, max_args) = matc... |
(0, 0)
}
#[bench]
fn bench_get_scalar_args_with_match(b: &mut Bencher) {
b.iter(|| {
for _ in 0..1000 {
black_box(get_scalar_args_with_match(black_box(ScalarFuncSig::AbsInt)));
}
})
}
#[bench]
fn bench_get_scalar_args_with_map(b: &mut Bencher) {
let m = init_scalar_args_m... | {
return (min_args, max_args);
} | conditional_block |
scalar.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use collections::HashMap;
use std::usize;
use test::{black_box, Bencher};
use tipb::ScalarFuncSig;
fn | (sig: ScalarFuncSig) -> (usize, usize) {
// Only select some functions to benchmark
let (min_args, max_args) = match sig {
ScalarFuncSig::LtInt => (2, 2),
ScalarFuncSig::CastIntAsInt => (1, 1),
ScalarFuncSig::IfInt => (3, 3),
ScalarFuncSig::JsonArraySig => (0, usize::MAX),
... | get_scalar_args_with_match | identifier_name |
scalar.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use collections::HashMap;
use std::usize;
use test::{black_box, Bencher};
use tipb::ScalarFuncSig;
fn get_scalar_args_with_match(sig: ScalarFuncSig) -> (usize, usize) {
// Only select some functions to benchmark
let (min_args, max_args) = matc... | {
let m = init_scalar_args_map();
b.iter(|| {
for _ in 0..1000 {
black_box(get_scalar_args_with_map(
black_box(&m),
black_box(ScalarFuncSig::AbsInt),
));
}
})
} | identifier_body | |
scalar.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use collections::HashMap;
use std::usize;
use test::{black_box, Bencher};
use tipb::ScalarFuncSig;
fn get_scalar_args_with_match(sig: ScalarFuncSig) -> (usize, usize) {
// Only select some functions to benchmark
let (min_args, max_args) = matc... | }
fn init_scalar_args_map() -> HashMap<ScalarFuncSig, (usize, usize)> {
let mut m: HashMap<ScalarFuncSig, (usize, usize)> = HashMap::default();
let tbls = vec![
(ScalarFuncSig::LtInt, (2, 2)),
(ScalarFuncSig::CastIntAsInt, (1, 1)),
(ScalarFuncSig::IfInt, (3, 3)),
(ScalarFuncSig... | _ => (0, 0),
};
(min_args, max_args) | random_line_split |
libstdbuf.rs | #![crate_name = "libstdbuf"]
#![crate_type = "staticlib"]
#![feature(core, libc, os)]
extern crate libc;
use libc::{c_int, size_t, c_char, FILE, _IOFBF, _IONBF, _IOLBF, setvbuf};
use std::ptr;
use std::os;
#[path = "../common/util.rs"]
#[macro_use]
mod util;
extern {
static stdin: *mut FILE;
static stdout: *... | pub extern fn stdbuf() {
if let Some(val) = os::getenv("_STDBUF_E") {
set_buffer(stderr, val.as_slice());
}
if let Some(val) = os::getenv("_STDBUF_I") {
set_buffer(stdin, val.as_slice());
}
if let Some(val) = os::getenv("_STDBUF_O") {
set_buffer(stdout, val.as_slice());
... | #[no_mangle] | random_line_split |
libstdbuf.rs | #![crate_name = "libstdbuf"]
#![crate_type = "staticlib"]
#![feature(core, libc, os)]
extern crate libc;
use libc::{c_int, size_t, c_char, FILE, _IOFBF, _IONBF, _IOLBF, setvbuf};
use std::ptr;
use std::os;
#[path = "../common/util.rs"]
#[macro_use]
mod util;
extern {
static stdin: *mut FILE;
static stdout: *... | {
if let Some(val) = os::getenv("_STDBUF_E") {
set_buffer(stderr, val.as_slice());
}
if let Some(val) = os::getenv("_STDBUF_I") {
set_buffer(stdin, val.as_slice());
}
if let Some(val) = os::getenv("_STDBUF_O") {
set_buffer(stdout, val.as_slice());
}
} | identifier_body | |
libstdbuf.rs | #![crate_name = "libstdbuf"]
#![crate_type = "staticlib"]
#![feature(core, libc, os)]
extern crate libc;
use libc::{c_int, size_t, c_char, FILE, _IOFBF, _IONBF, _IOLBF, setvbuf};
use std::ptr;
use std::os;
#[path = "../common/util.rs"]
#[macro_use]
mod util;
extern {
static stdin: *mut FILE;
static stdout: *... |
}
| {
set_buffer(stdout, val.as_slice());
} | conditional_block |
libstdbuf.rs | #![crate_name = "libstdbuf"]
#![crate_type = "staticlib"]
#![feature(core, libc, os)]
extern crate libc;
use libc::{c_int, size_t, c_char, FILE, _IOFBF, _IONBF, _IOLBF, setvbuf};
use std::ptr;
use std::os;
#[path = "../common/util.rs"]
#[macro_use]
mod util;
extern {
static stdin: *mut FILE;
static stdout: *... | () {
if let Some(val) = os::getenv("_STDBUF_E") {
set_buffer(stderr, val.as_slice());
}
if let Some(val) = os::getenv("_STDBUF_I") {
set_buffer(stdin, val.as_slice());
}
if let Some(val) = os::getenv("_STDBUF_O") {
set_buffer(stdout, val.as_slice());
}
}
| stdbuf | identifier_name |
main.rs | extern crate rustc_serialize;
extern crate hyper;
use rustc_serialize::json;
use rustc_serialize::json::Json;
#[macro_use] extern crate nickel;
use nickel::status::StatusCode;
use nickel::{Nickel, HttpRouter, MediaType, JsonBody};
#[derive(RustcDecodable, RustcEncodable)]
struct | {
status: i32,
title: String,
}
fn main() {
let mut server = Nickel::new();
let mut router = Nickel::router();
// index
router.get("/api/todos", middleware! { |_, mut _res|
let mut v: Vec<Todo> = vec![];
let todo1 = Todo{
status: 0,
title: "Shopping".to_string(),
};
v.push(tod... | Todo | identifier_name |
main.rs | extern crate rustc_serialize;
extern crate hyper;
use rustc_serialize::json;
use rustc_serialize::json::Json;
#[macro_use] extern crate nickel;
use nickel::status::StatusCode;
use nickel::{Nickel, HttpRouter, MediaType, JsonBody};
#[derive(RustcDecodable, RustcEncodable)]
struct Todo {
status: i32,
title: String... | let todo = _req.json_as::<Todo>().unwrap();
let status = todo.status;
let title = todo.title.to_string();
println!("create status {:?} title {}", status, title);
let json_obj = Json::from_str("{}").unwrap();
_res.set(MediaType::Json);
_res.set(StatusCode::Created);
return _res.send(j... |
// create
router.post("/api/todos", middleware! { |_req, mut _res| | random_line_split |
issue-14845.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x = X { a: [0] };
let _f = &x.a as *mut u8;
//~^ ERROR mismatched types
//~| expected `*mut u8`
//~| found `&[u8; 1]`
//~| expected u8
//~| found array of 1 elements
let local = [0u8];
let _v = &local as *mut u8;
//~^ ERROR mismatched types
//~| expected `*mut u8`
... | main | identifier_name |
issue-14845.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | } | random_line_split | |
show_tests.py | # coding=utf-8
# This file is part of SickChill.
#
# URL: https://sickchill.github.io
# Git: https://github.com/SickChill/SickChill.git
#
# SickChill 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 vers... | from sickbeard.common import Quality
from sickbeard.tv import TVShow
from sickchill.helper.exceptions import MultipleShowObjectsException
from sickchill.show.Show import Show
class ShowTests(unittest.TestCase):
"""
Test shows
"""
def test_find(self):
"""
Test find tv shows by indexer_... | import sickbeard
import six
| random_line_split |
show_tests.py | # coding=utf-8
# This file is part of SickChill.
#
# URL: https://sickchill.github.io
# Git: https://github.com/SickChill/SickChill.git
#
# SickChill 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 vers... |
class TestTVShow(TVShow):
"""
A test `TVShow` object that does not need DB access.
"""
def __init__(self, indexer, indexer_id):
super(TestTVShow, self).__init__(indexer, indexer_id)
def loadFromDB(self):
"""
Override TVShow.loadFromDB to avoid DB access during testing
... | """
Test shows
"""
def test_find(self):
"""
Test find tv shows by indexer_id
"""
sickbeard.QUALITY_DEFAULT = Quality.FULLHDTV
sickbeard.showList = []
show123 = TestTVShow(0, 123)
show456 = TestTVShow(0, 456)
show789 = TestTVShow(0, 789)
... | identifier_body |
show_tests.py | # coding=utf-8
# This file is part of SickChill.
#
# URL: https://sickchill.github.io
# Git: https://github.com/SickChill/SickChill.git
#
# SickChill 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 vers... | (self):
"""
Test find tv shows by indexer_id
"""
sickbeard.QUALITY_DEFAULT = Quality.FULLHDTV
sickbeard.showList = []
show123 = TestTVShow(0, 123)
show456 = TestTVShow(0, 456)
show789 = TestTVShow(0, 789)
shows = [show123, show456, show789]
... | test_find | identifier_name |
show_tests.py | # coding=utf-8
# This file is part of SickChill.
#
# URL: https://sickchill.github.io
# Git: https://github.com/SickChill/SickChill.git
#
# SickChill 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 vers... |
class TestTVShow(TVShow):
"""
A test `TVShow` object that does not need DB access.
"""
def __init__(self, indexer, indexer_id):
super(TestTVShow, self).__init__(indexer, indexer_id)
def loadFromDB(self):
"""
Override TVShow.loadFromDB to avoid DB access during testing
... | self.assertEqual(Show._validate_indexer_id(indexer_id), results_list[index]) # pylint: disable=protected-access | conditional_block |
trace_analyzer_old.py | __author__= "barun"
__date__ = "$20 May, 2011 12:25:36 PM$"
from metrics import Metrics
from wireless_fields import *
DATA_PKTS = ('tcp', 'udp', 'ack',)
def is_control_pkt(pkt_type=''):
return pkt_type not in DATA_PKTS
class TraceAnalyzer(object):
'''
Trace Analyzer
'''
def __init__(self, fil... | (self):
Metrics.averageThroughput()
def get_instantaneous_throughput(self):
Metrics.instantaneousThroughput()
| get_average_throughput | identifier_name |
trace_analyzer_old.py | __author__= "barun"
__date__ = "$20 May, 2011 12:25:36 PM$"
from metrics import Metrics
from wireless_fields import *
DATA_PKTS = ('tcp', 'udp', 'ack',)
def is_control_pkt(pkt_type=''):
return pkt_type not in DATA_PKTS
class TraceAnalyzer(object):
'''
Trace Analyzer
'''
def __init__(self, fil... |
# Compute simulation times
try:
self._simulationStartTime = float(self._sendEvents[0].split()[I_TIMESTAMP])
except IndexError:
self._simulationStartTime = 0
try:
self._simulationEndTime = float(self._sendEvents[len(self._... | try:
event = event.split()
if event[I_PKT_TYPE_TOKEN] == S_PKT_TYPE_TOKEN and \
event[I_PKT_TYPE] in DATA_PKTS:
if event[I_SRC_FIELD_TOKEN] == S_SRC_FIELD_TOKEN:
src = event[I_SRC_ADDR_PORT].split('.')[0]
... | conditional_block |
trace_analyzer_old.py | __author__= "barun"
__date__ = "$20 May, 2011 12:25:36 PM$"
from metrics import Metrics
from wireless_fields import *
DATA_PKTS = ('tcp', 'udp', 'ack',)
def is_control_pkt(pkt_type=''):
return pkt_type not in DATA_PKTS
class TraceAnalyzer(object):
'''
Trace Analyzer
'''
def __init__(self, fil... | # continue
except IndexError:
# IndexError can occur because certain log entries from MAC
# layer may not have source and destination infos -- don't
# know exactly why
continue
# Compu... | # dst = event[I_DST_ADDR_PORT].split('.')[0]
# if dst not in self._destinationNodes and int(dst) >= 0:
# self._destinationNodes.append(dst)
# else: | random_line_split |
trace_analyzer_old.py | __author__= "barun"
__date__ = "$20 May, 2011 12:25:36 PM$"
from metrics import Metrics
from wireless_fields import *
DATA_PKTS = ('tcp', 'udp', 'ack',)
def is_control_pkt(pkt_type=''):
return pkt_type not in DATA_PKTS
class TraceAnalyzer(object):
'''
Trace Analyzer
'''
def __init__(self, fil... |
def parse_events(self, file_name):
'''
Parse the send, receive and drop events, and store them in a list. This
method should get called only once (from inside __init__) at the
beginning of processing.
'''
print 'Parse events -- Use normal record scan to fil... | print 'Trace Analyzer'
self._receiveEvents = []
self._sendEvents = []
self._dropEvents = []
self._otherEvents = []
self._data_pkts_rcvd = []
self._cntrl_pkts_rcvd = []
self._sourceNodes = []
self._destinationNodes = []
self.pars... | identifier_body |
objects.py |
class ObjectXEDA:
kind= -1
name= ''
posX= 0
posY= 0
centerX= 0
centerY= 0
w= 0
h= 0
angle= 0
selected= False
mirrored= False
locked= False
glow= False
dragging= False
def is_over(self, x, y):
'''responde se a coordenada indicado esta sobre esse o... | (ObjectXEDA):
'''
componentes (descritos aqui)
fios
juncoes
power
portas (entre folhas)
net names
textos livres
caixa de texto
bus
entradas de bus
graficos (linhas, circulos, retangulos, arcos, poligonos)
'''
def __init__(self):
self.pn= '74hc123'
self.ref= 'U12'
self.comment= '74HC1... | SCHObject | identifier_name |
objects.py |
class ObjectXEDA:
kind= -1
name= ''
posX= 0
posY= 0
centerX= 0
centerY= 0
w= 0
h= 0
angle= 0
selected= False
mirrored= False
locked= False
glow= False
dragging= False
def is_over(self, x, y):
'''responde se a coordenada indicado esta sobre esse o... | '''
componentes (como descritos aqui)
pad isolado
via
linhas
arcos (partindo do centro e dos extermos)
textos
'''
def __init__(self):
self.foot= 'sop23'
self.ref= 'U12'
self.comment= 'teste'
self.pads= [(0, 0, 'id', 'quadrado', 'w', 'h', 'top', 'furo-diametro', 'net-name', 'mask'... | identifier_body | |
objects.py | class ObjectXEDA:
kind= -1
name= ''
posX= 0
posY= 0
centerX= 0
centerY= 0
w= 0
h= 0
angle= 0
selected= False
mirrored= False
locked= False
glow= False
dragging= False
def is_over(self, x, y):
'''responde se a coordenada indicado esta sobre esse ob... | juncoes
power
portas (entre folhas)
net names
textos livres
caixa de texto
bus
entradas de bus
graficos (linhas, circulos, retangulos, arcos, poligonos)
'''
def __init__(self):
self.pn= '74hc123'
self.ref= 'U12'
self.comment= '74HC123'
#parts deveria ser uma lista de parts do com... | class SCHObject(ObjectXEDA):
'''
componentes (descritos aqui)
fios | random_line_split |
lib.rs | extern crate lexer;
use lexer::{Item, StateFn, Lexer};
#[derive(Debug, PartialEq)]
pub enum ItemType {
Comma,
Text,
Comment,
EOF
}
fn lex_text(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> {
loop {
if l.remaining_input().starts_with("//") {
l.emit_nonempty(ItemType::T... | assert_eq!(items, expected_items);
} | random_line_split | |
lib.rs | extern crate lexer;
use lexer::{Item, StateFn, Lexer};
#[derive(Debug, PartialEq)]
pub enum ItemType {
Comma,
Text,
Comment,
EOF
}
fn lex_text(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> {
loop {
if l.remaining_input().starts_with("//") {
l.emit_nonempty(ItemType::T... |
#[test]
fn test_lexer() {
let data = "foo,bar,baz // some comment\nfoo,bar";
let items = lexer::lex(data, lex_text);
let expected_items = vec!(
Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 1},
Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 1},
Item{typ: ItemType::Te... | {
loop {
match l.next() {
None => break,
Some('\n') => {
l.backup();
l.emit_nonempty(ItemType::Comment);
l.next();
l.ignore();
return Some(StateFn(lex_text));
},
Some(_) => {},
... | identifier_body |
lib.rs | extern crate lexer;
use lexer::{Item, StateFn, Lexer};
#[derive(Debug, PartialEq)]
pub enum | {
Comma,
Text,
Comment,
EOF
}
fn lex_text(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> {
loop {
if l.remaining_input().starts_with("//") {
l.emit_nonempty(ItemType::Text);
l.next();
return Some(StateFn(lex_comment));
}
match l.n... | ItemType | identifier_name |
lib.rs | extern crate lexer;
use lexer::{Item, StateFn, Lexer};
#[derive(Debug, PartialEq)]
pub enum ItemType {
Comma,
Text,
Comment,
EOF
}
fn lex_text(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> {
loop {
if l.remaining_input().starts_with("//") {
l.emit_nonempty(ItemType::T... | ,
Some(_) => {},
}
}
l.emit_nonempty(ItemType::Comment);
l.emit(ItemType::EOF);
None
}
#[test]
fn test_lexer() {
let data = "foo,bar,baz // some comment\nfoo,bar";
let items = lexer::lex(data, lex_text);
let expected_items = vec!(
Item{typ: ItemType::Text, val: ... | {
l.backup();
l.emit_nonempty(ItemType::Comment);
l.next();
l.ignore();
return Some(StateFn(lex_text));
} | conditional_block |
libstdc++.a-gdb.py | # -*- python -*-
# Copyright (C) 2009 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
... |
# Load the pretty-printers.
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers (gdb.current_objfile ())
| pythondir = os.path.normpath (pythondir)
libdir = os.path.normpath (libdir)
prefix = os.path.commonprefix ([libdir, pythondir])
# In some bizarre configuration we might have found a match in the
# middle of a directory name.
if prefix[-1] != '/':
prefix = os.path.dirname (prefix) + '/'
... | conditional_block |
libstdc++.a-gdb.py | # -*- python -*-
# Copyright (C) 2009 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by | # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
i... | # the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, | random_line_split |
method_registry.py | # Eve W-Space
# Copyright 2014 Andrew Austin and contributors
#
# 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 requi... | if not name:
raise AttributeError("MethodRegistry not given a name for module.")
module.name = name
self[name] = module
def _autodiscover(registry):
import copy
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.modul... | random_line_split | |
method_registry.py | # Eve W-Space
# Copyright 2014 Andrew Austin and contributors
#
# 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 requi... |
registry = MethodRegistry()
def autodiscover():
_autodiscover(registry)
def register(name, module):
"""Proxy for register method."""
return registry.register(name, module)
| mod = import_module(app)
# Import alert_methods from each app
try:
before_import_registry = copy.copy(registry)
import_module('%s.alert_methods' % app)
except:
registry = before_import_registry
if module_has_submodule(mod, 'alert_methods'):
... | conditional_block |
method_registry.py | # Eve W-Space
# Copyright 2014 Andrew Austin and contributors
#
# 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 requi... |
registry = MethodRegistry()
def autodiscover():
_autodiscover(registry)
def register(name, module):
"""Proxy for register method."""
return registry.register(name, module)
| import copy
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Import alert_methods from each app
try:
before_im... | identifier_body |
method_registry.py | # Eve W-Space
# Copyright 2014 Andrew Austin and contributors
#
# 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 requi... | (self, name):
method = self[name]
del self[name]
def register(self, name, module):
"""
Registers a method with its name and module.
"""
if not issubclass(module, AlertMethodBase):
raise AttributeError("Module given to MethodRegistry not valid")
if... | unregister | identifier_name |
user-profile.component.ts | import {Component, EventEmitter, Output, Input, OnInit} from '@angular/core';
import {UserModel, UserResponse} from "../user-management/user.model";
import {UserService} from "../user-management/user.service";
import {Config} from "../../../shared/configs/general.config";
@Component({
selector: 'user-profile',
... |
onShowEdit() {
this.showView = false;
}
}
| {
if (!args) // isCanceled
this.getUserDetail();
this.showView = true;
} | identifier_body |
user-profile.component.ts | import {Component, EventEmitter, Output, Input, OnInit} from '@angular/core';
import {UserModel, UserResponse} from "../user-management/user.model";
import {UserService} from "../user-management/user.service";
import {Config} from "../../../shared/configs/general.config";
@Component({
selector: 'user-profile',
... | })
export class UserProfileComponent implements OnInit {
// @Input showInfo:boolean;
@Input() userId:string;
@Output() userEditEvent:EventEmitter<any> = new EventEmitter();
@Input() showView:boolean;
objUser:UserModel = new UserModel();
objResponse:UserResponse = new UserResponse();
imageS... | random_line_split | |
user-profile.component.ts | import {Component, EventEmitter, Output, Input, OnInit} from '@angular/core';
import {UserModel, UserResponse} from "../user-management/user.model";
import {UserService} from "../user-management/user.service";
import {Config} from "../../../shared/configs/general.config";
@Component({
selector: 'user-profile',
... | (objResponse:any) {
swal("Alert !", objResponse.message, "info");
}
bindDetail(objUser:UserModel) {
this.objUser = objUser;
if (!this.objUser.imageName)
this.imageSrc = Config.DefaultAvatar;
else {
let cl = Config.Cloudinary;
this.imageSrc = cl... | errorMessage | identifier_name |
mod.rs | extern crate sodiumoxide;
extern crate serialize;
extern crate sync;
extern crate extra;
use std::io::{Listener, Acceptor};
use std::io::{MemReader, BufReader};
use std::io::net::ip::{SocketAddr};
use std::io::net::tcp::{TcpListener, TcpStream};
use std::from_str::{from_str};
use capnp::message::{MallocMessageBuilder,... |
else {
fail!("sad :(");
}
client.write(comm::bare_msgs::HELLOBYTES);
client.write(my_pubkey.get().key_bytes());
let client_pubkey = ~{
let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap();
let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>();
let ... | {
println!("Connection hello received");
} | conditional_block |
mod.rs | extern crate sodiumoxide;
extern crate serialize;
extern crate sync;
extern crate extra;
use std::io::{Listener, Acceptor};
use std::io::{MemReader, BufReader};
use std::io::net::ip::{SocketAddr};
use std::io::net::tcp::{TcpListener, TcpStream};
use std::from_str::{from_str};
use capnp::message::{MallocMessageBuilder,... | () {
sodiumoxide::init();
let (s_pubkey, s_privkey) = gen_keypair();
let a_pubkey = Arc::new(s_pubkey);
let a_privkey = Arc::new(s_privkey);
let bind_addr : SocketAddr = from_str("0.0.0.0:44944").unwrap();
let s_listener = TcpListener::bind(bind_addr).ok().expect("Failed to bind");
let mut s_acceptor = s_liste... | main | identifier_name |
mod.rs | extern crate sodiumoxide;
extern crate serialize;
extern crate sync;
extern crate extra;
use std::io::{Listener, Acceptor};
use std::io::{MemReader, BufReader};
use std::io::net::ip::{SocketAddr};
use std::io::net::tcp::{TcpListener, TcpStream};
use std::from_str::{from_str};
use capnp::message::{MallocMessageBuilder,... |
pub fn main() {
sodiumoxide::init();
let (s_pubkey, s_privkey) = gen_keypair();
let a_pubkey = Arc::new(s_pubkey);
let a_privkey = Arc::new(s_privkey);
let bind_addr : SocketAddr = from_str("0.0.0.0:44944").unwrap();
let s_listener = TcpListener::bind(bind_addr).ok().expect("Failed to bind");
let mut s_accep... | {
} | identifier_body |
mod.rs | extern crate sodiumoxide;
extern crate serialize;
extern crate sync;
extern crate extra;
use std::io::{Listener, Acceptor};
use std::io::{MemReader, BufReader};
use std::io::net::ip::{SocketAddr};
use std::io::net::tcp::{TcpListener, TcpStream};
use std::from_str::{from_str};
use capnp::message::{MallocMessageBuilder,... |
let (s_pubkey, s_privkey) = gen_keypair();
let a_pubkey = Arc::new(s_pubkey);
let a_privkey = Arc::new(s_privkey);
let bind_addr : SocketAddr = from_str("0.0.0.0:44944").unwrap();
let s_listener = TcpListener::bind(bind_addr).ok().expect("Failed to bind");
let mut s_acceptor = s_listener.listen().ok().expect("F... | random_line_split | |
resource.js | var model = require( "../../model.js" );
module.exports = function( host ) {
return {
name: "board",
actions: {
self: {
include: [ "id", "title" ],
method: "get",
url: "/:id",
embed: {
lanes: {
resource: "lane",
render: "self",
actions: [ "self", "cards" ]
}
},
... | }
};
}; | }
} | random_line_split |
test_brightbox.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | (self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
self.assertEqual(balancer.id, 'lba-1235f')
self.assertEqual(balancer.name, 'lb1')
self.assertEqual(balancer.state, State.RUNNING)
def test_destroy_balancer(self):
balancer = self.driver.get_balancer(balanc... | test_get_balancer | identifier_name |
test_brightbox.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | sys.exit(unittest.main()) | conditional_block | |
test_brightbox.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
def _1_0_load_balancers_lba_1235f_add_nodes(self, method, url, body,
headers):
if method == 'POST':
return self.response(httplib.ACCEPTED, '')
def _1_0_load_balancers_lba_1235f_remove_nodes(self, method, url, body,
... | if method == 'GET':
body = self.fixtures.load('load_balancers_lba_1235f.json')
return self.response(httplib.OK, body)
elif method == 'DELETE':
return self.response(httplib.ACCEPTED, '') | identifier_body |
test_brightbox.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
self.assertTrue(balancer.detach_member(member))
class BrightboxLBMockHttp(MockHttpTestCase):
fixtures = LoadBalancerFileFixtures('brightbox')
def _token(self, method, url, body, headers):
if method == 'POST':
return self.response(httplib.OK, self.fixtures.load('token.json'))
... | member = Member('srv-lv426', None, None) | random_line_split |
headergen.py | #!/usr/bin/env python3
# Copyright (C) 2010-2011 Marcin Kościelnicki <koriakin@0x04.net>
# Copyright (C) 2010 Luca Barbieri <luca@luca-barbieri.com>
# Copyright (C) 2010 Marcin Slusarz <marcin.slusarz@gmail.com>
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy o... |
return db.estatus
if len(sys.argv) < 2:
sys.stdout.write ("Usage:\n"
"\theadergen file.xml\n"
)
sys.exit(2)
sys.exit(process(sys.argv[1]))
| outs[file].write("\n#endif /* {} */\n".format(guard(file)))
fouts[file].close()
| conditional_block |
headergen.py | #!/usr/bin/env python3
# Copyright (C) 2010-2011 Marcin Kościelnicki <koriakin@0x04.net>
# Copyright (C) 2010 Luca Barbieri <luca@luca-barbieri.com>
# Copyright (C) 2010 Marcin Slusarz <marcin.slusarz@gmail.com>
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy o... |
def print_file_info(fout, file):
#struct stat sb;
#struct tm tm;
#stat(file, &sb);
#gmtime_r(&sb.st_mtime, &tm);
#char timestr[64];
#strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", tm);
#fprintf(dst, "(%7Lu bytes, from %s)\n", (unsigned long long)sb->st_size, timestr);
fout.writ... | f elem.varinfo.dead:
return
if elem.length != 1:
strides = strides + [elem.stride]
offset = offset + elem.offset
if elem.name:
if strides:
name = elem.fullname + '(' + ", ".join("i{}".format(i) for i in range(len(strides))) + ')'
val = '(' + hex(offset) + "".j... | identifier_body |
headergen.py | #!/usr/bin/env python3
# Copyright (C) 2010-2011 Marcin Kościelnicki <koriakin@0x04.net>
# Copyright (C) 2010 Luca Barbieri <luca@luca-barbieri.com>
# Copyright (C) 2010 Marcin Slusarz <marcin.slusarz@gmail.com>
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy o... | val, shift):
if val.varinfo.dead:
return
if val.value is not None:
printdef(val.fullname, hex(val.value << shift), val.file)
def printtypeinfo(ti, prefix, shift, file):
if isinstance(ti, rnn.TypeHex) or isinstance(ti, rnn.TypeInt):
if ti.shr:
printdef (prefix + "__SHR", ... | rintvalue( | identifier_name |
headergen.py | #!/usr/bin/env python3
# Copyright (C) 2010-2011 Marcin Kościelnicki <koriakin@0x04.net>
# Copyright (C) 2010 Luca Barbieri <luca@luca-barbieri.com>
# Copyright (C) 2010 Marcin Slusarz <marcin.slusarz@gmail.com>
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy o... | "http://github.com/envytools/envytools/\n"
"git clone https://github.com/envytools/envytools.git\n"
"\n"
"The rules-ng-ng source files this header was generated from are:\n")
#struct stat sb;
#struct tm tm;
#stat(f.name, &sb);
#gmtime_r(&sb.st_mtime, &tm);
maxlen = ma... | "\n"
"This file was generated by the rules-ng-ng headergen tool in this git repository:\n" | random_line_split |
test_ce_is_is_instance.py | # (c) 2019 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is dis... | config = dict(
instance_id=100,
vpn_name='__public__',
state='present')
set_module_args(config)
result = self.execute_module(changed=True)
self.assertEquals(sorted(result['updates']), sorted(update))
def test_isis_instance_present(self):
x... | self.get_nc_config.side_effect = (xml_existing, xml_end_state) | random_line_split |
test_ce_is_is_instance.py | # (c) 2019 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is dis... |
def test_isis_instance_present(self):
xml_existing = load_fixture('ce_is_is_instance', 'after.txt')
xml_end_state = load_fixture('ce_is_is_instance', 'before.txt')
update = ['undo isis 100']
self.get_nc_config.side_effect = (xml_existing, xml_end_state)
config = dict(
... | xml_existing = load_fixture('ce_is_is_instance', 'before.txt')
xml_end_state = load_fixture('ce_is_is_instance', 'after.txt')
update = ['isis 100', 'vpn-instance __public__']
self.get_nc_config.side_effect = (xml_existing, xml_end_state)
config = dict(
instance_id=100,
... | identifier_body |
test_ce_is_is_instance.py | # (c) 2019 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is dis... | (self):
xml_existing = load_fixture('ce_is_is_instance', 'after.txt')
xml_end_state = load_fixture('ce_is_is_instance', 'before.txt')
update = ['undo isis 100']
self.get_nc_config.side_effect = (xml_existing, xml_end_state)
config = dict(
instance_id=100,
... | test_isis_instance_present | identifier_name |
where-clauses-no-bounds-or-predicates.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn equal2<T>(_: &T, _: &T) -> bool where T: {
//~^ ERROR each predicate in a `where` clause must have at least one bound
true
}
fn main() {
}
| {
//~^ ERROR a `where` clause must have at least one predicate in it
true
} | identifier_body |
where-clauses-no-bounds-or-predicates.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T>(_: &T, _: &T) -> bool where T: {
//~^ ERROR each predicate in a `where` clause must have at least one bound
true
}
fn main() {
}
| equal2 | identifier_name |
where-clauses-no-bounds-or-predicates.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | true
}
fn equal2<T>(_: &T, _: &T) -> bool where T: {
//~^ ERROR each predicate in a `where` clause must have at least one bound
true
}
fn main() {
} | // compile-flags: -Z parse-only
fn equal1<T>(_: &T, _: &T) -> bool where {
//~^ ERROR a `where` clause must have at least one predicate in it | random_line_split |
compute_capabilities_filter.py | # Copyright (c) 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | """HostFilter hard-coded to work with InstanceType records."""
# Instance type and host capabilities do not change within a request
run_filter_once_per_request = True
def _get_capabilities(self, host_state, scope):
cap = host_state
for index in range(0, len(scope)):
try:
... | identifier_body | |
compute_capabilities_filter.py | # Copyright (c) 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... |
from oslo_log import log as logging
from oslo_serialization import jsonutils
import six
from nova.scheduler import filters
from nova.scheduler.filters import extra_specs_ops
LOG = logging.getLogger(__name__)
class ComputeCapabilitiesFilter(filters.BaseHostFilter):
"""HostFilter hard-coded to work with Instanc... | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License. | random_line_split |
compute_capabilities_filter.py | # Copyright (c) 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... |
if not extra_specs_ops.match(str(cap), req):
LOG.debug("%(host_state)s fails extra_spec requirements. "
"'%(req)s' does not match '%(cap)s'",
{'host_state': host_state, 'req': req,
'cap': cap})
r... | return False | conditional_block |
compute_capabilities_filter.py | # Copyright (c) 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | (self, host_state, scope):
cap = host_state
for index in range(0, len(scope)):
try:
if isinstance(cap, six.string_types):
try:
cap = jsonutils.loads(cap)
except ValueError as e:
LOG.debug(... | _get_capabilities | identifier_name |
test_msvc9compiler.py | """Tests for distutils.msvc9compiler."""
import sys
import unittest
import os
from distutils.errors import DistutilsPlatformError
from distutils.tests import support
from test.support import run_unittest
_MANIFEST = """\
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-co... | <requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false">
</requestedExecutionLevel>
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.VC90.CRT"
version="9.0.2102... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.