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 |
|---|---|---|---|---|
post.js | require("should");
var PurchaseRequest = require('../../data-util/purchasing/purchase-request-data-util');
var helper = require("../../helper");
var validate = require("dl-models").validator.purchasing.purchaseRequest;
var PurchaseRequestManager = require("../../../src/managers/purchasing/purchase-request-manager");
v... | });
done();
})
.catch(e => {
done(e);
});
});
var purchaseRequest;
it('#01. should success when create new data', function(done) {
PurchaseRequest.getNewTestData()
.then(pr => {
purchaseRequest = pr;
validate(purchaseReques... | purchaseRequestManager = new PurchaseRequestManager(db, {
username: 'dev' | random_line_split |
webpack.config.js | // volontary written in ES5, so that it works with Node 4.x
var path = require('path');
var webpack = require('webpack');
var ProgressBarPlugin = require('progress-bar-webpack-plugin');
var HasteMapWebPackResolver = require('haste-map-webpack-resolver');
var currentDir = path.resolve(__dirname, '.');
var hasteMapWebP... | }; | random_line_split | |
atlas.py | #!/usr/bin/env python
#
# Copyright (c) 2013, NLnet Labs. All rights reserved.
#
# This software is open source.
#
# 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 reta... |
def result(self, msm_id):
return self.measurement(msm_id, 'result')
def create(self, definitions, *probes):
probes = list(probes)
req = { 'definitions': definitions if type(definitions) is list
else [definitions]
, 'probes' : list()
}
for key in ('... | return self.measurement(*path, **args) | identifier_body |
atlas.py | #!/usr/bin/env python
#
# Copyright (c) 2013, NLnet Labs. All rights reserved.
#
# This software is open source.
#
# 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 reta... |
for obj in j['objects']:
yield obj
url = j['meta'].get('next', None)
return get
def msm(self, *path, **args):
return self.measurement(*path, **args)
def result(self, msm_id):
return self.measurement(msm_id, 'result')
def create(self, definitions, *probes):
probes = list(probes)
req = { 'd... | yield j
return | conditional_block |
atlas.py | #!/usr/bin/env python
#
# Copyright (c) 2013, NLnet Labs. All rights reserved.
#
# This software is open source.
#
# 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 reta... | # | # | random_line_split |
atlas.py | #!/usr/bin/env python
#
# Copyright (c) 2013, NLnet Labs. All rights reserved.
#
# This software is open source.
#
# 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 reta... | :
def __init__(self, create_key = None, result_key = None):
if not create_key:
with file('%s/.atlas/auth' % os.path.expanduser('~')) \
as f:
keys_l = f.read().strip().split()
create_key = keys_l[0]
if not result_key and len(keys_l) > 1:
result_key = keys_l[1]
self.create_key = create_key
... | Atlas | identifier_name |
lib.rs | pub mod math;
pub mod objective;
pub mod tableau;
use math::variables::is_gen_arti_var;
use objective::problems::ProblemType;
use objective::functions::Function;
use objective::constraints::SystemOfConstraints;
use objective::solvers::{transform_constraint_rels_to_eq, rearrange_fun_eq_zero};
use tableau::tables::Table... | } else {
// Carry on with Phase II.
let mut table = get_initial_table_from(function, constraints);
return run_simplex(function, &mut table);
}
}
fn run_simplex(function: &Function, table: &mut Table) -> Vec<(String, Num)> {
loop {
match table.get_basic_solution() {
... | random_line_split | |
lib.rs | pub mod math;
pub mod objective;
pub mod tableau;
use math::variables::is_gen_arti_var;
use objective::problems::ProblemType;
use objective::functions::Function;
use objective::constraints::SystemOfConstraints;
use objective::solvers::{transform_constraint_rels_to_eq, rearrange_fun_eq_zero};
use tableau::tables::Table... |
}
fn run_simplex(function: &Function, table: &mut Table) -> Vec<(String, Num)> {
loop {
match table.get_basic_solution() {
Ok(mut basic_solution) => {
if table.is_solution_optimal() {
if function.p_type() == &ProblemType::MIN {
// Giv... | {
// Carry on with Phase II.
let mut table = get_initial_table_from(function, constraints);
return run_simplex(function, &mut table);
} | conditional_block |
lib.rs | pub mod math;
pub mod objective;
pub mod tableau;
use math::variables::is_gen_arti_var;
use objective::problems::ProblemType;
use objective::functions::Function;
use objective::constraints::SystemOfConstraints;
use objective::solvers::{transform_constraint_rels_to_eq, rearrange_fun_eq_zero};
use tableau::tables::Table... | }
} else {
panic!("Could not find a feasible solution to start Phase II.");
}
} else {
// Carry on with Phase II.
let mut table = get_initial_table_from(function, constraints);
return run_simplex(function, &mut table);
}
}
fn run_simplex(function... | {
rearrange_fun_eq_zero(function);
if let Some(mut phase1_fun) = transform_constraint_rels_to_eq(constraints) {
rearrange_fun_eq_zero(&mut phase1_fun);
let mut phase1_table = get_initial_table_from(function, constraints);
// Set Phase I function to work with.
append_function(&pha... | identifier_body |
lib.rs | pub mod math;
pub mod objective;
pub mod tableau;
use math::variables::is_gen_arti_var;
use objective::problems::ProblemType;
use objective::functions::Function;
use objective::constraints::SystemOfConstraints;
use objective::solvers::{transform_constraint_rels_to_eq, rearrange_fun_eq_zero};
use tableau::tables::Table... | (function: &Function, table: &mut Table) -> Vec<(String, Num)> {
loop {
match table.get_basic_solution() {
Ok(mut basic_solution) => {
if table.is_solution_optimal() {
if function.p_type() == &ProblemType::MIN {
// Give solution for MIN... | run_simplex | identifier_name |
renderpov.py | """
Pov-ray template rendering
==========================
This is a driver module that renders the pov-ray template for the given
molecule and user configuration based on the several other modules for
transforming molecular information into more and more primtive pov-ray objects.
"""
import pystache
import pkg_resou... |
render_dict['use-background'] = if_bkg
render_dict['background-settings'] = bkg_list
if ops_dict['draw-axes']:
axes_list = draw_axes(cam_foc, ops_dict)
else:
axes_list = []
render_dict['axes'] = axes_list
return render_dict
def render_pov(structure, output_file, ops_dict):
... | bkg_list = [
'colour %s' % bkg_colour
]
if_bkg = True | conditional_block |
renderpov.py | """
Pov-ray template rendering
==========================
This is a driver module that renders the pov-ray template for the given
molecule and user configuration based on the several other modules for
transforming molecular information into more and more primtive pov-ray objects.
"""
import pystache
import pkg_resou... | (structure, ops_dict):
"""Generates the dictionary for rendering the template"""
render_dict = {}
cam_dict, cam_loc, cam_foc = gen_camera_ops(ops_dict, structure)
render_dict['camera'] = cam_dict
lightsouce_dict = gen_light_ops(cam_loc, cam_foc, ops_dict)
render_dict.update(lightsouce_dict)
... | gen_render_dict | identifier_name |
renderpov.py | """
Pov-ray template rendering
==========================
This is a driver module that renders the pov-ray template for the given
molecule and user configuration based on the several other modules for
transforming molecular information into more and more primtive pov-ray objects.
"""
import pystache
import pkg_resou... | output_file.split('.')[0] + '.pov',
'w'
)
pov_file.write(result)
return None | renderer = pystache.Renderer(partials={'texturedef': texture_partial})
result = renderer.render(template, render_dict)
pov_file = open( | random_line_split |
renderpov.py | """
Pov-ray template rendering
==========================
This is a driver module that renders the pov-ray template for the given
molecule and user configuration based on the several other modules for
transforming molecular information into more and more primtive pov-ray objects.
"""
import pystache
import pkg_resou... | else:
bkg_list = [
'colour %s' % bkg_colour
]
if_bkg = True
render_dict['use-background'] = if_bkg
render_dict['background-settings'] = bkg_list
if ops_dict['draw-axes']:
axes_list = draw_axes(cam_foc, ops_dict)
else:
axes_list = []
render... | """Generates the dictionary for rendering the template"""
render_dict = {}
cam_dict, cam_loc, cam_foc = gen_camera_ops(ops_dict, structure)
render_dict['camera'] = cam_dict
lightsouce_dict = gen_light_ops(cam_loc, cam_foc, ops_dict)
render_dict.update(lightsouce_dict)
atms_list = draw_atms(s... | identifier_body |
test_game.py | from tictactoe import game, player
import unittest
from unittest import mock
class GameTest(unittest.TestCase):
def setUp(self):
self.num_of_players = 2
self.width = 3
self.height = 3
self.game = game.Game(2, 3, 3)
def test_init(self):
self.assertEqual(self.game.board,... | input_seq = ['Luke', 'x', 'Leia', 'o']
with mock.patch('builtins.input', side_effect=input_seq):
self.game.setup()
input_seq = ['2', '5', '3', '1', '9', '6', '7', '4']
with mock.patch('builtins.input', side_effect=input_seq):
self.game.play_round()
finished, win... | identifier_body | |
test_game.py | from tictactoe import game, player
import unittest
from unittest import mock
class GameTest(unittest.TestCase):
def setUp(self):
self.num_of_players = 2
self.width = 3
self.height = 3
self.game = game.Game(2, 3, 3)
def test_init(self):
self.assertEqual(self.game.board,... | (self):
# setup
input_seq = ['Luke', 'x', 'Leia', 'o']
with mock.patch('builtins.input', side_effect=input_seq):
self.game.setup()
input_seq = ['2', '5', '3', '1', '9', '6', '7', '4']
with mock.patch('builtins.input', side_effect=input_seq):
self.game.pla... | test_play_round | identifier_name |
test_game.py | from tictactoe import game, player
import unittest
from unittest import mock
class GameTest(unittest.TestCase):
def setUp(self):
self.num_of_players = 2
self.width = 3
self.height = 3
self.game = game.Game(2, 3, 3)
def test_init(self):
self.assertEqual(self.game.board,... |
def test_play_round(self):
# setup
input_seq = ['Luke', 'x', 'Leia', 'o']
with mock.patch('builtins.input', side_effect=input_seq):
self.game.setup()
input_seq = ['2', '5', '3', '1', '9', '6', '7', '4']
with mock.patch('builtins.input', side_effect=input_seq):
... | self.assertEqual(p.name, e[0])
self.assertEqual(p.symbol, e[1]) | conditional_block |
test_game.py | from tictactoe import game, player
import unittest
from unittest import mock
class GameTest(unittest.TestCase):
def setUp(self):
self.num_of_players = 2
self.width = 3
self.height = 3
self.game = game.Game(2, 3, 3)
def test_init(self):
self.assertEqual(self.game.board,... | self.assertEqual(p.name, e[0])
self.assertEqual(p.symbol, e[1])
def test_play_round(self):
# setup
input_seq = ['Luke', 'x', 'Leia', 'o']
with mock.patch('builtins.input', side_effect=input_seq):
self.game.setup()
input_seq = ['2', '5', '3', '1',... | with mock.patch('builtins.input', side_effect=input_seq):
self.game.setup()
expected = [('Luke', 'x'), ('Leia', 'o')]
for e, p in zip(expected, self.game.players): | random_line_split |
module.ts | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option)... | *
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
/// <reference path="components/MyCoReFrameToolbarProviderComponent.ts" />
/// <reference path="../desktop/components/MyCoReImageInformationComponent.ts" />
/// <reference path... | *
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. | random_line_split |
input_test.rs | //! Example that just prints out all the input events.
use ggez::event::{self, Axis, Button, GamepadId, KeyCode, KeyMods, MouseButton};
use ggez::graphics::{self, Color, DrawMode};
use ggez::{conf, input};
use ggez::{Context, GameResult};
use glam::*;
struct MainState {
pos_x: f32,
pos_y: f32,
mouse_down:... |
}
}
pub fn main() -> GameResult {
let cb = ggez::ContextBuilder::new("input_test", "ggez").window_mode(
conf::WindowMode::default()
.fullscreen_type(conf::FullscreenType::Windowed)
.resizable(true),
);
let (ctx, event_loop) = cb.build()?;
// remove the comment to s... | {
println!("Focus lost");
} | conditional_block |
input_test.rs | //! Example that just prints out all the input events.
use ggez::event::{self, Axis, Button, GamepadId, KeyCode, KeyMods, MouseButton};
use ggez::graphics::{self, Color, DrawMode};
use ggez::{conf, input};
use ggez::{Context, GameResult};
use glam::*;
struct MainState {
pos_x: f32,
pos_y: f32,
mouse_down:... | (&mut self, _ctx: &mut Context, ch: char) {
println!("Text input: {}", ch);
}
fn gamepad_button_down_event(&mut self, _ctx: &mut Context, btn: Button, id: GamepadId) {
println!("Gamepad button pressed: {:?} Gamepad_Id: {:?}", btn, id);
}
fn gamepad_button_up_event(&mut self, _ctx: &mut... | text_input_event | identifier_name |
input_test.rs | //! Example that just prints out all the input events.
use ggez::event::{self, Axis, Button, GamepadId, KeyCode, KeyMods, MouseButton};
use ggez::graphics::{self, Color, DrawMode};
use ggez::{conf, input};
use ggez::{Context, GameResult};
use glam::*;
struct MainState {
pos_x: f32,
pos_y: f32,
mouse_down:... | println!("Key released: {:?}, modifier {:?}", keycode, keymod);
}
fn text_input_event(&mut self, _ctx: &mut Context, ch: char) {
println!("Text input: {}", ch);
}
fn gamepad_button_down_event(&mut self, _ctx: &mut Context, btn: Button, id: GamepadId) {
println!("Gamepad button ... | keycode, keymod, repeat
);
}
fn key_up_event(&mut self, _ctx: &mut Context, keycode: KeyCode, keymod: KeyMods) { | random_line_split |
input_test.rs | //! Example that just prints out all the input events.
use ggez::event::{self, Axis, Button, GamepadId, KeyCode, KeyMods, MouseButton};
use ggez::graphics::{self, Color, DrawMode};
use ggez::{conf, input};
use ggez::{Context, GameResult};
use glam::*;
struct MainState {
pos_x: f32,
pos_y: f32,
mouse_down:... | {
let cb = ggez::ContextBuilder::new("input_test", "ggez").window_mode(
conf::WindowMode::default()
.fullscreen_type(conf::FullscreenType::Windowed)
.resizable(true),
);
let (ctx, event_loop) = cb.build()?;
// remove the comment to see how physical mouse coordinates can ... | identifier_body | |
role.py | Version
from shutil import rmtree
import ansible.constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.urls import open_url
from ansible.playbook.role.requirement import RoleRequirement
from ansible.galaxy.api import GalaxyAPI
try:
from __main__ import display
except ImportError:
fr... | (self):
# the file is a tar, so open it that way and extract it
# to the specified (or default) roles directory
local_file = False
if self.scm:
# create tar file from scm url
tmp_file = RoleRequirement.scm_archive_role(**self.spec)
elif self.src:
... | install | identifier_name |
role.py | Version
from shutil import rmtree
import ansible.constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.urls import open_url
from ansible.playbook.role.requirement import RoleRequirement
from ansible.galaxy.api import GalaxyAPI
try:
from __main__ import display
except ImportError:
fr... |
return True
def remove(self):
"""
Removes the specified role from the roles path.
There is a sanity check to make sure there's a meta/main.yml file at this
path so the user doesn't blow away random directories.
"""
if self.metadata:
try:
... | self._install_info = yaml.safe_dump(info, f)
except:
return False | random_line_split |
role.py | Version
from shutil import rmtree
import ansible.constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.urls import open_url
from ansible.playbook.role.requirement import RoleRequirement
from ansible.galaxy.api import GalaxyAPI
try:
from __main__ import display
except ImportError:
fr... |
else:
for role_path_dir in galaxy.roles_paths:
role_path = os.path.join(role_path_dir, self.name)
if os.path.exists(role_path):
self.path = role_path
break
else:
# use the first path by default
... | if self.name not in path:
path = os.path.join(path, self.name)
self.path = path | conditional_block |
role.py | Version
from shutil import rmtree
import ansible.constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.urls import open_url
from ansible.playbook.role.requirement import RoleRequirement
from ansible.galaxy.api import GalaxyAPI
try:
from __main__ import display
except ImportError:
fr... |
@property
def install_info(self):
"""
Returns role install info
"""
if self._install_info is None:
info_path = os.path.join(self.path, self.META_INSTALL)
if os.path.isfile(info_path):
try:
f = open(info_path, 'r')
... | """
Returns role metadata
"""
if self._metadata is None:
meta_path = os.path.join(self.path, self.META_MAIN)
if os.path.isfile(meta_path):
try:
f = open(meta_path, 'r')
self._metadata = yaml.safe_load(f)
... | identifier_body |
all_c.js | var searchData=
[
['makeexternal',['MakeExternal',['../classv8_1_1String.html#a5efd1eba40c1fa8a6aae2c4a175a63be',1,'v8::String::MakeExternal(ExternalStringResource *resource)'],['../classv8_1_1String.html#a19db11c97e2ce01244e06f5cbcd094f2',1,'v8::String::MakeExternal(ExternalAsciiStringResource *resource)']]],
['ma... | ['messagehandler',['MessageHandler',['../classv8_1_1Debug.html#a526826b857bd3e3efa184e12bcebc694',1,'v8::Debug']]]
]; | ['message',['Message',['../classv8_1_1Message.html',1,'v8']]],
['message',['Message',['../classv8_1_1Debug_1_1Message.html',1,'v8::Debug']]],
['message',['Message',['../classv8_1_1TryCatch.html#a2811e500fbb906ee505895a3d94fc66f',1,'v8::TryCatch']]], | random_line_split |
uuid.rs | #![allow(clippy::needless_lifetimes)]
use uuid::Uuid;
use crate::{
parser::{ParseError, ScalarToken, Token},
value::ParseScalarResult,
Value,
};
#[crate::graphql_scalar(description = "Uuid")]
impl<S> GraphQLScalar for Uuid
where
S: ScalarValue,
{
fn resolve(&self) -> Value {
Value::scalar... | assert_eq!(parsed, id);
}
} | random_line_split | |
uuid.rs | #![allow(clippy::needless_lifetimes)]
use uuid::Uuid;
use crate::{
parser::{ParseError, ScalarToken, Token},
value::ParseScalarResult,
Value,
};
#[crate::graphql_scalar(description = "Uuid")]
impl<S> GraphQLScalar for Uuid
where
S: ScalarValue,
{
fn resolve(&self) -> Value {
Value::scalar... | else {
Err(ParseError::UnexpectedToken(Token::Scalar(value)))
}
}
}
#[cfg(test)]
mod test {
use crate::{value::DefaultScalarValue, InputValue};
use uuid::Uuid;
#[test]
fn uuid_from_input_value() {
let raw = "123e4567-e89b-12d3-a456-426655440000";
let input: Inp... | {
Ok(S::from(value.to_owned()))
} | conditional_block |
uuid.rs | #![allow(clippy::needless_lifetimes)]
use uuid::Uuid;
use crate::{
parser::{ParseError, ScalarToken, Token},
value::ParseScalarResult,
Value,
};
#[crate::graphql_scalar(description = "Uuid")]
impl<S> GraphQLScalar for Uuid
where
S: ScalarValue,
{
fn resolve(&self) -> Value {
Value::scalar... | (v: &InputValue) -> Option<Uuid> {
v.as_string_value().and_then(|s| Uuid::parse_str(s).ok())
}
fn from_str<'a>(value: ScalarToken<'a>) -> ParseScalarResult<'a, S> {
if let ScalarToken::String(value) = value {
Ok(S::from(value.to_owned()))
} else {
Err(ParseError:... | from_input_value | identifier_name |
uuid.rs | #![allow(clippy::needless_lifetimes)]
use uuid::Uuid;
use crate::{
parser::{ParseError, ScalarToken, Token},
value::ParseScalarResult,
Value,
};
#[crate::graphql_scalar(description = "Uuid")]
impl<S> GraphQLScalar for Uuid
where
S: ScalarValue,
{
fn resolve(&self) -> Value {
Value::scalar... |
}
#[cfg(test)]
mod test {
use crate::{value::DefaultScalarValue, InputValue};
use uuid::Uuid;
#[test]
fn uuid_from_input_value() {
let raw = "123e4567-e89b-12d3-a456-426655440000";
let input: InputValue<DefaultScalarValue> = InputValue::scalar(raw.to_string());
let parsed: Uu... | {
if let ScalarToken::String(value) = value {
Ok(S::from(value.to_owned()))
} else {
Err(ParseError::UnexpectedToken(Token::Scalar(value)))
}
} | identifier_body |
apf.py | """
Support for Advanced Policy Firewall (APF)
==========================================
:maintainer: Mostafa Hussein <mostafa.hussein91@gmail.com>
:maturity: new
:depends: python-iptables
:platform: Linux
"""
import salt.utils.path
from salt.exceptions import CommandExecutionError
try:
import iptc
IPTC_IMP... |
return True if status else False
def running():
"""
Check apf status
CLI Example:
.. code-block:: bash
salt '*' apf.running
"""
return True if _status_apf() else False
def disable():
"""
Stop (flush) all firewall rules
CLI Example:
.. code-block:: bash
... | if "sanity" in chain.name.lower():
status = 1 | conditional_block |
apf.py | """
Support for Advanced Policy Firewall (APF)
==========================================
:maintainer: Mostafa Hussein <mostafa.hussein91@gmail.com>
:maturity: new
:depends: python-iptables
:platform: Linux
"""
import salt.utils.path
from salt.exceptions import CommandExecutionError
try:
import iptc
IPTC_IMP... |
CLI Example:
.. code-block:: bash
salt '*' apf.refresh
"""
return __apf_cmd("-e")
def allow(ip, port=None):
"""
Add host (IP/FQDN) to allow_hosts.rules and immediately load new rule into firewall
CLI Example:
.. code-block:: bash
salt '*' apf.allow 127.0.0.1
"... | random_line_split | |
apf.py | """
Support for Advanced Policy Firewall (APF)
==========================================
:maintainer: Mostafa Hussein <mostafa.hussein91@gmail.com>
:maturity: new
:depends: python-iptables
:platform: Linux
"""
import salt.utils.path
from salt.exceptions import CommandExecutionError
try:
import iptc
IPTC_IMP... |
def deny(ip):
"""
Add host (IP/FQDN) to deny_hosts.rules and immediately load new rule into firewall
CLI Example:
.. code-block:: bash
salt '*' apf.deny 1.2.3.4
"""
return __apf_cmd("-d {}".format(ip))
def remove(ip):
"""
Remove host from [glob]*_hosts.rules and immediate... | """
Add host (IP/FQDN) to allow_hosts.rules and immediately load new rule into firewall
CLI Example:
.. code-block:: bash
salt '*' apf.allow 127.0.0.1
"""
if port is None:
return __apf_cmd("-a {}".format(ip)) | identifier_body |
apf.py | """
Support for Advanced Policy Firewall (APF)
==========================================
:maintainer: Mostafa Hussein <mostafa.hussein91@gmail.com>
:maturity: new
:depends: python-iptables
:platform: Linux
"""
import salt.utils.path
from salt.exceptions import CommandExecutionError
try:
import iptc
IPTC_IMP... | (cmd):
"""
Return the apf location
"""
apf_cmd = "{} {}".format(salt.utils.path.which("apf"), cmd)
out = __salt__["cmd.run_all"](apf_cmd)
if out["retcode"] != 0:
if not out["stderr"]:
msg = out["stdout"]
else:
msg = out["stderr"]
raise CommandExec... | __apf_cmd | identifier_name |
XSConsoleConfig.py | # Copyright (c) 2007-2009 Citrix Systems Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ... |
# Import a more specific configuration if available
if os.path.isfile(sys.path[0]+'/XSConsoleConfigOEM.py'):
import XSConsoleConfigOEM
| return ['/EULA'] | identifier_body |
XSConsoleConfig.py | # Copyright (c) 2007-2009 Citrix Systems Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ... | (self):
return True
def DisplaySerialNumber(self):
return True
def DisplayAssetTag(self):
return True
def BMCName(self):
return 'BMC'
def FirstBootEULAs(self):
# Subclasses in XSConsoleConfigOEM can add their EULAs to this array
... | AllShellsTimeout | identifier_name |
XSConsoleConfig.py | # Copyright (c) 2007-2009 Citrix Systems Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ... |
return cls.instance
@classmethod
def Mutate(cls, inConfig):
cls.instance = inConfig
def Colour(self, inName):
return self.colours[inName]
def FTPServer(self):
return self.ftpserver
def BrandingMap(self):
return {}
def AllShellsTi... | cls.instance = Config() | conditional_block |
XSConsoleConfig.py | # Copyright (c) 2007-2009 Citrix Systems Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ... | def FirstBootEULAs(self):
# Subclasses in XSConsoleConfigOEM can add their EULAs to this array
return ['/EULA']
# Import a more specific configuration if available
if os.path.isfile(sys.path[0]+'/XSConsoleConfigOEM.py'):
import XSConsoleConfigOEM | def BMCName(self):
return 'BMC'
| random_line_split |
dns_driver.py | # Copyright 2011 Andrew Bogott for the Wikimedia Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | (self, _name, _domain):
raise NotImplementedError()
def create_domain(self, _fqdomain):
raise NotImplementedError()
def delete_domain(self, _fqdomain):
raise NotImplementedError()
| get_entries_by_name | identifier_name |
dns_driver.py | # Copyright 2011 Andrew Bogott for the Wikimedia Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
def get_domains(self):
raise NotImplementedError()
def create_entry(self, _name, _address, _type, _domain):
raise NotImplementedError()
def delete_entry(self, _name, _domain):
raise NotImplementedError()
def modify_address(self, _name, _address, _domain):
raise NotIm... | pass | identifier_body |
dns_driver.py | # Copyright 2011 Andrew Bogott for the Wikimedia Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | raise NotImplementedError()
def modify_address(self, _name, _address, _domain):
raise NotImplementedError()
def get_entries_by_address(self, _address, _domain):
raise NotImplementedError()
def get_entries_by_name(self, _name, _domain):
raise NotImplementedError()
def ... | def create_entry(self, _name, _address, _type, _domain):
raise NotImplementedError()
def delete_entry(self, _name, _domain): | random_line_split |
coordseq.py | from ctypes import POINTER, c_double, c_int, c_uint
from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR
from django.contrib.gis.geos.prototypes.errcheck import (
GEOSException, last_arg_byref,
)
from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
# ## Error-checking routines spec... | (func):
"For coordinate sequence routines that return an integer."
func.argtypes = [CS_PTR, POINTER(c_uint)]
func.restype = c_int
func.errcheck = check_cs_get
return func
def cs_operation(func, ordinate=False, get=False):
"For coordinate sequence operations."
if get:
# G... | cs_int | identifier_name |
coordseq.py | from ctypes import POINTER, c_double, c_int, c_uint
from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR
from django.contrib.gis.geos.prototypes.errcheck import (
GEOSException, last_arg_byref,
)
from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
# ## Error-checking routines spec... |
def cs_output(func, argtypes):
"For routines that return a coordinate sequence."
func.argtypes = argtypes
func.restype = CS_PTR
func.errcheck = check_cs_ptr
return func
# ## Coordinate Sequence ctypes prototypes ##
# Coordinate Sequence constructors & cloning.
cs_clone = cs_output(... | "For coordinate sequence operations."
if get:
# Get routines get double parameter passed-in by reference.
func.errcheck = check_cs_get
dbl_param = POINTER(c_double)
else:
func.errcheck = check_cs_op
dbl_param = c_double
if ordinate:
# Get/Set ordina... | identifier_body |
coordseq.py | from ctypes import POINTER, c_double, c_int, c_uint
from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR
from django.contrib.gis.geos.prototypes.errcheck import (
GEOSException, last_arg_byref,
)
from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
# ## Error-checking routines spec... |
def check_cs_get(result, func, cargs):
"Checking the coordinate sequence retrieval."
check_cs_op(result, func, cargs)
# Object in by reference, return its value.
return last_arg_byref(cargs)
# ## Coordinate sequence prototype generation functions. ##
def cs_int(func):
"For coordinat... | return result | conditional_block |
coordseq.py | from ctypes import POINTER, c_double, c_int, c_uint
from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR
from django.contrib.gis.geos.prototypes.errcheck import (
GEOSException, last_arg_byref,
)
from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
# ## Error-checking routines spec... | cs_setx = cs_operation(GEOSFunc('GEOSCoordSeq_setX'))
cs_sety = cs_operation(GEOSFunc('GEOSCoordSeq_setY'))
cs_setz = cs_operation(GEOSFunc('GEOSCoordSeq_setZ'))
# These routines return size & dimensions.
cs_getsize = cs_int(GEOSFunc('GEOSCoordSeq_getSize'))
cs_getdims = cs_int(GEOSFunc('GEOSCoordSeq_getDimensio... | cs_getx = cs_operation(GEOSFunc('GEOSCoordSeq_getX'), get=True)
cs_gety = cs_operation(GEOSFunc('GEOSCoordSeq_getY'), get=True)
cs_getz = cs_operation(GEOSFunc('GEOSCoordSeq_getZ'), get=True)
# For setting, x, y, z
| random_line_split |
ConversationHeader.tsx | // Copyright 2020-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import { connect } from 'react-redux';
import { pick } from 'lodash';
import {
ConversationHeader,
OutgoingCallButtonStyle,
} from '../../components/conversation/ConversationHeader';
import { getConversationSelector } from '../s... | return OutgoingCallButtonStyle.Join;
}
return OutgoingCallButtonStyle.JustVideo;
}
default:
throw missingCaseError(conversationCallMode);
}
};
const mapStateToProps = (state: StateType, ownProps: OwnProps) => {
const { id } = ownProps;
const conversation = getConversationSelect... | if (
call?.callMode === CallMode.Group &&
isAnybodyElseInGroupCall(call.peekInfo, getUserConversationId(state))
) { | random_line_split |
ConversationHeader.tsx | // Copyright 2020-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import { connect } from 'react-redux';
import { pick } from 'lodash';
import {
ConversationHeader,
OutgoingCallButtonStyle,
} from '../../components/conversation/ConversationHeader';
import { getConversationSelector } from '../s... |
const conversationCallMode = getConversationCallMode(conversation);
switch (conversationCallMode) {
case CallMode.None:
return OutgoingCallButtonStyle.None;
case CallMode.Direct:
return OutgoingCallButtonStyle.Both;
case CallMode.Group: {
if (!isGroupCallingEnabled()) {
retur... | {
return OutgoingCallButtonStyle.None;
} | conditional_block |
kendo.mobile.shim.js | /*
* Kendo UI Complete v2013.2.918 (http://kendoui.com)
* Copyright 2013 Telerik AD. All rights reserved.
*
* Kendo UI Complete commercial licenses may be obtained at
* https://www.kendoui.com/purchase/license-agreement/kendo-ui-complete-commercial.aspx
* If you do not own a commercial license, this file shall be gover... | }
},
deactivate: function() {
shim.hide();
},
open: function() {
shim.show();
}
});
kendo.notify(that);
},
options: {
name: "S... | },
close: {
duration: that.options.duration | random_line_split |
kendo.mobile.shim.js | /*
* Kendo UI Complete v2013.2.918 (http://kendoui.com)
* Copyright 2013 Telerik AD. All rights reserved.
*
* Kendo UI Complete commercial licenses may be obtained at
* https://www.kendoui.com/purchase/license-agreement/kendo-ui-complete-commercial.aspx
* If you do not own a commercial license, this file shall be gover... |
},
destroy: function() {
Widget.fn.destroy.call(this);
this.shim.kendoDestroy();
this.popup.destroy();
this.shim.remove();
}
});
ui.plugin(Shim);
})(window.kendo.jQuery);
| {
this.popup.close();
} | conditional_block |
path-lookahead.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
}
| main | identifier_name |
path-lookahead.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
}
| { //~WARN function is never used: `no_parens`
return <T as ToString>::to_string(&arg);
} | identifier_body |
path-lookahead.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn with_parens<T: ToString>(arg: T) -> String { //~WARN function is never used: `with_parens`
return (<T as ToString>::to_string(&arg)); //~WARN unnecessary parentheses around `return` value
}
fn no_parens<T: ToString>(arg: T) -> String { //~WARN function is never used: `no_parens`
return <T as ToString>::to_stri... | // Parser test for #37765 | random_line_split |
error.rs | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | pub enum SgeError {
IO(std::io::Error),
StdErr(Box<dyn std::error::Error>),
Literal(&'static str),
Message(String),
}
pub type SgeResult<T> = Result<T, SgeError>;
impl From<std::io::Error> for SgeError {
fn from(e: std::io::Error) -> Self {
SgeError::IO(e)
}
}
impl From<Box<dyn std::e... | random_line_split | |
error.rs | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (self) -> &'static str {
match self {
SgeError::IO(_) => "io error",
SgeError::StdErr(_) => "std err",
SgeError::Literal(_) => "literal",
SgeError::Message(_) => "message",
}
}
}
impl std::error::Error for SgeError {
fn source(&self) -> Option<&(d... | into | identifier_name |
error.rs | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
}
impl From<Box<dyn std::error::Error>> for SgeError {
fn from(e: Box<dyn std::error::Error>) -> Self {
SgeError::StdErr(e)
}
}
impl From<&'static str> for SgeError {
fn from(e: &'static str) -> Self {
SgeError::Literal(e)
}
}
impl From<String> for SgeError {
fn from(e: String) -... | {
SgeError::IO(e)
} | identifier_body |
L0MSBuildDefaults.ts | import ma = require('vsts-task-lib/mock-answer');
import tmrm = require('vsts-task-lib/mock-run');
import path = require('path');
let taskPath = path.join(__dirname, '..', 'msbuild.js');
let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath);
tr.setInput('solution', '**/*.sln');
tr.setInput('platform', '$(Pl... | "checkPath": {
"/home/bin/xbuild": true
},
"findMatch": {
"**/*.sln": [
"/user/build/fun.sln"
]
},
"exec": {
"/home/bin/xbuild /user/build/fun.sln /p:Platform=$(Platform) /p:Configuration=$(Configuration)": {
"code": 0,
"stdout": "x... | // provide answers for task mock
let a: ma.TaskLibAnswers = <ma.TaskLibAnswers>{
"which": {
"xbuild": "/home/bin/xbuild"
}, | random_line_split |
convert-images-spec.js | var fs = require('fs');
var PNG = require('../lib/png').PNG;
var test = require('tape');
var noLargeOption = process.argv.indexOf("nolarge") >= 0;
fs.readdir(__dirname + '/in/', function (err, files) {
if (err) throw err;
files = files.filter(function (file) {
return (!noLargeOption || !file.match(/large/i))... |
test('convert sync - ' + file, function (t) {
t.timeoutAfter(1000 * 60 * 5);
var data = fs.readFileSync(__dirname + '/in/' + file);
try {
var png = PNG.sync.read(data);
} catch (e) {
if (!expectedError) {
t.fail('Unexpected error parsing..' + file + '\n' + e.mes... | {
expectedError = true;
} | conditional_block |
convert-images-spec.js | var fs = require('fs');
var PNG = require('../lib/png').PNG;
var test = require('tape');
var noLargeOption = process.argv.indexOf("nolarge") >= 0;
fs.readdir(__dirname + '/in/', function (err, files) {
if (err) throw err;
files = files.filter(function (file) {
return (!noLargeOption || !file.match(/large/i))... | });
test('convert async - ' + file, function (t) {
t.timeoutAfter(1000 * 60 * 5);
fs.createReadStream(__dirname + '/in/' + file)
.pipe(new PNG())
.on('error', function (err) {
if (!expectedError) {
t.fail("Async: Unexpected error parsing.." + file + '\n' + er... | .on("finish", function () {
t.pass("completed");
t.end();
})); | random_line_split |
Header.js | import React, { Component } from 'react'
import { connect } from 'react-redux'
import { setSearchTerm } from './actionCreators'
import { Link } from 'react-router'
class Header extends Component {
constructor (props) {
super(props)
this.handleSearchTermChange = this.handleSearchTermChange.bind(this)
}
| (event) {
this.props.dispatch(setSearchTerm(event.target.value))
}
render () {
let utilSpace
if (this.props.showSearch) {
utilSpace = <input onChange={this.handleSearchTermChange} value={this.props.searchTerm} type='text' placeholder='Search' />
} else {
utilSpace = (
<h2>
... | handleSearchTermChange | identifier_name |
Header.js | import React, { Component } from 'react'
import { connect } from 'react-redux'
import { setSearchTerm } from './actionCreators'
import { Link } from 'react-router'
class Header extends Component {
constructor (props) {
super(props)
this.handleSearchTermChange = this.handleSearchTermChange.bind(this)
}
h... |
return (
<header>
<h1>
<Link to='/'>
jordaflix
</Link>
</h1>
{utilSpace}
</header>
)
}
}
const mapStateToProps = (state) => {
return {
searchTerm: state.searchTerm
}
}
const { func, bool, string } = React.PropTypes
Header.propTypes ... | {
utilSpace = (
<h2>
<Link to='/search'>Back</Link>
</h2>
)
} | conditional_block |
Header.js | import React, { Component } from 'react'
import { connect } from 'react-redux'
import { setSearchTerm } from './actionCreators'
import { Link } from 'react-router'
class Header extends Component {
constructor (props) {
super(props)
this.handleSearchTermChange = this.handleSearchTermChange.bind(this)
}
h... | utilSpace = (
<h2>
<Link to='/search'>Back</Link>
</h2>
)
}
return (
<header>
<h1>
<Link to='/'>
jordaflix
</Link>
</h1>
{utilSpace}
</header>
)
}
}
const mapStateToProps = (state) => {
return {
... | utilSpace = <input onChange={this.handleSearchTermChange} value={this.props.searchTerm} type='text' placeholder='Search' />
} else { | random_line_split |
AppVersionString.ts | /*
Copyright 2016 Sony Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agre... | }
} | this.otherinfo = separateString[3];
}
}
} | random_line_split |
AppVersionString.ts | /*
Copyright 2016 Sony Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agre... | rateString[3];
}
}
}
}
}
| TION_NAME + "version block num is invalid : " + separateString.length);
return;
}
this.otherinfo = sepa | conditional_block |
AppVersionString.ts | /*
Copyright 2016 Sony Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agre... | ;
const FUNCTION_NAME: string = this.TAG + ": constructor : ";
if (!stringVersion) {
console.warn(FUNCTION_NAME + "stringVersion is undefined");
return;
}
let separateString: string[] = stri... | identifier_body | |
AppVersionString.ts | /*
Copyright 2016 Sony Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agre... | xtends VersionString {
private otherinfo: string;
private TAG: string = "[Garage.Model.Version.AppVersionString] ";
// 比較系のもので otherInfo の比較は行わない事に注意。
constructor(stringVersion: string) {
super(stringVersion);
co... | pVersionString e | identifier_name |
parser-unicode-whitespace.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | // 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 according to those terms.
// Beware editing: it has numerous whitespace characters which are important.
// It con... | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
parser-unicode-whitespace.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
assert_eq!(4+
7 * 2
/3*
2
, 4 + 7 * 2 / 3 * 2);
}
| identifier_body | |
parser-unicode-whitespace.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
assert_eq!(4+
7 * 2
/3*
2
, 4 + 7 * 2 / 3 * 2);
}
| main | identifier_name |
formfields.py | # -*- coding: utf-8 -*-
#
# This file is part of the jabber.at homepage (https://github.com/jabber-at/hp).
#
# This project 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 (... |
# path (url or name of TARGET_NAMED_URL)
forms.CharField(required=False, label=_('URL/URL name'), widget=text_widget),
# args (for TARGET_NAMED_URL args)
forms.CharField(required=False, label=_('args'), widget=text_widget),
# kwargs (for TARGET_NAMED_URL kw... | is_admin = kwargs.pop('admin', False) # if we're on an admin page
model_choices = []
# TODO: make default models configurable
for model in kwargs.pop('models', ['blog.page', 'blog.blogpost']):
if isinstance(model, str):
app_label, model = model.split('.', 1)
... | identifier_body |
formfields.py | # -*- coding: utf-8 -*-
#
# This file is part of the jabber.at homepage (https://github.com/jabber-at/hp).
#
# This project 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 (... | (forms.MultiValueField):
"""Form field for :py:class:`~core.modelfields.LinkTarget` database fields.
Parameters
----------
admin : bool, optional
If True, the field will use the admin widgets instead of the default widgets.
models : list, optional
A list of models this target could... | LinkTargetField | identifier_name |
formfields.py | # -*- coding: utf-8 -*-
#
# This file is part of the jabber.at homepage (https://github.com/jabber-at/hp).
#
# This project 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 (... |
model_choices = ContentType.objects.filter(pk__in=[c.pk for c in model_choices])
text_widget = forms.TextInput
if is_admin is True:
text_widget = AdminTextInputWidget
fields = (
forms.ChoiceField(choices=TARGET_CHOICES.items(), widget=forms.RadioSelect(attrs={
... | model_choices.append(ContentType.objects.get_for_model(model)) | conditional_block |
formfields.py | # -*- coding: utf-8 -*-
#
# This file is part of the jabber.at homepage (https://github.com/jabber-at/hp).
#
# This project 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 (... | widgets = []
for field in fields:
w = field.widget
w.label = field.label
widgets.append(w)
self.widget = LinkTargetWidget(widgets=widgets, models=model_choices)
super(LinkTargetField, self).__init__(fields=fields,
... | })),
)
# enrich widgets with label, so we can output it in LinkTargetWidget.render() | random_line_split |
main-menu.controller.spec.js | /* jshint -W030 */
'use strict';
describe('Controller: MainMenuController', function () {
// load the controller's module
beforeEach(module('ftiApp.mainMenu'));
var controller;
var menuEntry = {name: 'test', state: 'test.main'};
var mainMenuMock = {
getMenu: function () {
return [menuEntry]
}
};
var $m... | beforeEach(inject(function ($controller, $rootScope) {
controller = $controller('MainMenuController', {
mainMenu: mainMenuMock,
$mdSidenav: $mdSidenavMock
});
}));
it('object should exist', function () {
Should.exist(controller);
controller.should.be.an.Object;
});
it('should have an items property... | // Initialize the controller and a mock scope | random_line_split |
test.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn main() {
let program = r#"
#[no_mangle]
pub static TEST_STATIC: i32 = 42;
"#;
let program2 = r#"
#[no_mangle]
pub fn test_add(a: i32, b: i32) -> i32 { a + b }
"#;
let mut path = match std::env::args().nth(2) {
Some(path) => PathBuf::from(&path),
None => panic!("m... | random_line_split | |
test.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let ast_map = driver::assign_node_ids_and_map(&sess, &mut forest);
driver::phase_3_run_analysis_passes(
sess, ast_map, &arenas, id, MakeGlobMap::No, |tcx, analysis| {
let trans = driver::phase_4_translate_to_llvm(tcx, analysis);
let crates = tcx.sess.cstore.get_use... | {
let input = Input::Str(input.to_string());
let thread = Builder::new().name("compile_program".to_string());
let handle = thread.spawn(move || {
let opts = build_exec_options(sysroot);
let sess = build_session(opts, None, Registry::new(&rustc::DIAGNOSTICS));
rustc_lint::register_bu... | identifier_body |
test.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (input: &str, sysroot: PathBuf)
-> Option<(llvm::ModuleRef, Vec<PathBuf>)> {
let input = Input::Str(input.to_string());
let thread = Builder::new().name("compile_program".to_string());
let handle = thread.spawn(move || {
let opts = build_exec_options(sysroot);
let sess = ... | compile_program | identifier_name |
test_utils.py | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | fsmanager.restore_cache(old_caches[1]) | random_line_split | |
test_utils.py | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | (username, groupname, permname, appname):
user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
perm, created = HuePermission.objects.get_or_create(app=appname, action=permname)
GroupPermission.objects.get_or_create(group=group, hue_permission=perm)
... | add_permission | identifier_name |
test_utils.py | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cd... | user = User.objects.get(username=username)
group, created = Group.objects.get_or_create(name=groupname)
if user.groups.filter(name=group.name).exists():
user.groups.remove(group)
user.save() | identifier_body |
test_utils.py | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
def reformat_json(json_obj):
if isinstance(json_obj, basestring):
return json.dumps(json.loads(json_obj))
else:
return json.dumps(json_obj)
def reformat_xml(xml_obj):
if isinstance(xml_obj, basestring):
return etree.tostring(objectify.fromstring(xml_obj, etree.XMLParser(strip_cd... | user.groups.remove(group)
user.save() | conditional_block |
function_wrapper_cpp.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in w... | use super::type_to_cpp::{type_to_cpp, CppNameMap};
impl TypeConversionPolicy {
pub(super) fn unconverted_type(
&self,
cpp_name_map: &CppNameMap,
) -> Result<String, ConvertError> {
match self.cpp_conversion {
CppConversionType::FromUniquePtrToValue => self.wrapped_type(cpp_n... | random_line_split | |
function_wrapper_cpp.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in w... |
}
| {
Ok(match self.cpp_conversion {
CppConversionType::None => {
if type_lacks_copy_constructor(&self.unwrapped_type) && !use_rvo {
format!("std::move({})", var_name)
} else {
var_name.to_string()
}
}
... | identifier_body |
function_wrapper_cpp.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in w... | (&self, cpp_name_map: &CppNameMap) -> Result<String, ConvertError> {
match self.cpp_conversion {
CppConversionType::FromValueToUniquePtr => self.wrapped_type(cpp_name_map),
_ => self.unwrapped_type_as_string(cpp_name_map),
}
}
fn unwrapped_type_as_string(&self, cpp_name_... | converted_type | identifier_name |
mock_tool.py | # 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 of conditions and the f... | return 'echo' | identifier_body | |
mock_tool.py | # 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 of conditions and the f... | (self):
return 'echo'
| path | identifier_name |
mock_tool.py | # 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 of conditions and the f... | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from blinkpy.common.host_mock import MockHost
class MockBlinkTool(MockHost):
def __init__(self, *args, **kwargs):
MockHost.__init__(self, *args, **kwargs)
de... | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | random_line_split |
gaia_auth.py | # Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
| import urllib
DEFAULT_GAIA_URL = "https://www.google.com:443/accounts/ClientLogin"
class GaiaAuthenticator:
def __init__(self, service, url = DEFAULT_GAIA_URL):
self._service = service
self._url = url
## Logins to gaia and returns auth token.
def authenticate(self, email, passwd):
params = urllib.u... | import getpass
import os | random_line_split |
gaia_auth.py | # Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import getpass
import os
import urllib
DEFAULT_GAIA_URL = "https://www.google.com:443/accounts/ClientLogin"
class GaiaAuthenticator:
def __init__(sel... |
raise Exception("Gaia didn't return auth token: " + result)
| auth_string = line[5:]
return auth_string | conditional_block |
gaia_auth.py | # Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import getpass
import os
import urllib
DEFAULT_GAIA_URL = "https://www.google.com:443/accounts/ClientLogin"
class GaiaAuthenticator:
def __init__(sel... | params = urllib.urlencode({'Email': email, 'Passwd': passwd,
'source': 'chromoting',
'service': self._service,
'PersistentCookie': 'true',
'accountType': 'GOOGLE'})
f = urllib.urlopen(self._ur... | identifier_body | |
gaia_auth.py | # Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import getpass
import os
import urllib
DEFAULT_GAIA_URL = "https://www.google.com:443/accounts/ClientLogin"
class GaiaAuthenticator:
def __init__(sel... | (self, email, passwd):
params = urllib.urlencode({'Email': email, 'Passwd': passwd,
'source': 'chromoting',
'service': self._service,
'PersistentCookie': 'true',
'accountType': 'GOOGLE'})
... | authenticate | identifier_name |
task-comm-13.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | while i < number_of_messages { tx.send(start + i); i += 1; }
}
pub fn main() {
println!("Check that we don't deadlock.");
let (tx, rx) = channel();
task::try(proc() { start(&tx, 0, 10) });
println!("Joined task");
} | use std::task;
fn start(tx: &Sender<int>, start: int, number_of_messages: int) {
let mut i: int = 0; | random_line_split |
task-comm-13.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub fn main() {
println!("Check that we don't deadlock.");
let (tx, rx) = channel();
task::try(proc() { start(&tx, 0, 10) });
println!("Joined task");
}
| {
let mut i: int = 0;
while i < number_of_messages { tx.send(start + i); i += 1; }
} | identifier_body |
task-comm-13.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
println!("Check that we don't deadlock.");
let (tx, rx) = channel();
task::try(proc() { start(&tx, 0, 10) });
println!("Joined task");
}
| main | identifier_name |
config.rs | use std::io::Read;
use std;
use serde_json;
#[derive(Serialize, Deserialize)]
pub struct ConfigData{
pub username:String,
pub password:String,
pub channels:Vec<String>,
pub admins:Vec<String>,
pub nyaa:Nyaa,
}
#[derive(Serialize, Deserialize,Clone)]
pub struct Nyaa{
pub delay:u64,
}
#[derive(... | assert_eq!("name",cd.username());
assert_eq!("oauth:1234",cd.password());
assert_eq!("___4Header",cd.channels()[0]);
assert_eq!("PagChomp",cd.channels()[1]);
assert_eq!("Keepo",cd.channels()[2]);
assert_eq!(3,cd.channels().len());
assert_eq!("443297327",cd.admins(... | let mut cd = ConfigData::new("tests/config_test.json").unwrap(); | random_line_split |
config.rs | use std::io::Read;
use std;
use serde_json;
#[derive(Serialize, Deserialize)]
pub struct ConfigData{
pub username:String,
pub password:String,
pub channels:Vec<String>,
pub admins:Vec<String>,
pub nyaa:Nyaa,
}
#[derive(Serialize, Deserialize,Clone)]
pub struct | {
pub delay:u64,
}
#[derive(Debug)]
pub enum ConfigErr{
Parse,
Open,
Read
}
impl ConfigData{
pub fn new(file: &str)->Result<ConfigData,ConfigErr>{
let s = try!(file_to_string(file));
serde_json::from_str(&s).map_err(|_|ConfigErr::Parse)
}
}
fn file_to_string(file: &str)->Res... | Nyaa | identifier_name |
utils_libguestfs.py | """
libguestfs tools test utility functions.
"""
import logging
from autotest.client import os_dep, utils
from autotest.client.shared import error
import propcan
| """
Error of libguestfs-tool command.
"""
def __init__(self, details=''):
self.details = details
Exception.__init__(self)
def __str__(self):
return str(self.details)
def lgf_cmd_check(cmd):
"""
To check whether the cmd is supported on this host.
@param cmd: ... |
class LibguestfsCmdError(Exception): | random_line_split |
utils_libguestfs.py | """
libguestfs tools test utility functions.
"""
import logging
from autotest.client import os_dep, utils
from autotest.client.shared import error
import propcan
class LibguestfsCmdError(Exception):
"""
Error of libguestfs-tool command.
"""
def __init__(self, details=''):
self.details = det... | except error.CmdError, detail:
raise LibguestfsCmdError(detail)
if debug:
logging.debug("status: %s", ret.exit_status)
logging.debug("stdout: %s", ret.stdout.strip())
logging.debug("stderr: %s", ret.stderr.strip())
# Return CmdResult instance when ignore_status is True
... | """
Interface of libguestfs tools' commands.
@param cmd: Command line to execute.
@param dargs: standardized command keywords.
@return: CmdResult object.
@raise: LibguestfsCmdError if non-zero exit status
and ignore_status=False
"""
ignore_status = dargs.get('ignore_status', Tru... | identifier_body |
utils_libguestfs.py | """
libguestfs tools test utility functions.
"""
import logging
from autotest.client import os_dep, utils
from autotest.client.shared import error
import propcan
class LibguestfsCmdError(Exception):
"""
Error of libguestfs-tool command.
"""
def __init__(self, details=''):
self.details = det... | (cmd, **dargs):
"""
Interface of libguestfs tools' commands.
@param cmd: Command line to execute.
@param dargs: standardized command keywords.
@return: CmdResult object.
@raise: LibguestfsCmdError if non-zero exit status
and ignore_status=False
"""
ignore_status = dargs.get(... | lgf_command | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.