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 |
|---|---|---|---|---|
process.py | #!/usr/bin/env python3
delineator = "//"
hashtag = "#"
# generate poems from a file
# out: list of poem lines
def generate_poems(filename):
g = []
# get to the first poem in the file
with open(filename, 'r') as f: | if line:
g.append(line)
yield g
# convert a list of strings
# into a poem dictionary
def to_dictionary(poem_lines):
d = {}
d['content'] = []
d['tags'] = []
tags = []
for line in poem_lines:
if line.startswith( delineator ):
d['title'] = line.l... | for line in f:
line = line.rstrip()
if line.startswith( delineator ) and g:
yield g
g = [] | random_line_split |
process.py | #!/usr/bin/env python3
delineator = "//"
hashtag = "#"
# generate poems from a file
# out: list of poem lines
def generate_poems(filename):
g = []
# get to the first poem in the file
with open(filename, 'r') as f:
for line in f:
line = line.rstrip()
if line.startswith( deli... |
return d
| d['tags'].append(tag) | conditional_block |
process.py | #!/usr/bin/env python3
delineator = "//"
hashtag = "#"
# generate poems from a file
# out: list of poem lines
def generate_poems(filename):
g = []
# get to the first poem in the file
with open(filename, 'r') as f:
for line in f:
line = line.rstrip()
if line.startswith( deli... | (poem_lines):
d = {}
d['content'] = []
d['tags'] = []
tags = []
for line in poem_lines:
if line.startswith( delineator ):
d['title'] = line.lstrip( delineator ).strip()
elif line.startswith( hashtag ):
tags.append(line)
else:
d['content'].a... | to_dictionary | identifier_name |
batch.rs | //! Module providing write batches
use leveldb_sys::*;
use libc::{c_char, size_t, c_void};
use std::slice;
use options::{WriteOptions, c_writeoptions};
use super::error::Error;
use std::ptr;
use super::Database;
#[allow(missing_docs)]
struct RawWritebatch {
ptr: *mut leveldb_writebatch_t,
}
impl Drop for RawWrit... | else {
Err(Error::new_from_i8(error))
}
}
}
}
impl Writebatch {
/// Create a new writebatch
pub fn new() -> Writebatch {
let ptr = unsafe { leveldb_writebatch_create() };
let raw = RawWritebatch { ptr: ptr };
Writebatch { writebatch: raw }
}
... | {
Ok(())
} | conditional_block |
batch.rs | //! Module providing write batches
use leveldb_sys::*;
use libc::{c_char, size_t, c_void};
use std::slice;
use options::{WriteOptions, c_writeoptions};
use super::error::Error;
use std::ptr;
use super::Database;
#[allow(missing_docs)]
struct RawWritebatch {
ptr: *mut leveldb_writebatch_t,
}
impl Drop for RawWrit... | <T: WritebatchIterator>(&mut self, iterator: Box<T>) -> Box<T> {
use std::mem;
unsafe {
let mem = mem::transmute(iterator);
leveldb_writebatch_iterate(self.writebatch.ptr,
mem,
put_callback::<T>,
... | iterate | identifier_name |
batch.rs | //! Module providing write batches
use leveldb_sys::*;
use libc::{c_char, size_t, c_void};
use std::slice;
use options::{WriteOptions, c_writeoptions};
use super::error::Error;
use std::ptr;
use super::Database;
#[allow(missing_docs)]
struct RawWritebatch {
ptr: *mut leveldb_writebatch_t,
}
impl Drop for RawWrit... | }
extern "C" fn put_callback<T: WritebatchIterator>(state: *mut c_void,
key: *const i8,
keylen: size_t,
val: *const i8,
... | /// Callback for put items
fn put(&mut self, key: &[u8], value: &[u8]);
/// Callback for deleted items
fn deleted(&mut self, key: &[u8]); | random_line_split |
impl_numeric.rs | // Copyright 2014-2016 bluss and ndarray developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
... | let rhs_broadcast = rhs.broadcast_unwrap(self.raw_dim());
self.iter().zip(rhs_broadcast.iter()).all(|(x, y)| (*x - *y).abs() <= tol)
}
} | identifier_body | |
impl_numeric.rs | // Copyright 2014-2016 bluss and ndarray developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
... |
}
sum
}
/// Return sum along `axis`.
///
/// ```
/// use ndarray::{aview0, aview1, arr2, Axis};
///
/// let a = arr2(&[[1., 2.],
/// [3., 4.]]);
/// assert!(
/// a.sum(Axis(0)) == aview1(&[4., 6.]) &&
/// a.sum(Axis(1)) == aview1(&[3.,... | {
sum = sum + row.iter().fold(A::zero(), |acc, elt| acc + elt.clone());
} | conditional_block |
impl_numeric.rs | // Copyright 2014-2016 bluss and ndarray developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
... | if let Some(slc) = row.as_slice() {
sum = sum + numeric_util::unrolled_sum(slc);
} else {
sum = sum + row.iter().fold(A::zero(), |acc, elt| acc + elt.clone());
}
}
sum
}
/// Return sum along `axis`.
///
/// ```
/// ... | let mut sum = A::zero();
for row in self.inner_iter() { | random_line_split |
impl_numeric.rs | // Copyright 2014-2016 bluss and ndarray developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
... | (&self, axis: Axis) -> Array<A, <D as RemoveAxis>::Smaller>
where A: Clone + Zero + Add<Output=A>,
D: RemoveAxis,
{
let n = self.shape().axis(axis);
let mut res = self.subview(axis, 0).to_owned();
let stride = self.strides()[axis.index()];
if self.ndim() == 2 &&... | sum | identifier_name |
CONSTANTS.js | export class ElementType {
static ROOT_FOLDER = 'ROOT_FOLDER';
static FOLDER = 'FOLDER';
static NOTE = 'NOTE';
static FILE = 'FILE';
static IGNORE_NOTE_KEYS = ['_id', 'parentId', 'attachments', 'title', 'type', 'content'];
static FORCE_UPDATE_KEYS = ['attachments', '_id', 'type', 'parentId', 'created'];
s... | type: ElementType.NOTE,
parentId: '',
content: '',
attachments: [
// {type: 'LINK', title: '', path: '', mime: 'IMAGE'},
// {type: 'ATTACHMENT', title: '', data: '', mime: 'PDF'}
]
};
static FILE_DEFAULT_STORAGE = {
_id: '',
title: '',
type: ElementType.FILE,
parent: ... | elements: []
}
static NOTE_DEFAULT_STORAGE = {
// _id: '',
title: '', | random_line_split |
CONSTANTS.js | export class | {
static ROOT_FOLDER = 'ROOT_FOLDER';
static FOLDER = 'FOLDER';
static NOTE = 'NOTE';
static FILE = 'FILE';
static IGNORE_NOTE_KEYS = ['_id', 'parentId', 'attachments', 'title', 'type', 'content'];
static FORCE_UPDATE_KEYS = ['attachments', '_id', 'type', 'parentId', 'created'];
static ALLOWED_STYLE_KEYS... | ElementType | identifier_name |
position.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Generic types for CSS handling of specified and computed values of
//! [`position`](https://drafts.csswg.org/c... |
}
| {
match self {
ZIndex::Integer(n) => n,
ZIndex::Auto => auto,
}
} | identifier_body |
position.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Generic types for CSS handling of specified and computed values of
//! [`position`](https://drafts.csswg.org/c... | <Integer> {
/// An integer value.
Integer(Integer),
/// The keyword `auto`.
Auto,
}
impl<Integer> ZIndex<Integer> {
/// Returns `auto`
#[inline]
pub fn auto() -> Self {
ZIndex::Auto
}
/// Returns whether `self` is `auto`.
#[inline]
pub fn is_auto(self) -> bool {
... | ZIndex | identifier_name |
position.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Generic types for CSS handling of specified and computed values of
//! [`position`](https://drafts.csswg.org/c... | /// The vertical component of position.
pub vertical: V,
}
impl<H, V> Position<H, V> {
/// Returns a new position.
pub fn new(horizontal: H, vertical: V) -> Self {
Self {
horizontal: horizontal,
vertical: vertical,
}
}
}
/// A generic value for the `z-index`... | random_line_split | |
client.rs | };
use track::{Track, TrackRequestBuilder, SingleTrackRequestBuilder};
use error::{Error, Result};
pub type Params<'a, K, V> = &'a [(K, V)];
#[derive(Debug)]
pub struct Client {
client_id: String,
http_client: hyper::Client,
}
/// Registered client application.
#[derive(Serialize, Deserialize, Debug, Clone)... | /// Starts streaming the track provided in the tracks `stream_url` to the `writer` if the track
/// is streamable via the API.
pub fn stream<W: Write>(&self, track: &Track, mut writer: W) -> Result<usize> {
use hyper::header::Location;
if !track.streamable || !track.stream_url.is_some() {
... | use hyper::header::Location;
if !track.downloadable || !track.download_url.is_some() {
return Err(Error::TrackNotDownloadable);
}
let url = self.parse_url(track.download_url.as_ref().unwrap());
let mut response = try!(self.http_client.get(url).send());
// F... | identifier_body |
client.rs | use track::{Track, TrackRequestBuilder, SingleTrackRequestBuilder};
use error::{Error, Result};
pub type Params<'a, K, V> = &'a [(K, V)];
#[derive(Debug)]
pub struct Client {
client_id: String,
http_client: hyper::Client,
}
/// Registered client application.
#[derive(Serialize, Deserialize, Debug, Clone)]
pu... | lse {
Err(Error::ApiError("expected location header".to_owned()))
}
}
/// Returns a builder for a single track-by-id request.
///
/// # Examples
///
/// ```
/// use soundcloud::Client;
///
/// let client = Client::new(env!("SOUNDCLOUD_CLIENT_ID"));
/// let tr... | Ok(Url::parse(header).unwrap())
} e | conditional_block |
client.rs | use track::{Track, TrackRequestBuilder, SingleTrackRequestBuilder};
use error::{Error, Result};
pub type Params<'a, K, V> = &'a [(K, V)];
#[derive(Debug)]
pub struct Client {
client_id: String,
http_client: hyper::Client,
}
/// Registered client application.
#[derive(Serialize, Deserialize, Debug, Clone)]
pu... | {
/// Integer ID.
pub id: usize,
/// API resource URL.
pub uri: String,
/// URL to the SoundCloud.com page
pub permalink_url: String,
/// URL to an external site.
pub external_url: String,
/// Username of the app creator.
pub creator: Option<String>,
}
/// User comment.
#[deriv... | App | identifier_name |
client.rs | use url::Url;
use hyper;
use std::result;
use std::borrow::Borrow;
use std::io::{self, Write};
use track::{Track, TrackRequestBuilder, SingleTrackRequestBuilder};
use error::{Error, Result};
pub type Params<'a, K, V> = &'a [(K, V)];
#[derive(Debug)]
pub struct Client {
client_id: String,
http_client: hyper:... | // 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.
| random_line_split | |
junos.py | #
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is d... |
def load_provider(self):
provider = self._task.args.get('provider', {})
for key, value in iteritems(junos_argument_spec):
if key != 'provider' and key not in provider:
if key in self._task.args:
provider[key] = self._task.args[key]
el... | ssh = connection_loader.get('ssh', class_only=True)
path = unfrackpath("$HOME/.ansible/pc")
# use play_context.connection instea of play_context.port to avoid
# collision if netconf is listening on port 22
#cp = ssh._create_control_path(play_context.remote_addr, play_context.connection, ... | identifier_body |
junos.py | #
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is d... | (self, fallback):
strategy = fallback[0]
args = []
kwargs = {}
for item in fallback[1:]:
if isinstance(item, dict):
kwargs = item
else:
args = item
try:
return strategy(*args, **kwargs)
except AnsibleFal... | _fallback | identifier_name |
junos.py | #
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is d... |
module = module_loader._load_module_source(self._task.action, module_loader.find_plugin(self._task.action))
if not getattr(module, 'USE_PERSISTENT_CONNECTION', False):
return super(ActionModule, self).run(tmp, task_vars)
provider = self.load_provider()
pc = copy.deepcopy... | return dict(
failed=True,
msg='invalid connection specified, expected connection=local, '
'got %s' % self._play_context.connection
) | conditional_block |
junos.py | #
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is d... | provider[key] = self._task.args[key]
elif 'fallback' in value:
provider[key] = self._fallback(value['fallback'])
elif key not in provider:
provider[key] = None
return provider
def _fallback(self, fallback):
... | random_line_split | |
test_python_bundler.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import os
import logging
from textwrap import dedent
import collections
import pytest
import mock
from gcdt_testtools.helpers import temp_folder, create_tempfile, cleanup_tempfiles
from gcdt_testtools import helpers
from gcdt_bundler.pyth... |
assert 'werkzeug' in packages
@pytest.mark.slow
@pytest.mark.parametrize('runtime', ['python2.7', 'python3.6'])
def test_install_dependencies_with_pip_not_found(runtime, temp_folder, cleanup_tempfiles):
venv_dir = '%s/.gcdt/venv' % temp_folder[0]
requirements_txt = create_tempfile('werkzeug\nnotfound==0.... | log.debug(package) | conditional_block |
test_python_bundler.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import os
import logging
from textwrap import dedent
| import mock
from gcdt_testtools.helpers import temp_folder, create_tempfile, cleanup_tempfiles
from gcdt_testtools import helpers
from gcdt_bundler.python_bundler import _get_cached_manylinux_wheel, \
_have_correct_lambda_package_version, _site_packages_dir_in_venv, \
_have_any_lambda_package_version, _get_inst... | import collections
import pytest | random_line_split |
test_python_bundler.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import os
import logging
from textwrap import dedent
import collections
import pytest
import mock
from gcdt_testtools.helpers import temp_folder, create_tempfile, cleanup_tempfiles
from gcdt_testtools import helpers
from gcdt_bundler.pyth... | ():
#z = Zappa(runtime='python3.6')
#self.assertIsNotNone(z.get_cached_manylinux_wheel('psycopg2', '2.7.1'))
#self.assertIsNone(z.get_cached_manylinux_wheel('derpderpderpderp', '0.0'))
assert _get_cached_manylinux_wheel('python3.6', 'psycopg2', '2.7.1') is not None
assert _get_cached_manylinux_wheel... | test_get_manylinux_python36 | identifier_name |
test_python_bundler.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import os
import logging
from textwrap import dedent
import collections
import pytest
import mock
from gcdt_testtools.helpers import temp_folder, create_tempfile, cleanup_tempfiles
from gcdt_testtools import helpers
from gcdt_bundler.pyth... |
def test_getting_installed_packages():
#z = Zappa(runtime='python2.7')
# mock pip packages call to be same as what our mocked site packages dir has
mock_package = collections.namedtuple('mock_package', ['project_name', 'version'])
mock_pip_installed_packages = [mock_package('super_package', '0.1')]
... | assert _have_correct_lambda_package_version('python2.7', 'psycopg2', '2.6.1')
assert _have_correct_lambda_package_version('python2.7', 'psycopg2', '2.7.1') is False
#testing case-insensitivity with lambda_package MySQL-Python
assert _have_correct_lambda_package_version('python2.7', 'mysql-python', '1.2.5')
... | identifier_body |
issue-3556.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // "ETag(@~[ ~\"foo\" ], @~\"bar\")"));
let t = Text(box(GC) "foo".to_string());
let u = Section(box(GC) vec!("alpha".to_string()),
true,
box(GC) vec!(t),
box(GC) "foo".to_string(),
box(GC) "foo... | // assert!(check_strs(fmt!("%?", Text(@"foo".to_string())), "Text(@~\"foo\")"));
// assert!(check_strs(fmt!("%?", ETag(@~["foo".to_string()], @"bar".to_string())), | random_line_split |
issue-3556.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
// assert!(check_strs(fmt!("%?", Text(@"foo".to_string())), "Text(@~\"foo\")"));
// assert!(check_strs(fmt!("%?", ETag(@~["foo".to_string()], @"bar".to_string())),
// "ETag(@~[ ~\"foo\" ], @~\"bar\")"));
let t = Text(box(GC) "foo".to_string());
let u = Section(box(GC) vec!("alpha".to_strin... | identifier_body | |
issue-3556.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (actual: &str, expected: &str) -> bool
{
if actual != expected
{
println!("Found {}, but expected {}", actual, expected);
return false;
}
return true;
}
pub fn main()
{
// assert!(check_strs(fmt!("%?", Text(@"foo".to_string())), "Text(@~\"foo\")"));
// assert!(check_strs(fmt!("%?", ETag... | check_strs | identifier_name |
issue-3556.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
return true;
}
pub fn main()
{
// assert!(check_strs(fmt!("%?", Text(@"foo".to_string())), "Text(@~\"foo\")"));
// assert!(check_strs(fmt!("%?", ETag(@~["foo".to_string()], @"bar".to_string())),
// "ETag(@~[ ~\"foo\" ], @~\"bar\")"));
let t = Text(box(GC) "foo".to_string());
let u = Se... | {
println!("Found {}, but expected {}", actual, expected);
return false;
} | conditional_block |
price_history_pack.py | import numpy as np
class PriceHistoryPack(object):
def __init__(self, input_seq_len, num_features, target_seq_len):
super(PriceHistoryPack, self).__init__()
self.sku_ids = []
self.XX = np.empty((0, input_seq_len, num_features))
self.YY = np.empty((0, target_seq_len))
self.s... |
def save(self, filepath, fraction=None, random_state=None):
if fraction is None:
np.savez(filepath, sku_ids=self.sku_ids, inputs=self.XX, targets=self.YY,
sequence_lengths=self.sequence_lens,
sequence_masks=self.seq_mask)
else:
skuI... | skuIds, xx, yy, seqLens, seqMask = np.array(self.sku_ids), self.XX, self.YY, np.array(
self.sequence_lens), self.seq_mask
if fraction is None:
return skuIds, xx, yy, seqLens, seqMask
else:
random_state = np.random if random_state is None else random_state
... | identifier_body |
price_history_pack.py | import numpy as np
class PriceHistoryPack(object):
def __init__(self, input_seq_len, num_features, target_seq_len):
super(PriceHistoryPack, self).__init__()
self.sku_ids = []
self.XX = np.empty((0, input_seq_len, num_features))
self.YY = np.empty((0, target_seq_len))
self.s... |
self.seq_mask = np.vstack((self.seq_mask, cur_mask[np.newaxis]))
def get_data(self, fraction=None, random_state=None):
# from sklearn.model_selection import train_test_split
skuIds, xx, yy, seqLens, seqMask = np.array(self.sku_ids), self.XX, self.YY, np.array(
self.sequence_len... |
assert len(xx_padded) == input_seq_len
self.XX = np.vstack((self.XX, xx_padded[np.newaxis]))
self.YY = np.vstack((self.YY, targets[np.newaxis])) | random_line_split |
price_history_pack.py | import numpy as np
class PriceHistoryPack(object):
def __init__(self, input_seq_len, num_features, target_seq_len):
super(PriceHistoryPack, self).__init__()
self.sku_ids = []
self.XX = np.empty((0, input_seq_len, num_features))
self.YY = np.empty((0, target_seq_len))
self.s... | (self, sku_id, inputs, targets, input_seq_len):
self.sku_ids.append(sku_id)
inputs_len = len(inputs)
self.sequence_lens.append(inputs_len)
# build current mask with zeros and ones
cur_mask = np.zeros(input_seq_len)
cur_mask[:inputs_len] = 1 # only the valid firsts shoul... | update | identifier_name |
price_history_pack.py | import numpy as np
class PriceHistoryPack(object):
def __init__(self, input_seq_len, num_features, target_seq_len):
super(PriceHistoryPack, self).__init__()
self.sku_ids = []
self.XX = np.empty((0, input_seq_len, num_features))
self.YY = np.empty((0, target_seq_len))
self.s... | skuIds, xx, yy, seqLens, seqMask = self.get_data(fraction=fraction, random_state=random_state)
np.savez(filepath, sku_ids=skuIds, inputs=xx, targets=yy, sequence_lengths=seqLens, sequence_masks=seqMask) | conditional_block | |
angular-article-directive.js | (function() {
var app = angular.module('article-directive', ['ui.bootstrap.contextMenu']);
app.config(function($sceProvider) {
// Completely disable SCE. For demonstration purposes only!
// Do not use in new projects.
$sceProvider.enabled(false);
});
app.directive('article', function () {
var c... |
if(document.selection && document.selection.type != "Control") {
return document.selection.createRange().text;
}
return "";
};
var link = function link(scope, element, attrs) {
scope.toggleComments = function () {
scope.$broadcast("event:toggle");
}
scope.menuOptions = [['Co... | {
return window.getSelection().toString();
} | conditional_block |
angular-article-directive.js | (function() {
var app = angular.module('article-directive', ['ui.bootstrap.contextMenu']);
app.config(function($sceProvider) {
// Completely disable SCE. For demonstration purposes only!
// Do not use in new projects.
$sceProvider.enabled(false);
});
app.directive('article', function () {
var c... |
return "";
};
var link = function link(scope, element, attrs) {
scope.toggleComments = function () {
scope.$broadcast("event:toggle");
}
scope.menuOptions = [['Copy', function ($itemScope) {
}],
null, // Dividier
['Comment', function ($itemScope) {
scope.toggleComments();
}]... | } | random_line_split |
hex.rs | // Copyright 2013-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... |
#[test]
pub fn test_from_hex_ignores_whitespace() {
assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(),
b"foobar");
}
#[test]
pub fn test_to_hex_all_bytes() {
for i in 0..256 {
assert_eq!([i as u8].to_hex(), format!("{:02x}", i as usize));
}... | {
assert!("66y6".from_hex().is_err());
} | identifier_body |
hex.rs | // Copyright 2013-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... | () {
assert_eq!("foobar".as_bytes().to_hex(), "666f6f626172");
}
#[test]
pub fn test_from_hex_okay() {
assert_eq!("666f6f626172".from_hex().unwrap(),
b"foobar");
assert_eq!("666F6F626172".from_hex().unwrap(),
b"foobar");
}
#[test]
p... | test_to_hex | identifier_name |
hex.rs | // Copyright 2013-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... |
//! Hex binary-to-text encoding
pub use self::FromHexError::*;
use std::fmt;
use std::error;
/// A trait for converting a value to hexadecimal encoding
pub trait ToHex {
/// Converts the value of `self` to a hex value, returning the owned
/// string.
fn to_hex(&self) -> String;
}
const CHARS: &'static ... | // except according to those terms. | random_line_split |
quickopen.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
async waitForQuickOpenOpened(): Promise<void> {
await this.spectron.client.waitForActiveElement(QuickOpen.QUICK_OPEN_INPUT);
// we gotta wait 50 milliseconds due to https://github.com/Microsoft/vscode/blob/master/src/vs/platform/list/browser/listService.ts#L59
await new Promise(c => setTimeout(c, 50));
}
p... | {
await this.openQuickOpen(`> ${commandText}`);
// wait for best choice to be focused
await this.spectron.client.waitForTextContent(QuickOpen.QUICK_OPEN_FOCUSED_ELEMENT, commandText);
// wait and click on best choice
await this.spectron.client.waitAndClick(QuickOpen.QUICK_OPEN_FOCUSED_ELEMENT);
} | identifier_body |
quickopen.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): Promise<void> {
await this.spectron.client.waitForElement(QuickOpen.QUICK_OPEN_HIDDEN);
}
async submit(text: string): Promise<void> {
await this.spectron.client.setValue(QuickOpen.QUICK_OPEN_INPUT, text);
await this.spectron.client.keys(['Enter', 'NULL']);
await this.waitForQuickOpenClosed();
}
async ... | waitForQuickOpenClosed | identifier_name |
quickopen.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
await this.spectron.client.keys(['Enter', 'NULL']);
await this.waitForQuickOpenClosed();
}
async waitForQuickOpenElements(accept: (names: string[]) => boolean): Promise<void> {
await this.spectron.client.waitFor(() => this.getQuickOpenElements(), accept);
}
private async getQuickOpenElements(): Promise<str... | {
await this.spectron.client.keys(['ArrowDown', 'NULL']);
} | conditional_block |
quickopen.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
async waitForQuickOpenElements(accept: (names: string[]) => boolean): Promise<void> {
await this.spectron.client.waitFor(() => this.getQuickOpenElements(), accept);
}
private async getQuickOpenElements(): Promise<string[]> {
const result = await this.spectron.webclient.selectorExecute(QuickOpen.QUICK_OPEN_ENTR... | }
await this.spectron.client.keys(['Enter', 'NULL']);
await this.waitForQuickOpenClosed();
} | random_line_split |
basic-types.rs | // Copyright 2013-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... | () {()}
| _zzz | identifier_name |
basic-types.rs | // Copyright 2013-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... |
fn _zzz() {()} | random_line_split | |
basic-types.rs | // Copyright 2013-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... | {()} | identifier_body | |
tweet.rs | _rules! error {
($($args:tt)*) => { eprintln!("{} {}", "ERROR".red(), format_args!($($args)*))};
}
fn main() -> Result<()> {
color_eyre::install()?;
eprintln!("Welcome to {}!", APP_NAME.bold());
eprintln!();
let conf_path = conf_file::path()?;
let mut conf = conf_file::read_or_create(&conf_pa... |
}
}
pub(super) fn save(path: impl AsRef<Path>, conf: &Config) -> Result<()> {
let path = path.as_ref();
let mut file = create(&path)?;
write(&path, &mut file, conf)?;
Ok(())
}
fn create(path: impl AsRef<Path>) -> Result<File> {
let path = path.as_ref()... | {
error!("Failed to read the existing config file");
eprintln!("Error detail: {:?}", err);
confirm_and_recreate(&path)
} | conditional_block |
tweet.rs | _rules! error {
($($args:tt)*) => { eprintln!("{} {}", "ERROR".red(), format_args!($($args)*))};
}
fn main() -> Result<()> {
color_eyre::install()?;
eprintln!("Welcome to {}!", APP_NAME.bold());
eprintln!();
let conf_path = conf_file::path()?;
let mut conf = conf_file::read_or_create(&conf_pa... |
fn write(&self, mut writer: impl Write) -> Result<()> {
serde_json::to_writer_pretty(&mut writer, self)?;
Ok(())
}
fn consumer_token(&self) -> Token {
Token::new(&self.consumer_key, &self.consumer_secret)
}
fn access_token(&self) -> Token {
Token::new(&self.access... | {
let conf = serde_json::from_reader(&mut reader)?;
Ok(conf)
} | identifier_body |
tweet.rs | macro_rules! error {
($($args:tt)*) => { eprintln!("{} {}", "ERROR".red(), format_args!($($args)*))};
}
fn main() -> Result<()> {
color_eyre::install()?;
eprintln!("Welcome to {}!", APP_NAME.bold());
eprintln!();
let conf_path = conf_file::path()?;
let mut conf = conf_file::read_or_create(&co... | match twitter::get_access_token(&consumer_token, &request_token, &pin) {
Ok(token) => token,
Err(err) => {
error!("Failed to get `access token`: {:?}", err);
continue;
}
};
... | random_line_split | |
tweet.rs | macro_rules! error {
($($args:tt)*) => { eprintln!("{} {}", "ERROR".red(), format_args!($($args)*))};
}
fn main() -> Result<()> {
color_eyre::install()?;
eprintln!("Welcome to {}!", APP_NAME.bold());
eprintln!();
let conf_path = conf_file::path()?;
let mut conf = conf_file::read_or_create(&co... | {
consumer_key: String,
consumer_secret: String,
access_key: String,
access_secret: String,
}
impl Config {
fn from_user_input(old_value: Option<&Self>) -> Result<Self> {
let input = |prompt, old_value| {
match old_value {
Some(value) => console::input_with_defa... | Config | identifier_name |
get.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | () {
/* eslint-disable no-invalid-this */
return this._yScale;
}
// EXPORTS //
module.exports = get;
| get | identifier_name |
get.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
// EXPORTS //
module.exports = get;
| {
/* eslint-disable no-invalid-this */
return this._yScale;
} | identifier_body |
get.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | * @private
* @returns {Function} scale function
*/
function get() {
/* eslint-disable no-invalid-this */
return this._yScale;
}
// EXPORTS //
module.exports = get; | * | random_line_split |
Filter.js | /**
* Represents a filter that can be applied to a {@link Ext.util.MixedCollection MixedCollection}. Can either simply
* filter on a property/value pair or pass in a filter function with custom logic. Filters are always used in the
* context of MixedCollections, though {@link Ext.data.Store Store}s frequently create... |
}
value = new RegExp(value, caseSensitive ? '' : 'i');
}
return value;
}
}); | {
value += '$';
} | conditional_block |
Filter.js | /**
* Represents a filter that can be applied to a {@link Ext.util.MixedCollection MixedCollection}. Can either simply
* filter on a property/value pair or pass in a filter function with custom logic. Filters are always used in the
* context of MixedCollections, though {@link Ext.data.Store Store}s frequently create... | * property: 'age',
* value : 32
* });
*
* var longNameFilter = new Ext.util.Filter({
* filterFn: function(item) {
* return item.name.length > 4;
* }
* });
*
* //a new MixedCollection with the 3 names longer than 4 characters
* var longNames =... | * {id: 4, name: 'Aaron', age: 26},
* {id: 5, name: 'David', age: 32}
* ]);
*
* var ageFilter = new Ext.util.Filter({ | random_line_split |
cs.js | /*
| For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'link', 'cs', {
acccessKey: 'Přístupový klíč',
advanced: 'Rozšířené',
advisoryContentType: 'Pomocný typ obsahu',
advisoryTitle: 'Pomocný titulek',
anchor: {
toolbar: 'Záložka',
menu: 'Vlastnosti záložky',
titl... | Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
| random_line_split |
KeyIndex.d.ts | /**
* @license
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applica... | extends Index {
static __EMPTY_NODE: ChildrenNode;
/**
* @inheritDoc
*/
compare(a: NamedNode, b: NamedNode): number;
/**
* @inheritDoc
*/
isDefinedOn(node: Node): boolean;
/**
* @inheritDoc
*/
indexedValueChanged(oldNode: Node, newNode: Node): bool... | KeyIndex | identifier_name |
KeyIndex.d.ts | /**
* @license
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applica... | maxPost(): NamedNode;
/**
* @param {*} indexValue
* @param {string} name
* @return {!NamedNode}
*/
makePost(indexValue: string, name: string): NamedNode;
/**
* @return {!string} String representation for inclusion in a query spec
*/
toString(): string;
}
exp... | */
| random_line_split |
profile.js | module.exports = async ({ client, configJS, Utils: { IsURL }, Constants: { Colors } }, msg, commandData) => {
const handleQuit = () => {
msg.reply({
embed: {
color: Colors.RED,
description: `You've exited the profile setup menu!`,
},
});
};
if (msg.suffix === "setup") {
let m = await msg.reply({... | image: {
url: IsURL(msg.author.userDocument.profile_background_image) ? msg.author.userDocument.profile_background_image : ``,
},
thumbnail: {
url: msg.author.displayAvatarURL({ size: 64, format: "png" }),
},
author: {
name: `Profile setup for ${msg.author.tag}`,
},
descriptio... | m = await msg.reply({
embed: {
color: Colors.LIGHT_BLUE,
title: `Next, here's your current backround.`, | random_line_split |
profile.js | module.exports = async ({ client, configJS, Utils: { IsURL }, Constants: { Colors } }, msg, commandData) => {
const handleQuit = () => {
msg.reply({
embed: {
color: Colors.RED,
description: `You've exited the profile setup menu!`,
},
});
};
if (msg.suffix === "setup") | try {
message = await client.awaitPMMessage(msg.channel, msg.author);
} catch (err) {
switch (err.code) {
case "AWAIT_QUIT": return handleQuit();
case "AWAIT_EXPIRED": {
m = await m.edit({
embed: {
color: Colors.LIGHT_ORANGE,
description: `You didn't answer in time... We'll ke... | {
let m = await msg.reply({
embed: {
color: Colors.LIGHT_BLUE,
author: {
name: `Profile setup for ${msg.author.tag}`,
},
title: `Let's setup your GAwesomeBot profile ~~--~~ See it by clicking here`,
url: `${configJS.hostingURL}activity/users?q=${encodeURIComponent(`${msg.author.tag}`)}`,
... | conditional_block |
DTStructuredMesh2D.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This software is under a BSD license. See LICENSE.txt for details.
from datatank_py.DTStructuredGrid2D import DTStructuredGrid2D, _squeeze2d
import numpy as np
class DTStructuredMesh2D(object):
"""2D structured mesh object.
This class corresponds to DataT... | (self, datafile, name):
datafile.write_anonymous(self._grid, name)
datafile.write_anonymous(self._values, name + "_V")
def write_with_shared_grid(self, datafile, name, grid_name, time, time_index):
"""Allows saving a single grid and sharing it amongst different time
values o... | __dt_write__ | identifier_name |
DTStructuredMesh2D.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This software is under a BSD license. See LICENSE.txt for details.
from datatank_py.DTStructuredGrid2D import DTStructuredGrid2D, _squeeze2d
import numpy as np
class DTStructuredMesh2D(object):
"""2D structured mesh object.
This class corresponds to DataT... |
# DataTank indexes differently from numpy; the grid is z,y,x ordered
values = values.reshape(grid.shape())
mesh = DTStructuredMesh2D(values, grid=grid)
df["2D mesh"] = mesh
| values[i] = i | conditional_block |
DTStructuredMesh2D.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This software is under a BSD license. See LICENSE.txt for details.
from datatank_py.DTStructuredGrid2D import DTStructuredGrid2D, _squeeze2d
import numpy as np
class DTStructuredMesh2D(object):
"""2D structured mesh object.
This class corresponds to DataT... | @classmethod
def from_data_file(self, datafile, name):
grid = DTStructuredGrid2D.from_data_file(datafile, name)
values = datafile[name + "_V"]
return DTStructuredMesh2D(values, grid=grid)
if __name__ == '__main__':
from DTDataFile import DTDataFile
with DTDataFile("tes... | varname = "%s_%d" % (name, time_index)
datafile.write_anonymous(grid_name, varname)
datafile.write_anonymous(self._values, varname + "_V")
datafile.write_anonymous(np.array((time,)), varname + "_time")
| random_line_split |
DTStructuredMesh2D.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This software is under a BSD license. See LICENSE.txt for details.
from datatank_py.DTStructuredGrid2D import DTStructuredGrid2D, _squeeze2d
import numpy as np
class DTStructuredMesh2D(object):
"""2D structured mesh object.
This class corresponds to DataT... |
def __dt_type__(self):
return "2D Structured Mesh"
def __str__(self):
return self.__dt_type__() + ":\n " + str(self._grid) + "\n" + " Values:\n " + str(self._values)
def __dt_write__(self, datafile, name):
datafile.write_anonymous(self._grid, name)... | """:returns: a 2D numpy array of values at each grid node"""
return self._values | identifier_body |
seqCheck.py | #! /usr/bin/env python
#edited on c9
import os
import array as array
import sys
if (len(sys.argv)==1):
print "usage >>seqCheck.py [fileRootName, path ('.') for cwd]"
sys.exit()
elif (len(sys.argv)==2):
|
elif (len(sys.argv)==3):
fileRootName = sys.argv[1]
rootpath = os.getcwd() + sys.argv[2]
print rootpath
else:
print "usage >>seqCheck.py [fileRootname, path ('.') for cwd]"
'''
mypath = os.getcwd()
print("Path at terminal when executing this file")
print(os.getcwd() + "\n")
print("This file path, rel... | fileRootName = sys.argv[1]
rootpath = os.getcwd() | conditional_block |
seqCheck.py | #! /usr/bin/env python
#edited on c9
import os
import array as array
import sys
if (len(sys.argv)==1):
print "usage >>seqCheck.py [fileRootName, path ('.') for cwd]"
sys.exit()
elif (len(sys.argv)==2):
fileRootName = sys.argv[1]
rootpath = os.getcwd()
elif (len(sys.argv)==3):
fileRootName = sys.a... |
print("Path at terminal when executing this file")
print(os.getcwd() + "\n")
print("This file path, relative to os.getcwd()")
print(__file__ + "\n")
print("This file full path (following symlinks)")
full_path = os.path.realpath(__file__)
print(full_path + "\n")
print("This file directory and name")
path, file = os.... | mypath = os.getcwd() | random_line_split |
test_checksum.py | import pytest
import tempfile
import shutil
import os
import music_rename
from music_rename import checksum
@pytest.fixture()
def empty(request):
dir = tempfile.mkdtemp()
os.mknod(os.path.join(dir, 'empty.txt'))
def cleanup():
shutil.rmtree(dir)
request.addfinalizer(cleanup)
return os.p... | return file[1]
def test_emptyfile(empty):
assert music_rename.checksum.md5sum_file(
empty) == 'd41d8cd98f00b204e9800998ecf8427e'
def test_not_empty(not_empty):
assert music_rename.checksum.md5sum_file(
not_empty) == '4e3e88d75e5dc70c6ebb2712bcf16227' | request.addfinalizer(cleanup) | random_line_split |
test_checksum.py | import pytest
import tempfile
import shutil
import os
import music_rename
from music_rename import checksum
@pytest.fixture()
def empty(request):
dir = tempfile.mkdtemp()
os.mknod(os.path.join(dir, 'empty.txt'))
def | ():
shutil.rmtree(dir)
request.addfinalizer(cleanup)
return os.path.join(dir, 'empty.txt')
@pytest.fixture()
def not_empty(request):
file = tempfile.mkstemp()
print(file)
fp = open(file[1], 'w')
fp.write("Some text...\n")
fp.close()
def cleanup():
os.remove(file[1])
... | cleanup | identifier_name |
test_checksum.py | import pytest
import tempfile
import shutil
import os
import music_rename
from music_rename import checksum
@pytest.fixture()
def empty(request):
dir = tempfile.mkdtemp()
os.mknod(os.path.join(dir, 'empty.txt'))
def cleanup():
|
request.addfinalizer(cleanup)
return os.path.join(dir, 'empty.txt')
@pytest.fixture()
def not_empty(request):
file = tempfile.mkstemp()
print(file)
fp = open(file[1], 'w')
fp.write("Some text...\n")
fp.close()
def cleanup():
os.remove(file[1])
request.addfinalizer(clea... | shutil.rmtree(dir) | identifier_body |
CameraswitchRounded.js | import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", { | }, "0"), /*#__PURE__*/_jsx("path", {
d: "M9.45.28c-.4.08-.55.56-.26.84l3.01 3.01c.32.31.85.09.85-.35V2.04c4.45.44 8.06 3.82 8.84 8.17.08.46.5.78.97.78.62 0 1.09-.57.98-1.18C22.61 2.89 15.79-1.12 9.45.28zm2.35 19.59c-.32-.32-.85-.09-.85.35v1.74c-4.45-.44-8.06-3.82-8.84-8.17-.08-.46-.5-.78-.97-.78-.62 0-1.09.57-.98 1.1... | d: "M16 7h-1l-1-1h-4L9 7H8c-1.1 0-2 .9-2 2v6c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zm-4 7c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z" | random_line_split |
full_factorial.py | """
Author: Dr. John T. Hwang <hwangjt@umich.edu>
This package is distributed under New BSD license.
Full-factorial sampling.
"""
import numpy as np
from smt.sampling_methods.sampling_method import SamplingMethod
class FullFactorial(SamplingMethod):
def _initialize(self):
self.options.declare(
... | (self, nt):
"""
Compute the requested number of sampling points.
Arguments
---------
nt : int
Number of points requested.
Returns
-------
ndarray[nt, nx]
The sampling locations in the input space.
"""
xlimits = sel... | _compute | identifier_name |
full_factorial.py | """
Author: Dr. John T. Hwang <hwangjt@umich.edu>
This package is distributed under New BSD license.
Full-factorial sampling.
"""
import numpy as np
from smt.sampling_methods.sampling_method import SamplingMethod
class FullFactorial(SamplingMethod):
def _initialize(self):
self.options.declare(
... | weights = np.ones(nx) / nx
else:
weights = np.atleast_1d(self.options["weights"])
weights /= np.sum(weights)
num_list = np.ones(nx, int)
while np.prod(num_list) < nt:
ind = np.argmax(weights - num_list / np.sum(num_list))
num_list[ind]... | """
xlimits = self.options["xlimits"]
nx = xlimits.shape[0]
if self.options["weights"] is None: | random_line_split |
full_factorial.py | """
Author: Dr. John T. Hwang <hwangjt@umich.edu>
This package is distributed under New BSD license.
Full-factorial sampling.
"""
import numpy as np
from smt.sampling_methods.sampling_method import SamplingMethod
class FullFactorial(SamplingMethod):
def _initialize(self):
self.options.declare(
... |
lins_list = [np.linspace(0.0, 1.0, num_list[kx]) for kx in range(nx)]
x_list = np.meshgrid(*lins_list, indexing="ij")
if self.options["clip"]:
nt = np.prod(num_list)
x = np.zeros((nt, nx))
for kx in range(nx):
x[:, kx] = x_list[kx].reshape(np.prod(num_... | ind = np.argmax(weights - num_list / np.sum(num_list))
num_list[ind] += 1 | conditional_block |
full_factorial.py | """
Author: Dr. John T. Hwang <hwangjt@umich.edu>
This package is distributed under New BSD license.
Full-factorial sampling.
"""
import numpy as np
from smt.sampling_methods.sampling_method import SamplingMethod
class FullFactorial(SamplingMethod):
def _initialize(self):
|
def _compute(self, nt):
"""
Compute the requested number of sampling points.
Arguments
---------
nt : int
Number of points requested.
Returns
-------
ndarray[nt, nx]
The sampling locations in the input space.
"""
... | self.options.declare(
"weights",
values=None,
types=(list, np.ndarray),
desc="relative sampling weights for each nx dimensions",
)
self.options.declare(
"clip",
default=False,
types=bool,
desc="round number o... | identifier_body |
extern-return-TwoU8s.rs | // Copyright 2012 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 ... | }
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_extern_return_TwoU8s() -> TwoU8s;
}
pub fn main() {
unsafe {
let y = rust_dbg_extern_return_TwoU8s();
assert_eq!(y.one, 10);
assert_eq!(y.two, 20);
}
} | // except according to those terms.
pub struct TwoU8s {
one: u8, two: u8 | random_line_split |
extern-return-TwoU8s.rs | // Copyright 2012 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 ... | {
one: u8, two: u8
}
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_extern_return_TwoU8s() -> TwoU8s;
}
pub fn main() {
unsafe {
let y = rust_dbg_extern_return_TwoU8s();
assert_eq!(y.one, 10);
assert_eq!(y.two, 20);
}
}
| TwoU8s | identifier_name |
extern-return-TwoU8s.rs | // Copyright 2012 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 ... | {
unsafe {
let y = rust_dbg_extern_return_TwoU8s();
assert_eq!(y.one, 10);
assert_eq!(y.two, 20);
}
} | identifier_body | |
date.rs | //
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
//! Module for wrapping chrono::naive::datetime::NaiveDateTime
use std::ops::{Deref, DerefMut};
use serde::Se... | (&self) -> &NaiveDateTime {
&self.0
}
}
impl DerefMut for Date {
fn deref_mut(&mut self) -> &mut NaiveDateTime {
&mut self.0
}
}
impl From<NaiveDateTime> for Date {
fn from(ndt: NaiveDateTime) -> Date {
Date(ndt)
}
}
/// The date-time parsing template used to parse the dat... | deref | identifier_name |
date.rs | //
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
//! Module for wrapping chrono::naive::datetime::NaiveDateTime
use std::ops::{Deref, DerefMut};
use serde::Se... | use chrono::NaiveDateTime;
/// Date is a NaiveDateTime-Wrapper object to be able to implement foreign traits on it
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct Date(NaiveDateTime);
impl Deref for Date {
type Target = NaiveDateTime;
fn deref(&self) -> &NaiveDateTime {
&self.0
}
}
impl ... | use serde::Deserializer;
use serde::de::Visitor;
use serde::de::Error as SerdeError; | random_line_split |
date.rs | //
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
//! Module for wrapping chrono::naive::datetime::NaiveDateTime
use std::ops::{Deref, DerefMut};
use serde::Se... |
}
deserializer.deserialize_str(DateVisitor)
}
}
| {
NaiveDateTime::parse_from_str(value, TASKWARRIOR_DATETIME_TEMPLATE)
.map(|d| Date(d))
.map_err(|e| SerdeError::custom(e.to_string()))
} | identifier_body |
ckeditor_init.js | function CKEditor_Load() {
if (arguments.callee.done) return;
arguments.callee.done = true;
CKEDITOR.replaceAll(function( textarea, config ){
config.disableNativeSpellChecker = false;
config.scayt_autoStartup = true;
config.extraPlugins = 'bbcodehtml,syntaxhighlight,bb... | ['Blockquote', 'syntaxhighlight', 'bbcodeselector'],
['SelectAll', 'RemoveFormat'],
['About'],
'/',
['Bold', 'Italic', 'Underline', '-', 'TextColor', 'Font', 'FontSize'],
['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'PasteText... | random_line_split | |
ckeditor_init.js | function CKEditor_Load() | '/',
['Bold', 'Italic', 'Underline', '-', 'TextColor', 'Font', 'FontSize'],
['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'PasteText','PasteFromWord'],
['Outdent', 'Indent'],
['Scayt']
] ;
config.entities_greek = false;
config.enti... | {
if (arguments.callee.done) return;
arguments.callee.done = true;
CKEDITOR.replaceAll(function( textarea, config ){
config.disableNativeSpellChecker = false;
config.scayt_autoStartup = true;
config.extraPlugins = 'bbcodehtml,syntaxhighlight,bbcodeselector';
con... | identifier_body |
ckeditor_init.js | function CKEditor_Load() {
if (arguments.callee.done) return;
arguments.callee.done = true;
CKEDITOR.replaceAll(function( textarea, config ){
config.disableNativeSpellChecker = false;
config.scayt_autoStartup = true;
config.extraPlugins = 'bbcodehtml,syntaxhighlight,bb... |
window.onload = CKEditor_Load; | {
document.addEventListener("DOMContentLoaded", CKEditor_Load, false);
} | conditional_block |
ckeditor_init.js | function | () {
if (arguments.callee.done) return;
arguments.callee.done = true;
CKEDITOR.replaceAll(function( textarea, config ){
config.disableNativeSpellChecker = false;
config.scayt_autoStartup = true;
config.extraPlugins = 'bbcodehtml,syntaxhighlight,bbcodeselector';
... | CKEditor_Load | identifier_name |
game.py | import pyglet
from init_game import *
import random
def get_4_random_xy_combo_coordinates():
qs = (
( (width, 1.5*width), (0, height/2) ),
( (1.5*width, 2*width), (0, height/2) ),
( (width, 1.5*width), (height/2, height-150) ),
( (1.5*width, 2*widt... |
#playing continuous sound
snd = pyglet.media.load('bg.mp3')
looper = pyglet.media.SourceGroup(snd.audio_format, None)
looper.loop = True
looper.queue(snd)
p = pyglet.media.Player()
p.queue(looper)
p.play()
pyglet.clock.schedule_interval(change_score, 1)
#pyglet.clock.schedule_interval(collision_detection, 0.1)
#runn... | s_hero.y = s_hero.y-30 | conditional_block |
game.py | import pyglet
from init_game import *
import random
def get_4_random_xy_combo_coordinates():
qs = (
( (width, 1.5*width), (0, height/2) ),
( (1.5*width, 2*width), (0, height/2) ),
( (width, 1.5*width), (height/2, height-150) ),
( (1.5*width, 2*widt... | ():
global is_game_over
sprites = (s_bat, s_cat, s_bird, s_zombie, s_onion, s_devil, s_square, s_p5, s_p3, s_p7)
for sprite in sprites:
hero_y_low = s_hero.y - s_hero.height/2
hero_y_up = s_hero.y + s_hero.height/2
hero_x_low = s_hero.y - s_hero.width/2
hero_x_up = s_hero... | collision_detection | identifier_name |
game.py | import pyglet
from init_game import *
import random
def get_4_random_xy_combo_coordinates():
qs = (
( (width, 1.5*width), (0, height/2) ),
( (1.5*width, 2*width), (0, height/2) ),
( (width, 1.5*width), (height/2, height-150) ),
( (1.5*width, 2*widt... | s_p5.y = y
s_cat.x = x-25
s_cat.y = y+15
s_p5.draw()
s_cat.draw()
def draw_onion_on_platform(x, y):
s_p7.x = x
s_p7.y = y
s_onion.x = x-30
s_onion.y = y+15
s_p7.draw()
s_onion.draw()
def draw_zombie_on_platform(x,y):
s_p3.x=x
s_p3.y=y
s_zombie.x=x-20
s_zombie.y=y+15
s_... |
def draw_cat_on_platform(x, y):
s_p5.x = x | random_line_split |
game.py | import pyglet
from init_game import *
import random
def get_4_random_xy_combo_coordinates():
qs = (
( (width, 1.5*width), (0, height/2) ),
( (1.5*width, 2*width), (0, height/2) ),
( (width, 1.5*width), (height/2, height-150) ),
( (1.5*width, 2*widt... | draw_bird(x7-dx,y3)
dx = dx+speed
else:
dx = 1
collision_detection()
def draw_labels():
label = pyglet.text.Label("SCORE: " + str(score),
font_name='Arial',
font_size=16,
x=width/2-100, y=height-50,
... | global dx, list_xy, speed
if dx == 1:
list_xy = get_4_random_xy_combo_coordinates()
x1,y1 = list_xy[0]
x2,y2 = list_xy[1]
x3,y3 = list_xy[2]
x4,y4 = list_xy[3]
x5,y5 = width+x1, y1
x6,y5 = width+x2, y2
x7,y5 = width+x3, y3
if dx<2*width:
draw_cat_on_platform(x1-dx, ... | identifier_body |
cwrap.py | self.runTime = runTime
self.exitCode = exitCode
self.stdout = stdout
self.stderr = stderr
self.pyError = pythonError
def __str__(self):
ret = '%s\nCommand: %s\n' % (self.mainDelim, ' '.join(self.command))
ret += 'Start Time: %s\n' % time.ctime(self.timeStarte... |
start = self.lastRunStartTime = time.time()
stdout = ''
stderr = ''
if self.opts.timeout:
# We set an alarm for the execution of this program since a
# timeout was set
signal.signal(signal.SIGALRM, self._timeoutHandler)
signal.alarm(self.o... | time.sleep(randint(0, self.opts.fuzz)) | conditional_block |
cwrap.py |
class CmdTimeout(Exception):
pass
class MailError(Exception):
pass
# Define classes
class StateFile:
def __init__(self, name, mode='rb+', buffering=-1, lockFile=None):
"""
Override the init function to create a lockfile
"""
if lockFile:
self._lockName = loc... | return '{}\n{}'.format(
self.msg, '\n'.join([str(e) for e in self.eList])) | identifier_body | |
cwrap.py | (Exception):
"""
Error to be raised when a lockfile is found
"""
pass
class FileCreationError(Exception):
def __init__(self, msg, errorList=[]):
self.msg = msg
self.eList = errorList
def __str__(self):
return '{}\n{}'.format(
self.msg, '\n'.join([str(e) for... | LockError | identifier_name | |
cwrap.py | True
self._lastEmailNum = self.NumFails
if sendEmail:
sioFail = self._getFailText()
if self.opts.mail:
self._sendEmail(sioFail.getvalue())
if not self.opts.suppressOutput:
print(sioFail.getvalue())
... | random_line_split | ||
contents_view.js | /**
* iroha Board Project
*
* @author Kotaro Miura
* @copyright 2015-2021 iroha Soft, Inc. (https://irohasoft.jp)
* @link https://irohaboard.irohasoft.jp
* @license https://www.gnu.org/licenses/gpl-3.0.en.html GPL License
*/
var _studySec = 0;
$(document).ready(function()
{
setInter... | n.href.split('/')[location.href.split('/').length - 1] == 'preview')
{
window.close();
return;
}
// 中断の場合
if(val==0)
{
location.href = URL_RECORDS_ADD + '/0/' + _studySec + '/0';
return;
}
// 学習履歴を残さずに終了の場合
if(val==-1)
{
location.href = URL_CONTNES_INDEX;
return;
}
// 学習履歴を残して終了の場合
locatio... | ocatio | identifier_name |
contents_view.js | /**
* iroha Board Project
*
* @author Kotaro Miura
* @copyright 2015-2021 iroha Soft, Inc. (https://irohasoft.jp)
* @link https://irohaboard.irohasoft.jp
* @license https://www.gnu.org/licenses/gpl-3.0.en.html GPL License
*/
var _studySec = 0;
$(document).ready(function()
{
setInter... | }
// 中断の場合
if(val==0)
{
location.href = URL_RECORDS_ADD + '/0/' + _studySec + '/0';
return;
}
// 学習履歴を残さずに終了の場合
if(val==-1)
{
location.href = URL_CONTNES_INDEX;
return;
}
// 学習履歴を残して終了の場合
location.href = URL_RECORDS_ADD + '/1/' + _studySec + '/' + val;
return;
} | window.close();
return; | random_line_split |
contents_view.js | /**
* iroha Board Project
*
* @author Kotaro Miura
* @copyright 2015-2021 iroha Soft, Inc. (https://irohasoft.jp)
* @link https://irohaboard.irohasoft.jp
* @license https://www.gnu.org/licenses/gpl-3.0.en.html GPL License
*/
var _studySec = 0;
$(document).ready(function()
{
setInter... | // 学習履歴を残して終了の場合
location.href = URL_RECORDS_ADD + '/1/' + _studySec + '/' + val;
return;
}
| .split('/')[location.href.split('/').length - 1] == 'preview')
{
window.close();
return;
}
// 中断の場合
if(val==0)
{
location.href = URL_RECORDS_ADD + '/0/' + _studySec + '/0';
return;
}
// 学習履歴を残さずに終了の場合
if(val==-1)
{
location.href = URL_CONTNES_INDEX;
return;
}
| identifier_body |
issue-10228.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(dead_code)]
#![allow(unused_variables)]
// pretty-expanded FIXME #23616
enum StdioContainer {
CreatePipe(bool)
}
struct Test<'a> {
args: &'a [String],
io: &'a [StdioContainer]
}
pub ... | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | random_line_split |
issue-10228.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let test = Test {
args: &[],
io: &[StdioContainer::CreatePipe(true)]
};
}
| main | identifier_name |
autocomplete.component.ts | import { Component, OnInit, ViewChild, ElementRef, Input, Output, ViewEncapsulation } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import { Observable, Subject } from 'rxjs/Rx';
import bem from 'bem-cn';
import {DataService, ICity} from '../shared';
const selector = 'tch-au... | })
export class AutocompleteComponent implements OnInit {
private cls = bem(selector);
private citiesList$: Observable<ICity[]>;
private ngUnsubscribe: Subject<void> = new Subject<void>();
private isListVisible: boolean;
@Input('label') label: string;
@Input('name') name: string;
@Input('group') autocompl... | styleUrls: ['./autocomplete.component.scss'] | random_line_split |
autocomplete.component.ts | import { Component, OnInit, ViewChild, ElementRef, Input, Output, ViewEncapsulation } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import { Observable, Subject } from 'rxjs/Rx';
import bem from 'bem-cn';
import {DataService, ICity} from '../shared';
const selector = 'tch-au... |
//https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
| {
this.isListVisible = false;
this.autocompleteGroup.setValue({
value: title,
id: value,
});
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.