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
buffered_stream.rs
#![cfg(feature = "std")] extern crate combine; use combine::parser::char::{char, digit, spaces, string}; use combine::stream::buffered::BufferedStream; use combine::stream::easy::{self, Error}; use combine::stream::state::State; use combine::stream::IteratorStream; use combine::{choice, many, many1, sep_by, try, Parser...
else { c } }); let buffer = BufferedStream::new(State::new(IteratorStream::new(text)), 1); let int: &mut Parser<Input = _, Output = _, PartialState = _> = &mut many(digit()).map(|s: String| s.parse::<i64>().unwrap()); let result = sep_by(int, char(',')).parse(buffer).map(|t|...
{ (c as u8 + 1) as char }
conditional_block
buffered_stream.rs
#![cfg(feature = "std")] extern crate combine; use combine::parser::char::{char, digit, spaces, string}; use combine::stream::buffered::BufferedStream; use combine::stream::easy::{self, Error}; use combine::stream::state::State; use combine::stream::IteratorStream; use combine::{choice, many, many1, sep_by, try, Parser...
#[test] fn shared_stream_backtrack() { let text = "apple,apple,ananas,orangeblah"; let mut iter = text.chars(); // Iterator that can't be cloned let stream = BufferedStream::new(State::new(IteratorStream::new(&mut iter)), 2); let value: &mut Parser<Input = _, Output = _, PartialState = _> = &mut ...
{ // Iterator that can't be cloned let text = "10,222,3,44".chars().map(|c| { if c.is_digit(10) { (c as u8 + 1) as char } else { c } }); let buffer = BufferedStream::new(State::new(IteratorStream::new(text)), 1); let int: &mut Parser<Input = _, Output ...
identifier_body
buffered_stream.rs
#![cfg(feature = "std")] extern crate combine; use combine::parser::char::{char, digit, spaces, string}; use combine::stream::buffered::BufferedStream; use combine::stream::easy::{self, Error}; use combine::stream::state::State; use combine::stream::IteratorStream; use combine::{choice, many, many1, sep_by, try, Parser...
let value: &mut Parser<Input = _, Output = _, PartialState = _> = &mut choice([ try(string("apple")), try(string("orange")), try(string("ananas")), ]); let mut parser = sep_by(value, char(',')); let result: Result<Vec<&str>, _> = parser.parse(stream).map(|t| t.0); assert!(re...
let text = "apple,apple,ananas,orangeblah"; let mut iter = text.chars(); // Iterator that can't be cloned let stream = BufferedStream::new(easy::Stream(State::new(IteratorStream::new(&mut iter))), 1);
random_line_split
three-effectcomposer.d.ts
// Type definitions for three.js (EffectComposer.js) // Project: https://github.com/mrdoob/three.js/blob/r68/examples/js/postprocessing/EffectComposer.js // Definitions by: Satoru Kimura <https://github.com/gyohk> // Definitions: https://github.com/borisyankov/DefinitelyTyped /// <reference path="./three.d.ts" /> /// ...
{ constructor( renderer: WebGLRenderer, renderTarget?: WebGLRenderTarget); renderTarget1: WebGLRenderTarget; renderTarget2: WebGLRenderTarget; writeBuffer: WebGLRenderTarget; readBuffer: WebGLRenderTarget; passes: any[]; copyPass: ShaderPass; swapBuffers(): void; addPass(pass: any): void; inser...
EffectComposer
identifier_name
three-effectcomposer.d.ts
// Type definitions for three.js (EffectComposer.js) // Project: https://github.com/mrdoob/three.js/blob/r68/examples/js/postprocessing/EffectComposer.js // Definitions by: Satoru Kimura <https://github.com/gyohk> // Definitions: https://github.com/borisyankov/DefinitelyTyped /// <reference path="./three.d.ts" /> /// ...
constructor( renderer: WebGLRenderer, renderTarget?: WebGLRenderTarget); renderTarget1: WebGLRenderTarget; renderTarget2: WebGLRenderTarget; writeBuffer: WebGLRenderTarget; readBuffer: WebGLRenderTarget; passes: any[]; copyPass: ShaderPass; swapBuffers(): void; addPass(pass: any): void; insertPa...
declare module THREE { export class EffectComposer {
random_line_split
_ext_type.py
# $File: _ext_type.py # $Date: Wed Feb 22 15:04:06 2012 +0800 # # Copyright (C) 2012 the pynojo development team <see AUTHORS file> # # Contributors to this file: # Kai Jia <jia.kai66@gmail.com> # # This file is part of pynojo # # pynojo is free software: you can redistribute it and/or modify # it under the terms ...
_JSONEncodeDictMutabilize.associate_with(JSONEncodeDict)
@classmethod def coerce(cls, key, value): if not isinstance(value, _JSONEncodeDictMutabilize): if isinstance(value, dict): return _JSONEncodeDictMutabilize(value) return Mutable.coerce(key, value) else: return value def __setitem__(self, key...
identifier_body
_ext_type.py
# $File: _ext_type.py # $Date: Wed Feb 22 15:04:06 2012 +0800 # # Copyright (C) 2012 the pynojo development team <see AUTHORS file> # # Contributors to this file: # Kai Jia <jia.kai66@gmail.com> # # This file is part of pynojo # # pynojo is free software: you can redistribute it and/or modify # it under the terms ...
self.changed() _JSONEncodeDictMutabilize.associate_with(JSONEncodeDict)
random_line_split
_ext_type.py
# $File: _ext_type.py # $Date: Wed Feb 22 15:04:06 2012 +0800 # # Copyright (C) 2012 the pynojo development team <see AUTHORS file> # # Contributors to this file: # Kai Jia <jia.kai66@gmail.com> # # This file is part of pynojo # # pynojo is free software: you can redistribute it and/or modify # it under the terms ...
(Mutable, dict): @classmethod def coerce(cls, key, value): if not isinstance(value, _JSONEncodeDictMutabilize): if isinstance(value, dict): return _JSONEncodeDictMutabilize(value) return Mutable.coerce(key, value) else: return value def...
_JSONEncodeDictMutabilize
identifier_name
_ext_type.py
# $File: _ext_type.py # $Date: Wed Feb 22 15:04:06 2012 +0800 # # Copyright (C) 2012 the pynojo development team <see AUTHORS file> # # Contributors to this file: # Kai Jia <jia.kai66@gmail.com> # # This file is part of pynojo # # pynojo is free software: you can redistribute it and/or modify # it under the terms ...
return value def process_result_value(self, value, dialect): if value is not None: value = cjson.decode(value) return value class _JSONEncodeDictMutabilize(Mutable, dict): @classmethod def coerce(cls, key, value): if not isinstance(value, _JSONEncodeDictMu...
value = cjson.encode(value) if len(value) > self.length: raise PynojoRuntimeError(_( '{class_name}: encoded string too long', class_name = self.__class__.__name__))
conditional_block
lru_cache_unittest.py
#!/usr/bin/env python # Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list ...
(self): self.assertEqual(set(self.lru.items()), set([('key_1', 'item_1'), ('key_3', 'item_3'), ('key_2', 'item_2')])) def test_put(self): self.lru['key_4'] = 'item_4' self.assertEqual(set(self.lru.items()), set([('key_4', 'item_4'), ('key_3', 'item_3'), ('key_2', 'item_2')])) def test_...
test_items
identifier_name
lru_cache_unittest.py
#!/usr/bin/env python # Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list ...
self.lru['key_5'] = 'item_5' self.assertEqual(set(self.lru.keys()), set(['key_2', 'key_4', 'key_5'])) def test_set_again(self): self.lru['key_1'] = 'item_4' self.assertEqual(set(self.lru.items()), set([('key_1', 'item_4'), ('key_3', 'item_3'), ('key_2', 'item_2')])) if __name__ ==...
random_line_split
lru_cache_unittest.py
#!/usr/bin/env python # Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list ...
def test_size_one_delete(self): del self.lru2['key_1'] self.assertFalse('key_1' in self.lru2) def test_pop_error(self): self.assertRaises(KeyError, self.lru2.__getitem__, 'key_2') del self.lru2['key_1'] self.assertRaises(KeyError, self.lru2.__getitem__, 'key_2') d...
self.lru2['key_2'] = 'item_2' self.assertEqual(self.lru2.keys(), ['key_2'])
identifier_body
lru_cache_unittest.py
#!/usr/bin/env python # Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list ...
unittest.main()
conditional_block
gl_XML.py
processor macro `PURE' that wraps GCC's `pure' function attribute. The conditional code can be easilly adapted to other compilers that support a similar feature. The name is also added to the file's undef_list. """ self.undef_list.append("PURE") print """# if defined(__GNUC__) || (defined(__SUNPRO_C) &...
else: priority = 6 return priority + bias class gl_parameter: def __init__(self, element, context): self.name = element.nsProp( "name", None ) ts = element.nsProp( "type", None ) self.type_expr = typeexpr.type_expression( ts, context ) temp = element.nsProp( "variable_param", None ) if temp: ...
priority = 4
conditional_block
gl_XML.py
self.header_tag = None # List of file-private defines that must be undefined at the # end of the file. This can be used in header files to define # names for use in the file, then undefine them at the end of # the header file. self.undef_list = [] return def Print(self, api): self.printHeader(...
# generated C header files need this to be set. Setting it # causes code to be generated automatically in printHeader # and printFooter.
random_line_split
gl_XML.py
Visibility(self, S, s): """Conditionally define visibility function attribute. Conditionally defines a preprocessor macro name S that wraps GCC's visibility function attribute. The visibility used is the parameter s. The conditional code can be easilly adapted to other compilers that support a similar feat...
return len(self.count_parameter_list) or self.counter
identifier_body
gl_XML.py
macro `PURE' that wraps GCC's `pure' function attribute. The conditional code can be easilly adapted to other compilers that support a similar feature. The name is also added to the file's undef_list. """ self.undef_list.append("PURE") print """# if defined(__GNUC__) || (defined(__SUNPRO_C) && (__SUNP...
(parameters, include_names): """Create a parameter string from a list of gl_parameters.""" list = [] for p in parameters: if p.is_padding: continue if include_names: list.append( p.string() ) else: list.append( p.type_string() ) if len(list) == 0: list = ["void"] return string.join(list, ", ") ...
create_parameter_string
identifier_name
server.js
/**! * urllib - test/fixtures/server.js * * Copyright(c) 2011 - 2014 fengmk2 and other contributors. * MIT Licensed * * Authors: * fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com) */ "use strict"; /** * Module dependencies. */ var should = require('should'); var http = require('http'); var queryst...
} else if (req.url === '/stream') { res.writeHeader(200, { 'Content-Length': String(size) }); for (var i = 0; i < chunks.length; i++) { res.write(chunks[i]); } res.end(); return; } else if (req.url.indexOf('/json_mirror') === 0) { res.setHeader('Content-...
} else if (req.url === '/auth') { var auth = new Buffer(req.headers.authorization.split(' ')[1], 'base64').toString().split(':'); res.writeHeader(200); return res.end(JSON.stringify({user: auth[0], password: auth[1]}));
random_line_split
errors.rs
//! Tidy check to verify the validity of long error diagnostic codes. //! //! This ensures that error codes are used at most once and also prints out some //! statistics about the error codes. use std::collections::HashMap; use std::path::Path; pub fn check(path: &Path, bad: &mut bool)
// and these long messages often have error codes themselves inside // them, but we don't want to report duplicates in these cases. This // variable keeps track of whether we're currently inside one of these // long diagnostic messages. let mut inside_long_dia...
{ let mut map: HashMap<_, Vec<_>> = HashMap::new(); super::walk( path, &mut |path| super::filter_dirs(path) || path.ends_with("src/test"), &mut |entry, contents| { let file = entry.path(); let filename = file.file_name().unwrap().to_string_lossy(); if ...
identifier_body
errors.rs
//! Tidy check to verify the validity of long error diagnostic codes. //! //! This ensures that error codes are used at most once and also prints out some //! statistics about the error codes. use std::collections::HashMap; use std::path::Path;
pub fn check(path: &Path, bad: &mut bool) { let mut map: HashMap<_, Vec<_>> = HashMap::new(); super::walk( path, &mut |path| super::filter_dirs(path) || path.ends_with("src/test"), &mut |entry, contents| { let file = entry.path(); let filename = file.file_name().u...
random_line_split
errors.rs
//! Tidy check to verify the validity of long error diagnostic codes. //! //! This ensures that error codes are used at most once and also prints out some //! statistics about the error codes. use std::collections::HashMap; use std::path::Path; pub fn
(path: &Path, bad: &mut bool) { let mut map: HashMap<_, Vec<_>> = HashMap::new(); super::walk( path, &mut |path| super::filter_dirs(path) || path.ends_with("src/test"), &mut |entry, contents| { let file = entry.path(); let filename = file.file_name().unwrap().to_s...
check
identifier_name
mapping.py
# # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of REDHAWK core. # # REDHAWK core is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free ...
(PortMapper): def _mapPort(self, port, generator): javaport = {} javaport['javaname'] = java.identifier('port_'+port.name()) javaport['javatype'] = generator.className() javaport['constructor'] = generator.constructor(port.name()) javaport['start'] = generator.start() ...
JavaPortMapper
identifier_name
mapping.py
# # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of REDHAWK core. # # REDHAWK core is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free ...
javaport = {} javaport['javaname'] = java.identifier('port_'+port.name()) javaport['javatype'] = generator.className() javaport['constructor'] = generator.constructor(port.name()) javaport['start'] = generator.start() javaport['stop'] = generator.stop() javaport['multiout...
identifier_body
mapping.py
# # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of REDHAWK core. # # REDHAWK core is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free ...
return javaport
javaport['stop'] = generator.stop() javaport['multiout'] = generator.supportsMultiOut()
random_line_split
epoll.rs
use {Errno, Result}; use libc::c_int; use std::os::unix::io::RawFd; mod ffi { use libc::{c_int}; use super::EpollEvent; extern { pub fn epoll_create(size: c_int) -> c_int; pub fn epoll_ctl(epfd: c_int, op: c_int, fd: c_int, event: *const EpollEvent) -> c_int; pub fn epoll_wait(epfd...
{ EpollCtlAdd = 1, EpollCtlDel = 2, EpollCtlMod = 3 } #[cfg(not(target_arch = "x86_64"))] #[derive(Clone, Copy)] #[repr(C)] pub struct EpollEvent { pub events: EpollEventKind, pub data: u64 } #[cfg(target_arch = "x86_64")] #[derive(Clone, Copy)] #[repr(C, packed)] pub struct EpollEvent { pub ...
EpollOp
identifier_name
epoll.rs
use {Errno, Result}; use libc::c_int; use std::os::unix::io::RawFd; mod ffi { use libc::{c_int}; use super::EpollEvent; extern { pub fn epoll_create(size: c_int) -> c_int; pub fn epoll_ctl(epfd: c_int, op: c_int, fd: c_int, event: *const EpollEvent) -> c_int; pub fn epoll_wait(epfd...
const EPOLLOUT = 0x004, const EPOLLRDNORM = 0x040, const EPOLLRDBAND = 0x080, const EPOLLWRNORM = 0x100, const EPOLLWRBAND = 0x200, const EPOLLMSG = 0x400, const EPOLLERR = 0x008, const EPOLLHUP = 0x010, const EPOLLRDHUP = 0x2000, const EPO...
const EPOLLIN = 0x001, const EPOLLPRI = 0x002,
random_line_split
epoll.rs
use {Errno, Result}; use libc::c_int; use std::os::unix::io::RawFd; mod ffi { use libc::{c_int}; use super::EpollEvent; extern { pub fn epoll_create(size: c_int) -> c_int; pub fn epoll_ctl(epfd: c_int, op: c_int, fd: c_int, event: *const EpollEvent) -> c_int; pub fn epoll_wait(epfd...
#[inline] pub fn epoll_wait(epfd: RawFd, events: &mut [EpollEvent], timeout_ms: isize) -> Result<usize> { let res = unsafe { ffi::epoll_wait(epfd, events.as_mut_ptr(), events.len() as c_int, timeout_ms as c_int) }; Errno::result(res).map(|r| r as usize) }
{ let res = unsafe { ffi::epoll_ctl(epfd, op as c_int, fd, event as *const EpollEvent) }; Errno::result(res).map(drop) }
identifier_body
file-upload.js
const mtype = require('@lib/mediatype'); const model = require('@lib/model'); const fs = require('fs'); const mcdir = require('@lib/mcdir'); module.exports = function(r) { const db = require('../db')(r); async function addFileToDirectoryInProject(fileToUpload, directoryId, projectId, userId) { let fil...
else { // There is already a file in the store with the same checksum // so delete uploaded file. removeFile(fileEntry.path); } } // findMatchingFileIdByChecksum will return the id of the file that // was uploaded with the name checksum or "" if there is no matc...
{ // This is a brand new file so move into the object store. await mcdir.moveIntoStore(fileEntry.path, fileEntry.id); }
conditional_block
file-upload.js
const mtype = require('@lib/mediatype'); const model = require('@lib/model'); const fs = require('fs'); const mcdir = require('@lib/mcdir'); module.exports = function(r) { const db = require('../db')(r); async function addFileToDirectoryInProject(fileToUpload, directoryId, projectId, userId) { let fil...
async function addFileToProject(fileId, projectId) { let p2df = new model.Project2DataFile(projectId, fileId); await r.table('project2datafile').insert(p2df); } return { addFileToDirectoryInProject, createFile, }; };
{ const dd2df = new model.DataDir2DataFile(directoryId, fileId); await r.table('datadir2datafile').insert(dd2df); }
identifier_body
file-upload.js
const mtype = require('@lib/mediatype'); const model = require('@lib/model'); const fs = require('fs'); const mcdir = require('@lib/mcdir'); module.exports = function(r) { const db = require('../db')(r); async function addFileToDirectoryInProject(fileToUpload, directoryId, projectId, userId) { let fil...
(parent, fileEntry, directoryId, projectId) { await addToObjectStore(fileEntry); fileEntry.parentId = parent.id; let created = await createFile(fileEntry, directoryId, projectId); // Parent is no longer the current file await r.table('datafiles').get(parent.id).update({current:...
loadExistingFileIntoDirectory
identifier_name
file-upload.js
const mtype = require('@lib/mediatype'); const model = require('@lib/model'); const fs = require('fs'); const mcdir = require('@lib/mcdir'); module.exports = function(r) { const db = require('../db')(r); async function addFileToDirectoryInProject(fileToUpload, directoryId, projectId, userId) { let fil...
let created = await db.insert('datafiles', file); await addFileToDirectory(created.id, directoryId); await addFileToProject(created.id, projectId); return created; } async function addFileToDirectory(fileId, directoryId) { const dd2df = new model.DataDir2DataFile(dire...
random_line_split
build.rs
extern crate winres; extern crate rustc_version; extern crate chrono;
if cfg!(target_os = "windows") { let res = winres::WindowsResource::new(); // can't set an icon because its a DLL, but winres will still pull // values out of cargo.toml and stick them in the resource. res.compile().unwrap(); } // https://stackoverflow.com/questions/43753491/include-git-commit-h...
fn main() { use std::process::Command;
random_line_split
build.rs
extern crate winres; extern crate rustc_version; extern crate chrono; fn main()
println!("cargo:rustc-env=RUSTCVER={}", rustc_version::version().unwrap()); println!("cargo:rustc-env=RUSTCDATE={}", rustc_version::version_meta().unwrap().commit_date.unwrap()); }
{ use std::process::Command; if cfg!(target_os = "windows") { let res = winres::WindowsResource::new(); // can't set an icon because its a DLL, but winres will still pull // values out of cargo.toml and stick them in the resource. res.compile().unwrap(); } // https://stackoverflow.com/questio...
identifier_body
build.rs
extern crate winres; extern crate rustc_version; extern crate chrono; fn
() { use std::process::Command; if cfg!(target_os = "windows") { let res = winres::WindowsResource::new(); // can't set an icon because its a DLL, but winres will still pull // values out of cargo.toml and stick them in the resource. res.compile().unwrap(); } // https://stackoverflow.com/ques...
main
identifier_name
build.rs
extern crate winres; extern crate rustc_version; extern crate chrono; fn main() { use std::process::Command; if cfg!(target_os = "windows")
// https://stackoverflow.com/questions/43753491/include-git-commit-hash-as-string-into-rust-program let output = Command::new("git").args(&["rev-parse", "HEAD"]).output().unwrap(); let git_hash = String::from_utf8(output.stdout).unwrap(); println!("cargo:rustc-env=GIT_HASH={}", git_hash); // build timestam...
{ let res = winres::WindowsResource::new(); // can't set an icon because its a DLL, but winres will still pull // values out of cargo.toml and stick them in the resource. res.compile().unwrap(); }
conditional_block
ItemLink.jest.tsx
import React from "react" import { mount } from "enzyme" import ItemLink from "../ItemLink" import { CircleWhiteCheckIcon, PlusIcon } from "@artsy/palette" describe("ArtistSearchResults", () => { const mockedOnFollow = jest.fn() const mockedArtist = {} const props = { href: "#", item: mockedArtist, ...
expect(wrapper.find(CircleWhiteCheckIcon).exists()).toBeFalsy() expect(wrapper.find(PlusIcon).exists()).toBeTruthy() }) it("renders CircleWhiteCheckIcon", () => { const wrapper = mount(<ItemLink {...props} />) const onClick = wrapper.find("Link").prop("onClick") const event: any = {} // @t...
random_line_split
credentials.py
#!/usr/bin/env python # import keystoneclient.v2_0.client as ksclient # import glanceclient.v2.client as glclient # import novaclient.client as nvclient # import neutronclient.v2_0.client as ntclient # import cinderclient.v2.client as cdclient # import swiftclient.client as sftclient __author__ = 'Yuvv' OS_PROJECT_D...
def get_neutron_credits(): cred = dict() cred['username'] = OS_USERNAME cred['password'] = OS_PASSWORD cred['auth_url'] = OS_AUTH_URL cred['tenant_name'] = OS_TENANT_NAME return cred def get_cinder_credits(): cred = dict() cred['username'] = OS_USERNAME cred['api_key'] = OS_PASS...
cred = dict() cred['username'] = OS_USERNAME cred['password'] = OS_PASSWORD cred['auth_url'] = OS_AUTH_URL cred['tenant_name'] = OS_TENANT_NAME return cred
identifier_body
credentials.py
#!/usr/bin/env python # import keystoneclient.v2_0.client as ksclient # import glanceclient.v2.client as glclient # import novaclient.client as nvclient # import neutronclient.v2_0.client as ntclient # import cinderclient.v2.client as cdclient # import swiftclient.client as sftclient __author__ = 'Yuvv' OS_PROJECT_D...
cinder = cdclient.Client(auth_url=OS_AUTH_URL, username=OS_USERNAME, api_key=OS_PASSWORD, project_id=OS_TENANT_NAME) nova = nvclient.Client('2.1', auth_url=OS_AUTH_URL, username=OS_USERNAME, api_key=...
neutron = ntclient.Client(endpoint_url=keystone.service_catalog.url_for(service_type='network'), token=keystone.auth_token)
random_line_split
credentials.py
#!/usr/bin/env python # import keystoneclient.v2_0.client as ksclient # import glanceclient.v2.client as glclient # import novaclient.client as nvclient # import neutronclient.v2_0.client as ntclient # import cinderclient.v2.client as cdclient # import swiftclient.client as sftclient __author__ = 'Yuvv' OS_PROJECT_D...
(): cred = dict() cred['username'] = OS_USERNAME cred['password'] = OS_PASSWORD cred['auth_url'] = OS_AUTH_URL cred['tenant_name'] = OS_TENANT_NAME return cred def get_neutron_credits(): cred = dict() cred['username'] = OS_USERNAME cred['password'] = OS_PASSWORD cred['auth_url'...
get_keystone_credits
identifier_name
lrcserv.py
_port = 38439 def ChooiseItem(xml, artist): #print '===============================================' #print xml.decode('utf-8').encode('gbk') n = xml.find('<?xml') if n == -1: return False artist = ttlrcdump.FilterSearchStr(artist) #remove item if artist != artist n = 0 pos = ...
swith('/lrc'): try: id = get_arg(request.uri, 'id') artist = unquote(get_arg(request.uri, 'artist')) title = unquote(get_arg(request.uri, 'title')) ttservernum = int(get_arg(request.uri, 'ttservernum')) #print id.decode('utf-8').encode('gbk') ...
uest.uri.start
identifier_name
lrcserv.py
listen_port = 38439 def ChooiseItem(xml, artist): #print '===============================================' #print xml.decode('utf-8').encode('gbk') n = xml.find('<?xml') if n == -1: return False artist = ttlrcdump.FilterSearchStr(artist) #remove item if artist != artist n = 0 ...
#print xml.decode('utf-8').encode('gbk') #print '===============================================' n = xml.find('id=') if n == -1: return False #remove item if artist != artist n = 0 begin = xml.find('artist="', n) end = xml.find('" title', n) n = end _artist = ttlrcdump....
random_line_split
lrcserv.py
_port = 38439 def ChooiseItem(xml, artist): #print '===============================================' #print xml.decode('utf-8').encode('gbk') n = xml.find('<?xml') if n == -1: return False artist = ttlrcdump.FilterSearchStr(artist) #remove item if artist != artist n = 0 pos = ...
context = context.replace('%s',lrc, 1) #print context request.write('HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n%s' % (len(context), context)) except tornado.httpclient.HTTPError, code: print 'HTTPError except Code' + str(code) except Exception,e: ...
try: id = get_arg(request.uri, 'id') artist = unquote(get_arg(request.uri, 'artist')) title = unquote(get_arg(request.uri, 'title')) ttservernum = int(get_arg(request.uri, 'ttservernum')) #print id.decode('utf-8').encode('gbk') #print artist...
identifier_body
lrcserv.py
_port = 38439 def ChooiseItem(xml, artist): #print '===============================================' #print xml.decode('utf-8').encode('gbk') n = xml.find('<?xml') if n == -1: return False artist = ttlrcdump.FilterSearchStr(artist) #remove item if artist != artist n = 0 pos = ...
e: break if ret != False: context = '<div class="newscont mb15" style="line-height:160%;margin-top:10px">' \ '歌手:<a class="mr">%s</a><br>' \ '专辑:<a class="mr"></a>' \ '歌曲:<a class="mr ">%s<span...
Fals
conditional_block
schema.py
Operation from django.utils.translation import lazy from .exceptions import TemplateSchemaActivation, SchemaNotFound from .signals import find_schema LOGGER = logging.getLogger(__name__) LOGGER.addHandler(logging.NullHandler()) _thread_locals = threading.local() def get_schema_model(): """ Return the clas...
(schema_name): """ Activate the current schema: this will execute, in the database connection, something like: .. code:: sql SET search_path TO "foo",public; It sends signals before and after that the schema will be, and was activated. Must be passed a string: the internal name o...
activate_schema
identifier_name
schema.py
Operation from django.utils.translation import lazy from .exceptions import TemplateSchemaActivation, SchemaNotFound from .signals import find_schema LOGGER = logging.getLogger(__name__) LOGGER.addHandler(logging.NullHandler()) _thread_locals = threading.local() def get_schema_model(): """ Return the clas...
return apps.get_models() def _get_join_model(table, table_map): """ Given a database table, and a mapping of tables to models, look for a many-to-many field on models that uses that database table. Currently, it only looks within models that have a matching prefix. """ for db_table, mod...
""" If we are in a migration operation, we need to look in that for models. We really only should be injecting ourselves if we find a frame that contains a database_(forwards|backwards) function. Otherwise, we can look in the `apps` object passed in. """ for frame in stack: frame_locals ...
identifier_body
schema.py
Operation from django.utils.translation import lazy from .exceptions import TemplateSchemaActivation, SchemaNotFound from .signals import find_schema LOGGER = logging.getLogger(__name__) LOGGER.addHandler(logging.NullHandler()) _thread_locals = threading.local() def get_schema_model(): """ Return the clas...
schema_pre_activate.send(sender=None, schema_name=schema_name) _set_search_path(schema_name) found_schema = _get_search_path() if found_schema != schema_name: raise SchemaNotFound('Schema activation failed. Expected "{0}", saw "{1}"'.format( schema_name, found_schema, )) ...
raise TemplateSchemaActivation()
conditional_block
schema.py
Operation from django.utils.translation import lazy from .exceptions import TemplateSchemaActivation, SchemaNotFound from .signals import find_schema LOGGER = logging.getLogger(__name__) LOGGER.addHandler(logging.NullHandler()) _thread_locals = threading.local() def get_schema_model(): """ Return the clas...
""" try: return apps.get_model(settings.BOARDINGHOUSE_SCHEMA_MODEL) except AttributeError: raise ImproperlyConfigured("BOARDINGHOUSE_SCHEMA_MODEL is not set: is 'boardinghouse' in your INSTALLED_APPS?") except ValueError: raise ImproperlyConfigured("BOARDINGHOUSE_SCHEMA_MODEL mus...
random_line_split
DbOpen.py
# Copyright (C) 2009, 2010, 2011 Rickard Lindberg, Roger Lindberg # # This file is part of Timeline. # # Timeline 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...
elif cat.get_name() == "Category 2": self.assertEqual(cat.get_color(), (255, 165, 0)) self.assertTrue(vp.is_category_visible(cat)) self.assertEqual(cat.get_parent().get_name(), "Category 1") elif cat.get_name() == "Category 3": sel...
self.assertEqual(cat.get_color(), (188, 129, 224)) self.assertTrue(vp.is_category_visible(cat)) self.assertEqual(cat.get_parent(), None)
conditional_block
DbOpen.py
# Copyright (C) 2009, 2010, 2011 Rickard Lindberg, Roger Lindberg # # This file is part of Timeline. # # Timeline 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...
(self): self.writeContentToTmpFile(CONTENT_010) try: db_open(self.tmp_path) except TimelineIOError, e: self.assertTrue("old file with a new version" in str(e)) def testRead0100File(self): self.writeContentToTmpFile(CONTENT_0100) db = db_open(self.tmp_...
test_raises_error_when_reading_non_xml_file
identifier_name
DbOpen.py
# Copyright (C) 2009, 2010, 2011 Rickard Lindberg, Roger Lindberg # # This file is part of Timeline. # # Timeline 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...
self.assertEqual(event.get_category().get_name(), "Category 1") self.assertEqual(event.get_data("description"), "The first event.") self.assertEqual(event.get_data("icon"), None) # Assert that correct view properties are loaded (category visibility # checked later) vp = V...
def test_raises_error_when_reading_non_xml_file(self): self.writeContentToTmpFile(CONTENT_010) try: db_open(self.tmp_path) except TimelineIOError, e: self.assertTrue("old file with a new version" in str(e)) def testRead0100File(self): self.writeContentToTmpFi...
identifier_body
DbOpen.py
# Copyright (C) 2009, 2010, 2011 Rickard Lindberg, Roger Lindberg # # This file is part of Timeline. # # Timeline 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...
f.close()
f.write(content)
random_line_split
settings.py
# Django settings for apmanager project. import os from django.utils.translation import ugettext_lazy as _ DEBUG = True USE_DAEMON = True if os.environ.get("USE_DEV_PATHS", None):
else: DEV_PATHS = False TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'. DATABASE_NAME = 'papas.sqlite' # Or path to database file if usi...
DEV_PATHS = True
conditional_block
settings.py
# Django settings for apmanager project. import os from django.utils.translation import ugettext_lazy as _ DEBUG = True USE_DAEMON = True if os.environ.get("USE_DEV_PATHS", None): DEV_PATHS = True else: DEV_PATHS = False TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGE...
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = "/media/" # Make this unique, and don't share it with anybody. SECRET_KEY = ')@1wt()$4x&&e9c#n&viv-g#k20(p!_ga)s$+4i!*hbdcid$)s' # List of callables th...
MEDIA_ROOT = "/usr/share/apmanager/templates/site-media" # URL that handles the media served from MEDIA_ROOT. # Example: "http://media.lawrence.com" MEDIA_URL = "/site-media/"
random_line_split
jsonp.js
// Copyright 2012 Mark Cavage, Inc. All rights reserved. 'use strict'; ///--- Exports /** * JSONP formatter. like JSON, but with a callback invocation. * * Unicode escapes line and paragraph separators. * * @public * @function formatJSONP * @param {Object} req the request object * @param {Object} res...
data = data.replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029'); res.setHeader('Content-Length', Buffer.byteLength(data)); return data; } module.exports = formatJSONP;
{ data = JSON.stringify(body); }
conditional_block
jsonp.js
// Copyright 2012 Mark Cavage, Inc. All rights reserved. 'use strict'; ///--- Exports /** * JSONP formatter. like JSON, but with a callback invocation. * * Unicode escapes line and paragraph separators. * * @public * @function formatJSONP * @param {Object} req the request object * @param {Object} res...
data = data.replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029'); res.setHeader('Content-Length', Buffer.byteLength(data)); return data; } module.exports = formatJSONP;
{ if (!body) { res.setHeader('Content-Length', 0); return (null); } if (Buffer.isBuffer(body)) { body = body.toString('base64'); } var _cb = req.query.callback || req.query.jsonp; var data; if (_cb) { data = 'typeof ' + _cb + ' === \'function\' && ' + ...
identifier_body
jsonp.js
// Copyright 2012 Mark Cavage, Inc. All rights reserved. 'use strict'; ///--- Exports /** * JSONP formatter. like JSON, but with a callback invocation. * * Unicode escapes line and paragraph separators. * * @public * @function formatJSONP * @param {Object} req the request object * @param {Object} res...
function formatJSONP(req, res, body) { if (!body) { res.setHeader('Content-Length', 0); return (null); } if (Buffer.isBuffer(body)) { body = body.toString('base64'); } var _cb = req.query.callback || req.query.jsonp; var data; if (_cb) { data = 'typeof ' + ...
* @param {Object} body response body * @returns {String} */
random_line_split
jsonp.js
// Copyright 2012 Mark Cavage, Inc. All rights reserved. 'use strict'; ///--- Exports /** * JSONP formatter. like JSON, but with a callback invocation. * * Unicode escapes line and paragraph separators. * * @public * @function formatJSONP * @param {Object} req the request object * @param {Object} res...
(req, res, body) { if (!body) { res.setHeader('Content-Length', 0); return (null); } if (Buffer.isBuffer(body)) { body = body.toString('base64'); } var _cb = req.query.callback || req.query.jsonp; var data; if (_cb) { data = 'typeof ' + _cb + ' === \'functi...
formatJSONP
identifier_name
orffasta.py
""" Creates fasta file from orfs """ import argparse import os import sys import site import re import numpy as np import numpy.random base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) base_path="%s/src"%base_path for directory_name in os.listdir(base_path):
import fasta import faa import gff import cPickle if __name__=="__main__": parser = argparse.ArgumentParser(description=\ 'Extracts orfs and creates fasta files') parser.add_argument('--gff', type=str, required=False, help='Input gff file') parser.add_argume...
site.addsitedir(os.path.join(base_path, directory_name))
conditional_block
orffasta.py
""" Creates fasta file from orfs """ import argparse import os import sys import site import re import numpy as np import numpy.random base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) base_path="%s/src"%base_path for directory_name in os.listdir(base_path): site.addsitedir(os.path.join(base...
if args.pickle==None: clusters = clique_filter.findContextGeneClusters(all_hits,faidx,backtrans=False, functions=["toxin","transport"]) cPickle.dump(open(args.pickle,'wb')) else: clusters,_ = cPickle.load(open(args.pickle,'rb')) ...
print "Loading pickle" faaindex = faa.FAA(args.faa) faaindex.load("faa.pickle")
random_line_split
DaoVendedorCliente.ts
import { Injectable } from '@angular/core'; import { VendedorCliente } from "../model/VendedorCliente"; import { DaoGenerico } from '../dao/Dao'; import { ToastMensagem } from '../providers/toast/toast' @Injectable() export class DaoVendedorCliente { private objRepositorio: any; constructor ( public daoGen...
getRepositorio(): any{ if(this.objRepositorio == null){ this.objRepositorio = this.daoGenerico.connection.getRepository(VendedorCliente); } return this.objRepositorio; } }
}) }
random_line_split
DaoVendedorCliente.ts
import { Injectable } from '@angular/core'; import { VendedorCliente } from "../model/VendedorCliente"; import { DaoGenerico } from '../dao/Dao'; import { ToastMensagem } from '../providers/toast/toast' @Injectable() export class DaoVendedorCliente { private objRepositorio: any; constructor ( public daoGen...
return this.objRepositorio; } }
{ this.objRepositorio = this.daoGenerico.connection.getRepository(VendedorCliente); }
conditional_block
DaoVendedorCliente.ts
import { Injectable } from '@angular/core'; import { VendedorCliente } from "../model/VendedorCliente"; import { DaoGenerico } from '../dao/Dao'; import { ToastMensagem } from '../providers/toast/toast' @Injectable() export class DaoVendedorCliente { private objRepositorio: any; constructor ( public daoGen...
}
{ if(this.objRepositorio == null){ this.objRepositorio = this.daoGenerico.connection.getRepository(VendedorCliente); } return this.objRepositorio; }
identifier_body
DaoVendedorCliente.ts
import { Injectable } from '@angular/core'; import { VendedorCliente } from "../model/VendedorCliente"; import { DaoGenerico } from '../dao/Dao'; import { ToastMensagem } from '../providers/toast/toast' @Injectable() export class
{ private objRepositorio: any; constructor ( public daoGenerico : DaoGenerico, public toast: ToastMensagem ){ } save(obj: VendedorCliente): any { this.getRepositorio().persist(obj).then(retorno => { return true; }) .catch(error => { return error; }) } delete(ob...
DaoVendedorCliente
identifier_name
farm_designer_settings_test.tsx
jest.mock("../../farm_designer/map/layers/farmbot/bot_trail", () => ({ resetVirtualTrail: jest.fn(), })); jest.mock("../../config_storage/actions", () => ({ getWebAppConfigValue: jest.fn(() => jest.fn()), setWebAppConfigValue: jest.fn(), })); import React from "react"; import { mount } from "enzyme"; import { P...
});
expect(window.confirm).toHaveBeenCalledWith("confirmation message"); expect(setWebAppConfigValue).not.toHaveBeenCalled(); });
random_line_split
macros.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except accordin...
random_line_split
__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) Open Solutions Finland 2013. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Gen...
{ "name" : "Exporting and Intrastat", "version" : "1.0", "author" : "Open Solutions Finland", "description" : """ OpenERP module for exporting goods. Intrastat additions to invoices. Adds country of origin and customs code fields to products. """, "website" : "www.opensolutions.fi", "de...
# You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ##############################################################################
random_line_split
__init__.py
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # ...
if t_salle.coords.z == z: t_x, t_y, t_z = t_salle.coords.tuple() t_distance = sqrt((x - t_x) ** 2 + (y - t_y) ** 2) if t_distance < distance and t_salle.nom_terrain in \ TERRAINS_ACCOSTABLES: d_salle = t_salle ...
hode d'interprétation de commande""" salle = personnage.salle if not hasattr(salle, "navire") or salle.navire is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return navire = salle.navire if navire.etendue is None: personnage << "|err|...
identifier_body
__init__.py
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # ...
personnage, dic_masques): """Méthode d'interprétation de commande""" salle = personnage.salle if not hasattr(salle, "navire") or salle.navire is None: personnage << "|err|Vous n'êtes pas sur un navire.|ff|" return navire = salle.navire if navire.etendue ...
reter(self,
identifier_name
__init__.py
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # ...
if d_salle is None: personnage << "|err|Aucun quai n'a pu être trouvé à " \ "proximité.|ff|" return personnage.salle = d_salle personnage << "Vous sautez sur {}.".format( d_salle.titre.lower()) personnage << d_salle.regarder(personnage...
.coords.z == z: t_x, t_y, t_z = t_salle.coords.tuple() t_distance = sqrt((x - t_x) ** 2 + (y - t_y) ** 2) if t_distance < distance and t_salle.nom_terrain in \ TERRAINS_ACCOSTABLES: d_salle = t_salle distance...
conditional_block
__init__.py
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # ...
self.nom_categorie = "navire" self.aide_courte = "débarque du navire" self.aide_longue = \ "Cette commande permet de débarquer du navire sur lequel " \ "on se trouve. On doit se trouver assez prêt d'une côte " \ "pour débarquer dessus." def interpreter(se...
def __init__(self): """Constructeur de la commande""" Commande.__init__(self, "debarquer", "debark")
random_line_split
issue-4366-2.rs
// Copyright 2013 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 ...
() { foo(); //~ ERROR: unresolved name }
main
identifier_name
issue-4366-2.rs
// Copyright 2013 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 ...
mod foo { pub fn foo() {} } mod a { pub mod b { use foo::foo; type bar = isize; } pub mod sub { use a::b::*; fn sub() -> bar { 1 } //~^ ERROR: undeclared type name } } mod m1 { fn foo() {} } fn main() { foo(); //~ ERROR: unresolved name }
random_line_split
issue-4366-2.rs
// Copyright 2013 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 ...
//~^ ERROR: undeclared type name } } mod m1 { fn foo() {} } fn main() { foo(); //~ ERROR: unresolved name }
{ 1 }
identifier_body
gsdSubsample.py
#open a gsd file and write out a subsampled version, keeping only every N timesteps #useful if you want to be analyzing a shorter trajectory import gsd.hoomd import argparse import time start = time.time() parser = argparse.ArgumentParser(description='Subsamble GSD trajectory') parser.add_argument('fname',metavar='inpu...
end = time.time() print('Subsampling took {0} s.'.format(end-start))
s = gsd.hoomd.Snapshot() pos = traj[i].particles.position s.particles.position = pos s.particles.N = len(pos) newtraj.append(s)
conditional_block
gsdSubsample.py
#open a gsd file and write out a subsampled version, keeping only every N timesteps #useful if you want to be analyzing a shorter trajectory
parser = argparse.ArgumentParser(description='Subsamble GSD trajectory') parser.add_argument('fname',metavar='input',type=str,help='trajectory file to be subsampled') parser.add_argument('ofname',metavar='output',type=str,help='where to write subsampled trajectory file') parser.add_argument('N',metavar='N',type=int,hel...
import gsd.hoomd import argparse import time start = time.time()
random_line_split
sprequire.js
var __context = this; var depth = 0; var LOCALE = 'en'; // TODO Add support for more locales later Array.prototype.insert = function(index) { this.splice.apply(this, [index, 0].concat( Array.prototype.slice.call(arguments, 1))); return this; }; var sprequirejs = function (exports) { var Spotify = fu...
this._always.call(this, data); }, setFail: function (data) { this._fail.call(this, data); this._always.call(this, data); }, }; exports.Promise = Promise; var Observable = function() { }; Observable.prototype = { addEventListener: function(ty...
setDone: function (data) { this._done.call(this, data);
random_line_split
sprequire.js
var __context = this; var depth = 0; var LOCALE = 'en'; // TODO Add support for more locales later Array.prototype.insert = function(index) { this.splice.apply(this, [index, 0].concat( Array.prototype.slice.call(arguments, 1))); return this; }; var sprequirejs = function (exports) { var Spotify = fu...
}; exports.require = function () { var modules = arguments[0]; var callback = arguments[1]; var items = []; for (var i = 0; i < modules.length; i++) { var xmlHttp = new XMLHttpRequest(); var module = modules[i]; console.log(module); ...
{ return typeof(var_args) !== 'undefined' ? var_args : key; }
conditional_block
test_ae_detector.py
# # Copyright 2018 Analytics Zoo Authors. # # 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...
def teardown_method(self, method): pass def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): y = self.create_data() ad = AE...
pass
identifier_body
test_ae_detector.py
# # Copyright 2018 Analytics Zoo Authors. # # 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...
ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_corner_cases(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="...
def test_ae_fit_score_unrolled(self): y = self.create_data() ad = AEDetector(roll_len=0)
random_line_split
test_ae_detector.py
# # Copyright 2018 Analytics Zoo Authors. # # 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...
(self, method): pass def teardown_method(self, method): pass def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): y = self.c...
setup_method
identifier_name
QItemWrapper.js
import QItem from './QItem' import QItemMain from './QItemMain' import QItemSide from './QItemSide' function
(child, h, name, slot, replace, conf) { const defaultProps = { props: { right: conf.right } } if (slot && replace) { child.push(h(name, defaultProps, slot)) return } let props, v = false if (!slot) { for (let p in conf) { if (conf.hasOwnProperty(p)) { v = conf[p] if (v !== ...
push
identifier_name
QItemWrapper.js
import QItem from './QItem' import QItemMain from './QItemMain' import QItemSide from './QItemSide' function push (child, h, name, slot, replace, conf) { const defaultProps = { props: { right: conf.right } } if (slot && replace) { child.push(h(name, defaultProps, slot)) return } let props, v = false ...
} } } } if (props || slot) { child.push(h(name, props ? {props: conf} : defaultProps, slot)) } } export default { name: 'q-item-wrapper', functional: true, props: { cfg: { type: Object, default: () => ({}) }, slotReplace: Boolean }, render (h, ctx) { co...
random_line_split
QItemWrapper.js
import QItem from './QItem' import QItemMain from './QItemMain' import QItemSide from './QItemSide' function push (child, h, name, slot, replace, conf)
child.push(h(name, props ? {props: conf} : defaultProps, slot)) } } export default { name: 'q-item-wrapper', functional: true, props: { cfg: { type: Object, default: () => ({}) }, slotReplace: Boolean }, render (h, ctx) { const cfg = ctx.props.cfg, replace = ctx...
{ const defaultProps = { props: { right: conf.right } } if (slot && replace) { child.push(h(name, defaultProps, slot)) return } let props, v = false if (!slot) { for (let p in conf) { if (conf.hasOwnProperty(p)) { v = conf[p] if (v !== void 0 && v !== true) { props...
identifier_body
QItemWrapper.js
import QItem from './QItem' import QItemMain from './QItemMain' import QItemSide from './QItemSide' function push (child, h, name, slot, replace, conf) { const defaultProps = { props: { right: conf.right } } if (slot && replace) { child.push(h(name, defaultProps, slot)) return } let props, v = false ...
ctx.data.props = cfg return h(QItem, ctx.data, child) } }
{ child.push(slot.default) }
conditional_block
main.rs
use std::num::Float; use std::io; struct Velocity { x: f32, y: f32, v: f32 } fn main() { println!("DCC Tennis Ball Launcher Calculator"); loop { let time: f32 = calculate_time(); let velocity: Velocity = calculate_velocity(time); let angle: f32 = calculate_angle(&velocity)...
return mass * acceleration; }
println!("Enter the mass of the ball"); let input_m = io::stdin().read_line().ok().expect("Failed to read line"); let input_num_m: Option<f32> = input_m.trim().parse(); let mass = match input_num_m { Some(mass) => mass, None => 0.0 }; println!("Enter the length of the pipe"); ...
identifier_body
main.rs
use std::num::Float; use std::io; struct Velocity { x: f32, y: f32, v: f32 } fn main() { println!("DCC Tennis Ball Launcher Calculator"); loop { let time: f32 = calculate_time(); let velocity: Velocity = calculate_velocity(time); let angle: f32 = calculate_angle(&velocity)...
time: f32) -> Velocity { println!("Enter the range of the appeture"); let input = io::stdin().read_line().ok().expect("Failed to read line"); let input_num: Option<f32> = input.trim().parse(); let range = match input_num { Some(range) => range, None => 0.0 }; let velocity_x: f3...
alculate_velocity(
identifier_name
main.rs
use std::num::Float; use std::io; struct Velocity { x: f32, y: f32, v: f32 } fn main() { println!("DCC Tennis Ball Launcher Calculator"); loop {
println!("The time it'll take the ball to travel is {}s", time); println!("The velocity of the ball will be {} m/s", velocity.v); println!("The angle of the launcher should be {}º", angle); println!("The force exerted by the launcher on the ball should be {} N", force); } } fn calcu...
let time: f32 = calculate_time(); let velocity: Velocity = calculate_velocity(time); let angle: f32 = calculate_angle(&velocity); let force: f32 = calculate_force(&velocity);
random_line_split
wildcard.py
# -*- coding: utf-8 -*- # # Cheroke-admin # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2009-2010 Alvaro Lopez Ortega # # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as published by the Free So...
def __init__ (self, key, vsrv_num): CTK.Plugin.__init__ (self, key) pre = '%s!domain' %(key) url_apply = '%s/%s' %(URL_APPLY, vsrv_num) self += CTK.RawHTML ("<h2>%s</h2>" % (_('Accepted Domains'))) # Content refresh = CTK.Refreshable ({'id': 'plugin_wildcard'}) ...
identifier_body
wildcard.py
# -*- coding: utf-8 -*- # # Cheroke-admin # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2009-2010 Alvaro Lopez Ortega # # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as published by the Free So...
(self, refreshable, key, url_apply, **kwargs): CTK.Container.__init__ (self, **kwargs) entries = CTK.cfg.keys (key) # Warning message if not entries: notice = CTK.Notice('warning') notice += CTK.RawHTML (_(WARNING_EMPTY)) self += notice # Li...
__init__
identifier_name
wildcard.py
# -*- coding: utf-8 -*- # # Cheroke-admin # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2009-2010 Alvaro Lopez Ortega # # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as published by the Free So...
NOTE_WILDCARD = N_("Accepted host name. Wildcard characters (* and ?) are allowed. Eg: *example.com") WARNING_EMPTY = N_("At least one wildcard string must be defined.") class Content (CTK.Container): def __init__ (self, refreshable, key, url_apply, **kwargs): CTK.Container.__init__ (self, **kwargs) ...
import CTK URL_APPLY = '/plugin/wildcard/apply'
random_line_split
wildcard.py
# -*- coding: utf-8 -*- # # Cheroke-admin # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2009-2010 Alvaro Lopez Ortega # # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as published by the Free So...
table += [e1, rm] # Add New table = CTK.PropsTable() next = CTK.cfg.get_next_entry_prefix (key) table.Add (_('New host name'), CTK.TextCfg(next, False, {'class':'noauto'}), _(NOTE_WILDCARD)) submit = CTK.Submitter(url_apply) dialog = CTK.Dialog2Buttons...
rm = CTK.ImageStock('del') rm.bind('click', CTK.JS.Ajax (url_apply, data = {"%s!%s"%(key,i): ''}, complete = refreshable.JS_to_refresh()))
conditional_block
meta_strategies.py
# Copyright 2019 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
return result, joint_strategies META_STRATEGY_METHODS = { "uniform_biased": uniform_biased_strategy, "uniform": uniform_strategy, "nash": nash_strategy, "prd": prd_strategy, }
"""Computes Projected Replicator Dynamics strategies. Args: solver: GenPSROSolver instance. return_joint: If true, only returns marginals. Otherwise marginals as well as joint probabilities. Returns: PRD-computed strategies. """ meta_games = solver.get_meta_game() if not isinstance(meta_ga...
identifier_body
meta_strategies.py
# Copyright 2019 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
meta_games = [x.tolist() for x in meta_games] if len(meta_games) != 2: raise NotImplementedError( "nash_strategy solver works only for 2p zero-sum" "games, but was invoked for a {} player game".format(len(meta_games))) nash_prob_1, nash_prob_2, _, _ = ( lp_solver.solve_zero_sum_matrix_g...
meta_games = [meta_games, -meta_games]
conditional_block
meta_strategies.py
# Copyright 2019 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
(solver, return_joint=False): """Returns a Random Uniform distribution on policies. Args: solver: GenPSROSolver instance. return_joint: If true, only returns marginals. Otherwise marginals as well as joint probabilities. Returns: uniform distribution on strategies. """ policies = solver.ge...
uniform_strategy
identifier_name
meta_strategies.py
# Copyright 2019 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
"""Returns a joint strategy matrix from a list of marginals. Args: probabilities: list of probabilities. Returns: A joint strategy from a list of marginals. """ probas = [] for i in range(len(probabilities)): probas_shapes = [1] * len(probabilities) probas_shapes[i] = -1 probas.append(...
def get_joint_strategy_from_marginals(probabilities):
random_line_split
type-ascription.rs
// run-pass #![allow(dead_code)] #![allow(unused_variables)] // Type ascription doesn't lead to unsoundness #![feature(type_ascription)] use std::mem; const C1: u8 = 10: u8; const C2: [u8; 1: usize] = [1]; struct S { a: u8 } fn main() { assert_eq!(C1.into(): i32, 10); assert_eq!(C2[0], 1);
let s = S { a: 10: u8 }; let arr = &[1u8, 2, 3]; let mut v = arr.iter().cloned().collect(): Vec<_>; v.push(4); assert_eq!(v, [1, 2, 3, 4]); let a = 1: u8; let b = a.into(): u16; assert_eq!(v[a.into(): usize], 2); assert_eq!(mem::size_of_val(&a), 1); assert_eq!(mem::size_of_val...
random_line_split
type-ascription.rs
// run-pass #![allow(dead_code)] #![allow(unused_variables)] // Type ascription doesn't lead to unsoundness #![feature(type_ascription)] use std::mem; const C1: u8 = 10: u8; const C2: [u8; 1: usize] = [1]; struct
{ a: u8 } fn main() { assert_eq!(C1.into(): i32, 10); assert_eq!(C2[0], 1); let s = S { a: 10: u8 }; let arr = &[1u8, 2, 3]; let mut v = arr.iter().cloned().collect(): Vec<_>; v.push(4); assert_eq!(v, [1, 2, 3, 4]); let a = 1: u8; let b = a.into(): u16; assert_eq!(v[a.in...
S
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ //! This crate contains a GraphQL schema representation. #![deny(warnings)] #![deny(rust_2018_idioms)] #![deny(clippy::all)] pu...
(bytes: &[u8]) -> DiagnosticsResult<FlatBufferSchema<'_>> { Ok(FlatBufferSchema::build(bytes)) } pub fn builtins() -> DiagnosticsResult<SchemaDocument> { graphql_syntax::parse_schema_document(BUILTINS, SourceLocationKey::generated()) }
build_schema_from_flat_buffer
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ //! This crate contains a GraphQL schema representation. #![deny(warnings)] #![deny(rust_2018_idioms)] #![deny(clippy::all)] pu...
pub fn builtins() -> DiagnosticsResult<SchemaDocument> { graphql_syntax::parse_schema_document(BUILTINS, SourceLocationKey::generated()) }
{ Ok(FlatBufferSchema::build(bytes)) }
identifier_body
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ //! This crate contains a GraphQL schema representation. #![deny(warnings)] #![deny(rust_2018_idioms)] #![deny(clippy::all)] pu...
client_schema_documents.push(graphql_syntax::parse_schema_document( extension_sdl.as_ref(), *location_key, )?); } SDLSchema::build(&server_documents, &client_schema_documents) } pub fn build_schema_with_flat_buffer(bytes: Vec<u8>) -> SDLSchema { SDLSchema::FlatBuffe...
SourceLocationKey::generated(), )?); let mut client_schema_documents = Vec::new(); for (extension_sdl, location_key) in extension_sdls {
random_line_split