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
openbsd_base.rs
// Copyright 2014-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-MI...
() -> TargetOptions { TargetOptions { linker: "cc".to_string(), dynamic_linking: true, executables: true, morestack: false, linker_is_gnu: true, has_rpath: true, pre_link_args: vec!( // GNU-style linkers will use this to omit linking to libraries ...
opts
identifier_name
openbsd_base.rs
// Copyright 2014-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-MI...
{ TargetOptions { linker: "cc".to_string(), dynamic_linking: true, executables: true, morestack: false, linker_is_gnu: true, has_rpath: true, pre_link_args: vec!( // GNU-style linkers will use this to omit linking to libraries // which ...
identifier_body
openbsd_base.rs
// Copyright 2014-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-MI...
TargetOptions { linker: "cc".to_string(), dynamic_linking: true, executables: true, morestack: false, linker_is_gnu: true, has_rpath: true, pre_link_args: vec!( // GNU-style linkers will use this to omit linking to libraries // which do...
random_line_split
model.api.js
import _ from 'lodash' export const composite = (commands) => { if (!Array.isArray(commands)) { return commands; } if (commands.length === 1) { return commands[0]; } return { 'composite': _.chain(commands).reduce((o, v, idx) => { o[idx] = v; return o; }, {}).value() }; }; export const addElement = (json) ...
name: name, ...payload } });
random_line_split
model.api.js
import _ from 'lodash' export const composite = (commands) => { if (!Array.isArray(commands))
if (commands.length === 1) { return commands[0]; } return { 'composite': _.chain(commands).reduce((o, v, idx) => { o[idx] = v; return o; }, {}).value() }; }; export const addElement = (json) => ({ 'add-element' : json }); export const addConnector = (json) => ({ 'add-connector' : json }); export const addRe...
{ return commands; }
conditional_block
resource_manager.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 i...
{ pub(super) cluster_manager: SharedClusterManager, pub(super) filter_manager: SharedFilterManager, pub(super) execution_result_rx: oneshot::Receiver<crate::Result<()>>, } impl StaticResourceManagers { pub(super) fn new( endpoints: Endpoints, filter_chain: Arc<FilterChain>, ) -> Re...
DynamicResourceManagers
identifier_name
resource_manager.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 i...
) -> Result<DynamicResourceManagers, InitializeError> { let (cluster_updates_tx, cluster_updates_rx) = Self::cluster_updates_channel(); let (filter_chain_updates_tx, filter_chain_updates_rx) = Self::filter_chain_updates_channel(); let listener_manager_args = ListenerManagerArgs:...
shutdown_rx: watch::Receiver<()>,
random_line_split
p24.rs
use rand::{weak_rng, Rng, SeedableRng}; use util::{MT19937Rng, prng_crypt}; #[test] fn run()
ks_rng.reseed(s); let test_ctxt = prng_crypt(&mut ks_rng, &test_input); &ctxt[2..] == &test_ctxt[2..] }); assert!(rec_seed.is_some()); assert_eq!(seed, rec_seed.unwrap()); }
{ let mut wk_rng = weak_rng(); // rng seeded from weak 16-bit seed let seed = wk_rng.next_u32() & 0xFFFF; let mut ks_rng = MT19937Rng::from_seed(seed); let attack_input = "AAAAAAAAAAAAAA".as_bytes(); let rand_prefix: [u8; 2] = wk_rng.gen(); let mut input = Vec::new(); input.extend_from...
identifier_body
p24.rs
use rand::{weak_rng, Rng, SeedableRng}; use util::{MT19937Rng, prng_crypt}; #[test] fn
() { let mut wk_rng = weak_rng(); // rng seeded from weak 16-bit seed let seed = wk_rng.next_u32() & 0xFFFF; let mut ks_rng = MT19937Rng::from_seed(seed); let attack_input = "AAAAAAAAAAAAAA".as_bytes(); let rand_prefix: [u8; 2] = wk_rng.gen(); let mut input = Vec::new(); input.extend_f...
run
identifier_name
p24.rs
use rand::{weak_rng, Rng, SeedableRng}; use util::{MT19937Rng, prng_crypt}; #[test] fn run() { let mut wk_rng = weak_rng(); // rng seeded from weak 16-bit seed let seed = wk_rng.next_u32() & 0xFFFF; let mut ks_rng = MT19937Rng::from_seed(seed); let attack_input = "AAAAAAAAAAAAAA".as_bytes(); ...
.find(|&s: &u32| { ks_rng.reseed(s); let test_ctxt = prng_crypt(&mut ks_rng, &test_input); &ctxt[2..] == &test_ctxt[2..] }); assert!(rec_seed.is_some()); assert_eq!(seed, rec_seed.unwrap()); }
let rec_seed = (0..(1 << 16))
random_line_split
test_sup.rs
, net::TcpListener, path::{Path, PathBuf}, process::{Child, Command, Stdio}, string::ToString, sync::Mutex, thread, time::Duration}; use crate::hcore::url::BLDR_URL_ENVVAR; use rand::{self, ...
service_group: &str) -> TestSup where R: AsRef<Path> { // We'll give 10 tries to find a free port number let http_port = unclaimed_port(10); let butterfly_port = unclaimed_port(10); let control_port = unc...
random_line_split
test_sup.rs
net::TcpListener, path::{Path, PathBuf}, process::{Child, Command, Stdio}, string::ToString, sync::Mutex, thread, time::Duration}; use crate::hcore::url::BLDR_URL_ENVVAR; use rand::{self, ...
impl TestSup { /// Create a new `TestSup` that will listen on randomly-selected /// ports for both gossip and HTTP requests so tests run in /// parallel don't step on each other. /// /// See also `new`. pub fn new_with_random_ports<R>(fs_root: R, origin: &st...
{ if env::args().any(|arg| arg == "--nocapture") { true } else { match env::var("RUST_TEST_NOCAPTURE") { Ok(val) => &val != "0", Err(_) => false, } } }
identifier_body
test_sup.rs
net::TcpListener, path::{Path, PathBuf}, process::{Child, Command, Stdio}, string::ToString, sync::Mutex, thread, time::Duration}; use crate::hcore::url::BLDR_URL_ENVVAR; use rand::{self, ...
{ pub hab_root: PathBuf, pub origin_name: String, pub package_name: String, pub service_group: String, pub http_port: u16, pub butterfly_port: u16, pub control_port: u16, pub butterfly_client: test_butterfly::Client, pub cmd: Command, ...
TestSup
identifier_name
test_legacy_v2_compatible_wrapper.py
# Copyright 2015 Intel Corporation. # 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 requir...
(self): response = self.api.api_post('os-keypairs', {"keypair": {"name": "test", "foooooo": "barrrrrr"}}, headers={wsgi.API_VERSION_REQUEST_HEADER: '2.100'}) self.assertNotIn(wsgi.API_VERSION_REQUEST_HEADER, response.headers) self.assertNotIn('Vary', response.headers) ...
test_request_without_addtional_properties_check
identifier_name
test_legacy_v2_compatible_wrapper.py
# Copyright 2015 Intel Corporation. # 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 requir...
from nova.api.openstack import wsgi from nova.tests.functional.api import client from nova.tests.functional import api_paste_fixture from nova.tests.functional import test_servers from nova.tests.unit import fake_network class LegacyV2CompatibleTestBase(test_servers.ServersTestBase): _api_version = 'v2' def ...
# License for the specific language governing permissions and limitations # under the License. from nova.api import openstack from nova.api.openstack import compute
random_line_split
test_legacy_v2_compatible_wrapper.py
# Copyright 2015 Intel Corporation. # 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 requir...
fake_network.set_stub_network_methods(self.stubs) server = self._build_minimal_create_server_request() post = {'server': server} created_server = self.api.post_server(post) exc = self.assertRaises(client.OpenStackApiException, self.api.post_server_metadata...
identifier_body
test_callbacks.py
import pytest from collections import namedtuple from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_less from skopt import dummy_minimize from skopt.benchmarks import bench1 from skopt.callbacks import TimerCallback from skopt.callbacks import DeltaYStopper @pytest.mark.fast_te...
(): callback = TimerCallback() dummy_minimize(bench1, [(-1.0, 1.0)], callback=callback, n_calls=10) assert_equal(len(callback.iter_time), 10) assert_less(0.0, sum(callback.iter_time)) @pytest.mark.fast_test def test_deltay_stopper(): deltay = DeltaYStopper(0.2, 3) Result = namedtuple('Result'...
test_timer_callback
identifier_name
test_callbacks.py
from collections import namedtuple from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_less from skopt import dummy_minimize from skopt.benchmarks import bench1 from skopt.callbacks import TimerCallback from skopt.callbacks import DeltaYStopper @pytest.mark.fast_test def test_tim...
import pytest
random_line_split
test_callbacks.py
import pytest from collections import namedtuple from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_less from skopt import dummy_minimize from skopt.benchmarks import bench1 from skopt.callbacks import TimerCallback from skopt.callbacks import DeltaYStopper @pytest.mark.fast_te...
deltay = DeltaYStopper(0.2, 3) Result = namedtuple('Result', ['func_vals']) assert deltay(Result([0, 1, 2, 3, 4, 0.1, 0.19])) assert not deltay(Result([0, 1, 2, 3, 4, 0.1])) assert deltay(Result([0, 1])) is None
identifier_body
default_handler.py
#!/usr/bin/python # -*- coding: utf-8 -*- # import json # replace with simplejson import simplejson as json import os import time import logging import traceback import sys from oslo_config import cfg from yabgp.common import constants as bgp_cons from yabgp.handler import BaseHandler CONF = cfg.CONF LOG = loggin...
(self, peer, msg): pass
on_established
identifier_name
default_handler.py
#!/usr/bin/python # -*- coding: utf-8 -*- # import json # replace with simplejson import simplejson as json import os import time import logging import traceback import sys from oslo_config import cfg from yabgp.common import constants as bgp_cons from yabgp.handler import BaseHandler CONF = cfg.CONF LOG = loggin...
def init_msg_file(self, peer_addr): msg_file_path_for_peer = os.path.join( CONF.message.write_dir, peer_addr ) if not os.path.exists(msg_file_path_for_peer): os.makedirs(msg_file_path_for_peer) LOG.info('Create dir %s for peer %s', msg_file_p...
if CONF.message.write_disk: self.init_msg_file(CONF.bgp.running_config['remote_addr'].lower())
identifier_body
default_handler.py
#!/usr/bin/python # -*- coding: utf-8 -*- # import json # replace with simplejson import simplejson as json import os import time import logging import traceback import sys from oslo_config import cfg from yabgp.common import constants as bgp_cons from yabgp.handler import BaseHandler CONF = cfg.CONF LOG = loggin...
default=False, help='Whether write keepalive message to disk') ] CONF.register_opts(MSG_PROCESS_OPTS, group='message') class DefaultHandler(BaseHandler): def __init__(self): super(DefaultHandler, self).__init__() ''' {<peer>: (<path>, <current file>)} ...
default=500, help='The Max size of one BGP message file, the unit is MB'), cfg.BoolOpt('write_keepalive',
random_line_split
default_handler.py
#!/usr/bin/python # -*- coding: utf-8 -*- # import json # replace with simplejson import simplejson as json import os import time import logging import traceback import sys from oslo_config import cfg from yabgp.common import constants as bgp_cons from yabgp.handler import BaseHandler CONF = cfg.CONF LOG = loggin...
file_list.sort() msg_file_name = file_list[-1] try: with open(msg_path + msg_file_name, 'r') as fh: line = None for line in fh: pass last = line if line: if last.startswith('['): ...
return last_seq, None
conditional_block
install.py
from ceph_deploy.util import templates from ceph_deploy.lib import remoto from ceph_deploy.hosts.common import map_components from ceph_deploy.util.paths import gpg NON_SPLIT_PACKAGES = ['ceph-osd', 'ceph-mon', 'ceph-mds'] def rpm_dist(distro): if distro.normalized_name in ['redhat', 'centos', 'scientific'] and...
packages = map_components( NON_SPLIT_PACKAGES, kw.pop('components', []) ) logger = distro.conn.logger # Get some defaults name = kw.pop('name', '%s repo' % reponame) enabled = kw.pop('enabled', 1) gpgcheck = kw.pop('gpgcheck', 1) install_ceph = kw.pop('install_ceph', Fals...
if extra_installs and packages: distro.packager.install(packages) def repo_install(distro, reponame, baseurl, gpgkey, **kw):
random_line_split
install.py
from ceph_deploy.util import templates from ceph_deploy.lib import remoto from ceph_deploy.hosts.common import map_components from ceph_deploy.util.paths import gpg NON_SPLIT_PACKAGES = ['ceph-osd', 'ceph-mon', 'ceph-mds'] def rpm_dist(distro): if distro.normalized_name in ['redhat', 'centos', 'scientific'] and...
return 'el6' def install(distro, version_kind, version, adjust_repos, **kw): packages = map_components( NON_SPLIT_PACKAGES, kw.pop('components', []) ) logger = distro.conn.logger release = distro.release machine = distro.machine_type repo_part = repository_url_part(distro...
""" Historically everything CentOS, RHEL, and Scientific has been mapped to `el6` urls, but as we are adding repositories for `rhel`, the URLs should map correctly to, say, `rhel6` or `rhel7`. This function looks into the `distro` object and determines the right url part for the given distro, falli...
identifier_body
install.py
from ceph_deploy.util import templates from ceph_deploy.lib import remoto from ceph_deploy.hosts.common import map_components from ceph_deploy.util.paths import gpg NON_SPLIT_PACKAGES = ['ceph-osd', 'ceph-mon', 'ceph-mds'] def rpm_dist(distro): if distro.normalized_name in ['redhat', 'centos', 'scientific'] and...
(distro, version_kind, version, adjust_repos, **kw): packages = map_components( NON_SPLIT_PACKAGES, kw.pop('components', []) ) logger = distro.conn.logger release = distro.release machine = distro.machine_type repo_part = repository_url_part(distro) dist = rpm_dist(distro) ...
install
identifier_name
install.py
from ceph_deploy.util import templates from ceph_deploy.lib import remoto from ceph_deploy.hosts.common import map_components from ceph_deploy.util.paths import gpg NON_SPLIT_PACKAGES = ['ceph-osd', 'ceph-mon', 'ceph-mds'] def rpm_dist(distro): if distro.normalized_name in ['redhat', 'centos', 'scientific'] and...
return 'el6' def install(distro, version_kind, version, adjust_repos, **kw): packages = map_components( NON_SPLIT_PACKAGES, kw.pop('components', []) ) logger = distro.conn.logger release = distro.release machine = distro.machine_type repo_part = repository_url_part(distro...
if distro.normalized_name == 'redhat': return 'rhel' + distro.normalized_release.major if distro.normalized_name in ['centos', 'scientific']: return 'el' + distro.normalized_release.major
conditional_block
indexing_slicing.rs
//! lint on indexing and slicing operations use clippy_utils::consts::{constant, Constant}; use clippy_utils::diagnostics::{span_lint, span_lint_and_help}; use clippy_utils::higher; use rustc_ast::ast::RangeLimits; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use ...
}, Some(_) => None, None => Some(array_size), }; (start, end) }
{ Some(x) }
conditional_block
indexing_slicing.rs
//! lint on indexing and slicing operations use clippy_utils::consts::{constant, Constant}; use clippy_utils::diagnostics::{span_lint, span_lint_and_help}; use clippy_utils::higher; use rustc_ast::ast::RangeLimits; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use ...
"range is out of bounds", ); return; } } if let (_, Some(end)) = const_range { if end > size { span_lint( ...
{ if let ExprKind::Index(array, index) = &expr.kind { let ty = cx.typeck_results().expr_ty(array).peel_refs(); if let Some(range) = higher::Range::hir(index) { // Ranged indexes, i.e., &x[n..m], &x[n..], &x[..n] and &x[..] if let ty::Array(_, s) = ty.kind(...
identifier_body
indexing_slicing.rs
//! lint on indexing and slicing operations use clippy_utils::consts::{constant, Constant}; use clippy_utils::diagnostics::{span_lint, span_lint_and_help}; use clippy_utils::higher; use rustc_ast::ast::RangeLimits; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use ...
/// &x[2..100]; /// &x[2..]; /// &x[..100]; /// /// // Good /// x.get(2); /// x.get(2..100); /// x.get(2..); /// x.get(..100); /// /// // Array /// let y = [0, 1, 2, 3]; /// /// // Bad /// &y[10..100]; /// &y[10..]; /// &y[..100]; /// /// // Go...
/// // Vector /// let x = vec![0; 5]; /// /// // Bad /// x[2];
random_line_split
indexing_slicing.rs
//! lint on indexing and slicing operations use clippy_utils::consts::{constant, Constant}; use clippy_utils::diagnostics::{span_lint, span_lint_and_help}; use clippy_utils::higher; use rustc_ast::ast::RangeLimits; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use ...
(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if let ExprKind::Index(array, index) = &expr.kind { let ty = cx.typeck_results().expr_ty(array).peel_refs(); if let Some(range) = higher::Range::hir(index) { // Ranged indexes, i.e., &x[n..m], &x[n..], &x[..n] an...
check_expr
identifier_name
Scene.tsx
/* eslint react/jsx-props-no-spreading: 0 */ import React from 'react'; // Libs import { Box, CubeCamera } from '@react-three/drei'; const Sphere = ({ ...props }: any) => { const ref = React.useRef<THREE.Group>(); return ( <CubeCamera {...props}> {(texture) => ( <mesh ref={ref}> <sph...
roughness={0} /> </mesh> )} </CubeCamera> ); }; const Scene: React.FC = () => ( <group> <fog args={['#f0f0f0', 100, 200]} attach="fog" /> <Sphere position={[-10, 10, 0]} /> <Box args={[5, 5, 5]} material-color="hotpink" position-y={1.5} /> <gridHelper args...
metalness={1}
random_line_split
iter_any.rs
fn main()
{ let vec1 = vec![1, 2, 3]; let vec2 = vec![4, 5, 6]; // 对 vec 的 `iter()` 产出 `&i32`(原文:`iter()` for vecs yields // `&i32`)。解构成 `i32` 类型。 println!("2 in vec1: {}", vec1.iter() .any(|&x| x == 2)); // 对 vec 的 `into_iter()` 产出 `i32` 类型。无需解构。 println!("2 in vec2: {}", vec2.into_iter().any(| ...
identifier_body
iter_any.rs
fn main() { let vec1 = vec![1, 2, 3]; let vec2 = vec![4, 5, 6]; // 对 vec 的 `iter()` 产出 `&i32`(原文:`iter()` for vecs yields // `&i32`)。解构成 `i32` 类型。 println!("2 in vec1: {}", vec1.iter() .any(|&x| x == 2)); // 对 vec 的 `into_iter()` 产出 `i32` 类型。无需解构。 println!("2 in vec2: {}", vec2.into_ite...
println!("2 in array2: {}", array2.into_iter().any(|&x| x == 2)); }
random_line_split
iter_any.rs
fn
() { let vec1 = vec![1, 2, 3]; let vec2 = vec![4, 5, 6]; // 对 vec 的 `iter()` 产出 `&i32`(原文:`iter()` for vecs yields // `&i32`)。解构成 `i32` 类型。 println!("2 in vec1: {}", vec1.iter() .any(|&x| x == 2)); // 对 vec 的 `into_iter()` 产出 `i32` 类型。无需解构。 println!("2 in vec2: {}", vec2.into_iter().any...
main
identifier_name
container.tsx
import * as Container from '../../../util/container' import {memoize} from '../../../util/memoize' import DestinationPicker from '.' import * as Types from '../../../constants/types/fs' import * as Constants from '../../../constants/fs' import * as FsGen from '../../../actions/fs-gen' import {isMobile} from '../../../c...
dispatch(FsGen.createMove({destinationParentPath})) dispatch(RouteTreeGen.createClearModals()) dispatch( nav.safeNavigateAppendPayload({ path: [{props: {path: destinationParentPath}, selected: 'fsRoot'}], }) ) }, _onNewFolder: destinationParentPath => disp...
_onMoveHere: destinationParentPath => {
random_line_split
container.tsx
import * as Container from '../../../util/container' import {memoize} from '../../../util/memoize' import DestinationPicker from '.' import * as Types from '../../../constants/types/fs' import * as Constants from '../../../constants/fs' import * as FsGen from '../../../actions/fs-gen' import {isMobile} from '../../../c...
return undefined }) const canMove = memoize( (dp: Types.DestinationPicker, pathItems: Types.PathItems, ownProps: OwnProps) => canCopy(dp, pathItems, ownProps) && dp.source.type === Types.DestinationPickerSource.MoveOrCopy && Constants.pathsInSameTlf(dp.source.path, getDestinationParentPath(dp, ownProp...
{ const source: Types.MoveOrCopySource = dp.source return getDestinationParentPath(dp, ownProps) !== Types.getPathParent(source.path) }
conditional_block
gradient_hf_test.py
import numpy as np from openfermioncirq.experiments.hfvqe.gradient_hf import (rhf_func_generator, rhf_minimization) from openfermioncirq.experiments.hfvqe.molecular_example import make_h6_1_3 def test_rhf_func_gen(): rhf_objective, molecule, parameters, _, _ = make_h6_1_3()
ansatz, energy, _, opdm_func = rhf_func_generator( rhf_objective, initial_occ_vec=[1] * 3 + [0] * 3, get_opdm_func=True) assert np.isclose(molecule.hf_energy, energy(parameters)) test_opdm = opdm_func(parameters) u = ansatz(parameters) initial_opdm = np.diag([1] * 3 + [0] * 3) final_odp...
ansatz, energy, _ = rhf_func_generator(rhf_objective) assert np.isclose(molecule.hf_energy, energy(parameters))
random_line_split
gradient_hf_test.py
import numpy as np from openfermioncirq.experiments.hfvqe.gradient_hf import (rhf_func_generator, rhf_minimization) from openfermioncirq.experiments.hfvqe.molecular_example import make_h6_1_3 def test_rhf_func_gen():
rhf_objective, molecule, parameters, _, _ = make_h6_1_3() ansatz, energy, _ = rhf_func_generator(rhf_objective) assert np.isclose(molecule.hf_energy, energy(parameters)) ansatz, energy, _, opdm_func = rhf_func_generator( rhf_objective, initial_occ_vec=[1] * 3 + [0] * 3, get_opdm_func=True) asse...
identifier_body
gradient_hf_test.py
import numpy as np from openfermioncirq.experiments.hfvqe.gradient_hf import (rhf_func_generator, rhf_minimization) from openfermioncirq.experiments.hfvqe.molecular_example import make_h6_1_3 def
(): rhf_objective, molecule, parameters, _, _ = make_h6_1_3() ansatz, energy, _ = rhf_func_generator(rhf_objective) assert np.isclose(molecule.hf_energy, energy(parameters)) ansatz, energy, _, opdm_func = rhf_func_generator( rhf_objective, initial_occ_vec=[1] * 3 + [0] * 3, get_opdm_func=True) ...
test_rhf_func_gen
identifier_name
logjam-call-graph.js
import * as d3 from "d3"; function logjam_graph_app_data(appCallers) { var r1 = 800 / 2, r0 = r1 - 120, w = 1400, h = w, cw = 700, ch = 420; function colors(s) { return s.match(/.{6}/g).map((x) => "#" + x); }; var category20c = colors("1f77b4aec7e8ff7f0effbb782ca02c98df8ad6...
appCallers.forEach((d) => { var source = indexByName[appName(d.target)], row = matrix[source], scaled_row = scaled_matrix[source], index = indexByName[appName(d.source)]; if (!row) { row = matrix[source] = []; for (var i = -1; ++i < n;) row[i] = 0; } row[index] = d...
{ matrix[i] = []; scaled_matrix[i] = []; for (var j = 0; j < n; j++) { matrix[i][j] = 0; scaled_matrix[i][j] = 0; } }
conditional_block
logjam-call-graph.js
import * as d3 from "d3"; function logjam_graph_app_data(appCallers)
var arc = d3.arc() .innerRadius(r0) .outerRadius(r0 + 20); var svg = d3.select("#call-graph-display").append("svg") .attr("width", w) .attr("height", h) .append("g") .attr("transform", "translate(" + cw + "," + ch + ")"); // Initialize the info display. var inf...
{ var r1 = 800 / 2, r0 = r1 - 120, w = 1400, h = w, cw = 700, ch = 420; function colors(s) { return s.match(/.{6}/g).map((x) => "#" + x); }; var category20c = colors("1f77b4aec7e8ff7f0effbb782ca02c98df8ad62728ff98969467bdc5b0d58c564bc49c94e377c2f7b6d27f7f7fc7c7c7bcbd22dbdb8d...
identifier_body
logjam-call-graph.js
import * as d3 from "d3"; function logjam_graph_app_data(appCallers) { var r1 = 800 / 2, r0 = r1 - 120, w = 1400, h = w, cw = 700, ch = 420; function colors(s) { return s.match(/.{6}/g).map((x) => "#" + x); }; var category20c = colors("1f77b4aec7e8ff7f0effbb782ca02c98df8ad6...
return text; } var g = svg.append("g") .datum(chord(scaled_matrix)); var group = g.append("g") .attr("class", "groups") .selectAll("g") .data((chords) => chords.groups) .enter().append("g"); group.append("path") .style("fill", (d) => fill(d.index)) .style("...
var text = caller + " called " + callee + " " + formatter(n) + " times."; if (m>0) { text += "</br>" + callee + " called " + caller + " " + formatter(m) + " times."; }
random_line_split
logjam-call-graph.js
import * as d3 from "d3"; function logjam_graph_app_data(appCallers) { var r1 = 800 / 2, r0 = r1 - 120, w = 1400, h = w, cw = 700, ch = 420; function colors(s) { return s.match(/.{6}/g).map((x) => "#" + x); }; var category20c = colors("1f77b4aec7e8ff7f0effbb782ca02c98df8ad6...
(name) { return name; } appCallers.forEach((app) => { appNames.add(app.source); appNames.add(app.target); }); Array.from(appNames.values()).sort().forEach((name) => { name = appName(name); if (!(name in indexByName)) { nameByIndex[n] = name; indexByName[name] = n++; } }); ...
appName
identifier_name
descriptionreponamelstm.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from Models.FeatureProcessing import * from keras.models import Sequential from keras.layers import Activation, Dense, LSTM from keras.optimizers import Adam, SGD import numpy as np import abc from ClassificationModule import ClassificationModule class
(ClassificationModule): """A basic lstm neural network""" def __init__(self, num_hidden_layers=3): ClassificationModule.__init__(self, "Description and reponame LSTM", "A LSTM reading the description and reponame character by character") hidden_size = 300 self.maxlen = 300 ...
descriptionreponamelstm
identifier_name
descriptionreponamelstm.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from Models.FeatureProcessing import * from keras.models import Sequential from keras.layers import Activation, Dense, LSTM
from keras.optimizers import Adam, SGD import numpy as np import abc from ClassificationModule import ClassificationModule class descriptionreponamelstm(ClassificationModule): """A basic lstm neural network""" def __init__(self, num_hidden_layers=3): ClassificationModule.__init__(self, "Descripti...
random_line_split
descriptionreponamelstm.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from Models.FeatureProcessing import * from keras.models import Sequential from keras.layers import Activation, Dense, LSTM from keras.optimizers import Adam, SGD import numpy as np import abc from ClassificationModule import ClassificationModule class descriptionreponame...
def predictLabelAndProbability(self, sample): """Return the probability the module assignes each label""" if not self.isTrained: return [0, 0, 0, 0, 0, 0, 0, 0] sample = self.formatInputData(sample) prediction = self.model.predict(sample)[0] return [np.argmax(pr...
"Gibt zurück, wie der Klassifikator ein gegebenes Sample klassifizieren würde""" if not self.isTrained: return 0 sample = self.formatInputData(sample) return np.argmax(self.model.predict(sample))
identifier_body
descriptionreponamelstm.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from Models.FeatureProcessing import * from keras.models import Sequential from keras.layers import Activation, Dense, LSTM from keras.optimizers import Adam, SGD import numpy as np import abc from ClassificationModule import ClassificationModule class descriptionreponame...
sample = self.formatInputData(sample) prediction = self.model.predict(sample)[0] return [np.argmax(prediction)] + list(prediction) # [0] So 1-D array is returned def formatInputData(self, sample): """Extract description and transform to vector""" sd = getDescription(sample) ...
rn [0, 0, 0, 0, 0, 0, 0, 0]
conditional_block
Header-test.tsx
jest.mock('react-router-dom'); jest.mock('../Search'); import { mount } from 'enzyme'; import * as React from 'react'; import Header from '../Header'; const setup = () => { const component = mount(<Header location={{ pathname: 'testing' }} />); return { button: component.find('button'), component, nav...
expect(button.hasClass('hamburger__squeeze--active')).toBe(false); expect(nav.hasClass('header__nav--open')).toBe(false); }); it('should toggle the menu on click', () => { const { component } = setup(); expect(component.find('button').hasClass('hamburger__squeeze--active')).toBe(false); expect(...
describe('<Header />', () => { it('should render with menu closed', () => { const { button, nav } = setup();
random_line_split
ec2_placement_group.py
# -*- coding: utf-8 -*- # Automatic provisioning of EC2 placement groups import boto.ec2.placementgroup import nixops.resources import nixops.util import nixops.ec2_utils class EC2PlacementGroupDefinition(nixops.resources.ResourceDefinition): """Definition of an EC2 placement group.""" @classmethod def ...
f, wipe=False): if self.state == self.UP or self.state == self.STARTING: self.logger.log("deleting EC2 placement group `{0}'...".format(self.placement_group_name)) self._connect() self._conn.delete_placement_group(self.placement_group_name) self.state = self.MISSI...
roy(sel
identifier_name
ec2_placement_group.py
# -*- coding: utf-8 -*- # Automatic provisioning of EC2 placement groups import boto.ec2.placementgroup import nixops.resources import nixops.util import nixops.ec2_utils class EC2PlacementGroupDefinition(nixops.resources.ResourceDefinition): """Definition of an EC2 placement group.""" @classmethod def ...
self.placement_group_name = defn.placement_group_name self.placement_group_strategy = defn.placement_group_strategy grp = None if check: with self.depl._db: self._connect() try: grp = self._conn.get_all_placement_g...
self.old_placement_groups = self.old_placement_groups + [{'name': self.placement_group_name, 'region': self.region}] with self.depl._db: self.region = defn.region self.access_key_id = defn.access_key_id or nixops.ec2_utils.get_access_key_id()
random_line_split
ec2_placement_group.py
# -*- coding: utf-8 -*- # Automatic provisioning of EC2 placement groups import boto.ec2.placementgroup import nixops.resources import nixops.util import nixops.ec2_utils class EC2PlacementGroupDefinition(nixops.resources.ResourceDefinition): """Definition of an EC2 placement group.""" @classmethod def ...
try: conn.delete_placement_group(group['name']) except boto.exception.EC2ResponseError as e: if e.error_code != u'InvalidGroup.NotFound': raise self.old_placement_groups = [] def destroy(self, wipe=False): if self.state == sel...
on = group['region'] conn = nixops.ec2_utils.connect(region, self.access_key_id)
conditional_block
ec2_placement_group.py
# -*- coding: utf-8 -*- # Automatic provisioning of EC2 placement groups import boto.ec2.placementgroup import nixops.resources import nixops.util import nixops.ec2_utils class EC2PlacementGroupDefinition(nixops.resources.ResourceDefinition): """Definition of an EC2 placement group.""" @classmethod def ...
def show_type(self): s = super(EC2PlacementGroupState, self).show_type() if self.region: s = "{0} [{1}]".format(s, self.region) return s def prefix_definition(self, attr): return {('resources', 'ec2PlacementGroups'): attr} def get_physical_spec(self): return {} ...
super(EC2PlacementGroupState, self).__init__(depl, name, id) self._conn = None
identifier_body
funcs.py
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ''' Processor functions for images ''' import numpy as np def squeeze_image(img):
>>> data = np.arange(np.prod(shape)).reshape(shape) >>> affine = np.eye(4) >>> img = nf.Nifti1Image(data, affine) >>> img.get_shape() (10, 20, 30, 1, 1) >>> img2 = squeeze_image(img) >>> img2.get_shape() (10, 20, 30) If the data are 3D then last dimensions of 1 are ignored >>> ...
''' Return image, remove axes length 1 at end of image shape For example, an image may have shape (10,20,30,1,1). In this case squeeze will result in an image with shape (10,20,30). See doctests for further description of behavior. Parameters ---------- img : ``SpatialImage`` Returns ...
identifier_body
funcs.py
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ''' Processor functions for images ''' import numpy as np def
(img): ''' Return image, remove axes length 1 at end of image shape For example, an image may have shape (10,20,30,1,1). In this case squeeze will result in an image with shape (10,20,30). See doctests for further description of behavior. Parameters ---------- img : ``SpatialImage`` ...
squeeze_image
identifier_name
funcs.py
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ''' Processor functions for images ''' import numpy as np def squeeze_image(img): ''' Return image, remove axes length 1 at end of image shape For example, an image may have shape (10,20,30,1,1). ...
out_data = np.rollaxis(out_data, 0, len(i0shape)+1) klass = img0.__class__ return klass(out_data, affine, header)
if not np.all(img.get_affine() == affine): raise ValueError('Affines do not match') out_data[i] = img.get_data()
conditional_block
funcs.py
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ''' Processor functions for images ''' import numpy as np def squeeze_image(img): ''' Return image, remove axes length 1 at end of image shape For example, an image may have shape (10,20,30,1,1). ...
out_data[i] = img.get_data() out_data = np.rollaxis(out_data, 0, len(i0shape)+1) klass = img0.__class__ return klass(out_data, affine, header)
random_line_split
webpack.config.js
const path = require('path'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const LiveReloadPlugin = require('webpack-livereload-plugin'); module.exports = { context: __dirname, entry: ['./js/App.jsx', './scss/main.scss'], devtool: 'eval', output: { path: path.join(__dirname, 'public')...
stats: { colors: true, reasons: true, chunks: true }, module: { rules: [ { test: /\.jsx?$/, loaders: ['babel-loader'] }, { test: /(\.scss|\.css)$/, loaders: [ require.resolve('style-loader'), require.resolve('css-loader') + ...
resolve: { extensions: ['.js', '.jsx', '.json'] },
random_line_split
descriptor.py
the instance variable will result in a :meth:`Keyword.modify` operation. Parameters ---------- name : str Keyword name. Case-insensitive, will be translated to upper case. initial : str Keyword initial value, should be a string. If not set, no initial value is used and...
_KeywordEvent(self.keyword(obj), obj, event)
conditional_block
descriptor.py
(service=...) method.") for desc in cls.keyword_descriptors(): desc.service = service class KeywordDescriptor(object): """A descriptor which maintains a relationship with a keyword. The descriptor should be used as a class level variable. It can be accessed as a regular instance va...
if service is not None and not self._bound:
random_line_split
descriptor.py
via :meth:`bind`. This can be done at the class level. 2. Bind an instance to the the service. This can be done at __init__ time. """ def __init__(self, *args, **kwargs): """This initalizer tries to bind the instance, if it can.""" super(DescriptorBase, self).__init__(*args, **kwa...
(self, name, initial=None, type=lambda v : v, doc=None, readonly=False, writeonly=False): super(KeywordDescriptor, self).__init__() self.name = name.upper() self.type = type self.__doc__ = doc if readonly and writeonly: raise ValueError("Keyword {0} cannot be 'readonl...
__init__
identifier_name
descriptor.py
via :meth:`bind`. This can be done at the class level. 2. Bind an instance to the the service. This can be done at __init__ time. """ def __init__(self, *args, **kwargs): """This initalizer tries to bind the instance, if it can.""" super(DescriptorBase, self).__init__(*args, **kwa...
@name.setter def name(self, value): """Set the keyword name.""" if self._bound: raise ServiceAlreadyBound("Can't change the name of the keyword after the service has bound to it.") self._name = str(value).upper() self._name_attr = "_{0}_name_{1}".format(self...
"""Keyword name""" return self._name
identifier_body
mnist.py
# Copyright 2015 The TensorFlow 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 required by applica...
file_hash='8a61469f7ea1b51cbae51d4f78837e45') with np.load(path) as f: x_train, y_train = f['x_train'], f['y_train'] x_test, y_test = f['x_test'], f['y_test'] return (x_train, y_train), (x_test, y_test)
"""Loads the MNIST dataset. Arguments: path: path where to cache the dataset locally (relative to ~/.keras/datasets). Returns: Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. License: Yann LeCun and Corinna Cortes hold the copyright of MNIST dataset, which is a ...
identifier_body
mnist.py
# Copyright 2015 The TensorFlow 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 #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """MNIST handwritten digits dataset. """ from __future__ impo...
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS,
random_line_split
mnist.py
# Copyright 2015 The TensorFlow 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 required by applica...
(path='mnist.npz'): """Loads the MNIST dataset. Arguments: path: path where to cache the dataset locally (relative to ~/.keras/datasets). Returns: Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. License: Yann LeCun and Corinna Cortes hold the copyright of MNIST data...
load_data
identifier_name
sale_order.py
# -*- encoding: utf-8 -*- ############################################################################## # # Avanzosc - Avanced Open Source Consulting # Copyright (C) 2011 - 2014 Avanzosc <http://www.avanzosc.com> # # This program is free software: you can redistribute it and/or modify # it under the terms ...
(orm.Model): _inherit = 'sale.order' def action_wait(self, cr, uid, ids, context=None): product_obj = self.pool['product.product'] res = super(SaleOrder, self).action_wait(cr, uid, ids, context) for o in self.browse(cr, uid, ids, context): for line in o.order_line: ...
SaleOrder
identifier_name
sale_order.py
# -*- encoding: utf-8 -*- ############################################################################## # # Avanzosc - Avanced Open Source Consulting # Copyright (C) 2011 - 2014 Avanzosc <http://www.avanzosc.com> # # This program is free software: you can redistribute it and/or modify # it under the terms ...
# along with this program. If not, see http://www.gnu.org/licenses/. # ############################################################################## from openerp.osv import orm import time class SaleOrder(orm.Model): _inherit = 'sale.order' def action_wait(self, cr, uid, ids, context=None): pro...
# GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License
random_line_split
sale_order.py
# -*- encoding: utf-8 -*- ############################################################################## # # Avanzosc - Avanced Open Source Consulting # Copyright (C) 2011 - 2014 Avanzosc <http://www.avanzosc.com> # # This program is free software: you can redistribute it and/or modify # it under the terms ...
return res
vals = {'last_sale_date': time.strftime('%Y-%m-%d %H:%M:%S'), 'last_customer_id': line.order_id.partner_id.id, } product_obj.write(cr, uid, [line.product_id.id], vals, context)
conditional_block
sale_order.py
# -*- encoding: utf-8 -*- ############################################################################## # # Avanzosc - Avanced Open Source Consulting # Copyright (C) 2011 - 2014 Avanzosc <http://www.avanzosc.com> # # This program is free software: you can redistribute it and/or modify # it under the terms ...
product_obj = self.pool['product.product'] res = super(SaleOrder, self).action_wait(cr, uid, ids, context) for o in self.browse(cr, uid, ids, context): for line in o.order_line: if line.product_id: vals = {'last_sale_date': time...
identifier_body
171.py
import copy class
: # @param strs: A list of strings # @return: A list of strings def anagrams(self, strs): # write your code here str1=copy.deepcopy(strs) def hashLize(s): dicts1= dict() for i in range(26): dicts1[chr(i+ord("a"))]=0 ...
Solution
identifier_name
171.py
import copy class Solution: # @param strs: A list of strings # @return: A list of strings def anagrams(self, strs): # write your code here
check_dict=dict() for i in range(len(strs)): str_s1=sortLize(strs[i]) if str_s1 in check_dict.keys(): check_dict[str_s1].append(strs[i]) else: check_dict[str_s1]=[] check_dict[str_s1].append(strs[i]) ...
str1=copy.deepcopy(strs) def hashLize(s): dicts1= dict() for i in range(26): dicts1[chr(i+ord("a"))]=0 for j in s: if j in dicts1.keys(): dicts1[j]+=1 return dicts1 def...
identifier_body
171.py
import copy class Solution:
# @return: A list of strings def anagrams(self, strs): # write your code here str1=copy.deepcopy(strs) def hashLize(s): dicts1= dict() for i in range(26): dicts1[chr(i+ord("a"))]=0 for j in s: if j in ...
# @param strs: A list of strings
random_line_split
171.py
import copy class Solution: # @param strs: A list of strings # @return: A list of strings def anagrams(self, strs): # write your code here str1=copy.deepcopy(strs) def hashLize(s): dicts1= dict() for i in range(26): dicts1[chr(i+ord("a"...
str_rt=[] for i in check_dict.keys(): if (len(check_dict[i]) > 1): str_rt.extend(check_dict[i]) return str_rt #Total Runtime: 835 ms # for i in range(len(strs)): # str1[i]=hashLize(strs[i]) # str_rt=[] # flag = [0 ...
str_s1=sortLize(strs[i]) if str_s1 in check_dict.keys(): check_dict[str_s1].append(strs[i]) else: check_dict[str_s1]=[] check_dict[str_s1].append(strs[i])
conditional_block
aurelia-pal.d.ts
export interface Feature { /** * Does the runtime environment support ShadowDOM? */ shadowDOM: boolean; /** * Does the runtime environment support the css scoped attribute? */ scopedCSS: boolean; /** * Does the runtime environment support native HTMLTem...
createElement(tagName: string): Element; /** * Creates a new Text node. * @param text A string to populate the new Text node. * @return A Text node. */ createTextNode(text: string): Text; /** * Creates a new Comment node. * @param text A string to populate t...
* @return The created element. */
random_line_split
scatteringTools.py
# # Copyright 2015 VTT Technical Research Center of Finland # # 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 applicabl...
(cosTheta, asymmetry_factor): g = asymmetry_factor p = 0.5 * (1.0 - g ** 2) / (1 + g ** 2 - 2 * g * cosTheta) ** (3.0 / 2.0) return(p) def cumulativeDistribution(phaseFunction, cosTheta): return(-0.5 * cumtrapz(phaseFunction, cosTheta, initial=0)) def cumulativeDistributionTheta(phaseFunction, theta...
henyeyGreensteinPhaseFunction
identifier_name
scatteringTools.py
# # Copyright 2015 VTT Technical Research Center of Finland # # 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 applicabl...
return(new_y) ''' th = np.arange(0, 180, 0.5) th = np.radians(th) rv = np.linspace(0, 1, 1000) phase = rayleighScatteringPhaseFunction(np.cos(th)) phase = henyeyGreensteinPhaseFunction(np.cos(th), -0.6) cumul = cumulativeDistribution(phase, np.cos(th)) invers = invertNiceFunction(np.cos(th), cumul, rv) plt.pl...
new_y[-1] = x[-1]
conditional_block
scatteringTools.py
# # Copyright 2015 VTT Technical Research Center of Finland # # 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 applicabl...
def invertNiceFunction(x, y, yi): new_y = griddata(y, x, yi) if np.isnan(new_y[0]): new_y[0] = x[0] if np.isnan(new_y[-1]): new_y[-1] = x[-1] return(new_y) ''' th = np.arange(0, 180, 0.5) th = np.radians(th) rv = np.linspace(0, 1, 1000) phase = rayleighScatteringPhaseFunction(np.c...
return(cumtrapz(phaseFunction * np.sin(theta), theta, initial=0))
identifier_body
scatteringTools.py
# # Copyright 2015 VTT Technical Research Center of Finland # # 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 applicabl...
density_host=1.1, mu=1, sigma=1, particle_diameters=np.array([1, 2])) '''
particle_diameters=np.array([1, 2])) particlesInVolumeLogNormWeight(weight_frac=0.24, density_p=5.0,
random_line_split
Tools_todo_Model.py
# -*- coding: utf-8 -*- from django.db import models from ..Models import * from center.Exceptions.ModelsExceptions import * class Tools_todo(models.Model): STATUS_TYPES = ( (1, u'New'), (2, u'Doing'), (3, u'Waiting'), (4, u'Done'), ) SPECIES_TYPES = ( (1, u'Task')...
, **kwargs): try: super(Tools_todo, self).update(*args, **kwargs) except: raise updateException(self.model_name) def delete(self, *args, **kwargs): try: super(Tools_todo, self).delete(*args, **kwargs) except: raise updateException(self...
*args
identifier_name
Tools_todo_Model.py
# -*- coding: utf-8 -*- from django.db import models from ..Models import * from center.Exceptions.ModelsExceptions import * class Tools_todo(models.Model):
priority = models.IntegerField(choices=PRIORITY_TYPES, default=2) creation_date = models.DateTimeField(auto_now_add=True) modify_date = models.DateTimeField(auto_now=True) model_name = "计划" def create(self, *args, **kwargs): try: super(Tools_todo, self).save(*args, **kwargs) ...
STATUS_TYPES = ( (1, u'New'), (2, u'Doing'), (3, u'Waiting'), (4, u'Done'), ) SPECIES_TYPES = ( (1, u'Task'), # 查询 (2, u'Check'), # 任务 ) PRIORITY_TYPES = ( (1, 'Low'), (2, 'Normal'), (3, 'High'), ) user = models.ForeignKey(U...
identifier_body
Tools_todo_Model.py
# -*- coding: utf-8 -*- from django.db import models from ..Models import * from center.Exceptions.ModelsExceptions import * class Tools_todo(models.Model): STATUS_TYPES = ( (1, u'New'), (2, u'Doing'), (3, u'Waiting'), (4, u'Done'), ) SPECIES_TYPES = ( (1, u'Task')...
except: raise updateException(self.model_name)
random_line_split
ex32.py
the_count = [1, 2, 3, 4, 5] fruits = ['apple', 'oranges', 'pears', 'apricots',] change = [1, 'pennies', 2, 'dimes', 3, 'quarters',] #this first kind of for-loop goes through a list for number in the_count: print("This is count %d" % number) # same as above for fruit in fruits: print("A fruit of type: %s" % fr...
# then use the range function to do 0 to 5 counts for i in range(0,6): print("Adding %d to the list." % i) # append is a function that lists understand elements.append(i) # now we can print them out too for i in elements: print("Element was: %d" % i)
# we can alse build lists, first start with an empty one elements = []
random_line_split
ex32.py
the_count = [1, 2, 3, 4, 5] fruits = ['apple', 'oranges', 'pears', 'apricots',] change = [1, 'pennies', 2, 'dimes', 3, 'quarters',] #this first kind of for-loop goes through a list for number in the_count: print("This is count %d" % number) # same as above for fruit in fruits: print("A fruit of type: %s" % fr...
# now we can print them out too for i in elements: print("Element was: %d" % i)
print("Adding %d to the list." % i) # append is a function that lists understand elements.append(i)
conditional_block
display.py
# in a single non printable length width -= 1 counter -= 1 continue try: w = _LIBC.wcwidth(c) except ctypes.ArgumentError: w = -1 if w == -1: # -1 signifies a non-printable character # use 0 here as a best effo...
header = '[DEPRECATION WARNING]: {0}'.format(msg) removal_fragment = 'This feature will be removed' # FUTURE: make this a standalone warning so it only shows up once? help_text = 'Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.'
random_line_split
display.py
= 0 for c in text: counter += 1 if c in (u'\x08', u'\x7f', u'\x94', u'\x1b'): # A few characters result in a subtraction of length: # BS, DEL, CCH, ESC # ESC is slightly different in that it's part of an escape sequence, and # while ESC is non printab...
collection_name = 'ansible-core'
conditional_block
display.py
.exists(path) and os.access(path, os.W_OK)) or os.access(os.path.dirname(path), os.W_OK): # NOTE: level is kept at INFO to avoid security disclosures caused by certain libraries when using DEBUG logging.basicConfig(filename=path, level=logging.INFO, # DO NOT set to logging.DEBUG ...
banner
identifier_name
display.py
ate() if cmd.returncode: raise Exception self.cows_available = {to_text(c) for c in out.split()} # set comprehension if C.ANSIBLE_COW_ACCEPTLIST and any(C.ANSIBLE_COW_ACCEPTLIST): self.cows_available = set(C.ANSIBLE_COW_ACCEPTLIST)...
if wrap_text: new_msg = u"\n[ERROR]: %s" % msg wrapped = textwrap.wrap(new_msg, self.columns) new_msg = u"\n".join(wrapped) + u"\n" else: new_msg = u"ERROR! %s" % msg if new_msg not in self._errors: self.display(new_msg, color=C.COLOR_ERROR, st...
identifier_body
missingglut.py
#! /usr/bin/env python """Script to find missing GLUT entry points""" from OpenGL import GLUT import subprocess, re func_finder = re.compile( 'FGAPIENTRY (\w+)\(' ) constant_finder = re.compile( '#define\W+([0-9a-zA-Z_]+)\W+((0x)?\d+)' ) INCLUDE_DIR = '/usr/include/GL' def defined( ): """Grep FGAPIENTRY headers ...
for file,variables in missing.items(): print file variables.sort() for key,value in variables: print '%s=%s'%(key,value) if __name__ == "__main__": main()
match = constant_finder.search( line ) if match: key,value=(match.group(1),match.group(2)) if not hasattr( GLUT, key ): file = line.split(':',1)[0] missing.setdefault(file,[]).append( (key,value))
conditional_block
missingglut.py
#! /usr/bin/env python """Script to find missing GLUT entry points""" from OpenGL import GLUT import subprocess, re func_finder = re.compile( 'FGAPIENTRY (\w+)\(' ) constant_finder = re.compile( '#define\W+([0-9a-zA-Z_]+)\W+((0x)?\d+)' ) INCLUDE_DIR = '/usr/include/GL' def defined( ): """Grep FGAPIENTRY headers ...
(): headers = {} for line in defined().splitlines(): match = func_finder.search( line ) if match: headers[match.group(1)] = line.split(':',1)[0] for key in headers.keys(): if hasattr( GLUT, key ): del headers[key] import pprint pprint.pprint( headers ...
main
identifier_name
missingglut.py
#! /usr/bin/env python """Script to find missing GLUT entry points""" from OpenGL import GLUT import subprocess, re func_finder = re.compile( 'FGAPIENTRY (\w+)\(' ) constant_finder = re.compile( '#define\W+([0-9a-zA-Z_]+)\W+((0x)?\d+)' ) INCLUDE_DIR = '/usr/include/GL' def defined( ): """Grep FGAPIENTRY headers ...
if hasattr( GLUT, key ): del headers[key] import pprint pprint.pprint( headers ) missing = {} for line in constants().splitlines(): match = constant_finder.search( line ) if match: key,value=(match.group(1),match.group(2)) if not hasattr( GLUT...
for key in headers.keys():
random_line_split
missingglut.py
#! /usr/bin/env python """Script to find missing GLUT entry points""" from OpenGL import GLUT import subprocess, re func_finder = re.compile( 'FGAPIENTRY (\w+)\(' ) constant_finder = re.compile( '#define\W+([0-9a-zA-Z_]+)\W+((0x)?\d+)' ) INCLUDE_DIR = '/usr/include/GL' def defined( ): """Grep FGAPIENTRY headers ...
variables.sort() for key,value in variables: print '%s=%s'%(key,value) if __name__ == "__main__": main()
headers = {} for line in defined().splitlines(): match = func_finder.search( line ) if match: headers[match.group(1)] = line.split(':',1)[0] for key in headers.keys(): if hasattr( GLUT, key ): del headers[key] import pprint pprint.pprint( headers ) mi...
identifier_body
BudgetTypeList.js
/** * Created by * Pratish Shrestha <pratishshrestha@lftechnology.com> * on 2/15/16. */ ;(function () { 'use strict'; //React and Redux dependencies var React = require('react'); var Link = require('react-router').Link; var connect = require('react-redux').connect; var bindActionCreators =...
})();
random_line_split
util.ts
import {defaultIdKeys} from '../defaults'; import {Action, ContentRange} from '../typings'; // type UnknownObject = Record<string | number | symbol, unknown>; export const includes = (array: unknown[], value: unknown): boolean => array.indexOf(value) !== -1; export const isString = (maybeString: unknown): maybeStrin...
export const upperSnakeCase = (string: string): string => String( string.split('').reduce((soFar, letter, index) => { const charCode = letter.charCodeAt(0); return soFar + (index && charCode < 97 ? `_${letter}` : letter).toUpperCase(); }, '') ); export const getGerundName = (name: string): stri...
random_line_split
util.ts
import {defaultIdKeys} from '../defaults'; import {Action, ContentRange} from '../typings'; // type UnknownObject = Record<string | number | symbol, unknown>; export const includes = (array: unknown[], value: unknown): boolean => array.indexOf(value) !== -1; export const isString = (maybeString: unknown): maybeStrin...
return null; }; export const getIdKey = (_action: Action, {multi = false}: {multi: boolean}): string => multi ? defaultIdKeys.plural : defaultIdKeys.singular;
{ const matches = string.match(/^(\w+) (\d+)-(\d+)\/(\d+|\*)/); if (matches) { return { unit: matches[1], first: +matches[2], last: +matches[3], length: matches[4] === '*' ? null : +matches[4] }; } }
conditional_block
yahoo.py
# coding: utf-8 from __future__ import absolute_import import flask import auth import model import util from main import app yahoo_config = dict( access_token_url='https://api.login.yahoo.com/oauth/v2/get_token', authorize_url='https://api.login.yahoo.com/oauth/v2/request_auth', base_url='https://query.yaho...
return auth.signin_user_db(user_db) @yahoo.tokengetter def get_yahoo_oauth_token(): return flask.session.get('oauth_token') @app.route('/signin/yahoo/') def signin_yahoo(): return auth.signin_oauth(yahoo) def retrieve_user_from_yahoo(response): auth_id = 'yahoo_%s' % response['guid'] user_db = model.Us...
response = yahoo.authorized_response() if response is None: flask.flash('You denied the request to sign in.') return flask.redirect(util.get_next_url()) flask.session['oauth_token'] = ( response['oauth_token'], response['oauth_token_secret'], ) fields = 'guid, emails, familyName, givenName, ni...
identifier_body
yahoo.py
# coding: utf-8 from __future__ import absolute_import import flask import auth import model import util from main import app yahoo_config = dict( access_token_url='https://api.login.yahoo.com/oauth/v2/get_token', authorize_url='https://api.login.yahoo.com/oauth/v2/request_auth', base_url='https://query.yaho...
flask.session['oauth_token'] = ( response['oauth_token'], response['oauth_token_secret'], ) fields = 'guid, emails, familyName, givenName, nickname' me = yahoo.get( '/v1/yql', data={ 'format': 'json', 'q': 'select %s from social.profile where guid = me;' % fields, 'realm': '...
flask.flash('You denied the request to sign in.') return flask.redirect(util.get_next_url())
conditional_block
yahoo.py
# coding: utf-8 from __future__ import absolute_import import flask import auth import model import util from main import app yahoo_config = dict( access_token_url='https://api.login.yahoo.com/oauth/v2/get_token', authorize_url='https://api.login.yahoo.com/oauth/v2/request_auth', base_url='https://query.yaho...
(): return flask.session.get('oauth_token') @app.route('/signin/yahoo/') def signin_yahoo(): return auth.signin_oauth(yahoo) def retrieve_user_from_yahoo(response): auth_id = 'yahoo_%s' % response['guid'] user_db = model.User.get_by('auth_ids', auth_id) if user_db: return user_db names = [response....
get_yahoo_oauth_token
identifier_name
yahoo.py
# coding: utf-8 from __future__ import absolute_import import flask import auth import model import util from main import app yahoo_config = dict( access_token_url='https://api.login.yahoo.com/oauth/v2/get_token', authorize_url='https://api.login.yahoo.com/oauth/v2/request_auth', base_url='https://query.yaho...
@app.route('/api/auth/callback/yahoo/') def yahoo_authorized(): response = yahoo.authorized_response() if response is None: flask.flash('You denied the request to sign in.') return flask.redirect(util.get_next_url()) flask.session['oauth_token'] = ( response['oauth_token'], response['oauth_token_...
yahoo = auth.create_oauth_app(yahoo_config, 'yahoo')
random_line_split
ff-Latn-GN.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; func...
(n: number): number { let i = Math.floor(Math.abs(n)); if (i === 0 || i === 1) return 1; return 5; } export default [ 'ff-Latn-GN', [['subaka', 'kikiiɗe'], u, u], u, [ ['d', 'a', 'm', 'n', 'n', 'm', 'h'], ['dew', 'aaɓ', 'maw', 'nje', 'naa', 'mwd', 'hbi'], ['dewo', 'aaɓnde', 'mawbaare', 'njeslaare...
plural
identifier_name
ff-Latn-GN.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; func...
export default [ 'ff-Latn-GN', [['subaka', 'kikiiɗe'], u, u], u, [ ['d', 'a', 'm', 'n', 'n', 'm', 'h'], ['dew', 'aaɓ', 'maw', 'nje', 'naa', 'mwd', 'hbi'], ['dewo', 'aaɓnde', 'mawbaare', 'njeslaare', 'naasaande', 'mawnde', 'hoore-biir'], ['dew', 'aaɓ', 'maw', 'nje', 'naa', 'mwd', 'hbi'] ], u, ...
{ let i = Math.floor(Math.abs(n)); if (i === 0 || i === 1) return 1; return 5; }
identifier_body