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
utils.js
import pidcrypt from 'pidcrypt' import { path, pipe, type, equals } from 'rambda' import { toByteArray, decodeBase64, encodeBase64, convertFromHex } from 'pidcrypt/pidcrypt_util' import 'pidcrypt/asn1' import 'pidcrypt/rsa' import createError from './error' const { RSA, ASN1 } = pidcrypt const CHARS =...
const asn = ASN1.decode(toByteArray(decodeBase64(key))) const rsa = new RSA() rsa.setPublicKeyFromASN(asn.toHexTree()) return encodeBase64(convertFromHex(rsa.encrypt(value))) } export function get(inputObject, inputPath, defaultValue) { const inputValue = path(inputPath, inputObject) return isUndefined(inp...
random_line_split
buffer_map.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/. */ use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use geom::size::Size2D; ...
} impl PartialEq for BufferKey { fn eq(&self, other: &BufferKey) -> bool { let BufferKey(s) = *self; let BufferKey(o) = *other; s[0] == o[0] && s[1] == o[1] } } /// Create a key from a given size impl BufferKey { fn get(input: Size2D<uint>) -> BufferKey { BufferKey([input....
{ let BufferKey(ref bytes) = *self; bytes.as_slice().hash(state); }
identifier_body
buffer_map.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/. */ use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use geom::size::Size2D; ...
(&mut self, size: Size2D<uint>) -> Option<Box<LayerBuffer>> { let mut flag = false; // True if key needs to be popped after retrieval. let key = BufferKey::get(size); let ret = match self.map.get_mut(&key) { Some(ref mut buffer_val) => { buffer_val.last_action = self....
find
identifier_name
buffer_map.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/. */ use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use geom::size::Size2D; ...
mem: uint, /// The maximum allowed memory. Unused buffers will be deleted /// when this threshold is exceeded. max_mem: uint, /// A monotonically increasing counter to track how recently tile sizes were used. counter: uint, } /// A key with which to store buffers. It is based on the size of the...
pub struct BufferMap { /// A HashMap that stores the Buffers. map: HashMap<BufferKey, BufferValue>, /// The current amount of memory stored by the BufferMap's buffers.
random_line_split
WebRtcTransport.d.ts
import { EnhancedEventEmitter } from './EnhancedEventEmitter'; import { Transport, TransportListenIp, TransportProtocol, TransportTuple, SctpState } from './Transport'; import { SctpParameters, NumSctpStreams } from './SctpParameters'; export declare type WebRtcTransportOptions = { /** * Listening IP address o...
/** * DTLS parameters. */ get dtlsParameters(): DtlsParameters; /** * DTLS state. */ get dtlsState(): DtlsState; /** * Remote certificate in PEM format. */ get dtlsRemoteCert(): string | undefined; /** * SCTP parameters. */ get sctpParameters(): Sc...
* ICE selected tuple. */ get iceSelectedTuple(): TransportTuple | undefined;
random_line_split
WebRtcTransport.d.ts
import { EnhancedEventEmitter } from './EnhancedEventEmitter'; import { Transport, TransportListenIp, TransportProtocol, TransportTuple, SctpState } from './Transport'; import { SctpParameters, NumSctpStreams } from './SctpParameters'; export declare type WebRtcTransportOptions = { /** * Listening IP address o...
extends Transport { protected readonly _data: { iceRole: 'controlled'; iceParameters: IceParameters; iceCandidates: IceCandidate[]; iceState: IceState; iceSelectedTuple?: TransportTuple; dtlsParameters: DtlsParameters; dtlsState: DtlsState; dtlsRemote...
WebRtcTransport
identifier_name
indexer_v2.py
_log = configData['purgeLog'] #Initialization... print ("\n-----------------------= AMS Py =----------------------") print ("Azure Media Analytics - Indexer v2 Preview Sample") print ("for details : https://azure.microsoft.com/en-us/documentation/articles/media-services-process-content-with-indexer2/ ") print ("------...
### Start upload the video file print_phase_header("Uploading the Video File") with open(VIDEO_PATH, mode='rb') as file: video_content = file.read() video_content_length = len(video_content) response = block_blob_service.create_blob_from_path( sto_asset_name, VIDEO_NAME, VIDEO_PATH, max_conne...
if (current != None): print_phase_message('{0:2,f}/{1:2,.0f} MB'.format(current,total/1024/1024))
identifier_body
indexer_v2.py
_log = configData['purgeLog'] #Initialization... print ("\n-----------------------= AMS Py =----------------------") print ("Azure Media Analytics - Indexer v2 Preview Sample") print ("for details : https://azure.microsoft.com/en-us/documentation/articles/media-services-process-content-with-indexer2/ ") print ("------...
(message): time_stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") print (str(time_stamp) + ": " + message) ### get ams redirected url response = amspy.get_url(access_token) if (response.status_code == 200): ams_redirected_rest_endpoint = str(response.url) else: print_phase_...
print_phase_message
identifier_name
indexer_v2.py
_log = configData['purgeLog'] #Initialization... print ("\n-----------------------= AMS Py =----------------------") print ("Azure Media Analytics - Indexer v2 Preview Sample") print ("for details : https://azure.microsoft.com/en-us/documentation/articles/media-services-process-content-with-indexer2/ ") print ("------...
print_phase_message("SAS URL Locator Content Access Component: " + saslocator_cac) else: print_phase_message("POST Status: " + str(response.status_code) + " - SAS URL Locator Creation ERROR." + str(response.content)) ### Use the Azure Blob Blob Servic library from the Azure Storage SDK. block_blob_service = BlockBlo...
print_phase_message("SAS URL Locator Base URI................: " + saslocator_baseuri)
random_line_split
indexer_v2.py
_log = configData['purgeLog'] #Initialization... print ("\n-----------------------= AMS Py =----------------------") print ("Azure Media Analytics - Indexer v2 Preview Sample") print ("for details : https://azure.microsoft.com/en-us/documentation/articles/media-services-process-content-with-indexer2/ ") print ("------...
### create an asset write access policy for uploading print_phase_header("Creating an Asset Write Access Policy") duration = "440" response = amspy.create_asset_accesspolicy(access_token, "NewUploadPolicy", duration, "2") if (response.status_code == 201): resjson = response.json() write_accesspolicy_id = str(resjso...
print_phase_message("POST Status: " + str(response.status_code) + " - Media Assetfile: '" + VIDEO_NAME + "' Creation ERROR." + str(response.content))
conditional_block
inflightmap.rs
use std::cmp::Ordering; use std::collections::hash_map::{Entry, RandomState}; use std::collections::{BinaryHeap, HashMap}; use std::fmt; use std::hash::{BuildHasher, Hash}; use std::ops::Deref; // TODO: need a more efficient implementation and possibly more flexibility #[derive(Debug)] pub struct InFlightMap<K: Hash ...
} impl<T: Eq, V> Eq for Pair<T, V> {} impl<T: PartialOrd, V> PartialOrd<Pair<T, V>> for Pair<T, V> { fn partial_cmp(&self, other: &Pair<T, V>) -> Option<Ordering> { other.0.partial_cmp(&self.0) } } impl<T: Ord, V> Ord for Pair<T, V> { fn cmp(&self, other: &Pair<T, V>) -> Ordering { other...
{ other.0.eq(&self.0) }
identifier_body
inflightmap.rs
use std::cmp::Ordering; use std::collections::hash_map::{Entry, RandomState}; use std::collections::{BinaryHeap, HashMap}; use std::fmt; use std::hash::{BuildHasher, Hash}; use std::ops::Deref; // TODO: need a more efficient implementation and possibly more flexibility #[derive(Debug)] pub struct InFlightMap<K: Hash ...
(&mut self, key: &K) -> Option<V> { self.map.remove(key) } pub fn entry_with_timeout(&mut self, key: K, expire: T) -> Entry<K, V> { self.heap.push(Pair(expire, key)); self.map.entry(key) } pub fn entry(&mut self, key: K) -> Entry<K, V> { self.map.entry(key) } p...
remove
identifier_name
inflightmap.rs
use std::cmp::Ordering; use std::collections::hash_map::{Entry, RandomState}; use std::collections::{BinaryHeap, HashMap}; use std::fmt; use std::hash::{BuildHasher, Hash}; use std::ops::Deref; // TODO: need a more efficient implementation and possibly more flexibility #[derive(Debug)] pub struct InFlightMap<K: Hash ...
} pub fn entry_with_timeout(&mut self, key: K, expire: T) -> Entry<K, V> { self.heap.push(Pair(expire, key)); self.map.entry(key) } pub fn entry(&mut self, key: K) -> Entry<K, V> { self.map.entry(key) } pub fn insert(&mut self, key: K, value: V, expire: T) -> &mut V { ...
pub fn remove(&mut self, key: &K) -> Option<V> { self.map.remove(key)
random_line_split
resampling.py
######################################################################################### # # Resample data using nibabel. # # --------------------------------------------------------------------------------------- # Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca> # Authors: Julien Cohen-Adad, Sara Dup...
# to view results display_viewer_syntax([fname_out], verbose=verbose) return nii_r
nib.save(nii_r, fname_out)
random_line_split
resampling.py
######################################################################################### # # Resample data using nibabel. # # --------------------------------------------------------------------------------------- # Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca> # Authors: Julien Cohen-Adad, Sara Dup...
def resample_file(fname_data, fname_out, new_size, new_size_type, interpolation, verbose, fname_ref=None): """This function will resample the specified input image file to the target size. Can deal with 2d, 3d or 4d image objects. :param fname_data: The input image filename. :param fname_out: Th...
return Image(img_r.get_data(), hdr=img_r.header, orientation=image.orientation, dim=img_r.header.get_data_shape())
conditional_block
resampling.py
######################################################################################### # # Resample data using nibabel. # # --------------------------------------------------------------------------------------- # Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca> # Authors: Julien Cohen-Adad, Sara Dup...
# If input is an Image object, create nibabel object from it if type(image) == nib.nifti1.Nifti1Image: img = image elif type(image) == Image: img = nib.nifti1.Nifti1Image(image.data, image.hdr.get_best_affine()) else: raise Exception(TypeError) if image_dest is None: ...
""" Resample a nibabel or Image object based on a specified resampling factor. Can deal with 2d, 3d or 4d image objects. :param image: nibabel or Image image. :param new_size: list of float: Resampling factor, final dimension or resolution, depending on new_size_type. :param new_size_type: {'vox', ...
identifier_body
resampling.py
######################################################################################### # # Resample data using nibabel. # # --------------------------------------------------------------------------------------- # Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca> # Authors: Julien Cohen-Adad, Sara Dup...
(image, new_size=None, new_size_type=None, image_dest=None, interpolation='linear', mode='nearest'): """ Resample a nibabel or Image object based on a specified resampling factor. Can deal with 2d, 3d or 4d image objects. :param image: nibabel or Image image. :param new_size: list of float: Resampl...
resample_nib
identifier_name
test_application.py
from StringIO import StringIO import unittest from shunter.request import HTTPRequest import mockapp class TestApplication(unittest.TestCase): def setUp(self): self.app = mockapp.application def test_get_response(self): request = HTTPRequest({'REQUEST_METHOD': 'GET', ...
'Content-Type': 'text/plain', 'wsgi.errors': StringIO()}) response = self.app.get_response(request) self.assertEqual(response.status, 500)
random_line_split
test_application.py
from StringIO import StringIO import unittest from shunter.request import HTTPRequest import mockapp class TestApplication(unittest.TestCase):
'Content-Type': 'text/plain', 'wsgi.errors': StringIO()}) response = self.app.get_response(request) self.assertEqual(response.status, 500)
def setUp(self): self.app = mockapp.application def test_get_response(self): request = HTTPRequest({'REQUEST_METHOD': 'GET', 'PATH_INFO': '', 'Content-Type': 'text/plain'}) response = self.app.get_response(request) self....
identifier_body
test_application.py
from StringIO import StringIO import unittest from shunter.request import HTTPRequest import mockapp class TestApplication(unittest.TestCase): def setUp(self): self.app = mockapp.application def
(self): request = HTTPRequest({'REQUEST_METHOD': 'GET', 'PATH_INFO': '', 'Content-Type': 'text/plain'}) response = self.app.get_response(request) self.assertEqual(response.content.read(), 'Hello World!') self.assertEqual(resp...
test_get_response
identifier_name
objectLiteralShorthandRule.ts
/** * @license * Copyright 2016 Palantir Technologies, 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...
prefix = "*"; } if (hasModifier(initializer.modifiers, ts.SyntaxKind.AsyncKeyword)) { prefix = `async ${prefix}`; } if (prefix !== "") { fix = [fix, Lint.Replacement.appendText(nameStart, prefix)]; } return [prefix + sourceFile.text.substring(nameStart, name.end), fix]; }
let fix: Lint.Fix = Lint.Replacement.deleteFromTo(name.end, getChildOfKind(initializer, ts.SyntaxKind.OpenParenToken)!.pos); let prefix = ""; if (initializer.asteriskToken !== undefined) {
random_line_split
objectLiteralShorthandRule.ts
/** * @license * Copyright 2016 Palantir Technologies, 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...
(name: ts.PropertyName, initializer: ts.FunctionExpression, sourceFile: ts.SourceFile): [string, Lint.Fix] { const nameStart = name.getStart(sourceFile); let fix: Lint.Fix = Lint.Replacement.deleteFromTo(name.end, getChildOfKind(initializer, ts.SyntaxKind.OpenParenToken)!.pos); let prefix = ""; if (init...
handleLonghandMethod
identifier_name
test_md.py
# SPDX-License-Identifier: GPL-2.0 # Copyright (c) 2015 Stephen Warren # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved. import pytest import u_boot_utils @pytest.mark.buildconfigspec('cmd_memory') def test_md(u_boot_console):
@pytest.mark.buildconfigspec('cmd_memory') def test_md_repeat(u_boot_console): """Test command repeat (via executing an empty command) operates correctly for "md"; the command must repeat and dump an incrementing address.""" ram_base = u_boot_utils.find_ram_base(u_boot_console) addr_base = '%08x' % r...
"""Test that md reads memory as expected, and that memory can be modified using the mw command.""" ram_base = u_boot_utils.find_ram_base(u_boot_console) addr = '%08x' % ram_base val = 'a5f09876' expected_response = addr + ': ' + val u_boot_console.run_command('mw ' + addr + ' 0 10') respons...
identifier_body
test_md.py
# SPDX-License-Identifier: GPL-2.0 # Copyright (c) 2015 Stephen Warren # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved. import pytest import u_boot_utils @pytest.mark.buildconfigspec('cmd_memory') def
(u_boot_console): """Test that md reads memory as expected, and that memory can be modified using the mw command.""" ram_base = u_boot_utils.find_ram_base(u_boot_console) addr = '%08x' % ram_base val = 'a5f09876' expected_response = addr + ': ' + val u_boot_console.run_command('mw ' + addr ...
test_md
identifier_name
test_md.py
# SPDX-License-Identifier: GPL-2.0 # Copyright (c) 2015 Stephen Warren # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved. import pytest import u_boot_utils @pytest.mark.buildconfigspec('cmd_memory') def test_md(u_boot_console): """Test that md reads memory as expected, and that memory can be modi...
expected_response = addr_repeat + ': ' assert(expected_response in response)
u_boot_console.run_command('md %s %x' % (addr_base, words)) response = u_boot_console.run_command('')
random_line_split
list_documents.rs
use crate::domain::model::error::Error as ModelError; use crate::domain::ports::secondary::list::{List, Parameters}; use async_trait::async_trait; use common::document::ContainerDocument; use futures::stream::{Stream, StreamExt}; use std::pin::Pin; use tracing::info_span; use tracing_futures::Instrument; type PinnedSt...
(&self) -> Result<PinnedStream<Result<D, ModelError>>, ModelError> { let doc_type = D::static_doc_type().to_string(); let documents = self .list_documents(Parameters { doc_type }) .await? .map(|raw| raw.map_err(|err| ModelError::DocumentRetrievalError { source: err.i...
list_documents
identifier_name
list_documents.rs
use crate::domain::model::error::Error as ModelError; use crate::domain::ports::secondary::list::{List, Parameters}; use async_trait::async_trait; use common::document::ContainerDocument;
use tracing_futures::Instrument; type PinnedStream<T> = Pin<Box<dyn Stream<Item = T> + Send + 'static>>; #[async_trait] pub trait ListDocuments<D> { async fn list_documents(&self) -> Result<PinnedStream<Result<D, ModelError>>, ModelError>; } #[async_trait] impl<D, T> ListDocuments<D> for T where D: Container...
use futures::stream::{Stream, StreamExt}; use std::pin::Pin; use tracing::info_span;
random_line_split
list_documents.rs
use crate::domain::model::error::Error as ModelError; use crate::domain::ports::secondary::list::{List, Parameters}; use async_trait::async_trait; use common::document::ContainerDocument; use futures::stream::{Stream, StreamExt}; use std::pin::Pin; use tracing::info_span; use tracing_futures::Instrument; type PinnedSt...
}
{ let doc_type = D::static_doc_type().to_string(); let documents = self .list_documents(Parameters { doc_type }) .await? .map(|raw| raw.map_err(|err| ModelError::DocumentRetrievalError { source: err.into() })) .instrument(info_span!( "List...
identifier_body
user.js
"use strict"; let mongoose = require('mongoose'), Schema = mongoose.Schema, EmailValidator = require('./emailValidator'); class User { constructor(explicitConnection) { this.explicitConnection = explicitConnection; this.schema = new Schema({ email: { type: 'string', trim:...
type: 'string', } }).index({ email: 1, organization: 1 }, { unique: true }); } getModel() { if (this.explicitConnection === undefined) { return mongoose.model('User', this.schema); } else { return this.explicitConnection.model('User', this.schema); } } } module....
isBlocked: { type: 'boolean', required: true }, blockedCause: {
random_line_split
user.js
"use strict"; let mongoose = require('mongoose'), Schema = mongoose.Schema, EmailValidator = require('./emailValidator'); class
{ constructor(explicitConnection) { this.explicitConnection = explicitConnection; this.schema = new Schema({ email: { type: 'string', trim: true, required: true }, organization: { type: 'string', trim: true, requi...
User
identifier_name
user.js
"use strict"; let mongoose = require('mongoose'), Schema = mongoose.Schema, EmailValidator = require('./emailValidator'); class User { constructor(explicitConnection) { this.explicitConnection = explicitConnection; this.schema = new Schema({ email: { type: 'string', trim:...
} } module.exports = User;
{ return this.explicitConnection.model('User', this.schema); }
conditional_block
equals.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator;
use core::cmp::Eq; struct A<T: Eq> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); ...
use core::iter::order::equals;
random_line_split
equals.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::order::equals; use core::cmp::Eq; struct A<T: Eq> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -...
() { let a: L = L { begin: 0, end: 10 }; let b: R = R { begin: 0, end: 10 }; let result: bool = equals::<AA, L, R>(a, b); assert_eq!(result, true); } #[test] fn equals_test2() { let a: L = L { begin: 0, end: 10 }; let b: R = R { begin: 0, end: 11 }; let result: bool = equals::<AA, L, R>(a, b); as...
equals_test1
identifier_name
view.py
+ -- + '), list(' / \ '), list('+ +'), list(' \ / '), list(' + -- + '), ] BORDER_TILE_TEMPLATE = [ list(' | -- | '), list(' - - '), list(' | | '), list(' - - '), list(' | -- | '), ] NUMBER_SPACES = [ (2, 4), (2, 5) ] PERIMETER_SPACES = [ (0,...
def remove_border_characters(board, coordinate, diff, tile_grid): # First, calculate some helper values helper_value_one = board.size.width // 2 helper_value_two = board.size.height - helper_value_one # Top vertical ticks if ( coordinate.row == -1 or coordinate.column == -1 ):...
# Orientation.SOUTH_WEST: [(2, 2), (3, 3)], # Orientation.SOUTH: [(3, 3), (3, 6)], # Orientation.SOUTH_EAST: [(3, 6), (2, 7)], # }
random_line_split
view.py
+ -- + '), list(' / \ '), list('+ +'), list(' \ / '), list(' + -- + '), ] BORDER_TILE_TEMPLATE = [ list(' | -- | '), list(' - - '), list(' | | '), list(' - - '), list(' | -- | '), ] NUMBER_SPACES = [ (2, 4), (2, 5) ] PERIMETER_SPACES = [ (0,...
total_grid_width = ( (num_tiles_wide // 2 + 1) * (tile_grid_wide - 1) + (num_tiles_wide // 2 ) * (tile_grid_narrow - 1) + 1 ) # Create a 2D array of empty spaces, large enough to # contain all characters for all tiles (but no larger) board_grid = [ ...
def __init__(self, board): self.board = board def __str__(self): return grid_to_str(self.get_board_grid()) def get_board_grid(self): # Add two to the height and width of the # board to account for the perimeter tiles num_tiles_tall = self.board.size.height + 2 num_ti...
identifier_body
view.py
+ -- + '), list(' / \ '), list('+ +'), list(' \ / '), list(' + -- + '), ] BORDER_TILE_TEMPLATE = [ list(' | -- | '), list(' - - '), list(' | | '), list(' - - '), list(' | -- | '), ] NUMBER_SPACES = [ (2, 4), (2, 5) ] PERIMETER_SPACES = [ (0, ...
(self): # Add two to the height and width of the # board to account for the perimeter tiles num_tiles_tall = self.board.size.height + 2 num_tiles_wide = self.board.size.width + 2 # The number of characters tall and wide for the tile grid tile_grid_height = len(CENTER_TILE_TEM...
get_board_grid
identifier_name
view.py
+ -- + '), list(' / \ '), list('+ +'), list(' \ / '), list(' + -- + '), ] BORDER_TILE_TEMPLATE = [ list(' | -- | '), list(' - - '), list(' | | '), list(' - - '), list(' | -- | '), ] NUMBER_SPACES = [ (2, 4), (2, 5) ] PERIMETER_SPACES = [ (0,...
char = '?' if tile.resource: char = tile.resource.color.apply(tile.resource.char) tile_grid = copy_grid(tile_grid) for row, col in spaces: tile_grid[row][col] = char return tile_grid class View(object): def __init__(self, board): self.board = board def __str__(se...
return tile_grid spaces = NUMBER_SPACES
conditional_block
JSONStabilizer.ts
/// <reference path="../_ref.d.ts" /> 'use strict'; import detectIndent = require('detect-indent'); import CodeStyle = require('../lib/CodeStyle'); import collection = require('../collection'); import assertVar = require('../assertVar'); import typeOf = require('../typeOf'); var sniffExp = /([ \t]*).*((?:\r?\n)|$)/...
} export = JSONStabilizer;
{ assertVar(json, 'object', 'json'); if (!assumeStable) { json = this.getStablized(json); } var str = JSON.stringify(json, null, this.style.indent); if (this.style.eol !== '\n') { str = str.replace(/\r?\n/g, this.style.eol); } if (this.style.trailingEOL) { str += this.style.eol; } return str;...
identifier_body
JSONStabilizer.ts
/// <reference path="../_ref.d.ts" /> 'use strict'; import detectIndent = require('detect-indent'); import CodeStyle = require('../lib/CodeStyle'); import collection = require('../collection'); import assertVar = require('../assertVar'); import typeOf = require('../typeOf'); var sniffExp = /([ \t]*).*((?:\r?\n)|$)/...
return this; } parseString(jsonString: string): Object { var object = JSON.parse(jsonString.trim()); this.style = new CodeStyle(); this.sniff(jsonString); this.snapshot(object); return object; } sniff(jsonString: string): void { assertVar(jsonString, 'string', 'jsonString'); var eolWin = 0; va...
{ return this.parent.root; }
conditional_block
JSONStabilizer.ts
/// <reference path="../_ref.d.ts" /> 'use strict'; import detectIndent = require('detect-indent'); import CodeStyle = require('../lib/CodeStyle'); import collection = require('../collection'); import assertVar = require('../assertVar'); import typeOf = require('../typeOf'); var sniffExp = /([ \t]*).*((?:\r?\n)|$)/...
{ depth: number; style: CodeStyle; keys: string[] = []; parent: JSONStabilizer = null; children = new collection.Hash<JSONStabilizer>(); constructor(depth: number = 2, style: CodeStyle = null) { this.depth = depth; this.style = style || new CodeStyle(); } get root(): JSONStabilizer { if (this.parent...
JSONStabilizer
identifier_name
JSONStabilizer.ts
/// <reference path="../_ref.d.ts" /> 'use strict'; import detectIndent = require('detect-indent'); import CodeStyle = require('../lib/CodeStyle'); import collection = require('../collection'); import assertVar = require('../assertVar'); import typeOf = require('../typeOf'); var sniffExp = /([ \t]*).*((?:\r?\n)|$)/...
var eolWin = 0; var eolNix = 0; // sanity limit var sampleLines = 10; var match: RegExpExecArray; sniffExp.lastIndex = 0; // test line-end while (sampleLines > 0 && (match = sniffExp.exec(jsonString))) { sniffExp.lastIndex = match.index + (match[0].length || 1); sampleLines--; if (match[2].l...
assertVar(jsonString, 'string', 'jsonString');
random_line_split
generate.py
#!/usr/bin/python import sys import os import re sys.path.append('/home/al/sites') os.environ['DJANGO_SETTINGS_MODULE'] = '__main__' DEFAULT_CHARSET = "utf-8" TEMPLATE_DEBUG = False LANGUAGE_CODE = "en" INSTALLED_APPS = ( 'django.contrib.markup', ) TEMPLATE_DIRS = ( '/home/al/sites/liquidx/templates', ...
(src, dst): print '%s -> %s' % (src, dst) c = Context({}) filled = loader.render_to_string(src, {}) open(dst, 'w').write(filled) if __name__ == "__main__": for dirname, dirs, files in os.walk('.'): if re.search('/\.svn', dirname): continue for f in files: ...
make
identifier_name
generate.py
#!/usr/bin/python import sys import os import re sys.path.append('/home/al/sites') os.environ['DJANGO_SETTINGS_MODULE'] = '__main__' DEFAULT_CHARSET = "utf-8" TEMPLATE_DEBUG = False LANGUAGE_CODE = "en" INSTALLED_APPS = ( 'django.contrib.markup', ) TEMPLATE_DIRS = ( '/home/al/sites/liquidx/templates', ...
if __name__ == "__main__": for dirname, dirs, files in os.walk('.'): if re.search('/\.svn', dirname): continue for f in files: if f[-4:] == ".txt": newname = f.replace('.txt', '.html') make(os.path.join(dirname, f), os.path.join(dirname, ...
print '%s -> %s' % (src, dst) c = Context({}) filled = loader.render_to_string(src, {}) open(dst, 'w').write(filled)
identifier_body
generate.py
#!/usr/bin/python import sys import os import re sys.path.append('/home/al/sites') os.environ['DJANGO_SETTINGS_MODULE'] = '__main__' DEFAULT_CHARSET = "utf-8" TEMPLATE_DEBUG = False LANGUAGE_CODE = "en" INSTALLED_APPS = ( 'django.contrib.markup', ) TEMPLATE_DIRS = ( '/home/al/sites/liquidx/templates', ...
filled = loader.render_to_string(src, {}) open(dst, 'w').write(filled) if __name__ == "__main__": for dirname, dirs, files in os.walk('.'): if re.search('/\.svn', dirname): continue for f in files: if f[-4:] == ".txt": newname = f.replace('.txt', ...
random_line_split
generate.py
#!/usr/bin/python import sys import os import re sys.path.append('/home/al/sites') os.environ['DJANGO_SETTINGS_MODULE'] = '__main__' DEFAULT_CHARSET = "utf-8" TEMPLATE_DEBUG = False LANGUAGE_CODE = "en" INSTALLED_APPS = ( 'django.contrib.markup', ) TEMPLATE_DIRS = ( '/home/al/sites/liquidx/templates', ...
if f[-4:] == ".txt": newname = f.replace('.txt', '.html') make(os.path.join(dirname, f), os.path.join(dirname, newname))
conditional_block
issue-13808.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 ...
} impl<'a> Foo<'a> { fn new<F>(listener: F) -> Foo<'a> where F: FnMut() + 'a { Foo { listener: box listener } } } fn main() { let a = Foo::new(|| {}); }
#![feature(box_syntax)] struct Foo<'a> { listener: Box<FnMut() + 'a>,
random_line_split
issue-13808.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 a = Foo::new(|| {}); }
identifier_body
issue-13808.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 ...
<'a> { listener: Box<FnMut() + 'a>, } impl<'a> Foo<'a> { fn new<F>(listener: F) -> Foo<'a> where F: FnMut() + 'a { Foo { listener: box listener } } } fn main() { let a = Foo::new(|| {}); }
Foo
identifier_name
index.d.ts
/* * @license Apache-2.0 * * Copyright (c) 2021 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 ap...
export = isBufferLengthCompatible;
random_line_split
test_insertion_sort.py
# -*- coding utf-8 -*- from __future__ import unicode_literals import pytest from structures.insertion_sort import insertion_sort @pytest.fixture def sorted_list(): return [i for i in xrange(10)] @pytest.fixture def reverse_list(): return [i for i in xrange(9, -1, -1)]
@pytest.fixture def average_list(): return [5, 9, 2, 4, 1, 6, 8, 7, 0, 3] def test_sorted(sorted_list): insertion_sort(sorted_list) assert sorted_list == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] def test_worst(reverse_list): insertion_sort(reverse_list) assert reverse_list == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9...
random_line_split
test_insertion_sort.py
# -*- coding utf-8 -*- from __future__ import unicode_literals import pytest from structures.insertion_sort import insertion_sort @pytest.fixture def sorted_list(): return [i for i in xrange(10)] @pytest.fixture def reverse_list(): return [i for i in xrange(9, -1, -1)] @pytest.fixture def average_list(): ...
(sorted_list): insertion_sort(sorted_list) assert sorted_list == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] def test_worst(reverse_list): insertion_sort(reverse_list) assert reverse_list == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] def test_average(average_list): insertion_sort(average_list) assert average_list ==...
test_sorted
identifier_name
test_insertion_sort.py
# -*- coding utf-8 -*- from __future__ import unicode_literals import pytest from structures.insertion_sort import insertion_sort @pytest.fixture def sorted_list(): return [i for i in xrange(10)] @pytest.fixture def reverse_list(): return [i for i in xrange(9, -1, -1)] @pytest.fixture def average_list(): ...
def test_repeats(): l = [3, 6, 7, 3, 9, 5, 2, 7] insertion_sort(l) assert l == [2, 3, 3, 5, 6, 7, 7, 9] def test_multiple_types(): l = [3, 'foo', 2.8, True, []] # python 2 sorting is crazy insertion_sort(l) assert l == [True, 2.8, 3, [], 'foo']
insertion_sort(average_list) assert average_list == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
identifier_body
workspace.rs
use crate::config::GeneralConfig; use crate::core::stack::Stack; use crate::layout::{Layout, LayoutMessage}; use crate::window_system::{Window, WindowSystem}; /// Represents a single workspace with a `tag` (name), /// `id`, a `layout` and a `stack` for all windows pub struct Workspace { pub id: u32, pub tag: S...
(&self) -> usize { self.stack.clone().map_or(0usize, |x| x.len()) } pub fn is_empty(&self) -> bool { self.len() == 0 } /// Checks if the workspace contains the given window pub fn contains(&self, window: Window) -> bool { self.stack.clone().map_or(false, |x| x.contains(wind...
len
identifier_name
workspace.rs
use crate::config::GeneralConfig; use crate::core::stack::Stack; use crate::layout::{Layout, LayoutMessage}; use crate::window_system::{Window, WindowSystem}; /// Represents a single workspace with a `tag` (name), /// `id`, a `layout` and a `stack` for all windows pub struct Workspace { pub id: u32, pub tag: S...
pub fn map_or<F>(&self, default: Stack<Window>, f: F) -> Workspace where F: Fn(Stack<Window>) -> Stack<Window>, { Workspace::new( self.id, self.tag.clone(), self.layout.copy(), Some(self.stack.clone().map_or(default, |x| f(x))), ) ...
random_line_split
workspace.rs
use crate::config::GeneralConfig; use crate::core::stack::Stack; use crate::layout::{Layout, LayoutMessage}; use crate::window_system::{Window, WindowSystem}; /// Represents a single workspace with a `tag` (name), /// `id`, a `layout` and a `stack` for all windows pub struct Workspace { pub id: u32, pub tag: S...
/// Returns the number of windows contained in this workspace pub fn len(&self) -> usize { self.stack.clone().map_or(0usize, |x| x.len()) } pub fn is_empty(&self) -> bool { self.len() == 0 } /// Checks if the workspace contains the given window pub fn contains(&self, wind...
{ Workspace::new( self.id, self.tag.clone(), self.layout.copy(), Some( self.stack .clone() .map_or(Stack::from_element(window), |s| s.add(window)), ), ) }
identifier_body
node-gyp.js
/** * Module exports. */ module.exports = exports = gyp /** * Module dependencies. */ var fs = require('graceful-fs') , path = require('path') , nopt = require('nopt') , log = require('npmlog') , child_process = require('child_process') , EE = require('events').EventEmitter , inheri...
() { return new Gyp() } function Gyp () { var self = this // set the dir where node-gyp dev files get installed // TODO: make this *more* configurable? // see: https://github.com/nodejs/node-gyp/issues/21 var homeDir = process.env.HOME || process.env.USERPROFILE if (!homeDir) { th...
gyp
identifier_name
node-gyp.js
/** * Module exports. */ module.exports = exports = gyp /** * Module dependencies. */ var fs = require('graceful-fs') , path = require('path') , nopt = require('nopt') , log = require('npmlog') , child_process = require('child_process') , EE = require('events').EventEmitter , inheri...
return require('./' + command)(self, argv, callback) } }) } inherits(Gyp, EE) exports.Gyp = Gyp var proto = Gyp.prototype /** * Export the contents of the package.json. */ proto.package = require('../package') /** * nopt configuration definitions */ proto.configDefs = { help:...
{ var self = this // set the dir where node-gyp dev files get installed // TODO: make this *more* configurable? // see: https://github.com/nodejs/node-gyp/issues/21 var homeDir = process.env.HOME || process.env.USERPROFILE if (!homeDir) { throw new Error( "node-gyp requires that th...
identifier_body
node-gyp.js
/** * Module exports. */ module.exports = exports = gyp /** * Module dependencies. */ var fs = require('graceful-fs') , path = require('path') , nopt = require('nopt') , log = require('npmlog') , child_process = require('child_process') , EE = require('events').EventEmitter , inherits...
* expose the command aliases for the bin file to use. */ proto.aliases = aliases /** * Parses the given argv array and sets the 'opts', * 'argv' and 'command' properties. */ proto.parseArgv = function parseOpts (argv) { this.opts = nopt(this.configDefs, this.shorthands, argv) this.argv = this.op...
random_line_split
node-gyp.js
/** * Module exports. */ module.exports = exports = gyp /** * Module dependencies. */ var fs = require('graceful-fs') , path = require('path') , nopt = require('nopt') , log = require('npmlog') , child_process = require('child_process') , EE = require('events').EventEmitter , inheri...
this.devDir = path.resolve(homeDir, '.node-gyp') this.commands = {} commands.forEach(function (command) { self.commands[command] = function (argv, callback) { log.verbose('command', command, argv) return require('./' + command)(self, argv, callback) } }) } inherits(Gyp, EE) e...
{ throw new Error( "node-gyp requires that the user's home directory is specified " + "in either of the environmental variables HOME or USERPROFILE" ); }
conditional_block
cli-help.js
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTH...
/* * This file provides support for displaying the application and * command specific help. */ // ============================================================================ // export class CliHelp { // -------------------------------------------------------------------------- constructor (ctx) { this.c...
// ----------------------------------------------------------------------------
random_line_split
cli-help.js
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTH...
() { const log = this.context.log const pkgJson = this.context.package log.output() const pkgPath = this.context.rootPath log.output(`npm ${pkgJson.name}@${pkgJson.version} '${pkgPath}'`) if (pkgJson.homepage) { log.output(`Home page: <${pkgJson.homepage}>`) } const br
outputFooter
identifier_name
cli-help.js
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTH...
}) if (optionDef.hasValue || optionDef.values || optionDef.param) { if (optionDef.param) { strOpts += ` <${optionDef.param}>` } else { strOpts += ' <s>' } } if (more.isFirstPass) { if (strOpts.length > more.width) { ...
{ strOpts += '|' }
conditional_block
cli-help.js
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTH...
outputEarlyDetails (optionGroups, more = this.more) { const programName = this.context.programName if (!more.isFirstPass) { // log.output() } optionGroups.forEach((optionGroup) => { optionGroup.optionDefs.forEach((optionDef) => { if (optionDef.msg && optionDef.doProcessEarly) {...
{ const log = this.context.log if (out.length >= more.limit) { log.output(out) out = '' } out += ' '.repeat(more.width) let desc = '' if (msg) { desc = msg + ' ' } log.output(`${CliHelp.padRight(out, more.width)} ${desc}`) }
identifier_body
protocol.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/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.o...
<'a, T: Encodable>(&mut self, obj: &T) { let s = json::encode(obj).unwrap().replace("__type__", "type"); println!("<- {}", s); self.write_all(s.len().to_string().as_bytes()).unwrap(); self.write_all(&[':' as u8]).unwrap(); self.write_all(s.as_bytes()).unwrap(); } fn read...
write_json_packet
identifier_name
protocol.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/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.o...
let packet_len = match u64::from_str_radix(&packet_len_str, 10) { Ok(packet_len) => packet_len, Err(_) => return Err("packet length missing / not parsable".to_string()), }; let mut packet = String::new(); ...
let packet_len_str = match String::from_utf8(buffer) { Ok(packet_len) => packet_len, Err(_) => return Err("nonvalid UTF8 in packet length".to_string()), };
random_line_split
protocol.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/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.o...
Err(_) => return Err("packet length missing / not parsable".to_string()), }; let mut packet = String::new(); self.take(packet_len).read_to_string(&mut packet).unwrap(); println!("{}", packet); ret...
{ // https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport // In short, each JSON packet is [ascii length]:[JSON data of given length] let mut buffer = vec!(); loop { let mut buf = [0]; let byte = match self.read(&mut buf) { Ok(0) => ...
identifier_body
cannot-mutate-captured-non-mut-var.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 x = 1; to_fn_once(move|| { x = 2; }); //[ast]~^ ERROR: cannot assign to immutable captured outer variable //[mir]~^^ ERROR: cannot assign to `x`, as it is not declared as mutable let s = std::io::stdin(); to_fn_once(move|| { s.read_to_end(&mut Vec::new()); }); //[ast]~^ ERROR: cann...
main
identifier_name
cannot-mutate-captured-non-mut-var.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 ...
//[ast]~^ ERROR: cannot assign to immutable captured outer variable //[mir]~^^ ERROR: cannot assign to `x`, as it is not declared as mutable let s = std::io::stdin(); to_fn_once(move|| { s.read_to_end(&mut Vec::new()); }); //[ast]~^ ERROR: cannot borrow immutable captured outer variable //[mir]...
let x = 1; to_fn_once(move|| { x = 2; });
random_line_split
cannot-mutate-captured-non-mut-var.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 ...
fn main() { let x = 1; to_fn_once(move|| { x = 2; }); //[ast]~^ ERROR: cannot assign to immutable captured outer variable //[mir]~^^ ERROR: cannot assign to `x`, as it is not declared as mutable let s = std::io::stdin(); to_fn_once(move|| { s.read_to_end(&mut Vec::new()); }); //[ast]~^ ER...
{ f }
identifier_body
views.py
#!/usr/bin/env python # encoding: utf-8 """ views.py Created by Christophe VAN FRACKEM on 2014/05/25. Copyright (c) 2014 Tiss'Page. All rights reserved. """ __author__ = 'Christophe VAN FRACKEM <contact@tisspage.fr>' __version__= '0.0.1' __copyright__ = '© 2014 Tiss\'Page' from django.shortcuts import render_to_res...
actFormView, FormView): template_name="mentions.html"
onsView(Cont
identifier_name
views.py
#!/usr/bin/env python # encoding: utf-8 """ views.py Created by Christophe VAN FRACKEM on 2014/05/25. Copyright (c) 2014 Tiss'Page. All rights reserved. """ __author__ = 'Christophe VAN FRACKEM <contact@tisspage.fr>' __version__= '0.0.1' __copyright__ = '© 2014 Tiss\'Page' from django.shortcuts import render_to_res...
ate_name="mentions.html"
identifier_body
views.py
#!/usr/bin/env python # encoding: utf-8 """
""" __author__ = 'Christophe VAN FRACKEM <contact@tisspage.fr>' __version__= '0.0.1' __copyright__ = '© 2014 Tiss\'Page' from django.shortcuts import render_to_response from django.views.generic import View, TemplateView, FormView, UpdateView from django.http import HttpResponseRedirect, HttpResponse from django.core...
views.py Created by Christophe VAN FRACKEM on 2014/05/25. Copyright (c) 2014 Tiss'Page. All rights reserved.
random_line_split
datasource-arrayschema.js
/* YUI 3.13.0 (build 508226d) Copyright 2013 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('datasource-arrayschema', function (Y, NAME) { /** * Extends DataSource with schema-parsing on array data. * * @module datasource * @submodule datasource-arraysch...
payload.response = response; this.get("host").fire("response", payload); return new Y.Do.Halt("DataSourceArraySchema plugin halted _defDataFn"); } }); Y.namespace('Plugin').DataSourceArraySchema = DataSourceArraySchema; }, '3.13.0', {"requires": ["datasource-local", "plugin", "datasch...
{ response = { meta: {}, results: data }; }
conditional_block
datasource-arrayschema.js
/* YUI 3.13.0 (build 508226d) Copyright 2013 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('datasource-arrayschema', function (Y, NAME) { /** * Extends DataSource with schema-parsing on array data. * * @module datasource * @submodule datasource-arraysch...
* Class name. * * @property NAME * @type String * @static * @final * @value "dataSourceArraySchema" */ NAME: "dataSourceArraySchema", ///////////////////////////////////////////////////////////////////////////// // // DataSourceArraySchema Attributes // /...
/**
random_line_split
generate_times.ts
/* MIT License Copyright (c) 2022 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modi...
return timeValues }
{ timeValues.push(get24HourTime({ hour: i })) }
conditional_block
generate_times.ts
/* MIT License Copyright (c) 2022 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND N...
in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
random_line_split
__init__.py
""" A framework for data processing and data preparation DAG (directed acyclic graph) pipelines. The examples in the documentation assume >>> from __future__ import print_function if running pre Py3K, as well as >>> from dagpype import * """ import types from . import _core from . import _src from . import _fi...
__all__.extend(['np', 'plot']) __version__ = '0.1.0.3' __author__ = 'Ami Tavory <atavory at gmail.com>'
if s[0] == '_': continue if eval('not isinstance(m.%s, types.ModuleType)' % s): __all__.append(s)
conditional_block
__init__.py
""" A framework for data processing and data preparation DAG (directed acyclic graph) pipelines. The examples in the documentation assume >>> from __future__ import print_function if running pre Py3K, as well as >>> from dagpype import * """ import types from . import _core from . import _src from . import _fi...
__all__ = [] for m in [_core, _src, _filt, _snk, _subgroup_filt]: for s in dir(m): if s[0] == '_': continue if eval('not isinstance(m.%s, types.ModuleType)' % s): __all__.append(s) __all__.extend(['np', 'plot']) __version__ = '0.1.0.3' __author__ = 'Ami Tavory <atavory at g...
from . import np from . import plot
random_line_split
poi_flag_email.py
#!/usr/bin/python ### ### in poiFlagEmail() below, write code that returns a boolean ### indicating if a given emails is from a POI ### import sys import reader import poi_emails def getToFromStrings(f): f.seek(0) to_string, from_string, cc_string = reader.getAddresses(f) to_emails = reader.parseAdd...
(f): """ given an email file f, return a trio of booleans for whether that email is to, from, or cc'ing a poi """ to_emails, from_emails, cc_emails = getToFromStrings(f) ### list of email addresses of all the POIs poi_email_list = poi_emails.poiEmails() to_poi = False from_poi...
poiFlagEmail
identifier_name
poi_flag_email.py
#!/usr/bin/python ### ### in poiFlagEmail() below, write code that returns a boolean ### indicating if a given emails is from a POI ### import sys import reader import poi_emails def getToFromStrings(f): f.seek(0) to_string, from_string, cc_string = reader.getAddresses(f) to_emails = reader.parseAdd...
ctr += 1 ################################# ######## your code below ######## ### set from_poi to True if ##### ### the email is from a POI ##### ################################# if from_emails and from_emails[0] in poi_email_list: from_poi = True #########...
cc_poi = True
conditional_block
poi_flag_email.py
#!/usr/bin/python ### ### in poiFlagEmail() below, write code that returns a boolean ### indicating if a given emails is from a POI ### import sys import reader import poi_emails def getToFromStrings(f): f.seek(0) to_string, from_string, cc_string = reader.getAddresses(f) to_emails = reader.parseAddr...
def poiFlagEmail(f): """ given an email file f, return a trio of booleans for whether that email is to, from, or cc'ing a poi """ to_emails, from_emails, cc_emails = getToFromStrings(f) ### list of email addresses of all the POIs poi_email_list = poi_emails.poiEmails() to_poi = F...
### POI flag an email
random_line_split
poi_flag_email.py
#!/usr/bin/python ### ### in poiFlagEmail() below, write code that returns a boolean ### indicating if a given emails is from a POI ### import sys import reader import poi_emails def getToFromStrings(f):
### POI flag an email def poiFlagEmail(f): """ given an email file f, return a trio of booleans for whether that email is to, from, or cc'ing a poi """ to_emails, from_emails, cc_emails = getToFromStrings(f) ### list of email addresses of all the POIs poi_email_list = poi_emails.po...
f.seek(0) to_string, from_string, cc_string = reader.getAddresses(f) to_emails = reader.parseAddresses( to_string ) from_emails = reader.parseAddresses( from_string ) cc_emails = reader.parseAddresses( cc_string ) return to_emails, from_emails, cc_emails
identifier_body
ej.culture.es-BO.js
language: "es", numberFormat: { ",": ".", ".": ",", "NaN": "NeuN", negativeInfinity: "-Infinito", positiveInfinity: "Infinito", percent: { ",": ".", ".": "," }, currency: { pattern: ["($ n)","$ n"], ",": ".", ".": ",", symbol: "$b" } }, calendars: { standard: { days: { n...
ej.addCulture( "es-BO", { name: "es-BO", englishName: "Spanish (Bolivia)", nativeName: "Español (Bolivia)",
random_line_split
main.rs
/* Aurélien DESBRIÈRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations // Modules Struct Visibility in Rust mod my { // A public struct with a public field of generic type `T` pub struct WhiteBox<T> { pub contents: T, } // A public struct with a private field o...
> { contents: T, } impl<T> BlackBox<T> { // A public constructor method pub fn new(contents: T) -> BlackBox<T> { BlackBox { contents: contents, } } } } fn main() { // Public structs with public fields can be constructed as usual ...
ackBox<T
identifier_name
main.rs
/* Aurélien DESBRIÈRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations // Modules Struct Visibility in Rust mod my { // A public struct with a public field of generic type `T` pub struct WhiteBox<T> { pub contents: T, } // A public struct with a private field o...
impl<T> BlackBox<T> { // A public constructor method pub fn new(contents: T) -> BlackBox<T> { BlackBox { contents: contents, } } } } fn main() { // Public structs with public fields can be constructed as usual let white_box = my::WhiteBox...
random_line_split
when.py
formats = _FormatsMetaClass('formats', (object,), {}) formats.__doc__ = """A set of predefined datetime formats. .. versionadded:: 0.3.0 """ def _add_time(value, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, milliseconds=0, microseconds=0): assert _is_date_type(value)...
yield attr
conditional_block
when.py
will do # the trick. day = value.day - destination_days month += 1 if month > 12: month = 1 year += 1 value = value.replace(year=year, month=month, day=day) return value def _is_date_type(value): # Acceptible types m...
"""Get a random datetime. Instead of using ``datetime.MINYEAR`` and ``datetime.MAXYEAR`` as the bounds, the current year +/- 100 is used. The thought behind this is that years that are too extreme will not be as useful. :returns: datetime.datetime -- a random datetime. .. versionadded:: 0.3.0...
def ever():
random_line_split
when.py
(self, attr): return getattr(_FormatsMetaClass, attr) def __iter__(self): for attr in dir(_FormatsMetaClass): if not attr.startswith('__') and attr != 'mro': yield attr formats = _FormatsMetaClass('formats', (object,), {}) formats.__doc__ = """A set of predefined dateti...
__getitem__
identifier_name
when.py
if _FORCE_UTC or utc: return datetime.datetime.utcnow() else: return datetime.datetime.now() def past(years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, milliseconds=0, microseconds=0, utc=False): """Get a datetime in the past. ``past()`` accepts the ...
"""Get a date representing yesterday's date. :returns: datetime.date -- the current date minus one day. .. versionadded:: 0.1.0 """ return datetime.date.today() - datetime.timedelta(days=1)
identifier_body
radio_tool_button.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Actionable; use Bin; use Buildable; use Container; use RadioButton; use ToggleToolButton; use ToolButton; use ToolItem; use Widget; use ffi; use glib::object::Cast; use glib::obj...
} pub const NONE_RADIO_TOOL_BUTTON: Option<&RadioToolButton> = None; pub trait RadioToolButtonExt: 'static { fn get_group(&self) -> Vec<RadioButton>; } impl<O: IsA<RadioToolButton>> RadioToolButtonExt for O { fn get_group(&self) -> Vec<RadioButton> { unsafe { FromGlibPtrContainer::from_g...
{ skip_assert_initialized!(); unsafe { ToolItem::from_glib_none(ffi::gtk_radio_tool_button_new_from_widget(group.as_ref().to_glib_none().0)).unsafe_cast() } }
identifier_body
radio_tool_button.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Actionable; use Bin; use Buildable; use Container; use RadioButton; use ToggleToolButton; use ToolButton; use ToolItem; use Widget; use ffi; use glib::object::Cast; use glib::obj...
pub const NONE_RADIO_TOOL_BUTTON: Option<&RadioToolButton> = None; pub trait RadioToolButtonExt: 'static { fn get_group(&self) -> Vec<RadioButton>; } impl<O: IsA<RadioToolButton>> RadioToolButtonExt for O { fn get_group(&self) -> Vec<RadioButton> { unsafe { FromGlibPtrContainer::from_glib...
ToolItem::from_glib_none(ffi::gtk_radio_tool_button_new_from_widget(group.as_ref().to_glib_none().0)).unsafe_cast() } } }
random_line_split
radio_tool_button.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Actionable; use Bin; use Buildable; use Container; use RadioButton; use ToggleToolButton; use ToolButton; use ToolItem; use Widget; use ffi; use glib::object::Cast; use glib::obj...
(&self) -> Vec<RadioButton> { unsafe { FromGlibPtrContainer::from_glib_none(ffi::gtk_radio_tool_button_get_group(self.as_ref().to_glib_none().0)) } } } impl fmt::Display for RadioToolButton { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "RadioToolButton")...
get_group
identifier_name
Auth.ts
import { CustomJWT } from '../libraries/CustomJWT'; import { User } from '../models/User'; import { Logs } from '../models/Logs'; import { BaseController } from '../core/BaseController'; import * as express from 'express'; export abstract class Auth { /** * authenticate * ...
* @param {express.Response} res the response for the request * @param {express.Request} req the request object * @param {express.NextFunction} net a call for the next function * @return {boolean} if the user is Authenticate or not */ public static authenticate(req: express.Request...
random_line_split
Auth.ts
import { CustomJWT } from '../libraries/CustomJWT'; import { User } from '../models/User'; import { Logs } from '../models/Logs'; import { BaseController } from '../core/BaseController'; import * as express from 'express'; export abstract class Auth { /** * authenticate * ...
(req: express.Request, res: express.Response, next: express.NextFunction): boolean { // Get the data from de request header let token = req.headers ? req.headers['token'] : req.query['token']; // create a new CustomJWT let jwt = new CustomJWT(token); // create a new user model...
authenticate
identifier_name
Auth.ts
import { CustomJWT } from '../libraries/CustomJWT'; import { User } from '../models/User'; import { Logs } from '../models/Logs'; import { BaseController } from '../core/BaseController'; import * as express from 'express'; export abstract class Auth { /** * authenticate * ...
// compare the header data with JWT if (req.headers['user_id'] === userID.toString() && req.headers['email'] === email) { // try to Authenticate the user userModel.authenticate(email, userID, jwt.token ) .then( response => { ...
{ // Get the data from de request header let token = req.headers ? req.headers['token'] : req.query['token']; // create a new CustomJWT let jwt = new CustomJWT(token); // create a new user model instance let userModel = new User(); // create a new base instanc...
identifier_body
Auth.ts
import { CustomJWT } from '../libraries/CustomJWT'; import { User } from '../models/User'; import { Logs } from '../models/Logs'; import { BaseController } from '../core/BaseController'; import * as express from 'express'; export abstract class Auth { /** * authenticate * ...
} else { // show Access Denied message base.showAccessDenied(req, res); return false; } } };
// show Access Denied message base.showAccessDenied(req, res); return false; }
conditional_block
day25.rs
#[macro_use] extern crate lazy_static; extern crate regex; extern crate aoc2016; use std::io::{BufReader, BufRead}; use std::fs::File; use aoc2016::assembunny::Cpu; fn main() { let file = File::open("input/day25.in").expect("Failed to open input"); let reader = BufReader::new(&file); let mut program = Ve...
} if good { break; } input += 1; } println!("1: {:?}", input); }
{ good = good && o == 1; }
conditional_block
day25.rs
#[macro_use] extern crate lazy_static; extern crate regex; extern crate aoc2016; use std::io::{BufReader, BufRead}; use std::fs::File; use aoc2016::assembunny::Cpu; fn main()
let mut good = output.len() % 2 == 0; for (i, &o) in output.iter().enumerate() { if i % 2 == 0 { good = good && o == 0; } else { good = good && o == 1; } } if good { break; } input += 1; ...
{ let file = File::open("input/day25.in").expect("Failed to open input"); let reader = BufReader::new(&file); let mut program = Vec::new(); for line in reader.lines() { let line = line.unwrap(); program.push(line.parse().unwrap()); } let mut cpu = Cpu::new(); let mut inpu...
identifier_body
day25.rs
#[macro_use] extern crate lazy_static; extern crate regex; extern crate aoc2016; use std::io::{BufReader, BufRead}; use std::fs::File; use aoc2016::assembunny::Cpu; fn
() { let file = File::open("input/day25.in").expect("Failed to open input"); let reader = BufReader::new(&file); let mut program = Vec::new(); for line in reader.lines() { let line = line.unwrap(); program.push(line.parse().unwrap()); } let mut cpu = Cpu::new(); let mut i...
main
identifier_name
day25.rs
#[macro_use] extern crate lazy_static; extern crate regex; extern crate aoc2016; use std::io::{BufReader, BufRead}; use std::fs::File; use aoc2016::assembunny::Cpu; fn main() { let file = File::open("input/day25.in").expect("Failed to open input"); let reader = BufReader::new(&file); let mut program = Ve...
loop { cpu.reset(); cpu.registers[0] = input; let output = cpu.run(&program); let mut good = output.len() % 2 == 0; for (i, &o) in output.iter().enumerate() { if i % 2 == 0 { good = good && o == 0; } else { good = good ...
random_line_split