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 |
|---|---|---|---|---|
extended_execute_process.ts | import * as dotenv from "dotenv"
import * as winston from "winston"
import { registerDebugAction } from "../actions/debug/debug"
import "../actions/index.ts"
import * as Hub from "../hub/index"
dotenv.config()
registerDebugAction()
async function execute(jsonPayload: any) {
const req = JSON.parse(jsonPayload)
co... | process.on("message", (req) => {
execute(req)
.then((val) => { process.send!(val) })
.catch((err) => {
const stringErr = JSON.stringify(err)
winston.error("Error on child: " + stringErr)
process.send!({success: false, message: stringErr})
})
}) | }
return action.execute(request)
}
| random_line_split |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Kcov(CMakePackage):
"""Code coverage tool for compiled programs, Python and Bash which use... |
@run_after('install')
@on_package_attributes(run_tests=True)
def test_install(self):
# The help message exits with an exit code of 1
kcov = Executable(self.prefix.bin.kcov)
kcov('-h', ignore_errors=1)
| return ['-DSPECIFY_RPATH=ON'] | identifier_body |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class | (CMakePackage):
"""Code coverage tool for compiled programs, Python and Bash which uses
debugging information to collect and report data without special
compilation options"""
homepage = "http://simonkagstrom.github.io/kcov/index.html"
url = "https://github.com/SimonKagstrom/kcov/archive/38.ta... | Kcov | identifier_name |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Kcov(CMakePackage):
"""Code coverage tool for compiled programs, Python and Bash which use... | # The help message exits with an exit code of 1
kcov = Executable(self.prefix.bin.kcov)
kcov('-h', ignore_errors=1) | random_line_split | |
enums.rs | use operation::*;
/// Raw opcodes
///
/// Provides a way of storing both ARM and THUMB opcodes (which have
/// different sizes) in a single type.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Opcode {
/// A raw ARM opcode
///
/// Contains a 32-bit ARM opcode in machine encoding.
Arm(u32),
/// A... |
}
| {
use arm;
use thumb;
match opcode {
Opcode::Arm(w) => {
let condition = arm::condition(w);
let operation = arm::decode(w);
Instruction::Arm(condition, operation)
}
Opcode::Thumb(s) => {
let oper... | identifier_body |
enums.rs | use operation::*;
/// Raw opcodes
///
/// Provides a way of storing both ARM and THUMB opcodes (which have
/// different sizes) in a single type.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum | {
/// A raw ARM opcode
///
/// Contains a 32-bit ARM opcode in machine encoding.
Arm(u32),
/// A raw THUMB opcode
///
/// Contains a 16-bit THUMB opcode in machine encoding.
Thumb(u16),
}
macro_rules! simple_from {
($src:ty => $dst:ty as $variant:path) => {
impl From<$src> ... | Opcode | identifier_name |
enums.rs | use operation::*;
/// Raw opcodes
///
/// Provides a way of storing both ARM and THUMB opcodes (which have
/// different sizes) in a single type.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Opcode {
/// A raw ARM opcode
///
/// Contains a 32-bit ARM opcode in machine encoding.
Arm(u32),
/// A... | let condition = arm::condition(w);
let operation = arm::decode(w);
Instruction::Arm(condition, operation)
}
Opcode::Thumb(s) => {
let operation = thumb::decode(s);
Instruction::Thumb(operation)
}
... | match opcode {
Opcode::Arm(w) => { | random_line_split |
auth.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... | ,
}
}
}
#[derive(Debug)]
enum Access {
Granted,
Denied,
AuthRequired,
}
impl HttpBasicAuth {
/// Creates `HttpBasicAuth` instance with only one user.
pub fn single_user(username: &str, password: &str) -> Self {
let mut users = HashMap::new();
users.insert(username.to_owned(), password.to_owned());
HttpB... | {
Authorized::Yes
} | conditional_block |
auth.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... | (username: &str, password: &str) -> Self {
let mut users = HashMap::new();
users.insert(username.to_owned(), password.to_owned());
HttpBasicAuth {
users: users
}
}
fn is_authorized(&self, username: &str, password: &str) -> bool {
self.users.get(&username.to_owned()).map_or(false, |pass| pass == password... | single_user | identifier_name |
auth.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... | Yes,
/// Unsuccessful authorization. Handler for further work is returned.
No(Box<Handler>),
}
/// Authorization interface
pub trait Authorization : Send + Sync {
/// Checks if authorization is valid.
fn is_authorized(&self, req: &server::Request<net::HttpStream>)-> Authorized;
}
/// HTTP Basic Authorization han... | random_line_split | |
uiEditorRenderer.ts | !== undefined) {
query["session"] = session;
}
// If key is singular we can short circuit this filter for speed improvements at selection time.
var filterByKey = false;
if(key !== undefined && keys.length === 1) {
query[code.name(keys[0])] = key;
} else if(key !== undefined && keys.len... | bindingToValue | identifier_name | |
uiEditorRenderer.ts | export function render() {
if(renderer.queued === false) {
renderer.queued = true;
requestAnimationFrame(function() {
renderer.queued = false;
renderer.render(rendererRoot());
});
}
}
function rendererRoot() {
if(dispatcher.isApp) {
//in an app we check the acti... | var items = [];
if(subLayers) {
subLayers.forEach(function(subLayer) {
items.push(renderLayer(subLayer, rowToKey(row), offsetForChildren));
})
}
if(elements) {
elements.forEach(function(element) {
items.push(renderElement(element, offsetForChildren, ro... | {
var layerId = layer[1];
var layerIx = layer[3];
var elements = ixer.select("uiComponentElement", {layer: layerId});
var parentLayerIndex = ixer.index("parentLayerToLayers");
var subLayers = parentLayerIndex[layerId];
var bindingIndex = ixer.index("groupToBinding");
var binding = bindingInd... | identifier_body |
uiEditorRenderer.ts | });
var query = {};
if(sessionIx !== undefined) {
query["session"] = session;
}
// If key is singular we can short circuit this filter for speed improvements at selection time.
var filterByKey = false;
if(key !== undefined && keys.length === 1) {
query[code.name(keys[0])] = key;... | {
elem.c += " non-interactive";
} | conditional_block | |
uiEditorRenderer.ts | renderer.queued = false;
renderer.render(rendererRoot());
});
}
}
function rendererRoot() {
if(dispatcher.isApp) {
//in an app we check the active page
var componentId = ixer.index("active page")[session];
} else {
//we're in the editor, so we render based on wha... | renderer.queued = false;
export function render() {
if(renderer.queued === false) {
renderer.queued = true;
requestAnimationFrame(function() { | random_line_split | |
Backend.py | # Copyright (C) 2009, 2010, 2011 Rickard Lindberg, Roger Lindberg
#
# This file is part of Timeline.
#
# Timeline 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... | (self):
self.given_event_and_category_lists()
self.when_cloning()
self.assertTrue(self.new_category is not self.old_category)
self.assertTrue(self.new_event is not self.old_event)
self.assertTrue(self.db.events[0].get_category() is not self.old_category)
self.assertEquals... | test_when_db_data_is_cloned_category_event_relasionship_is_preserved | identifier_name |
Backend.py | # Copyright (C) 2009, 2010, 2011 Rickard Lindberg, Roger Lindberg
#
# This file is part of Timeline.
#
# Timeline 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... |
def setUp(self):
self.db = MemoryDB()
self.now = self.db.get_time_type().now()
| self.db.categories = [a_category_with(name="cat1")]
self.db.events = [Event(self.db.get_time_type(), self.now, self.now, "evt", category=self.db.categories[0])]
self.old_category = self.db.categories[0]
self.old_event = self.db.events[0] | identifier_body |
Backend.py | # Copyright (C) 2009, 2010, 2011 Rickard Lindberg, Roger Lindberg
#
# This file is part of Timeline.
#
# Timeline 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... |
ICS_EXAMPLE = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT
UID:uid1@example.com
DTSTAMP:19970714T170000Z
ORGANIZER;CN=John Doe:MAILTO:john.doe@example.com
DTSTART:19970714T170000Z
DTEND:19970715T035959Z
SUMMARY:Bastille Day Party
END:VEVENT
END:VCALENDAR
"""
class CloningT... | f = open(tmp_path, "w")
f.write(ICS_EXAMPLE)
f.close()
return tmp_path | random_line_split |
generate-data-key.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_kms::model::DataKeySpec;
use aws_sdk_kms::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
stru... |
// snippet-end:[kms.rust.generate-data-key]
/// Creates an AWS KMS data key.
/// # Arguments
///
/// * `[-k KEY]` - The name of the key.
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variabl... | {
let resp = client
.generate_data_key()
.key_id(key)
.key_spec(DataKeySpec::Aes256)
.send()
.await?;
// Did we get an encrypted blob?
let blob = resp.ciphertext_blob.expect("Could not get encrypted text");
let bytes = blob.as_ref();
let s = base64::encode(&... | identifier_body |
generate-data-key.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_kms::model::DataKeySpec;
use aws_sdk_kms::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
stru... | (client: &Client, key: &str) -> Result<(), Error> {
let resp = client
.generate_data_key()
.key_id(key)
.key_spec(DataKeySpec::Aes256)
.send()
.await?;
// Did we get an encrypted blob?
let blob = resp.ciphertext_blob.expect("Could not get encrypted text");
let by... | make_key | identifier_name |
generate-data-key.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_kms::model::DataKeySpec;
use aws_sdk_kms::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
stru... | println!();
if verbose {
println!("KMS client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("Key: {}", &key);
println!();
}
let shared_config = ... |
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2")); | random_line_split |
generate-data-key.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_kms::model::DataKeySpec;
use aws_sdk_kms::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
stru... |
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
make_key(&client, &key).await
}
| {
println!("KMS client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("Key: {}", &key);
println!();
} | conditional_block |
lead_sheet_pipelines.py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | lead_sheets, stats = lead_sheets_lib.extract_lead_sheet_fragments(
quantized_sequence,
min_bars=self._min_bars,
max_steps_truncate=self._max_steps,
min_unique_pitches=self._min_unique_pitches,
gap_bars=self._gap_bars,
ignore_polyphonic_notes=self._ignore... | """Extracts lead sheet fragments from a quantized NoteSequence."""
def __init__(self, min_bars=7, max_steps=512, min_unique_pitches=5,
gap_bars=1.0, ignore_polyphonic_notes=False, filter_drums=True,
require_chords=True, all_transpositions=True, name=None):
super(LeadSheetExtractor, ... | identifier_body |
lead_sheet_pipelines.py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | (self, quantized_sequence):
try:
lead_sheets, stats = lead_sheets_lib.extract_lead_sheet_fragments(
quantized_sequence,
min_bars=self._min_bars,
max_steps_truncate=self._max_steps,
min_unique_pitches=self._min_unique_pitches,
gap_bars=self._gap_bars,
... | transform | identifier_name |
lead_sheet_pipelines.py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); | #
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing p... | # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at | random_line_split |
base.d.ts | // NOTE: These definitions support NodeJS and TypeScript 3.4.
// NOTE: TypeScript version-specific augmentations can be found in the following paths:
// - ~/base.d.ts - Shared definitions common to all TypeScript versions
// - ~/index.d.ts - Definitions specific to TypeScript 2.1
// ... | /// <reference path="globals.global.d.ts" /> | random_line_split | |
test_convert.py | #
# Copyright © 2012–2022 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licens... | def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc... | n bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
| identifier_body |
test_convert.py | #
# Copyright © 2012–2022 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licens... | MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertForma... | EXT = "html"
COUNT = 5 | random_line_split |
test_convert.py | #
# Copyright © 2012–2022 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licens... | , filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
class HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CO... | _file(self | identifier_name |
tilecutter.js | /*
* grunt-tilecutter
* https://github.com/jlawson/tilecutter-grunt
*
* Copyright (c) 2015 James Lawson
* Licensed under the MIT license.
*/
'use strict';
var gdal = require('gdal'),
chalk = require('chalk');
module.exports = function (grunt) {
grunt.registerMultiTask('tilecutter', 'Tilecutter Plugin... | else {
grunt.log.writeln('Tiled', chalk.cyan(f.dest), 'to', chalk.cyan(options.tiles));
complete();
return true;
}
});
... | {
grunt.log.error('Could not tile', f.dest);
grunt.log.error(error);
complete();
return false;
} | conditional_block |
tilecutter.js | /*
* grunt-tilecutter
* https://github.com/jlawson/tilecutter-grunt
*
* Copyright (c) 2015 James Lawson
* Licensed under the MIT license.
*/
'use strict';
var gdal = require('gdal'),
chalk = require('chalk');
module.exports = function (grunt) {
grunt.registerMultiTask('tilecutter', 'Tilecutter Plugin... | });
});
});
}; | random_line_split | |
rk4.rs | use libc::c_double;
/// Given a differential function dx(x, t),
/// initial condition x0,
/// and a list of times t,
/// find x(t) at each point in t
pub fn odeint(dx: (&Fn(c_double, c_double) -> c_double),
x0: c_double, t_vec: &Vec<c_double>) -> Vec<c_double> {
// Need there to be at least t... | let mut times = Vec::<f64>::new();
let mut i = 0.0;
while i <= 10.0 {
times.push(i);
i += 0.1;
}
let x0 = 0.0;
let mut result = odeint(&free_fall, x0, ×);
let expected_value = -490.5;
//println!("printing a result vector: {:?... |
#[test]
fn test_free_fall() { | random_line_split |
rk4.rs | use libc::c_double;
/// Given a differential function dx(x, t),
/// initial condition x0,
/// and a list of times t,
/// find x(t) at each point in t
pub fn odeint(dx: (&Fn(c_double, c_double) -> c_double),
x0: c_double, t_vec: &Vec<c_double>) -> Vec<c_double> {
// Need there to be at least t... |
#[test]
fn rk4_compiles() {
}
#[test]
fn test_velocity_one() {
let ref t = vec![0.0, 1.0];
let x0 = 0.0;
let mut result = odeint(&velocity_one, x0, t);
assert!((result.pop().unwrap() - 1.0).abs() < THRESHOLD);
}
#[test]
fn test_length() {
le... | {
let g = -9.81;
g*t
} | identifier_body |
rk4.rs | use libc::c_double;
/// Given a differential function dx(x, t),
/// initial condition x0,
/// and a list of times t,
/// find x(t) at each point in t
pub fn odeint(dx: (&Fn(c_double, c_double) -> c_double),
x0: c_double, t_vec: &Vec<c_double>) -> Vec<c_double> {
// Need there to be at least t... | (dx: (&Fn(c_double, c_double) -> c_double),
x0: c_double, t_vec: *mut Vec<c_double>) -> *mut Vec<c_double> {
unsafe { unsafe_alloc_vec_f64!(odeint(dx, x0, &*t_vec)) }
}
#[cfg(test)]
mod tests_rk4 {
use super::*;
const THRESHOLD: f64 = 0.0000001;
// Test differential to give to odei... | odeint_64 | identifier_name |
RouterEvent.ts | 'use strict';
/*
UMD Stuff
@import ../util/Extend as Extend
@import ./BaseEvent as BaseEvent
@export RouterEvent
*/
import BaseEvent = require('./BaseEvent');
/**
* The RouterEvent is used in the {{#crossLink "Router"}}{{/crossLink}} class and gets passed to the callback in the {{#crossLink "Route"}}{{/crossLink... | (type:string = RouterEvent.CHANGE, bubbles:boolean = false, cancelable:boolean = false, data:any = null)
{
super(type, bubbles, cancelable, data);
}
}
export = RouterEvent; | constructor | identifier_name |
RouterEvent.ts | 'use strict';
/*
UMD Stuff
@import ../util/Extend as Extend
@import ./BaseEvent as BaseEvent
@export RouterEvent
*/
import BaseEvent = require('./BaseEvent');
/**
* The RouterEvent is used in the {{#crossLink "Router"}}{{/crossLink}} class and gets passed to the callback in the {{#crossLink "Route"}}{{/crossLink... | * @module StructureJS
* @submodule event
* @requires Extend
* @requires BaseEvent
* @constructor
* @author Robert S. (www.codeBelt.com)
*/
class RouterEvent extends BaseEvent
{
/**
* The RouterEvent.CHANGE constant defines the value of the type property of an change route event object.
*
* @ev... | random_line_split | |
RouterEvent.ts | 'use strict';
/*
UMD Stuff
@import ../util/Extend as Extend
@import ./BaseEvent as BaseEvent
@export RouterEvent
*/
import BaseEvent = require('./BaseEvent');
/**
* The RouterEvent is used in the {{#crossLink "Router"}}{{/crossLink}} class and gets passed to the callback in the {{#crossLink "Route"}}{{/crossLink... |
}
export = RouterEvent; | {
super(type, bubbles, cancelable, data);
} | identifier_body |
09_convolutional_autoencoder.py | """Tutorial on how to create a convolutional autoencoder w/ Tensorflow.
Parag K. Mital, Jan 2016
"""
import tensorflow as tf
import numpy as np
import math
from libs.activations import lrelu
from libs.utils import corrupt
# %%
def autoencoder(input_shape=[None, 784],
n_filters=[1, 10, 10, 10],
... | current_input, W, strides=[1, 2, 2, 1], padding='SAME'), b))
current_input = output
# %%
# store the latent representation
z = current_input
encoder.reverse()
shapes.reverse()
# %%
# Build the decoder using the same weights
for layer_i, shape in enumerate(shapes... | output = lrelu(
tf.add(tf.nn.conv2d( | random_line_split |
09_convolutional_autoencoder.py | """Tutorial on how to create a convolutional autoencoder w/ Tensorflow.
Parag K. Mital, Jan 2016
"""
import tensorflow as tf
import numpy as np
import math
from libs.activations import lrelu
from libs.utils import corrupt
# %%
def | (input_shape=[None, 784],
n_filters=[1, 10, 10, 10],
filter_sizes=[3, 3, 3, 3],
corruption=False):
"""Build a deep denoising autoencoder w/ tied weights.
Parameters
----------
input_shape : list, optional
Description
n_filters : list, optional... | autoencoder | identifier_name |
09_convolutional_autoencoder.py | """Tutorial on how to create a convolutional autoencoder w/ Tensorflow.
Parag K. Mital, Jan 2016
"""
import tensorflow as tf
import numpy as np
import math
from libs.activations import lrelu
from libs.utils import corrupt
# %%
def autoencoder(input_shape=[None, 784],
n_filters=[1, 10, 10, 10],
... | Overall cost to use for training
Raises
------
ValueError
Description
"""
# %%
# input to the network
x = tf.placeholder(
tf.float32, input_shape, name='x')
# %%
# ensure 2-d is converted to square tensor.
if len(x.get_shape()) == 2:
x_dim = np.... | """Build a deep denoising autoencoder w/ tied weights.
Parameters
----------
input_shape : list, optional
Description
n_filters : list, optional
Description
filter_sizes : list, optional
Description
Returns
-------
x : Tensor
Input placeholder to the net... | identifier_body |
09_convolutional_autoencoder.py | """Tutorial on how to create a convolutional autoencoder w/ Tensorflow.
Parag K. Mital, Jan 2016
"""
import tensorflow as tf
import numpy as np
import math
from libs.activations import lrelu
from libs.utils import corrupt
# %%
def autoencoder(input_shape=[None, 784],
n_filters=[1, 10, 10, 10],
... |
x_dim = int(x_dim)
x_tensor = tf.reshape(
x, [-1, x_dim, x_dim, n_filters[0]])
elif len(x.get_shape()) == 4:
x_tensor = x
else:
raise ValueError('Unsupported input dimensions')
current_input = x_tensor
# %%
# Optionally apply denoising autoencoder
if... | raise ValueError('Unsupported input dimensions') | conditional_block |
photos.rs | use api::{Collection, Id, OwnerId, Timestamp};
request_ref! {
struct Search for ["photos.search"](v => 5.37) -> Collection<Photo> {
sized {
lat: f32 = () => {},
long: f32 = () => {},
start_time: Timestamp = () => {},
end_time: Timestamp = () => {},
... | (&self) -> &str {
use self::Sort::*;
match *self {
DateAdded => "0",
Popularity => "1",
}
}
}
| as_ref | identifier_name |
photos.rs | use api::{Collection, Id, OwnerId, Timestamp};
request_ref! {
struct Search for ["photos.search"](v => 5.37) -> Collection<Photo> {
sized {
lat: f32 = () => {},
long: f32 = () => {},
start_time: Timestamp = () => {},
end_time: Timestamp = () => {},
... | }
}
} | Popularity => "1", | random_line_split |
generate_manifest.py | #!/usr/bin/env python
# Copyright 2016 Sam Yaple
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | ():
parser = argparse.ArgumentParser(description='Backup Block Device')
parser.add_argument('--backupsize', required=True, type=int,
help='Size of backup for manifest gen (size in GB)')
parser.add_argument('--manifest', required=True,
help='manifest file')
... | parse_args | identifier_name |
generate_manifest.py | #!/usr/bin/env python
# Copyright 2016 Sam Yaple
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
def check_manifest(manifest_file):
return os.path.isfile(manifest_file)
def main():
args = parse_args()
if check_manifest(args.manifest):
print('manifest exists; exiting')
return
manifest = driver.DriverManager(
namespace='ekko.manifest.drivers',
name=args.driver,
... | yield manifest_structure.Segment(
metadata.backupset_id,
metadata.incremental,
segment,
0,
0,
os.urandom(20)
) | conditional_block |
generate_manifest.py | #!/usr/bin/env python
# Copyright 2016 Sam Yaple
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | from stevedore import driver
def parse_args():
parser = argparse.ArgumentParser(description='Backup Block Device')
parser.add_argument('--backupsize', required=True, type=int,
help='Size of backup for manifest gen (size in GB)')
parser.add_argument('--manifest', required=True,
... | import os
import sys
from ekko.manifest import structure as manifest_structure
from six.moves import range | random_line_split |
generate_manifest.py | #!/usr/bin/env python
# Copyright 2016 Sam Yaple
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
def read_segments(segments, metadata):
for segment in segments:
yield manifest_structure.Segment(
metadata.backupset_id,
metadata.incremental,
segment,
0,
0,
os.urandom(20)
)
def check_manifest(manifest_file):
return os... | parser = argparse.ArgumentParser(description='Backup Block Device')
parser.add_argument('--backupsize', required=True, type=int,
help='Size of backup for manifest gen (size in GB)')
parser.add_argument('--manifest', required=True,
help='manifest file')
parser.... | identifier_body |
classHelix_1_1Glob_1_1ActionMap.js | var classHelix_1_1Glob_1_1ActionMap = | [ "addHtmlAction", "classHelix_1_1Glob_1_1ActionMap.html#ae157f17e64ec5a86d1591fee474689a6", null ],
[ "addLogicAction", "classHelix_1_1Glob_1_1ActionMap.html#a7813c9ac72a1952afb3dbe5b5e84b3dc", null ],
[ "clearMap", "classHelix_1_1Glob_1_1ActionMap.html#af82dac2490e7cb2c67e63958ea35b88f", null ],
[ "fi... | [
[ "~ActionMap", "classHelix_1_1Glob_1_1ActionMap.html#a7d4aa57074e069641ab6bbb68884c25b", null ],
[ "ActionMap", "classHelix_1_1Glob_1_1ActionMap.html#a7f8755d9865b2a6285b8ed894dec6469", null ],
[ "ActionMap", "classHelix_1_1Glob_1_1ActionMap.html#afeedaa145c9fb85986699eaa8f37295c", null ],
[ "addActi... | random_line_split |
login.js | function Controller() {
function login() {
if (null != $.username.value && null != $.senha.value) {
Ti.App.fireEvent("app:preload", null);
Alloy.Globals.Util.login($.username.value, $.senha.value, processa);
}
}
function | (e) {
Ti.App.fireEvent("app:preload", null);
if (null != e) if ("error" != e.type) if (e.projeto.count > 0) {
Alloy.Globals.Usuario = e;
setProjeto();
} else alert(e.projeto.message); else alert(e.message);
}
function setProjeto() {
Ti.App.fireEvent("app:s... | processa | identifier_name |
login.js | function Controller() {
function login() |
function processa(e) {
Ti.App.fireEvent("app:preload", null);
if (null != e) if ("error" != e.type) if (e.projeto.count > 0) {
Alloy.Globals.Usuario = e;
setProjeto();
} else alert(e.projeto.message); else alert(e.message);
}
function setProjeto() {
T... | {
if (null != $.username.value && null != $.senha.value) {
Ti.App.fireEvent("app:preload", null);
Alloy.Globals.Util.login($.username.value, $.senha.value, processa);
}
} | identifier_body |
login.js | function Controller() {
function login() {
if (null != $.username.value && null != $.senha.value) {
Ti.App.fireEvent("app:preload", null);
Alloy.Globals.Util.login($.username.value, $.senha.value, processa);
}
}
function processa(e) {
Ti.App.fireEvent("app:pre... | $.__views.scrollview = Ti.UI.createScrollView({
backgroundColor: "transparent",
layout: "vertical",
id: "scrollview",
scrollingEnabled: "true"
});
$.__views.login.add($.__views.scrollview);
$.__views.__alloyId94 = Ti.UI.createView({
left: 0,
width: "100%",... | $.__views.login = Ti.UI.createView({
layout: "vertical",
id: "login"
});
$.__views.login && $.addTopLevelView($.__views.login); | random_line_split |
script.js.consoleStripped.js | , {
// summary:
// All the properties described in the dojo.__ioArgs type, apply to this
// type as well, EXCEPT "handleAs". It is not applicable to
// dojo/io/script.get() calls, since it is implied by the usage of
// "jsonp" (response will be a JSONP call returning JSON)
// or the response is pure Ja... |
script._deadScripts = [];
}
return true;
},
_ioCheck: function(dfd){
// summary:
// inflight check function to see if IO finished.
// dfd: Deferred
var ioArgs = dfd.ioArgs;
//Check for finished jsonp
if(ioArgs.json || (ioArgs.scriptLoaded && !ioArgs.args.checkString)){
return tru... | {
//Remove the script tag
script.remove(deadScripts[i].id, deadScripts[i].frameDoc);
//Clean up the deferreds
delete script["jsonp_" + deadScripts[i].id];
deadScripts[i].frameDoc = null;
} | conditional_block |
script.js.consoleStripped.js | Args, {
// summary:
// All the properties described in the dojo.__ioArgs type, apply to this
// type as well, EXCEPT "handleAs". It is not applicable to
// dojo/io/script.get() calls, since it is implied by the usage of
// "jsonp" (response will be a JSONP call returning JSON)
// or the response is pur... | //Setup the Deferred to have the jsonp callback.
ioArgs.canDelete = true;
dfd._jsonpCallback = this._jsonpCallback;
this["jsonp_" + ioArgs.id] = dfd;
}
// Make sure this runs no matter what happens to clean things up if need be
dfd.addBoth(function(value){
if(ioArgs.canDelete){
if(valu... | random_line_split | |
bootstrap.js | define([
'utils/Debug',
'core/Config',
'core/PubSub',
'core/Hub',
'utils/Dom',
'backbone',
'views/PageView',
'views/ToDoCollectionView',
'collections/ToDoCollection',
'caches/TodoCollectionCache'
], function(
Debug,
Config,
PubSub,
Hub, | PageView,
ToDoCollectionView,
ToDoCollection,
ToDoCollectionCache
) {
'use strict';
// To supress REST warnings.
Backbone.emulateHTTP = true;
var log = Debug.log,
moduleName = Config.moduleName,
event = Config.event;
/**
*
*/
return {
... | Dom,
Backbone, | random_line_split |
screen-bot-controller-service.ts | import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject, Subscription } from 'rxjs';
import { ScreenBotController } from '../@modules';
import { Store } from '@ngrx/store';
import { AppState, ScreenBotControllerActions } from '../@store';
@Injectable()
export class ScreenBotControllerService ... | } | get bot() { return this._bot }; | random_line_split |
screen-bot-controller-service.ts | import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject, Subscription } from 'rxjs';
import { ScreenBotController } from '../@modules';
import { Store } from '@ngrx/store';
import { AppState, ScreenBotControllerActions } from '../@store';
@Injectable()
export class | {
private _bot: ScreenBotController = new ScreenBotController();
private mergedObservable: Observable<any>;
private subscription: Subscription = new Subscription();
constructor( private store: Store<AppState> ) {
console.log( 'service' );
this._bot.init();
this.mergedObservable... | ScreenBotControllerService | identifier_name |
hgrid.py | # -*- coding: utf-8 -*-
from website.addons.dataverse.client import get_dataset, get_files, \
get_dataverse, connect_from_settings
from website.project.decorators import must_be_contributor_or_public
from website.project.decorators import must_have_addon
from website.util import rubeus
def dataverse_hgrid_root(... | (node_addon, auth, **kwargs):
return dataverse_hgrid_root(node_addon, auth=auth)
| dataverse_root_folder_public | identifier_name |
hgrid.py | # -*- coding: utf-8 -*-
from website.addons.dataverse.client import get_dataset, get_files, \
get_dataverse, connect_from_settings
from website.project.decorators import must_be_contributor_or_public
from website.project.decorators import must_have_addon
from website.util import rubeus
def dataverse_hgrid_root(... | doi=dataset.doi,
dataverse=dataverse.title,
hasPublishedFiles=bool(published_files),
dataverseIsPublished=dataverse.is_published,
version=version,
)]
@must_be_contributor_or_public
@must_have_addon('dataverse', 'node')
def dataverse_root_folder_public(node_addon, auth, **kw... | random_line_split | |
hgrid.py | # -*- coding: utf-8 -*-
from website.addons.dataverse.client import get_dataset, get_files, \
get_dataverse, connect_from_settings
from website.project.decorators import must_be_contributor_or_public
from website.project.decorators import must_have_addon
from website.util import rubeus
def dataverse_hgrid_root(... |
# Produce draft version or quit if no published version is available
if not published_files:
if can_edit:
version = 'latest'
else:
return []
permissions = {
'edit': can_edit and not node.is_registration,
'view': node.can_view(auth)
}
urls = ... | node = node_addon.owner
user_settings = node_addon.user_settings
default_version = 'latest-published'
version = 'latest-published' if not node.can_edit(auth) else default_version
# Quit if no dataset linked
if not node_addon.complete:
return []
connection = connect_from_settings(user_... | identifier_body |
hgrid.py | # -*- coding: utf-8 -*-
from website.addons.dataverse.client import get_dataset, get_files, \
get_dataverse, connect_from_settings
from website.project.decorators import must_be_contributor_or_public
from website.project.decorators import must_have_addon
from website.util import rubeus
def dataverse_hgrid_root(... |
published_files = get_files(dataset, published=True)
can_edit = node.can_edit(auth)
# Produce draft version or quit if no published version is available
if not published_files:
if can_edit:
version = 'latest'
else:
return []
permissions = {
'edit':... | return [] | conditional_block |
test_types.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
assert not types.is_temporal(pa.int32())
def test_timestamp_type():
# See ARROW-1683
assert isinstance(pa.timestamp('ns'), pa.TimestampType)
def test_union_type():
def check_fields(ty, fields):
assert ty.num_children == len(fields)
assert [ty[i] for i in range(ty.num_children)] == ... | assert types.is_timestamp(case)
assert not types.is_date(case)
assert not types.is_time(case) | conditional_block |
test_types.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | ():
def check_fields(ty, fields):
assert ty.num_children == len(fields)
assert [ty[i] for i in range(ty.num_children)] == fields
fields = [pa.field('x', pa.list_(pa.int32())),
pa.field('y', pa.binary())]
for mode in ('sparse', pa.lib.UnionMode_SPARSE):
ty = pa.union(fi... | test_union_type | identifier_name |
test_types.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | assert hash(type_) == hash(type_)
in_dict[type_] = i
assert in_dict[type_] == i
assert len(in_dict) == len(MANY_TYPES)
def test_types_picklable():
for ty in MANY_TYPES:
data = pickle.dumps(ty)
assert pickle.loads(data) == ty
@pytest.mark.parametrize('t,check_func', [
... | random_line_split | |
test_types.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
def test_is_decimal():
assert types.is_decimal(pa.decimal128(19, 4))
assert not types.is_decimal(pa.int32())
def test_is_list():
assert types.is_list(pa.list_(pa.int32()))
assert not types.is_list(pa.int32())
def test_is_dictionary():
assert types.is_dictionary(
pa.dictionary(pa.int32... | assert types.is_null(pa.null())
assert not types.is_null(pa.list_(pa.int32())) | identifier_body |
master-tab-factory.js | import { assign } from '@ember/polyfills';
import { A } from '@ember/array';
import { Promise } from 'rsvp';
import { run } from '@ember/runloop';
import Evented from '@ember/object/evented';
import Service from '@ember/service';
import { debug } from '../utils';
import {
namespace,
tabId,
tabIdKey,
shouldInval... | ,
/**
* Returns a promise which attempts to contest the master tab.
*/
contestMasterTab() {
return new Promise(resolve => {
if (!this.registerAsMasterTab()) {
debug('Trying to invalidate master tab.');
this.resolve = resolve;
this.contestTimeout = setTimeout(() => {
... | {
let success = false;
if (isMasterTab()) {
success = true;
} else {
if (typeof localStorage[tabIdKey] === 'undefined') {
localStorage[tabIdKey] = tabId;
localStorage[shouldInvalidateMasterTabKey] = false;
success = true;
}
debug(`Trying to register as master ... | identifier_body |
master-tab-factory.js | import { assign } from '@ember/polyfills';
import { A } from '@ember/array';
import { Promise } from 'rsvp';
import { run } from '@ember/runloop';
import Evented from '@ember/object/evented';
import Service from '@ember/service';
import { debug } from '../utils';
import {
namespace,
tabId,
tabIdKey,
shouldInval... | (func) {
if (!_isMasterTab && !finalOptions.force) {
func();
}
}
};
},
/**
* Runs the provided function (which should return a Promise) if this is the master tab.
* It creates a lock which is freed once the Promise is resolved or rejected.
* If this is not the master tab... | else | identifier_name |
master-tab-factory.js | import { assign } from '@ember/polyfills';
import { A } from '@ember/array';
import { Promise } from 'rsvp';
import { run } from '@ember/runloop';
import Evented from '@ember/object/evented';
import Service from '@ember/service';
import { debug } from '../utils';
import {
namespace,
tabId,
tabIdKey,
shouldInval... | else {
if (typeof localStorage[tabIdKey] === 'undefined') {
localStorage[tabIdKey] = tabId;
localStorage[shouldInvalidateMasterTabKey] = false;
success = true;
}
debug(`Trying to register as master tab... ${success ? 'SUCCESS' : 'FAILED'}.`);
}
run(() => {
this.s... | {
success = true;
} | conditional_block |
master-tab-factory.js | import { assign } from '@ember/polyfills';
import { A } from '@ember/array';
import { Promise } from 'rsvp';
import { run } from '@ember/runloop';
import Evented from '@ember/object/evented';
import Service from '@ember/service';
import { debug } from '../utils';
import {
namespace,
tabId,
tabIdKey,
shouldInval... | callCallback(true);
}
};
window.addEventListener('storage', handler);
if (finalOptions.waitNext) {
setTimeout(() => {
window.removeEventListener('storage', handler);
callCallback(true);
}, final... | window.removeEventListener('storage', handler); | random_line_split |
opaque-template-inst-member.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct | {
pub _address: u8,
}
/// This should not end up deriving Debug/Hash because its `mBlah` field cannot derive
/// Debug/Hash because the instantiation's definition cannot derive Debug/Hash.
#[repr(C)]
pub struct ContainsOpaqueTemplate {
pub mBlah: [u32; 101usize],
pub mBaz: ::std::os::raw::c_int,
}
#[test]
... | OpaqueTemplate | identifier_name |
opaque-template-inst-member.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct OpaqueTemplate {
pub _address: u8,
}
/// This should not end up deriving Debug/Hash because its `mBlah` field cannot derive
/// Debu... |
}
impl ::std::cmp::PartialEq for ContainsOpaqueTemplate {
fn eq(&self, other: &ContainsOpaqueTemplate) -> bool {
&self.mBlah[..] == &other.mBlah[..] && self.mBaz == other.mBaz
}
}
/// This should not end up deriving Debug/Hash either, for similar reasons, although
/// we're exercising base member edges... | {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
} | identifier_body |
opaque-template-inst-member.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct OpaqueTemplate {
pub _address: u8,
}
/// This should not end up deriving Debug/Hash because its `mBlah` field cannot derive
/// Debu... | &self.mBlah[..] == &other.mBlah[..] && self.mBaz == other.mBaz
}
}
/// This should not end up deriving Debug/Hash either, for similar reasons, although
/// we're exercising base member edges now.
#[repr(C)]
pub struct InheritsOpaqueTemplate {
pub _base: [u8; 401usize],
pub wow: *mut ::std::os::raw::... | impl ::std::cmp::PartialEq for ContainsOpaqueTemplate {
fn eq(&self, other: &ContainsOpaqueTemplate) -> bool { | random_line_split |
favourites.component.ts | import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { DEFAULT_PAGE_SIZE } from '@shared/validation/validators';
import { ItemViewModel } from '@shared/view-models/item/item.view-model';
import { OrderFavouriteViewModel } from... | (index: number, item: ItemViewModel): number {
return item.id;
}
drop(event: CdkDragDrop<string[]>): void {
if (event.previousIndex !== event.currentIndex) {
moveItemInArray(this.items, event.previousIndex, event.currentIndex);
this.orderFavourite(event.item.data, event.previousIndex, event.cur... | trackByFn | identifier_name |
favourites.component.ts | import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { DEFAULT_PAGE_SIZE } from '@shared/validation/validators';
import { ItemViewModel } from '@shared/view-models/item/item.view-model';
import { OrderFavouriteViewModel } from... |
}
filtersUpdated(): void {
this.getFavourites(true);
}
trackByFn(index: number, item: ItemViewModel): number {
return item.id;
}
drop(event: CdkDragDrop<string[]>): void {
if (event.previousIndex !== event.currentIndex) {
moveItemInArray(this.items, event.previousIndex, event.currentIn... | {
this.pageIndex++;
this.getFavourites();
} | conditional_block |
favourites.component.ts | import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { DEFAULT_PAGE_SIZE } from '@shared/validation/validators';
import { ItemViewModel } from '@shared/view-models/item/item.view-model';
import { OrderFavouriteViewModel } from... | this.listEnd = true;
}
} catch (error) {
this.formErrorsService.updateFormValidity(error);
} finally {
this.isProcessing = false;
}
}
onScroll(): void {
if (!this.listEnd && !this.isProcessing) {
this.pageIndex++;
this.getFavourites();
}
}
filtersUpdat... | // End of list
if (!response || (response && response.length !== DEFAULT_PAGE_SIZE)) { | random_line_split |
favourites.component.ts | import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { DEFAULT_PAGE_SIZE } from '@shared/validation/validators';
import { ItemViewModel } from '@shared/view-models/item/item.view-model';
import { OrderFavouriteViewModel } from... |
drop(event: CdkDragDrop<string[]>): void {
if (event.previousIndex !== event.currentIndex) {
moveItemInArray(this.items, event.previousIndex, event.currentIndex);
this.orderFavourite(event.item.data, event.previousIndex, event.currentIndex);
}
}
async orderFavourite(item: ItemViewModel, ori... | {
return item.id;
} | identifier_body |
index.js | module.exports = {
"parser": "babel-eslint",
"rules": {
"indent": [
2,
2
],
"quotes": [
2,
"single"
],
"linebreak-style": [
2,
"unix"
],
"semi": [
2,
"always"
],
"no-shadow" : 0,
"no-cond-assign" : 2,
... | "arrow-spacing" : [2, { "before": true, "after": true }],
"constructor-super" : 2,
"no-class-assign" : 2,
"no-const-assign" : 2,
"no-invalid-this" : 2,
"no-this-before-super" : 2,
"no-var" : 2,
"object-shorthand" : 2,
... | "space-before-blocks" : 2,
"no-implicit-coercion" : 2,
"no-useless-call" : 2,
"prefer-reflect" : 2,
// ES6+ Rules | random_line_split |
_baseView.js | var ViewAbstract = function () {
this.initialited = false; | };
ViewAbstract.prototype.setViewContainer = function($viewContainer) {
this.$viewContainer = $viewContainer;
return this;
};
ViewAbstract.prototype.getViewContainer = function() {
return this.$viewContainer;
};
ViewAbstract.prototype.setController = function(controller) {
this.controller = controll... | this.$viewContainer = null; | random_line_split |
api.py | # Copyright (c) 2016 The Johns Hopkins University/Applied Physics Laboratory
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICEN... |
@six.add_metaclass(ABCMeta)
class CryptographicEngine(object):
"""
The abstract base class of the cryptographic engine hierarchy.
A cryptographic engine is responsible for generating all cryptographic
objects and conducting all cryptographic operations for a KMIP server
instance.
"""
@ab... | import six | random_line_split |
api.py | # Copyright (c) 2016 The Johns Hopkins University/Applied Physics Laboratory
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICEN... | dict: A dictionary containing the key data, with the following
key/value fields:
* value - the bytes of the key
* format - a KeyFormatType enumeration for the bytes format
"""
@abstractmethod
def create_asymmetric_key_pair(self, algorithm, len... | """
The abstract base class of the cryptographic engine hierarchy.
A cryptographic engine is responsible for generating all cryptographic
objects and conducting all cryptographic operations for a KMIP server
instance.
"""
@abstractmethod
def create_symmetric_key(self, algorithm, length):
... | identifier_body |
api.py | # Copyright (c) 2016 The Johns Hopkins University/Applied Physics Laboratory
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICEN... | (self, algorithm, length):
"""
Create an asymmetric key pair.
Args:
algorithm(CryptographicAlgorithm): An enumeration specifying the
algorithm for which the created keys will be compliant.
length(int): The length of the keys to be created. This value must... | create_asymmetric_key_pair | identifier_name |
common.module.ts | import {NgModule} from "@angular/core";
import {MatButtonModule} from "@angular/material/button";
import {MatIconModule} from "@angular/material/icon";
import {MatListModule} from "@angular/material/list";
import {MatMenuModule} from "@angular/material/menu";
import {MatProgressSpinnerModule} from "@angular/material/pr... | MatProgressSpinnerModule
]
})
export class KyloCommonModule {
} | KyloServicesModule,
MatButtonModule,
MatIconModule,
MatListModule,
MatMenuModule, | random_line_split |
common.module.ts | import {NgModule} from "@angular/core";
import {MatButtonModule} from "@angular/material/button";
import {MatIconModule} from "@angular/material/icon";
import {MatListModule} from "@angular/material/list";
import {MatMenuModule} from "@angular/material/menu";
import {MatProgressSpinnerModule} from "@angular/material/pr... | {
}
| KyloCommonModule | identifier_name |
metric-collection.py | # !/usr/bin python
"""
#
# data-collect.py contain the python program to gather Metrics from vROps. Before you run this script
# set-config.py should be run once to set the environment
# Author Sajal Debnath <sdebnath@vmware.com>
#
"""
# Importing the Modules
import nagini
import requests
#import pprint
import json
... |
else:
# We have a range of values to store
for singlevalue in allvalues["values"][0]["stat-list"]["stat"]:
# pp.pprint(value)
all_metric_data = []
sample = len(singlevalue["data"])
for i in ran... | allstat[value["statKey"]["key"]] = value["data"][0] | conditional_block |
metric-collection.py | # !/usr/bin python
"""
#
# data-collect.py contain the python program to gather Metrics from vROps. Before you run this script
# set-config.py should be run once to set the environment
# Author Sajal Debnath <sdebnath@vmware.com>
#
"""
# Importing the Modules
import nagini
import requests
#import pprint
import json
... |
# Function to get the metric data
def get_metric_data(resourceknd,adapter,key,sampleno ):
outdata = [] # It's going to store the final JSON data
# Gettting a list of resources which matches the criteria or resourceKind and adapterKind
for resource in vrops.get_resources(resourceKind=resourceknd, adapterKi... | return os.path.dirname(os.path.realpath(sys.argv[0])) | identifier_body |
metric-collection.py | # !/usr/bin python
"""
#
# data-collect.py contain the python program to gather Metrics from vROps. Before you run this script
# set-config.py should be run once to set the environment
# Author Sajal Debnath <sdebnath@vmware.com>
#
"""
# Importing the Modules
import nagini
import requests
#import pprint
import json
... | ():
return os.path.dirname(os.path.realpath(sys.argv[0]))
# Function to get the metric data
def get_metric_data(resourceknd,adapter,key,sampleno ):
outdata = [] # It's going to store the final JSON data
# Gettting a list of resources which matches the criteria or resourceKind and adapterKind
for resour... | get_script_path | identifier_name |
metric-collection.py | # !/usr/bin python
"""
#
# data-collect.py contain the python program to gather Metrics from vROps. Before you run this script
# set-config.py should be run once to set the environment
# Author Sajal Debnath <sdebnath@vmware.com>
#
"""
# Importing the Modules
import nagini
import requests
#import pprint
import json
... | continue
else:
if int(sampleno) == 1:
for value in allvalues["values"][0]["stat-list"]["stat"]:
allstat[value["statKey"]["key"]] = value["data"][0]
else:
# We have a range of values to store
for singlevalue... |
# Checking for any null values
if not allvalues["values"]: | random_line_split |
metro.py | #####################################################################
#
# metro.py
#
# Copyright (c) 2016, Eran Egozy
#
# Released under the MIT License (http://opensource.org/licenses/MIT)
#
#####################################################################
from clock import kTicksPerQuarter, quantize_tick_up
cla... | (object):
"""Plays a steady click every beat.
"""
def __init__(self, sched, synth, channel = 0, patch=(128, 0), pitch = 60):
super(Metronome, self).__init__()
self.sched = sched
self.synth = synth
self.channel = channel
self.patch = patch
self.pitch = pitch
... | Metronome | identifier_name |
metro.py | #####################################################################
#
# metro.py
#
# Copyright (c) 2016, Eran Egozy
#
# Released under the MIT License (http://opensource.org/licenses/MIT)
#
#####################################################################
from clock import kTicksPerQuarter, quantize_tick_up
cla... |
else:
self.start()
def _noteon(self, tick, ignore):
# play the note right now:
self.synth.noteon(self.channel, self.pitch, 100)
# post the note off for half a beat later:
self.off_cmd = self.sched.post_at_tick(tick + self.beat_len/2, self._noteoff, self.pitch)
... | self.stop() | conditional_block |
metro.py | #####################################################################
#
# metro.py
#
# Copyright (c) 2016, Eran Egozy
#
# Released under the MIT License (http://opensource.org/licenses/MIT)
#
#####################################################################
from clock import kTicksPerQuarter, quantize_tick_up
cla... | self.stop()
else:
self.start()
def _noteon(self, tick, ignore):
# play the note right now:
self.synth.noteon(self.channel, self.pitch, 100)
# post the note off for half a beat later:
self.off_cmd = self.sched.post_at_tick(tick + self.beat_len/2, self... |
def toggle(self):
if self.playing: | random_line_split |
metro.py | #####################################################################
#
# metro.py
#
# Copyright (c) 2016, Eran Egozy
#
# Released under the MIT License (http://opensource.org/licenses/MIT)
#
#####################################################################
from clock import kTicksPerQuarter, quantize_tick_up
cla... |
def stop(self):
if not self.playing:
return
self.playing = False
# in case there is a note on hanging, turn it off immediately
if self.off_cmd:
self.off_cmd.execute()
# cancel anything pending in the future.
self.sched.remove(... | if self.playing:
return
self.playing = True
# set up the correct sound (program change)
self.synth.program(self.channel, self.patch[0], self.patch[1])
# find the tick of the next beat, and make it "beat aligned"
now = self.sched.get_tick()
next_beat = quant... | identifier_body |
ResourceInfo.test.tsx | import {Artifact, ArtifactCustomProperties, ArtifactProperties} from '@kubeflow/frontend';
import * as React from 'react';
import {ResourceInfo} from './ResourceInfo';
import {shallow, ShallowWrapper} from 'enzyme';
import {stringValue, testModel} from '../TestUtils';
describe('ResourceInfo', () => {
let tree: Shall... | expect(tree).toMatchSnapshot();
});
it('Renders Artifact information for a Model', () => {
tree = shallow(<ResourceInfo typeName='Model' resource={testModel} />);
expect(tree).toMatchSnapshot();
});
}); | random_line_split | |
rollup.config.js | "use strict";
|
let cfg;
const dest = process.env.DEST;
if (!dest) {
console.log("No destination specified - code will be compiled but not uploaded");
} else if ((cfg = require("./screeps.json")[dest]) == null) {
throw new Error("Invalid upload destination");
}
export default {
input: "src/main.ts",
output: {
... | import clear from "rollup-plugin-clear";
import resolve from "rollup-plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";
import typescript from "rollup-plugin-typescript2";
import screeps from "rollup-plugin-screeps"; | random_line_split |
Spot.js | (function(global) {
/* global RGPP */
"use strict";
var objName = "Spot";
var mGoalPosX = 0;
var mGoalPosY = 0;
var mMoveFlag = false;
var LINE_WIDTH = RGPP.System.ChangeableValue({
name: "Line Width",
minValue: 1,
maxValue: 10,
defaultValue: 2,
stepValue: 1,
type: "spinner"
});
var construct... | Menu.draw(ctx);
if (mEnable) {
// Draw Range Square
var fundDrawing = RGPP.System.FundamentalDrawing.getInstance();
fundDrawing.setColor(ctx, 0, 0, 255, 1);
var mapManager = RGPP.System.MapManager.getInstance();
var chipWidth = mapManager.chipWidth();
var chipHeight = mapManager.chipHeight()... | m | identifier_name |
Spot.js | (function(global) {
/* global RGPP */
"use strict";
var objName = "Spot";
var mGoalPosX = 0;
var mGoalPosY = 0;
var mMoveFlag = false;
var LINE_WIDTH = RGPP.System.ChangeableValue({
name: "Line Width",
minValue: 1,
maxValue: 10,
defaultValue: 2,
stepValue: 1,
type: "spinner"
});
var construct... | nable && mReachFlag && !mUpdateFlag) {
eventOperator.reactionByEventID(mNextSpotID.value());
mUpdateFlag = true;
}
}
}
var controlPlayerByMouse = function(playerSprite) {
//Check Mouse
var mapManager = RGPP.System.MapManager.getInstance();
var chipWidth = mapManager.chipWidth();
var c... | rSprite.setDirectionXY(mVx, mVy);
eventOperator.reactionByStateKey("player");
}
if (mE | conditional_block |
Spot.js | (function(global) {
/* global RGPP */
"use strict";
var objName = "Spot";
var mGoalPosX = 0;
var mGoalPosY = 0;
var mMoveFlag = false;
var LINE_WIDTH = RGPP.System.ChangeableValue({
name: "Line Width",
minValue: 1,
maxValue: 10,
defaultValue: 2,
stepValue: 1,
type: "spinner"
});
var construct... | draw(ctx) {
mMenu.draw(ctx);
if (mEnable) {
// Draw Range Square
var fundDrawing = RGPP.System.FundamentalDrawing.getInstance();
fundDrawing.setColor(ctx, 0, 0, 255, 1);
var mapManager = RGPP.System.MapManager.getInstance();
var chipWidth = mapManager.chipWidth();
var chipHeight = mapMan... | = true;
var mapManager = RGPP.System.MapManager.getInstance();
var firstX = event.currentX() - Math.floor(mDeleteWidth.value() / 2);
var firstY = event.currentY() - Math.floor(mDeleteHeight.value() / 2);
var deleteArray = [];
for (var y = 0; y < mDeleteHeight.value(); y += 1) {
deleteArray[y] = [... | identifier_body |
Spot.js | (function(global) {
/* global RGPP */
"use strict";
var objName = "Spot";
var mGoalPosX = 0;
var mGoalPosY = 0;
var mMoveFlag = false;
var LINE_WIDTH = RGPP.System.ChangeableValue({
name: "Line Width",
minValue: 1,
maxValue: 10,
defaultValue: 2,
stepValue: 1,
type: "spinner"
});
var construct... | function loadChangeableValuesPerScript() {
var changeableValues = mMenu.loadChangeableValuesPerScript();
changeableValues.push(LINE_WIDTH);
return changeableValues;
}
function loadChangeableValuesPerEvent() {
var changeableValues = [];
changeableValues.push(mNextSpotID);
changeableValues.push(m... | random_line_split | |
pill.d.ts | import * as React from "react";
import { MarginProps } from "styled-system";
export interface PillProps extends MarginProps {
/** Override color variant, provide any color from palette or any valid css color value. */
borderColor?: string;
/** Change the color of a status pill. */
colorVariant?: "neutral" | "n... | /** Sets the type of pill in use. */
pillRole?: "tag" | "status";
size?: "S" | "M" | "L" | "XL";
}
declare function Pill(props: PillProps): JSX.Element;
export default Pill; | fill?: boolean;
/** Callback function for when the pill is clicked. */
onClick?: React.MouseEventHandler<HTMLSpanElement>;
/** Callback function for when the remove icon is clicked. */
onDelete?: React.MouseEventHandler<HTMLButtonElement>; | random_line_split |
test_lazy_canteen.py | # -*- coding: UTF-8 -*-
from datetime import date
import re
import pytest
from pyopenmensa.feed import LazyBuilder
@pytest.fixture
def canteen():
|
def test_date_converting(canteen):
day = date(2013, 3, 7)
assert canteen.dayCount() == 0
canteen.setDayClosed('2013-03-07')
assert canteen.dayCount() == 1
canteen.setDayClosed(day)
assert canteen.dayCount() == 1
canteen.setDayClosed('07.03.2013')
assert canteen.dayCount() == 1
def t... | return LazyBuilder() | identifier_body |
test_lazy_canteen.py | # -*- coding: UTF-8 -*-
from datetime import date
import re
import pytest
from pyopenmensa.feed import LazyBuilder
@pytest.fixture
def canteen():
return LazyBuilder()
def test_date_converting(canteen):
day = date(2013, 3, 7)
assert canteen.dayCount() == 0
canteen.setDayClosed('2013-03-07')
ass... | canteen.setDayClosed(day)
assert canteen.hasMealsFor(day) is False
def test_add_meal(canteen):
day = date(2013, 3, 7)
canteen.addMeal(day, 'Hauptgericht', 'Gulasch')
assert canteen.hasMealsFor(day)
def test_to_long_meal_name(canteen):
day = date(2013, 3, 7)
canteen.addMeal(day, 'Hauptger... | canteen._days[day] = {'Hausgericht': ('Gulash', [], {})}
assert canteen.hasMealsFor(day) is True | random_line_split |
test_lazy_canteen.py | # -*- coding: UTF-8 -*-
from datetime import date
import re
import pytest
from pyopenmensa.feed import LazyBuilder
@pytest.fixture
def canteen():
return LazyBuilder()
def | (canteen):
day = date(2013, 3, 7)
assert canteen.dayCount() == 0
canteen.setDayClosed('2013-03-07')
assert canteen.dayCount() == 1
canteen.setDayClosed(day)
assert canteen.dayCount() == 1
canteen.setDayClosed('07.03.2013')
assert canteen.dayCount() == 1
def test_has_meals_for(canteen):... | test_date_converting | identifier_name |
video-comments.component.ts | import { Subject, Subscription } from 'rxjs'
import { Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewChild } from '@angular/core'
import { ActivatedRoute } from '@angular/router'
import { AuthService, ComponentPagination, ConfirmService, hasMoreItems, Notifier, User... | (
private authService: AuthService,
private notifier: Notifier,
private confirmService: ConfirmService,
private videoCommentService: VideoCommentService,
private activatedRoute: ActivatedRoute,
private hooks: HooksService
) {}
ngOnInit () {
// Find highlighted comment in params
thi... | constructor | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.