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 |
|---|---|---|---|---|
virtual_interface.py | # Copyright (C) 2014, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | @base.remotable_classmethod
def delete_by_instance_uuid(cls, context, instance_uuid):
db.virtual_interface_delete_by_instance(context, instance_uuid)
class VirtualInterfaceList(base.ObjectListBase, base.NovaObject):
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'objects... | self._from_db_object(self._context, self, db_vif)
| random_line_split |
virtual_interface.py | # Copyright (C) 2014, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | (cls, context, instance_uuid, use_slave=False):
db_vifs = db.virtual_interface_get_by_instance(context, instance_uuid,
use_slave=use_slave)
return base.obj_make_list(context, cls(context),
objects.VirtualInterface, db_vifs)
| get_by_instance_uuid | identifier_name |
virtual_interface.py | # Copyright (C) 2014, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
@base.remotable_classmethod
def get_by_instance_and_network(cls, context, instance_uuid, network_id):
db_vif = db.virtual_interface_get_by_instance_and_network(context,
instance_uuid, network_id)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@ba... | return cls._from_db_object(context, cls(), db_vif) | conditional_block |
mem.rs | use std::num::SignedInt;
use syntax::{Dir, Left, Right};
// size of allocated memory in bytes
const MEM_SIZE: usize = 65_536; // 64kB!
pub struct Mem {
cells: Box<[u8]>, // address space
ptr: usize // pointer in address space
}
impl Mem {
/// Create a new `Mem` stuct.
#[inline]
pub fn... |
/// Return the value of cell at the current pointer.
#[inline]
pub fn get(&self) -> u8 {
self.cells[self.ptr]
}
/// Set the value at the current pointer.
#[inline]
pub fn set(&mut self, value: u8) {
self.cells[self.ptr] = value;
}
/// Adds `value` to the current c... | {
Mem {
cells: box [0u8; MEM_SIZE],
ptr: 0
}
} | identifier_body |
mem.rs | use std::num::SignedInt;
use syntax::{Dir, Left, Right};
// size of allocated memory in bytes
const MEM_SIZE: usize = 65_536; // 64kB!
pub struct Mem {
cells: Box<[u8]>, // address space
ptr: usize // pointer in address space
}
impl Mem {
/// Create a new `Mem` stuct.
#[inline]
pub fn... | };
self.cells[index] += self.cells[self.ptr];
}
/// Multiplys the value of the current cell by a factor and inserts the
/// product into the cell left or right a number of steps.
pub fn multiply(&mut self, dir: Dir, steps: usize, factor: i8) {
let index = match dir {
... | pub fn copy(&mut self, dir: Dir, steps: usize) {
let index = match dir {
Left => self.ptr - steps,
Right => self.ptr + steps, | random_line_split |
mem.rs | use std::num::SignedInt;
use syntax::{Dir, Left, Right};
// size of allocated memory in bytes
const MEM_SIZE: usize = 65_536; // 64kB!
pub struct Mem {
cells: Box<[u8]>, // address space
ptr: usize // pointer in address space
}
impl Mem {
/// Create a new `Mem` stuct.
#[inline]
pub fn... | (&mut self, dir: Dir) {
while self.cells[self.ptr] != 0 {
self.shift(dir, 1);
}
}
/// Copys the value of the current cell into the cell left or right a
/// number of steps.
#[inline]
pub fn copy(&mut self, dir: Dir, steps: usize) {
let index = match dir {
... | scan | identifier_name |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | (AutotoolsPackage):
"""The Scientific Application Web server (SAWs) turns any C or C++
scientific or engineering application code into a webserver,
allowing one to examine (and even modify) the state of the
simulation with any browser from anywhere."""
homepage = "https://bitbucket.org/saws... | Saws | identifier_name |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | """The Scientific Application Web server (SAWs) turns any C or C++
scientific or engineering application code into a webserver,
allowing one to examine (and even modify) the state of the
simulation with any browser from anywhere."""
homepage = "https://bitbucket.org/saws/saws/wiki/Home"
ve... | identifier_body | |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
class Saws(AutotoolsPackage):
"""The Scientific Application Web server (SAWs) turns any C or C++
scientific or engineering application code into a webserver,
allowing one to examine (and even modify) the state of the
simulation with any browser from anywhere."""
homepage = "https://bitbuc... | # You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import * | random_line_split |
CustomStyles.tsx | import * as React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import {
createMuiTheme,
ThemeProvider,
experimentalStyled as styled,
} from '@material-ui/core/styles';
import { orange } from '@material-ui/core/colors';
declare module '@material-ui/core/styles' {
interface Theme {
status... | <ThemeProvider theme={theme}>
<CustomCheckbox defaultChecked />
</ThemeProvider>
);
} | });
export default function CustomStyles() {
return ( | random_line_split |
CustomStyles.tsx | import * as React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import {
createMuiTheme,
ThemeProvider,
experimentalStyled as styled,
} from '@material-ui/core/styles';
import { orange } from '@material-ui/core/colors';
declare module '@material-ui/core/styles' {
interface Theme {
status... | () {
return (
<ThemeProvider theme={theme}>
<CustomCheckbox defaultChecked />
</ThemeProvider>
);
}
| CustomStyles | identifier_name |
CustomStyles.tsx | import * as React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import {
createMuiTheme,
ThemeProvider,
experimentalStyled as styled,
} from '@material-ui/core/styles';
import { orange } from '@material-ui/core/colors';
declare module '@material-ui/core/styles' {
interface Theme {
status... | {
return (
<ThemeProvider theme={theme}>
<CustomCheckbox defaultChecked />
</ThemeProvider>
);
} | identifier_body | |
indexedlogauxstore.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::io::Cursor;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use anyhow::bail;
use anyhow::Result;
use byteorder::Read... |
Ok(open_options)
}
pub fn get(&self, hgid: HgId) -> Result<Option<Entry>> {
let log = self.0.read();
let mut entries = log.lookup(0, &hgid)?;
let slice = match entries.next() {
None => return Ok(None),
Some(slice) => slice?,
};
let bytes... | {
let log_count: u64 = open_options.max_log_count.unwrap_or(1).max(1).into();
open_options =
open_options.max_bytes_per_log((max_bytes_per_log.value() / log_count).max(1));
} | conditional_block |
indexedlogauxstore.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::io::Cursor;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use anyhow::bail;
use anyhow::Result;
use byteorder::Read... | () -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
store.flush()?;
Ok(())
}
#[test]
fn test_add_get() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&... | test_empty | identifier_name |
indexedlogauxstore.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::io::Cursor;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use anyhow::bail;
use anyhow::Result;
use byteorder::Read... |
fn deserialize(bytes: Bytes) -> Result<(HgId, Self)> {
let data: &[u8] = bytes.as_ref();
let mut cur = Cursor::new(data);
let hgid = cur.read_hgid()?;
let version = cur.read_u8()?;
if version != 0 {
bail!("unsupported auxstore entry version {}", version);
... | {
let mut buf = Vec::new();
buf.write_all(hgid.as_ref())?;
buf.write_u8(0)?; // write version
buf.write_all(self.content_id.as_ref())?;
buf.write_all(self.content_sha1.as_ref())?;
buf.write_all(self.content_sha256.as_ref())?;
buf.write_vlq(self.total_size)?;
... | identifier_body |
indexedlogauxstore.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::io::Cursor;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use anyhow::bail;
use anyhow::Result;
use byteorder::Read... | use types::testutil::*;
use super::*;
use crate::scmstore::FileAttributes;
use crate::scmstore::FileStore;
use crate::testutil::*;
use crate::ExtStoredPolicy;
use crate::HgIdMutableDeltaStore;
use crate::IndexedLogHgIdDataStore;
fn single_byte_sha1(fst: u8) -> Sha1 {
let mu... | random_line_split | |
index.tsx | /// <reference path="../node_modules/protobufjs/stub-node.d.ts" />
/**
* UI/NEXT TODO LIST
*
* ! = Potentially difficult to implement
*
* - All Pages / Shared Components
* - "Last Updated"
* - Dropdowns
* - Fix 1px offset bug
* - Tables
* - CSS Match to design
* - Management of colum... | <Route path="raft" component={ Raft }>
<IndexRedirect to="ranges" />
<Route path="ranges" component={ RaftRanges } />
</Route>
<Route path="clusterviz" component={ ClusterViz } />
</Route>
</Router>
</Provider>,
document.getElementById("react-layout"),
);
store... | <Route path="tables" component={ DatabaseTablesList } />
<Route path="grants" component={ DatabaseGrantsList } />
<Route path={ `database/:${databaseNameAttr}/table/:${tableNameAttr}` } component={ TableDetails } />
</Route> | random_line_split |
test_sys_call.py | # Copyright 2016: Mirantis Inc.
# 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 required b... |
def test_validate_error(self):
conf = {
"name": "sys_call",
"description": "list folder",
"args": {
"cmd": 50,
},
"trigger": {
"name": "event",
"args": {
"unit": "iteration",
... | hook.Hook.validate(
{
"name": "sys_call",
"description": "list folder",
"args": "ls",
"trigger": {
"name": "event",
"args": {
"unit": "iteration",
"at": [10... | identifier_body |
test_sys_call.py | # Copyright 2016: Mirantis Inc.
# 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 required b... | (test.TestCase):
def test_validate(self):
hook.Hook.validate(
{
"name": "sys_call",
"description": "list folder",
"args": "ls",
"trigger": {
"name": "event",
"args": {
... | SysCallHookTestCase | identifier_name |
test_sys_call.py | # Copyright 2016: Mirantis Inc.
# 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 required b... | "cmd": 50,
},
"trigger": {
"name": "event",
"args": {
"unit": "iteration",
"at": [10]
}
}
}
self.assertRaises(
jsonschema.ValidationError, hook.Hook.val... | "description": "list folder",
"args": { | random_line_split |
lib.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/. */
#![feature(box_syntax)]
#![feature(custom_derive)]
#![feature(plugin)]
#![feature(mpsc_select)]
#![feature(plugin)... | {
Script,
Layout,
}
/// Messages from the compositor to the constellation.
#[derive(Deserialize, Serialize)]
pub enum CompositorMsg {
Exit,
FrameSize(PipelineId, Size2D<f32>),
/// Request that the constellation send the FrameId corresponding to the document
/// with the provided pipeline id
... | AnimationTickType | identifier_name |
lib.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/. */
#![feature(box_syntax)]
#![feature(custom_derive)]
#![feature(plugin)]
#![feature(mpsc_select)]
#![feature(plugin)... | extern crate layout_traits;
#[macro_use]
extern crate log;
extern crate msg;
extern crate net_traits;
extern crate num;
extern crate offscreen_gl_context;
#[macro_use]
extern crate profile_traits;
extern crate rand;
extern crate script_traits;
extern crate serde;
extern crate style_traits;
extern crate time;
extern cra... | extern crate ipc_channel;
extern crate layers; | random_line_split |
save-action-service.js | (function() {
'use strict';
angular
.module('otusjs.player.core.phase')
.service('otusjs.player.core.phase.SaveActionService', Service);
Service.$inject = [
'otusjs.player.core.phase.ActionPipeService',
'otusjs.player.core.phase.PreSaveActionService',
'otusjs.player.core.phase.ExecutionSaveA... |
})();
| {
var self = this;
/* Public methods */
self.PreSaveActionService = PreSaveActionService;
self.ExecutionSaveActionService = ExecutionSaveActionService;
self.PostSaveActionService = PostSaveActionService;
self.execute = execute;
function execute() {
var phaseData = PreSaveActionServic... | identifier_body |
save-action-service.js | (function() {
'use strict';
angular
.module('otusjs.player.core.phase')
.service('otusjs.player.core.phase.SaveActionService', Service);
Service.$inject = [
'otusjs.player.core.phase.ActionPipeService',
'otusjs.player.core.phase.PreSaveActionService',
'otusjs.player.core.phase.ExecutionSaveA... |
/* Public methods */
self.PreSaveActionService = PreSaveActionService;
self.ExecutionSaveActionService = ExecutionSaveActionService;
self.PostSaveActionService = PostSaveActionService;
self.execute = execute;
function execute() {
var phaseData = PreSaveActionService.execute(ActionPipeSer... | ];
function Service(ActionPipeService, PreSaveActionService, ExecutionSaveActionService, PostSaveActionService) {
var self = this; | random_line_split |
save-action-service.js | (function() {
'use strict';
angular
.module('otusjs.player.core.phase')
.service('otusjs.player.core.phase.SaveActionService', Service);
Service.$inject = [
'otusjs.player.core.phase.ActionPipeService',
'otusjs.player.core.phase.PreSaveActionService',
'otusjs.player.core.phase.ExecutionSaveA... | () {
var phaseData = PreSaveActionService.execute(ActionPipeService.flowData);
phaseData = ExecutionSaveActionService.execute(phaseData);
phaseData = PostSaveActionService.execute(phaseData);
}
}
})();
| execute | identifier_name |
main.rs | /*
Full Monkey.
Generic preprocessor tool.
Copyright 2016 Sam Saint-Pettersen.
Released under the MIT/X11 License.
*/
extern crate clioptions;
extern crate regex;
use clioptions::CliOptions;
use regex::Regex;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn prep... | (program: &str, exit_code: i32) {
println!("\nFull Monkey.");
println!("Generic preprocessor tool.");
println!("\nCopyright 2016 Sam Saint-Pettersen.");
println!("Released under the MIT/X11 License.");
println!("\n{} -f|--file <input> [-c|--condition <condition(s)>] -o|--out <output>", program);
... | display_usage | identifier_name |
main.rs | /*
Full Monkey.
Generic preprocessor tool.
Copyright 2016 Sam Saint-Pettersen.
Released under the MIT/X11 License.
*/
extern crate clioptions;
extern crate regex;
use clioptions::CliOptions;
use regex::Regex;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn prep... |
fn display_version() {
println!("Full Monkey v. 0.1");
println!(r" __");
println!(r"w c(..)o (");
println!(r" \__(-) __)");
println!(r" /\ (");
println!(r" /(_)___)");
println!(r" w /|");
println!(r" | \");
println!(r" m m");
println!("\nMonkey appear... | {
let mut loc: Vec<String> = Vec::new();
let mut preprocessed: Vec<String> = Vec::new();
let mut cond = String::new();
let mut set_conds: Vec<String> = Vec::new();
let mut prefixed: Vec<String> = Vec::new();
let mut prefixes: Vec<String> = Vec::new();
let mut in_pp = false;
let conditio... | identifier_body |
main.rs | /*
Full Monkey.
Generic preprocessor tool.
Copyright 2016 Sam Saint-Pettersen.
Released under the MIT/X11 License.
*/
extern crate clioptions;
extern crate regex;
use clioptions::CliOptions;
use regex::Regex;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn prep... | preprocessed.push(l.to_string());
continue;
}
}
// Do any alterations:
for line in preprocessed {
let mut fl = line;
for (i, p) in prefixed.iter().enumerate() {
let r = Regex::new(®ex::quote(&p)).unwrap();
let repl = format!("{}{}", ... | }
if !in_pp { | random_line_split |
main.rs | /*
Full Monkey.
Generic preprocessor tool.
Copyright 2016 Sam Saint-Pettersen.
Released under the MIT/X11 License.
*/
extern crate clioptions;
extern crate regex;
use clioptions::CliOptions;
use regex::Regex;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn prep... |
// Process end block...
p = Regex::new("#[fi|endif]").unwrap();
if p.is_match(&l) {
in_pp = false;
continue;
}
// Push relevant LoC to vector...
for sc in set_conds.clone() {
if in_pp && cond == sc {
preprocessed.push(... | {
for cap in p.captures_iter(&l) {
cond = cap.at(1).unwrap().to_string();
in_pp = true;
}
continue;
} | conditional_block |
get_room_information.rs | //! `GET /_matrix/federation/*/query/directory`
//!
//! Endpoint to query room information with a room alias.
pub mod v1 {
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1querydirectory
use ruma_common::{api::ruma_api, RoomAliasId, RoomId, Serv... |
}
}
| {
Self { room_id, servers }
} | identifier_body |
get_room_information.rs | //! `GET /_matrix/federation/*/query/directory`
//!
//! Endpoint to query room information with a room alias.
pub mod v1 {
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1querydirectory
use ruma_common::{api::ruma_api, RoomAliasId, RoomId, Serv... | (room_id: Box<RoomId>, servers: Vec<Box<ServerName>>) -> Self {
Self { room_id, servers }
}
}
}
| new | identifier_name |
get_room_information.rs | //! `GET /_matrix/federation/*/query/directory`
//!
//! Endpoint to query room information with a room alias.
pub mod v1 {
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1querydirectory
use ruma_common::{api::ruma_api, RoomAliasId, RoomId, Serv... | impl<'a> Request<'a> {
/// Creates a new `Request` with the given room alias ID.
pub fn new(room_alias: &'a RoomAliasId) -> Self {
Self { room_alias }
}
}
impl Response {
/// Creates a new `Response` with the given room IDs and servers.
pub fn new(room_id... | pub servers: Vec<Box<ServerName>>,
}
}
| random_line_split |
lzw.py | #!/usr/bin/env python
import sys
stderr = sys.stderr
## LZWDecoder
##
class LZWDecoder(object):
debug = 0
def __init__(self, fp):
self.fp = fp
self.buff = 0
self.bpos = 8
self.nbits = 9
self.table = None
self.prevbuf = None
return
def readbits(self, bits):
v = 0
while 1:... | (self):
while 1:
try:
code = self.readbits(self.nbits)
except EOFError:
break
x = self.feed(code)
yield x
if self.debug:
print >>stderr, ('nbits=%d, code=%d, output=%r, table=%r' %
(self.nbits, code, x, self.table[258:]))
return
... | run | identifier_name |
lzw.py | #!/usr/bin/env python
import sys
stderr = sys.stderr
## LZWDecoder
##
class LZWDecoder(object):
debug = 0
def __init__(self, fp):
self.fp = fp
self.buff = 0
self.bpos = 8
self.nbits = 9
self.table = None
self.prevbuf = None
return
def readbits(self, bits):
v = 0
while 1:... |
def main(argv):
import StringIO
input = '\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01'
fp = StringIO.StringIO(input)
expected = '\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42'
LZWDecoder.debug = 1
output = ''.join(LZWDecoder(fp).run())
print (input, expected, output)
print output == expected
return 0
if __... | while 1:
try:
code = self.readbits(self.nbits)
except EOFError:
break
x = self.feed(code)
yield x
if self.debug:
print >>stderr, ('nbits=%d, code=%d, output=%r, table=%r' %
(self.nbits, code, x, self.table[258:]))
return | identifier_body |
lzw.py | #!/usr/bin/env python
import sys
stderr = sys.stderr
## LZWDecoder
##
class LZWDecoder(object):
debug = 0
def __init__(self, fp):
self.fp = fp
self.buff = 0
self.bpos = 8
self.nbits = 9
self.table = None
self.prevbuf = None
return
def readbits(self, bits):
v = 0
while 1:... | elif not self.prevbuf:
x = self.prevbuf = self.table[code]
else:
if code < len(self.table):
x = self.table[code]
self.table.append(self.prevbuf+x[0])
else:
self.table.append(self.prevbuf+self.prevbuf[0])
x = self.table[code]
l = len(self.table)
if l ... | random_line_split | |
lzw.py | #!/usr/bin/env python
import sys
stderr = sys.stderr
## LZWDecoder
##
class LZWDecoder(object):
debug = 0
def __init__(self, fp):
self.fp = fp
self.buff = 0
self.bpos = 8
self.nbits = 9
self.table = None
self.prevbuf = None
return
def readbits(self, bits):
v = 0
while 1:... |
return
def main(argv):
import StringIO
input = '\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01'
fp = StringIO.StringIO(input)
expected = '\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42'
LZWDecoder.debug = 1
output = ''.join(LZWDecoder(fp).run())
print (input, expected, output)
print output == expected
retu... | print >>stderr, ('nbits=%d, code=%d, output=%r, table=%r' %
(self.nbits, code, x, self.table[258:])) | conditional_block |
code_from_book.py | # Python Code From Book
# This file consists of code snippets only
# It is not intended to be run as a script
raise SystemExit
####################################################################
# 3. Thinking in Binary
####################################################################
import magic
print magic.f... | return '\n'.join(result)
with open("/path/to/my_file.ext", "r") as f:
print hexdump(f.read())
import struct
num = 0x103e4
struct.pack("I", 0x103e4)
# '\xe4\x03\x01\x00'
string = '\xe4\x03\x01\x00'
struct.unpack("i", string)
# (66532,)
bytes = '\x01\xc2'
struct.pack("<h", struct.unpack(">h", bytes)[0])... | = string[i:i + length]
hexa = "".join("{:0{}X}".format(ord(x), digits) for x in s)
text = "".join(x if 0x20 <= ord(x) < 0x7F else '.' for x in s)
result.append("{:04X} {:{}} {}".format(i, hexa, length * (digits + 1), text))
| conditional_block |
code_from_book.py | # Python Code From Book
# This file consists of code snippets only
# It is not intended to be run as a script
raise SystemExit
####################################################################
# 3. Thinking in Binary
####################################################################
import magic
print magic.f... | th open("/path/to/my_file.ext", "r") as f:
print hexdump(f.read())
import struct
num = 0x103e4
struct.pack("I", 0x103e4)
# '\xe4\x03\x01\x00'
string = '\xe4\x03\x01\x00'
struct.unpack("i", string)
# (66532,)
bytes = '\x01\xc2'
struct.pack("<h", struct.unpack(">h", bytes)[0])
# '\xc2\x01'
import base6... | sult = []
digits = 4 if isinstance(string, unicode) else 2
for i in xrange(0, len(string), length):
s = string[i:i + length]
hexa = "".join("{:0{}X}".format(ord(x), digits) for x in s)
text = "".join(x if 0x20 <= ord(x) < 0x7F else '.' for x in s)
result.append("{:04X} {:{}} ... | identifier_body |
code_from_book.py | # Python Code From Book
# This file consists of code snippets only
# It is not intended to be run as a script
raise SystemExit
####################################################################
# 3. Thinking in Binary
####################################################################
import magic
print magic.f... | pt = padder.update(pt) + padder.finalize()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
encryptor = cipher.encryptor()
ct = encryptor.update(pt) + encryptor.finalize()
decryptor = cipher.decryptor()
out = decryptor.update(ct) + decryptor.finalize()
unpadder = padding.PKCS7(128).unpadder()
out ... | padder = padding.PKCS7(128).padder() | random_line_split |
code_from_book.py | # Python Code From Book
# This file consists of code snippets only
# It is not intended to be run as a script
raise SystemExit
####################################################################
# 3. Thinking in Binary
####################################################################
import magic
print magic.f... | tring):
return " ".join(format(ord(char), '08b') for char in string)
string = "my ascii string"
"".join(hex(ord(char))[2:] for char in string)
# '6d7920617363696920737472696e67'
hex_string = "6d7920617363696920737472696e67"
hex_string.decode("hex")
# 'my ascii string'
"".join(chr(int(hex_string[i:i+2], 16)) f... | _ascii_bytes(s | identifier_name |
device_id.rs | #[cfg(feature = "rand")]
use super::generate_localpart;
/// A Matrix key ID.
///
/// Device identifiers in Matrix are completely opaque character sequences. This type is provided
/// simply for its semantic value.
///
/// # Example
///
/// ```
/// use ruma_common::{device_id, DeviceId};
///
/// let random_id = DeviceI... | opaque_identifier!(DeviceId);
impl DeviceId {
/// Generates a random `DeviceId`, suitable for assignment to a new device.
#[cfg(feature = "rand")]
pub fn new() -> Box<Self> {
Self::from_owned(generate_localpart(8))
}
}
#[cfg(all(test, feature = "rand"))]
mod tests {
use super::DeviceId;
... | random_line_split | |
device_id.rs | #[cfg(feature = "rand")]
use super::generate_localpart;
/// A Matrix key ID.
///
/// Device identifiers in Matrix are completely opaque character sequences. This type is provided
/// simply for its semantic value.
///
/// # Example
///
/// ```
/// use ruma_common::{device_id, DeviceId};
///
/// let random_id = DeviceI... | () -> Box<Self> {
Self::from_owned(generate_localpart(8))
}
}
#[cfg(all(test, feature = "rand"))]
mod tests {
use super::DeviceId;
#[test]
fn generate_device_id() {
assert_eq!(DeviceId::new().as_str().len(), 8);
}
#[test]
fn create_device_id_from_str() {
let ref_id... | new | identifier_name |
globals.ts | import * as path from 'path';
export const UPDATE_INTERVALL = 2 * 60 * 60 * 1000;
export const GITHUB_RELEASES_URL = "https://api.github.com/repos/kumpelblase2/proxtop/releases";
export const UPDATER_FEED_URL = "https://proxtop.eternalwings.de/update/";
export const APP_NAME = "proxtop";
export const PROXER_BASE_URL ... | }
};
export const Errors = {
CONNECTION: {
NO_NETWORK: 'ERROR.CONNECTION_NO_NETWORK',
UNABLE_TO_RESOLVE: 'ERROR.CONNECTION_NO_RESOLVE',
TIMEOUT: 'ERROR.CONNECTION_TIMEOUT',
NOT_FOUND: 'ERROR.CONNECTION_NOT_FOUND',
NO_CACHE: 'ERROR.CONNECTION_NO_CACHE_AVAILABLE',
... | random_line_split | |
fault.service.ts | import { TimeAndDateService,Date } from './../time_and_date/time-and-date.service';
import { Injectable } from '@angular/core';
@Injectable()
export class FaultService { //this service used to get, update and delete faults
constructor() { }
getFaults(){
let list:Fault[]=[]; //for testing generate static 10 fa... | this._remarks;}
}
class Base { //class for base include the number of the base and its name and sites. for example base 6 Hatzerim
constructor(
private _id: number,
private _name: string,
private _sites: string[]) { }
get id(){return this._id;}
get name(){return this._name;}
get sites(){re... | get remarks(){return | identifier_body |
fault.service.ts | import { TimeAndDateService,Date } from './../time_and_date/time-and-date.service';
import { Injectable } from '@angular/core';
@Injectable()
export class FaultService { //this service used to get, update and delete faults
constructor() { }
getFaults(){
let list:Fault[]=[]; //for testing generate static 10 fa... | tes(){return this._sites;}
}
| si | identifier_name |
fault.service.ts | import { TimeAndDateService,Date } from './../time_and_date/time-and-date.service';
import { Injectable } from '@angular/core';
@Injectable()
export class FaultService { //this service used to get, update and delete faults
constructor() { }
getFaults(){
let list:Fault[]=[]; //for testing generate static 10 fa... |
class Base { //class for base include the number of the base and its name and sites. for example base 6 Hatzerim
constructor(
private _id: number,
private _name: string,
private _sites: string[]) { }
get id(){return this._id;}
get name(){return this._name;}
get sites(){return this._sites;}
... | get startTime(){return this._startTime;}
get endTime(){return this._endTime;}
get contact(){return this._contact;}
get remarks(){return this._remarks;}
} | random_line_split |
fault.service.ts | import { TimeAndDateService,Date } from './../time_and_date/time-and-date.service';
import { Injectable } from '@angular/core';
@Injectable()
export class FaultService { //this service used to get, update and delete faults
constructor() { }
getFaults(){
let list:Fault[]=[]; //for testing generate static 10 fa... | i=6;i<11;i++)
{
list.push( new Fault(i,6,69,"מבצעית",true,new Date(2018,2,20),new Date(2018,2,20),"דני","בדיקה"));
}
return list;
}
}
export class Fault{
//this class describe how fault neet to seems
constructor(
private _id:number,
private _base:number,
private _site:number,
p... | {
list.push( new Fault(i,4,101,"ניסוי",false,new Date(2018,2,14),new Date(2018,2,14),"רון","בדיקה"));
}
for(var | conditional_block |
hud.rs | use super::wad_system::WadSystem;
use engine::{
ControlFlow, DependenciesFrom, Gesture, InfallibleSystem, Input, Scancode, TextId,
TextRenderer, Window,
};
use math::prelude::*;
use math::Pnt2f;
pub struct Bindings {
pub quit: Gesture,
pub next_level: Gesture,
pub previous_level: Gesture,
pub t... |
}
}
fn teardown(&mut self, deps: Dependencies) {
deps.text.remove(self.help_text);
deps.text.remove(self.prompt_text);
}
}
enum HelpState {
Prompt,
Shown,
Hidden,
}
const HELP_PADDING: u32 = 6;
const PROMPT_TEXT: &str = "WASD and mouse, 'E' to push/use, LB to shoot or... | {
deps.wad.change_level(index - 1);
} | conditional_block |
hud.rs | use super::wad_system::WadSystem;
use engine::{
ControlFlow, DependenciesFrom, Gesture, InfallibleSystem, Input, Scancode, TextId,
TextRenderer, Window,
};
use math::prelude::*;
use math::Pnt2f;
pub struct Bindings {
pub quit: Gesture,
pub next_level: Gesture,
pub previous_level: Gesture,
pub t... | (&mut self, deps: Dependencies) {
deps.text.remove(self.help_text);
deps.text.remove(self.prompt_text);
}
}
enum HelpState {
Prompt,
Shown,
Hidden,
}
const HELP_PADDING: u32 = 6;
const PROMPT_TEXT: &str = "WASD and mouse, 'E' to push/use, LB to shoot or 'h' for help.";
const HELP_TEXT:... | teardown | identifier_name |
hud.rs | use super::wad_system::WadSystem;
use engine::{
ControlFlow, DependenciesFrom, Gesture, InfallibleSystem, Input, Scancode, TextId,
TextRenderer, Window,
};
use math::prelude::*;
use math::Pnt2f;
pub struct Bindings {
pub quit: Gesture,
pub next_level: Gesture,
pub previous_level: Gesture,
pub t... | text[self.prompt_text].set_visible(false);
text[self.help_text].set_visible(true);
HelpState::Shown
}
HelpState::Shown => {
text[self.help_text].set_visible(false);
HelpState::Hidden
... | random_line_split | |
custom_tests.rs | extern crate rusoto_mock;
use crate::generated::{LexRuntime, LexRuntimeClient, PostTextRequest, PostTextResponse}; | #[tokio::test]
async fn test_post_text_resposnse_serialization() {
let mock_resp_body = r#"{
"dialogState": "ElicitSlot",
"intentName": "BookCar",
"message": "In what city do you need to rent a car?",
"messageFormat": "PlainText",
"responseCard": null,
"sessionAttributes": {},
... | use rusoto_core::Region;
use std::collections::HashMap;
use self::rusoto_mock::*;
| random_line_split |
custom_tests.rs | extern crate rusoto_mock;
use crate::generated::{LexRuntime, LexRuntimeClient, PostTextRequest, PostTextResponse};
use rusoto_core::Region;
use std::collections::HashMap;
use self::rusoto_mock::*;
#[tokio::test]
async fn | () {
let mock_resp_body = r#"{
"dialogState": "ElicitSlot",
"intentName": "BookCar",
"message": "In what city do you need to rent a car?",
"messageFormat": "PlainText",
"responseCard": null,
"sessionAttributes": {},
"slotToElicit": "PickUpCity",
"slots": {
"Ca... | test_post_text_resposnse_serialization | identifier_name |
custom_tests.rs | extern crate rusoto_mock;
use crate::generated::{LexRuntime, LexRuntimeClient, PostTextRequest, PostTextResponse};
use rusoto_core::Region;
use std::collections::HashMap;
use self::rusoto_mock::*;
#[tokio::test]
async fn test_post_text_resposnse_serialization() | {
let mock_resp_body = r#"{
"dialogState": "ElicitSlot",
"intentName": "BookCar",
"message": "In what city do you need to rent a car?",
"messageFormat": "PlainText",
"responseCard": null,
"sessionAttributes": {},
"slotToElicit": "PickUpCity",
"slots": {
"CarTy... | identifier_body | |
removeformatting.js | // Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless requ... |
}
}
// Replace with white space.
return goog.string.normalizeSpaces(sb.join(''));
};
/**
* Handle per node special processing if neccessary. If this function returns
* null then standard cleanup is applied. Otherwise this node and all children
* are assumed to be cleaned.
* NOTE(user): If an al... | {
// Push the current state on the stack.
stack[sp++] = nodeList;
stack[sp++] = numNodesProcessed;
// Iterate through the children nodes.
nodeList = children;
numNodesProcessed = 0;
} | conditional_block |
removeformatting.js | // Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless requ... | // savedCaretRange later on. So, we just remove it from the dom, and
// put it back later so we can create a range later (not exactly in the
// same spot, but don't worry we don't actually try to use it later)
// and then it will be removed when we dispose the range.
if (!startInTable) {
... | // for uber remove formatting, and it will get blown away. This is
// fine, except that we need to be able to re-create a range from the | random_line_split |
roundsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn roundsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM0)), operand2: Some(Direct(... |
fn roundsd_4() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledIndexedDisplaced(RDX, RCX, Eight, 1515642711, Some(OperandSize::Qword), None)), operand3: Some(Literal8(102)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: fa... | random_line_split | |
roundsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn roundsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM0)), operand2: Some(Direct(... | () {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM6)), operand2: Some(IndirectDisplaced(EAX, 455015242, Some(OperandSize::Qword), None)), operand3: Some(Literal8(66)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[10... | roundsd_2 | identifier_name |
roundsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn roundsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM0)), operand2: Some(Direct(... | {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledIndexedDisplaced(RDX, RCX, Eight, 1515642711, Some(OperandSize::Qword), None)), operand3: Some(Literal8(102)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None,... | identifier_body | |
process.rs | use std::io::process::{Command,ProcessOutput};
fn main() | {
// Initial command `rustc`
let mut cmd = Command::new("rustc");
// append the "--version" flag to the command
cmd.arg("--version");
// The `output` method will spawn `rustc --version`, wait until the process
// finishes and return the output of the process
match cmd.output() {
Err... | identifier_body | |
process.rs | use std::io::process::{Command,ProcessOutput};
fn main() {
// Initial command `rustc`
let mut cmd = Command::new("rustc");
// append the "--version" flag to the command
cmd.arg("--version");
| Ok(ProcessOutput { error: err, output: out, status: exit }) => {
// Check if the process succeeded, i.e. the exit code was 0
if exit.success() {
// `out` has type `Vec<u8>`, convert it to a UTF-8 `$str`
let s = String::from_utf8_lossy(out.as_slice());
... | // The `output` method will spawn `rustc --version`, wait until the process
// finishes and return the output of the process
match cmd.output() {
Err(why) => panic!("couldn't spawn rustc: {}", why.desc),
// Destructure `ProcessOutput` | random_line_split |
process.rs | use std::io::process::{Command,ProcessOutput};
fn | () {
// Initial command `rustc`
let mut cmd = Command::new("rustc");
// append the "--version" flag to the command
cmd.arg("--version");
// The `output` method will spawn `rustc --version`, wait until the process
// finishes and return the output of the process
match cmd.output() {
... | main | identifier_name |
test_operations.py | import pytest
from diofant import Integer, SympifyError
from diofant.core.operations import AssocOp, LatticeOp
__all__ = ()
class MyMul(AssocOp):
identity = Integer(1)
def | ():
assert MyMul(2, MyMul(4, 3)) == MyMul(2, 4, 3)
class Join(LatticeOp):
"""Simplest possible Lattice class."""
zero = Integer(0)
identity = Integer(1)
def test_lattice_simple():
assert Join(Join(2, 3), 4) == Join(2, Join(3, 4))
assert Join(2, 3) == Join(3, 2)
assert Join(0, 2) == 0
... | test_flatten | identifier_name |
test_operations.py | import pytest
from diofant import Integer, SympifyError
from diofant.core.operations import AssocOp, LatticeOp
__all__ = ()
class MyMul(AssocOp):
identity = Integer(1) |
def test_flatten():
assert MyMul(2, MyMul(4, 3)) == MyMul(2, 4, 3)
class Join(LatticeOp):
"""Simplest possible Lattice class."""
zero = Integer(0)
identity = Integer(1)
def test_lattice_simple():
assert Join(Join(2, 3), 4) == Join(2, Join(3, 4))
assert Join(2, 3) == Join(3, 2)
assert ... | random_line_split | |
test_operations.py | import pytest
from diofant import Integer, SympifyError
from diofant.core.operations import AssocOp, LatticeOp
__all__ = ()
class MyMul(AssocOp):
identity = Integer(1)
def test_flatten():
assert MyMul(2, MyMul(4, 3)) == MyMul(2, 4, 3)
class Join(LatticeOp):
"""Simplest possible Lattice class."""
... |
def test_lattice_shortcircuit():
pytest.raises(SympifyError, lambda: Join(object))
assert Join(0, object) == 0
def test_lattice_print():
assert str(Join(5, 4, 3, 2)) == 'Join(2, 3, 4, 5)'
def test_lattice_make_args():
assert Join.make_args(0) == {0}
assert Join.make_args(1) == {1}
assert ... | assert Join(Join(2, 3), 4) == Join(2, Join(3, 4))
assert Join(2, 3) == Join(3, 2)
assert Join(0, 2) == 0
assert Join(1, 2) == 2
assert Join(2, 2) == 2
assert Join(Join(2, 3), 4) == Join(2, 3, 4)
assert Join() == 1
assert Join(4) == 4
assert Join(1, 4, 2, 3, 1, 3, 2) == Join(2, 3, 4) | identifier_body |
Event.py | from django.db import models
from django.conf import settings
from django.utils import timezone
from django.core.validators import MinValueValidator
from django.urls import reverse
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from .Committee import Committee
fro... | (self):
"""
Return true if the event is published (past published date and not past end date)
"""
return self.published_at < timezone.now() < self.end_at
def is_expired(self):
"""
Return true if deadline is expired.
"""
return self.deadline_at is not None and self.deadline_at < timezone.now()
def is... | is_published | identifier_name |
Event.py | from django.db import models
from django.conf import settings
from django.utils import timezone
from django.core.validators import MinValueValidator
from django.urls import reverse
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from .Committee import Committee
fro... | name = models.CharField(max_length=25)
description = models.TextField(max_length=255)
long_description = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
published_at = models.DateTimeField(default=timezone.now, blank=True)
deadline... | identifier_body | |
Event.py | from django.db import models
from django.conf import settings
from django.utils import timezone
from django.core.validators import MinValueValidator
from django.urls import reverse
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from .Committee import Committee
fro... |
else:
return self.places - Registration.objects.filter(event=self, withdrawn_at__isnull=True).count()
def get_active_registrations_count(self):
"""
Return the number of non-withdrawn registrations
"""
return self.registration_set.filter(withdrawn_at__isnull=True).count()
def is_almost_expired(self):
... | return None | conditional_block |
Event.py | from django.db import models
from django.conf import settings
from django.utils import timezone
from django.core.validators import MinValueValidator
from django.urls import reverse
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from .Committee import Committee
fro... | return self.registration_set.filter(withdrawn_at__isnull=True).count()
def is_almost_expired(self):
"""
Return true if the deadline is closer than a day.
"""
return self.deadline_at - timezone.now() < timezone.timedelta(days=1) and not self.is_expired()
def get_note_field_options(self):
"""
Return lis... | """ | random_line_split |
lexer.py | # -*- coding: utf-8 -*-
"""
Collection of raw lexer test cases and class constructor.
"""
from __future__ import unicode_literals
import textwrap
swapquotes = {
39: 34, 34: 39,
# note the follow are interim error messages
96: 39,
}
# The structure and some test cases are taken
# from https://bitbucket.o... | lexer = lexer_cls()
lexer.input(textwrap.dedent(value).strip())
tokens = list(lexer)
return ([
'%s %d:%d' % (token.value, token.lineno, token.lexpos)
for token in tokens
], [
'%s %d:%d' % (token.value, token.lineno, token.colno)
for token in tokens
])
| lexer_cls):
| identifier_name |
lexer.py | # -*- coding: utf-8 -*-
"""
Collection of raw lexer test cases and class constructor.
"""
from __future__ import unicode_literals
import textwrap
swapquotes = {
39: 34, 34: 39,
# note the follow are interim error messages
96: 39,
}
# The structure and some test cases are taken
# from https://bitbucket.o... | lexer.input(textwrap.dedent(value).strip())
tokens = list(lexer)
return ([
'%s %d:%d' % (token.value, token.lineno, token.lexpos)
for token in tokens
], [
'%s %d:%d' % (token.value, token.lineno, token.colno)
for token in tokens
])
| identifier_body | |
lexer.py | # -*- coding: utf-8 -*-
"""
Collection of raw lexer test cases and class constructor.
"""
from __future__ import unicode_literals
import textwrap
swapquotes = {
39: 34, 34: 39,
# note the follow are interim error messages
96: 39,
}
# The structure and some test cases are taken
# from https://bitbucket.o... | (r'a=/a*/,1', ['ID a', 'EQ =', 'REGEX /a*/', 'COMMA ,', 'NUMBER 1']),
), (
'regex_2',
(r'a=/a*[^/]+/,1',
['ID a', 'EQ =', 'REGEX /a*[^/]+/', 'COMMA ,', 'NUMBER 1']
),
), (
'regex_3',
(r'a=/a*\[^/,1',
['ID a', 'EQ =', r'REGEX /a*\[^/', 'COMMA ,',... | random_line_split | |
search.ts | /// <amd-dependency path="koExtends/persist">
import $ = require("jquery");
import ko = require("knockout");
import _ = require("underscore");
import koControl = require("./koControl");
class searchParams {
array: KnockoutObservableArray<any>;
}
function extract(term: string, regex: RegExp, results: string[]): ... |
return term;
}
export class searchResult {
match: number;
antiMatch: number;
item: any;
}
export class SearchQuery {
matchTerms: string[] = [];
antiMatchTerms: string[] = [];
}
class search {
public searchQuery = ko.observable("").extend({persist: 'searchQuery'});
public titleOnly =... | {
results.push(term.match(regex)[0]);
term = term.replace(regex, "");
} | conditional_block |
search.ts | /// <amd-dependency path="koExtends/persist">
import $ = require("jquery");
import ko = require("knockout");
import _ = require("underscore");
import koControl = require("./koControl");
class searchParams {
array: KnockoutObservableArray<any>;
}
function extract(term: string, regex: RegExp, results: string[]): ... | {
public searchQuery = ko.observable("").extend({persist: 'searchQuery'});
public titleOnly = ko.observable(false);
public results: KnockoutComputed<any[]>;
searchData: KnockoutObservableArray<any>;
public searchQueryObj: KnockoutComputed<SearchQuery>;
constructor(element: HTMLElement, para... | search | identifier_name |
search.ts | /// <amd-dependency path="koExtends/persist">
import $ = require("jquery");
import ko = require("knockout");
import _ = require("underscore");
import koControl = require("./koControl");
class searchParams {
array: KnockoutObservableArray<any>;
}
function extract(term: string, regex: RegExp, results: string[]): ... | public searchQueryObj: KnockoutComputed<SearchQuery>;
constructor(element: HTMLElement, params: searchParams) {
this.searchData = params.array;
this.setupSearchQuery();
this.setupResults();
}
setupSearchQuery() {
this.searchQueryObj = ko.computed(() => {
v... | public results: KnockoutComputed<any[]>;
searchData: KnockoutObservableArray<any>;
| random_line_split |
static.module.js | const ng = require('angular');
ng.module('porybox.static', ['ngRoute']).config(['$routeProvider', $routeProvider => {
[
'about',
'donate',
'extracting-pokemon-files',
'faq',
'how-to-pk6-1-bvs',
'how-to-pk6-2-homebrew',
'how-to-pk6-3-4-save-files',
'how-to-pk6-6-decrypted-powersaves',
... | 'privacy-policy',
'tos'
].forEach(pageName => {
$routeProvider.when(`/${pageName}`, {templateUrl: `/static/${pageName}.html`});
});
$routeProvider.when('/extracting-pk6-files', {redirectTo: '/extracting-pokemon-files'});
}]); | 'markdown', | random_line_split |
events.d.ts | import { State, Ctx, PlayerID, Game } from '../../types';
export interface EventsAPI {
endGame?(...args: any[]): void;
endPhase?(...args: any[]): void;
endStage?(...args: any[]): void;
endTurn?(...args: any[]): void;
pass?(...args: any[]): void;
setActivePlayers?(...args: any[]): void;
... | update(state: State): State;
};
}
/**
* Events
*/
export declare class Events {
flow: Game['flow'];
playerID: PlayerID | undefined;
dispatch: Array<{
key: string;
args: any[];
phase: string;
turn: number;
}>;
constructor(flow: Game['flow']... | export interface PrivateEventsAPI {
_obj: {
isUsed(): boolean;
| random_line_split |
events.d.ts | import { State, Ctx, PlayerID, Game } from '../../types';
export interface EventsAPI {
endGame?(...args: any[]): void;
endPhase?(...args: any[]): void;
endStage?(...args: any[]): void;
endTurn?(...args: any[]): void;
pass?(...args: any[]): void;
setActivePlayers?(...args: any[]): void;
... | {
flow: Game['flow'];
playerID: PlayerID | undefined;
dispatch: Array<{
key: string;
args: any[];
phase: string;
turn: number;
}>;
constructor(flow: Game['flow'], playerID?: PlayerID);
/**
* Attaches the Events API to ctx.
* @param {object} ... | Events | identifier_name |
test_cli_config.py | import click
import mock
import pytest
from click.testing import CliRunner
from sigopt.cli import cli
class TestRunCli(object):
@pytest.mark.parametrize('opt_into_log_collection', [False, True])
@pytest.mark.parametrize('opt_into_cell_tracking', [False, True])
def test_config_command(self, opt_into_log_collect... | runner = CliRunner()
log_collection_arg = '--enable-log-collection' if opt_into_log_collection else '--no-enable-log-collection'
cell_tracking_arg = '--enable-cell-tracking' if opt_into_cell_tracking else '--no-enable-cell-tracking'
with mock.patch('sigopt.cli.commands.config._config.persist_configuration_o... | identifier_body | |
test_cli_config.py | import click
import mock
import pytest
from click.testing import CliRunner
from sigopt.cli import cli
class | (object):
@pytest.mark.parametrize('opt_into_log_collection', [False, True])
@pytest.mark.parametrize('opt_into_cell_tracking', [False, True])
def test_config_command(self, opt_into_log_collection, opt_into_cell_tracking):
runner = CliRunner()
log_collection_arg = '--enable-log-collection' if opt_into_log... | TestRunCli | identifier_name |
test_cli_config.py |
from sigopt.cli import cli
class TestRunCli(object):
@pytest.mark.parametrize('opt_into_log_collection', [False, True])
@pytest.mark.parametrize('opt_into_cell_tracking', [False, True])
def test_config_command(self, opt_into_log_collection, opt_into_cell_tracking):
runner = CliRunner()
log_collection_a... | import click
import mock
import pytest
from click.testing import CliRunner | random_line_split | |
gcs.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::{convert::TryInto, fmt::Display, io, sync::Arc};
use cloud::blob::{none_to_empty, BlobConfig, BlobStorage, BucketConf, StringNonEmpty};
use futures_util::{
future::TryFutureExt,
io::{AsyncRead, AsyncReadExt, Cursor},
stream::{Strea... |
let (parts, body) = res.into_parts();
let body = hyper::body::to_bytes(body)
.await
.map_err(|e| RequestError::Hyper(e, "set auth body".to_owned()))?;
svc_access
.parse_token_response(scope_hash, Response::from_... | {
return Err(status_code_error(
res.status(),
"set auth request".to_string(),
));
} | conditional_block |
gcs.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::{convert::TryInto, fmt::Display, io, sync::Arc};
use cloud::blob::{none_to_empty, BlobConfig, BlobStorage, BucketConf, StringNonEmpty};
use futures_util::{
future::TryFutureExt,
io::{AsyncRead, AsyncReadExt, Cursor},
stream::{Strea... | () {
let mut input = InputConfig::default();
input.set_bucket("bucket".to_owned());
input.set_prefix("backup 02/prefix/".to_owned());
let c1 = Config::from_input(input.clone()).unwrap();
let c2 = Config::from_cloud_dynamic(&cloud_dynamic_from_input(input)).unwrap();
asser... | test_config_round_trip | identifier_name |
gcs.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::{convert::TryInto, fmt::Display, io, sync::Arc};
use cloud::blob::{none_to_empty, BlobConfig, BlobStorage, BucketConf, StringNonEmpty};
use futures_util::{
future::TryFutureExt,
io::{AsyncRead, AsyncReadExt, Cursor},
stream::{Strea... |
fn deserialize_service_account_info(
cred: StringNonEmpty,
) -> std::result::Result<ServiceAccountInfo, RequestError> {
ServiceAccountInfo::deserialize(cred.to_string())
.map_err(|e| RequestError::OAuth(e, "deserialize ServiceAccountInfo".to_string()))
}
impl BlobConfig for Config {
fn name(&self)... | storage_class,
})
}
} | random_line_split |
gcs.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::{convert::TryInto, fmt::Display, io, sync::Arc};
use cloud::blob::{none_to_empty, BlobConfig, BlobStorage, BucketConf, StringNonEmpty};
use futures_util::{
future::TryFutureExt,
io::{AsyncRead, AsyncReadExt, Cursor},
stream::{Strea... |
async fn make_request(
&self,
mut req: Request<Body>,
scope: tame_gcs::Scopes,
) -> Result<Response<Body>, RequestError> {
// replace the hard-coded GCS endpoint by the custom one.
if let Some(endpoint) = &self.config.bucket.endpoint {
let uri = req.uri().t... | {
let token_or_request = svc_access
.get_token(&[scope])
.map_err(|e| RequestError::OAuth(e, "get_token".to_string()))?;
let token = match token_or_request {
TokenOrRequest::Token(token) => token,
TokenOrRequest::Request {
request,
... | identifier_body |
setup.py | from distutils.core import setup
import sys
import py2exe
try:
scriptName = sys.argv[3]
except IndexError:
print "Usage: python setup.py py2exe -i nombreApp"
| setup(
name=scriptName,
version="2.0",
description="Aplicacion Python creada con py2exe",
author="Pueyo Luciano",
author_email="PueyoLuciano.getMail()",
url="http://cafeidotica.blogspot.com.ar/",
license="Mozilla Public License 2.0",
scripts=[scriptName + ".py"],
console=[{"script":scriptName ... | sys.exit(2)
# Para crear el exe hay que ir al cmd y correr python setup.py py2exe
| random_line_split |
interaction-helper.ts |
import { find, values } from 'lodash';
import { Character } from '../../../shared/models/character';
import { SkillClassNames } from '../../../shared/interfaces/character';
export class InteractionHelper {
static tryToOpenDoor(player: Character, door, { gameState }): boolean {
door.properties = door.propertie... |
if(requireHeld && player.hasHeldItem(requireHeld)) {
shouldOpen = true;
player.rightHand.condition -= 1000;
} else {
player.sendClientMessage('The key snapped off in the lock!');
player.rightHand.condition = 0;
return;
}
}
/** PERK... | {
player.sendClientMessage('That key is not currently usable!');
return;
} | conditional_block |
interaction-helper.ts |
import { find, values } from 'lodash';
import { Character } from '../../../shared/models/character';
import { SkillClassNames } from '../../../shared/interfaces/character';
export class InteractionHelper {
static | (player: Character, door, { gameState }): boolean {
door.properties = door.properties || {};
const { requireLockpick, skillRequired, requireHeld, requireEventToOpen, lockedIfAlive } = door.properties;
if(requireEventToOpen) return false;
if(!door.isOpen
&& (requireLockpick || requireHeld || lock... | tryToOpenDoor | identifier_name |
interaction-helper.ts | import { SkillClassNames } from '../../../shared/interfaces/character';
export class InteractionHelper {
static tryToOpenDoor(player: Character, door, { gameState }): boolean {
door.properties = door.properties || {};
const { requireLockpick, skillRequired, requireHeld, requireEventToOpen, lockedIfAlive } =... | import { find, values } from 'lodash';
import { Character } from '../../../shared/models/character'; | random_line_split | |
endpoint-schema-errors-continue.config.ts | import { WeavingConfig } from '../../../src/config/weaving-config';
import { GraphQLClient } from '../../../src/graphql-client/graphql-client';
import { ExecutionResult } from 'graphql';
import { defaultTestSchema } from '../../helpers/grapqhl-http-test/graphql-http-test-schema';
import { WeavingErrorHandlingMode } fro... | (query, vars, context, introspection): Promise<ExecutionResult> {
throw new Error(introspection ? 'Throwing introspection' : 'Throwing query');
}
};
const normalSchema = makeExecutableSchema({
// ZInner should be alphabeticaly after Query so that joining occurs before linking (to test another error cas... | execute | identifier_name |
endpoint-schema-errors-continue.config.ts | import { WeavingConfig } from '../../../src/config/weaving-config';
import { GraphQLClient } from '../../../src/graphql-client/graphql-client';
import { ExecutionResult } from 'graphql';
import { defaultTestSchema } from '../../helpers/grapqhl-http-test/graphql-http-test-schema';
import { WeavingErrorHandlingMode } fro... | fieldMetadata: {
'ZInner.field': {
link: {
field: 'nonexisting',
argument: 'id',
batchMode: false
}
}
}
... | },
{
namespace: 'linkConfigError',
typePrefix: 'LinkConfigError',
schema: normalSchema, | random_line_split |
endpoint-schema-errors-continue.config.ts | import { WeavingConfig } from '../../../src/config/weaving-config';
import { GraphQLClient } from '../../../src/graphql-client/graphql-client';
import { ExecutionResult } from 'graphql';
import { defaultTestSchema } from '../../helpers/grapqhl-http-test/graphql-http-test-schema';
import { WeavingErrorHandlingMode } fro... | {
return {
endpoints: [
{
client: errorClient,
identifier: 'namespaceless-erroneous'
},
{
namespace: 'erroneous',
client: errorClient
},
{
namespace: 'erroneousPrefixed... | identifier_body | |
lib.rs | //! # nom, eating data byte by byte
//!
//! nom is a parser combinator library with a focus on safe parsing,
//! streaming patterns, and as much as possible zero copy.
//!
//! ## Example
//!
//! ```rust
//! use nom::{
//! IResult,
//! bytes::complete::{tag, take_while_m_n},
//! combinator::map_res,
//! sequence... | //! There are more complex (and more useful) parsers like `tuple!`, which is
//! used to apply a series of parsers then assemble their results.
//!
//! Example with `tuple`:
//!
//! ```rust
//! # fn main() {
//! use nom::{error::ErrorKind, Needed,
//! number::streaming::be_u16,
//! bytes::streaming::{tag, take},
//! se... | //! - **`many0`**: Will apply the parser 0 or more times (if it returns the `O` type, the new parser returns `Vec<O>`)
//! - **`many1`**: Will apply the parser 1 or more times
//! | random_line_split |
generate.ts | import selectorsLibrary from '../selectorsLibrary';
import cssVariablesLibrary from '../cssVariablesLibrary';
import keyframesLibrary from '../keyframesLibrary';
interface Stat {
appearanceCount: number;
}
export interface UsageCount {
[s: string]: number;
}
export interface Statistic {
unused: string[];
usa... |
export default generate; | random_line_split | |
mod.rs | //! Lexical analysis.
use std::str;
use std::fmt;
use kailua_diag::{Locale, Localize, Localized};
use string::{Name, Str};
/// A token.
#[derive(Clone, Debug, PartialEq)]
pub enum Tok {
/// A token which is distinct from all other tokens.
///
/// The lexer emits this token on an error.
Error,
//... | DashDashColon "`--:`", /// `--:`. [M]
DashDashGt "`-->`", /// `-->`. [M]
Ques "`?`", /// `?`. [M]
Bang "`!`", /// `!`. [M]
Newline match &locale[..] { "ko" => "개행문자", _ => "a newline" },
/// A newline. Only generated at the end... | DashDashHash "`--#`", /// `--#`. [M]
DashDashV "`--v`", /// `--v`. [M] | random_line_split |
mod.rs | //! Lexical analysis.
use std::str;
use std::fmt;
use kailua_diag::{Locale, Localize, Localized};
use string::{Name, Str};
/// A token.
#[derive(Clone, Debug, PartialEq)]
pub enum | {
/// A token which is distinct from all other tokens.
///
/// The lexer emits this token on an error.
Error,
/// A comment token. The parser should ignore this.
///
/// The shebang line (the first line starting with `#`) is also considered as a comment.
Comment,
/// A punctuation... | Tok | identifier_name |
mod.rs | //! Lexical analysis.
use std::str;
use std::fmt;
use kailua_diag::{Locale, Localize, Localized};
use string::{Name, Str};
/// A token.
#[derive(Clone, Debug, PartialEq)]
pub enum Tok {
/// A token which is distinct from all other tokens.
///
/// The lexer emits this token on an error.
Error,
//... | Keyword) -> Name {
kw.name().into()
}
}
impl Localize for Keyword {
fn fmt_localized(&self, f: &mut fmt::Formatter, locale: Locale) -> fmt::Result {
let name = str::from_utf8(self.name()).unwrap();
match &locale[..] {
"ko" => write!(f, "예약어 `{}`", name),
_ => wri... | ord> for Name {
fn from(kw: | identifier_body |
import_jenkinsserver.py | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
# TODO: implement optional field updating...
class Command(BaseCommand):
help ... |
name, url, username, password = args
import_jenkinsserver(
name, url, username, password, update=options["update"],
stdout=self.stdout)
transaction.commit_unless_managed()
| raise CommandError("must provide all parameters") | conditional_block |
import_jenkinsserver.py | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
# TODO: implement optional field updating...
class Command(BaseCommand):
help ... |
import_jenkinsserver(
name, url, username, password, update=options["update"],
stdout=self.stdout)
transaction.commit_unless_managed() | if len(args) != 4:
raise CommandError("must provide all parameters")
name, url, username, password = args | random_line_split |
import_jenkinsserver.py | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
# TODO: implement optional field updating...
class Command(BaseCommand):
help ... | (self, *args, **options):
if len(args) != 4:
raise CommandError("must provide all parameters")
name, url, username, password = args
import_jenkinsserver(
name, url, username, password, update=options["update"],
stdout=self.stdout)
transaction.commit_... | handle | identifier_name |
import_jenkinsserver.py | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
# TODO: implement optional field updating...
class Command(BaseCommand):
help ... | if len(args) != 4:
raise CommandError("must provide all parameters")
name, url, username, password = args
import_jenkinsserver(
name, url, username, password, update=options["update"],
stdout=self.stdout)
transaction.commit_unless_managed() | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.