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 |
|---|---|---|---|---|
bootstrap_commands.py | " % env["LD_LIBRARY_PATH"])
@Command('bootstrap',
description='Install required packages for building.',
category='bootstrap')
@CommandArgument('--force', '-f',
action='store_true',
help='Boostrap without confirmation')
def bootstrap(self,... |
os.makedirs(cargo_dir)
tgz_file = "cargo-nightly-%s.tar.gz" % host_triple()
nightly_url = "https://s3.amazonaws.com/rust-lang-ci/cargo-builds/%s/%s" % \
(self.cargo_build_id(), tgz_file)
download_file("Cargo nightly", nightly_url, tgz_file)
print("Extracting Cargo... | shutil.rmtree(cargo_dir) | conditional_block |
bootstrap_commands.py | ust_path()
rust_dir = path.join(self.context.sharedir, "rust", rust_path)
install_dir = path.join(self.context.sharedir, "rust", version)
if not self.config["build"]["llvm-assertions"]:
install_dir += "-alt"
if not force and path.exists(path.join(rust_dir, "rustc", "bin", "r... | bootstrap_pub_suffix | identifier_name | |
bootstrap_commands.py | " % env["LD_LIBRARY_PATH"])
@Command('bootstrap',
description='Install required packages for building.',
category='bootstrap')
@CommandArgument('--force', '-f',
action='store_true',
help='Boostrap without confirmation')
def bootstrap(self,... |
@Command('bootstrap-rust',
description='Download the Rust compiler',
category='bootstrap')
@CommandArgument('--force', '-f',
action='store_true',
help='Force download even if a copy already exists')
@CommandArgument('--target',
... | return bootstrap.bootstrap(self.context, force=force) | identifier_body |
qa.js | import React, { Component } from 'react';
import Steps from './widgets/steps/steps';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
const styles = {
container: {
display: 'flex',
justifyContent: 'space-around',
flexDirection: 'column',
marginBottom: '1vh',
... | () {
document.title = 'QA';
}
renderMetrics = (step, spectrographNumber, arm) => {
if (this.props.navigateToMetrics) {
this.props.navigateToMetrics(
step,
spectrographNumber,
arm,
this.props.exposureId
);
}
};
renderSteps = () => {
return (
<St... | componentDidMount | identifier_name |
qa.js | import React, { Component } from 'react';
import Steps from './widgets/steps/steps';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
const styles = {
container: {
display: 'flex',
justifyContent: 'space-around',
flexDirection: 'column',
marginBottom: '1vh',
... |
class QA extends Component {
static propTypes = {
exposureId: PropTypes.string,
qaTests: PropTypes.array,
arms: PropTypes.array.isRequired,
spectrographs: PropTypes.array.isRequired,
mjd: PropTypes.string,
date: PropTypes.string,
time: PropTypes.string,
navigateToMetrics: PropTypes.fu... | fontSize: 0,
textIndent: '-9999em',
},
}; | random_line_split |
qa.js | import React, { Component } from 'react';
import Steps from './widgets/steps/steps';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
const styles = {
container: {
display: 'flex',
justifyContent: 'space-around',
flexDirection: 'column',
marginBottom: '1vh',
... |
};
renderSteps = () => {
return (
<Steps
navigateToProcessingHistory={this.props.navigateToProcessingHistory}
qaTests={this.props.qaTests}
renderMetrics={this.renderMetrics}
mjd={this.props.mjd}
exposureId={this.props.exposureId}
date={this.props.date}
... | {
this.props.navigateToMetrics(
step,
spectrographNumber,
arm,
this.props.exposureId
);
} | conditional_block |
day_05.rs | pub fn first() {
let filename = "day05-01.txt";
let mut lines: Vec<String> = super::helpers::read_lines(filename)
.into_iter()
.map(|x| x.unwrap())
.collect();
lines.sort();
let mut max = 0;
for line in lines {
let id = get_id(&line);
if id > max {
... |
gap = max - min + 1;
println!("{} {} {}", max, min, gap);
}
idx = max * 8;
min = 0;
max = 7;
gap = max - min + 1;
for x in lr.chars() {
if x == 'L' {
max = max - gap / 2;
} else if x == 'R' {
min = min + gap / 2;
}
gap = ... | {
min = min + gap / 2;
} | conditional_block |
day_05.rs | pub fn first() {
let filename = "day05-01.txt";
let mut lines: Vec<String> = super::helpers::read_lines(filename)
.into_iter()
.map(|x| x.unwrap())
.collect();
lines.sort();
let mut max = 0;
for line in lines {
let id = get_id(&line);
if id > max {
... | let mut min: i32 = 0;
let mut max: i32 = 127;
let mut gap = max - min + 1;
for y in fb.chars() {
if y == 'F' {
max = max - gap / 2;
} else if y == 'B' {
min = min + gap / 2;
}
gap = max - min + 1;
println!("{} {} {}", max, min, gap);
}... | let lr = &code[7..];
let mut idx;
| random_line_split |
day_05.rs | pub fn first() |
fn get_id(code: &str) -> i32 {
let fb = &code[0..7];
let lr = &code[7..];
let mut idx;
let mut min: i32 = 0;
let mut max: i32 = 127;
let mut gap = max - min + 1;
for y in fb.chars() {
if y == 'F' {
max = max - gap / 2;
} else if y == 'B' {
min = mi... | {
let filename = "day05-01.txt";
let mut lines: Vec<String> = super::helpers::read_lines(filename)
.into_iter()
.map(|x| x.unwrap())
.collect();
lines.sort();
let mut max = 0;
for line in lines {
let id = get_id(&line);
if id > max {
max = id;
... | identifier_body |
day_05.rs | pub fn | () {
let filename = "day05-01.txt";
let mut lines: Vec<String> = super::helpers::read_lines(filename)
.into_iter()
.map(|x| x.unwrap())
.collect();
lines.sort();
let mut max = 0;
for line in lines {
let id = get_id(&line);
if id > max {
max = id... | first | identifier_name |
issue-19479.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {} | random_line_split | |
issue-19479.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) { }
}
trait AssocA {
type X: Base;
fn dummy(&self) { }
}
trait AssocB {
type Y: Base;
fn dummy(&self) { }
}
impl<T: AssocA> AssocB for T {
type Y = <T as AssocA>::X;
}
fn main() {}
| dummy | identifier_name |
issue-19479.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
trait AssocB {
type Y: Base;
fn dummy(&self) { }
}
impl<T: AssocA> AssocB for T {
type Y = <T as AssocA>::X;
}
fn main() {}
| { } | identifier_body |
build_target_lib_unittest.py | # -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""build_target_lib tests."""
from __future__ import print_function
import os
from chromite.lib.build_target_lib import BuildTa... |
def testNormalRoot(self):
"""Test normalized sysroot path."""
target = BuildTarget('board', build_root=self.sysroot)
self.assertEqual(self.sysroot, target.root)
def testDenormalizedRoot(self):
"""Test a non-normal sysroot path."""
target = BuildTarget('board', build_root=self.sysroot_denormali... | """BuildTarget tests."""
def setUp(self):
self.sysroot = os.path.join(self.tempdir, 'sysroot')
self.sysroot_denormalized = os.path.join(self.tempdir, 'dne', '..',
'sysroot')
osutils.SafeMakedirs(self.sysroot)
def testEqual(self):
"""Sanity check for __e... | identifier_body |
build_target_lib_unittest.py | # -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""build_target_lib tests."""
from __future__ import print_function
import os
from chromite.lib.build_target_lib import BuildTa... | def testDenormalizedRoot(self):
"""Test a non-normal sysroot path."""
target = BuildTarget('board', build_root=self.sysroot_denormalized)
self.assertEqual(self.sysroot, target.root)
def testDefaultRoot(self):
"""Test the default sysroot path."""
target = BuildTarget('board')
self.assertEqua... | self.assertEqual(self.sysroot, target.root)
| random_line_split |
build_target_lib_unittest.py | # -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""build_target_lib tests."""
from __future__ import print_function
import os
from chromite.lib.build_target_lib import BuildTa... | (cros_test_lib.TempDirTestCase):
"""BuildTarget tests."""
def setUp(self):
self.sysroot = os.path.join(self.tempdir, 'sysroot')
self.sysroot_denormalized = os.path.join(self.tempdir, 'dne', '..',
'sysroot')
osutils.SafeMakedirs(self.sysroot)
def testEqual... | BuildTargetTest | identifier_name |
server.py | from __future__ import absolute_import, division, print_function
from collections import Iterator
from flask import Flask, request, jsonify, json
from functools import partial, wraps
from .index import parse_index
class Server(object):
__slots__ = 'app', 'datasets'
def __init__(self, name='Blaze-Server', da... |
return f
@route('/datasets.json')
def dataset(datasets):
return jsonify(dict((k, str(v.dshape)) for k, v in datasets.items()))
@route('/data/<name>.json', methods=['POST', 'PUT', 'GET'])
def data(datasets, name):
""" Basic indexing API
Allows remote indexing of datasets. Takes indexing data as JS... | routes.append((args, kwargs, func))
return func | identifier_body |
server.py | from __future__ import absolute_import, division, print_function
from collections import Iterator
from flask import Flask, request, jsonify, json
from functools import partial, wraps
from .index import parse_index
class Server(object):
__slots__ = 'app', 'datasets'
def __init__(self, name='Blaze-Server', da... | return ("Bad index: %s" % (str(index)), 404)
if isinstance(rv, Iterator):
rv = list(rv)
return jsonify({'name': name,
'index': data['index'],
'datashape': str(dset.dshape.subshape[index]),
'data': rv}) | return ("Bad index", 404)
try:
rv = dset.py[index]
except RuntimeError: | random_line_split |
server.py | from __future__ import absolute_import, division, print_function
from collections import Iterator
from flask import Flask, request, jsonify, json
from functools import partial, wraps
from .index import parse_index
class Server(object):
__slots__ = 'app', 'datasets'
def | (self, name='Blaze-Server', datasets=None):
app = self.app = Flask(name)
self.datasets = datasets or dict()
for args, kwargs, func in routes:
func2 = wraps(func)(partial(func, self.datasets))
app.route(*args, **kwargs)(func2)
def __getitem__(self, key):
retu... | __init__ | identifier_name |
server.py | from __future__ import absolute_import, division, print_function
from collections import Iterator
from flask import Flask, request, jsonify, json
from functools import partial, wraps
from .index import parse_index
class Server(object):
__slots__ = 'app', 'datasets'
def __init__(self, name='Blaze-Server', da... |
try:
data = json.loads(request.data)
except ValueError:
return ("Bad JSON. Got %s " % request.data, 404)
try:
dset = datasets[name]
except KeyError:
return ("Dataset %s not found" % name, 404)
try:
index = parse_index(data['index'])
except ValueError:
... | return ("Expected JSON data", 404) | conditional_block |
dash_handler_template.py |
from {{appname}}.handlers.powhandler import PowHandler
from {{appname}}.conf.config import myapp
from {{appname}}.lib.application import app
import simplejson as json
import tornado.web
from tornado import gen
from {{appname}}.pow_dash import dispatcher
# Please import your model here. (from yourapp.models.dbtype)
@a... |
def dash_ajax_json(self):
"""
respond to the dash ajax json / react request's
"""
print(" processing dash_ajax method")
#
# now hand over to the dispatcher
#
retval = dispatcher(self.request, index=False, username="fa... | """
This is the place where dash is called.
dispatcher returns the HMTL including title, css, scripts and config via => dash.Dash.index()
(See: in pow_dash.py => myDash.index)
You can then insert the returned HTML into your template.
I do this below in the se... | identifier_body |
dash_handler_template.py | from {{appname}}.handlers.powhandler import PowHandler
from {{appname}}.conf.config import myapp
from {{appname}}.lib.application import app
import simplejson as json
import tornado.web
from tornado import gen
from {{appname}}.pow_dash import dispatcher
# Please import your model here. (from yourapp.models.dbtype)
@ap... | # #
# """Handle Dash requests and guess the mimetype. Needed for static files."""
# url = request.path.split('?')[0]
# content_type, _encoding = mimetypes.guess_type(url)
# retval = dispatcher(self.request, index=False, username="fake", session_id=1234, powapp=self.application... |
# #
# # now hand over to the dispatcher | random_line_split |
dash_handler_template.py |
from {{appname}}.handlers.powhandler import PowHandler
from {{appname}}.conf.config import myapp
from {{appname}}.lib.application import app
import simplejson as json
import tornado.web
from tornado import gen
from {{appname}}.pow_dash import dispatcher
# Please import your model here. (from yourapp.models.dbtype)
@a... | (self):
"""
respond to the dash ajax json / react request's
"""
print(" processing dash_ajax method")
#
# now hand over to the dispatcher
#
retval = dispatcher(self.request, index=False, username="fake", session_id=1234, powapp=... | dash_ajax_json | identifier_name |
middleware.py | from django.http import HttpResponseRedirect
from django.shortcuts import render
from kuma.core.utils import urlparams
from .exceptions import ReadOnlyException
from .jobs import DocumentZoneURLRemapsJob
class ReadOnlyMiddleware(object):
"""
Renders a 403.html page with a flag for a specific message.
""... | new_path = urlparams(new_path, query_dict=query)
return HttpResponseRedirect(new_path)
elif request.path_info.startswith(new_path):
# Is this a request for the relocated wiki path? If so, rewrite
# the path as a request for the proper wiki vi... | if request.method == 'POST' and '$subscribe' in request.path:
return None
remaps = DocumentZoneURLRemapsJob().get(request.LANGUAGE_CODE)
for original_path, new_path in remaps:
if (
request.path_info == original_path or
request.path_info.startswit... | identifier_body |
middleware.py | from django.http import HttpResponseRedirect
from django.shortcuts import render
from kuma.core.utils import urlparams
from .exceptions import ReadOnlyException
from .jobs import DocumentZoneURLRemapsJob
class ReadOnlyMiddleware(object):
""" | return render(request, '403.html', context, status=403)
return None
class DocumentZoneMiddleware(object):
"""
For document zones with specified URL roots, this middleware modifies the
incoming path_info to point at the internal wiki path
"""
def process_request(self, request):
... | Renders a 403.html page with a flag for a specific message.
"""
def process_exception(self, request, exception):
if isinstance(exception, ReadOnlyException):
context = {'reason': exception.args[0]} | random_line_split |
middleware.py | from django.http import HttpResponseRedirect
from django.shortcuts import render
from kuma.core.utils import urlparams
from .exceptions import ReadOnlyException
from .jobs import DocumentZoneURLRemapsJob
class ReadOnlyMiddleware(object):
"""
Renders a 403.html page with a flag for a specific message.
""... | # the path as a request for the proper wiki view.
request.path_info = request.path_info.replace(new_path,
original_path,
1)
break
| if (
request.path_info == original_path or
request.path_info.startswith(u''.join([original_path, '/']))
):
# Is this a request for the "original" wiki path? Redirect to
# new URL root, if so.
new_path = request.path_info.replace... | conditional_block |
middleware.py | from django.http import HttpResponseRedirect
from django.shortcuts import render
from kuma.core.utils import urlparams
from .exceptions import ReadOnlyException
from .jobs import DocumentZoneURLRemapsJob
class | (object):
"""
Renders a 403.html page with a flag for a specific message.
"""
def process_exception(self, request, exception):
if isinstance(exception, ReadOnlyException):
context = {'reason': exception.args[0]}
return render(request, '403.html', context, status=403)
... | ReadOnlyMiddleware | identifier_name |
simulations.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 25 17:30:28 2017
@author: wroscoe
"""
import numpy as np
import random
class MovingSquareTelemetry:
"""
Generator of cordinates of a bouncing moving square for simulations.
"""
def __init__(self, max_velocity=29,
... | (self):
#move
self.x += self.x_direction * self.velocity
self.y += self.y_direction * self.velocity
#make square bounce off walls
if self.y < self.y_min or self.y > self.y_max:
self.y_direction *= -1
if self.x < self.x_min or self.x > self.x_max:
... | run | identifier_name |
simulations.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 25 17:30:28 2017
@author: wroscoe
"""
import numpy as np
import random
class MovingSquareTelemetry:
"""
Generator of cordinates of a bouncing moving square for simulations.
"""
def __init__(self, max_velocity=29,
... |
return int(self.x), int(self.y)
def update(self):
self.tel = self.run()
def run_threaded(self):
return self.tel
class SquareBoxCamera:
"""
Fake camera that returns an image with a square box.
This can be used to test if a learning algorithm ... | self.x_direction *= -1 | conditional_block |
simulations.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 25 17:30:28 2017
@author: wroscoe
"""
import numpy as np
import random
class MovingSquareTelemetry:
"""
Generator of cordinates of a bouncing moving square for simulations.
"""
def __init__(self, max_velocity=29,
... |
class SquareBoxCamera:
"""
Fake camera that returns an image with a square box.
This can be used to test if a learning algorithm can learn.
"""
def __init__(self, resolution=(120,160), box_size=4, color=(255, 0, 0)):
self.resolution = resolution
self.box_size = box_s... | return self.tel | identifier_body |
simulations.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 25 17:30:28 2017
@author: wroscoe
"""
import numpy as np
import random
class MovingSquareTelemetry:
"""
Generator of cordinates of a bouncing moving square for simulations.
"""
def __init__(self, max_velocity=29,
... | self.x_min, self.x_max = x_min, x_max
self.y_min, self.y_max = y_min, y_max
self.x_direction = random.random() * 2 - 1
self.y_direction = random.random() * 2 - 1
self.x = random.random() * x_max
self.y = random.random() * y_max
s... | self.velocity = random.random() * max_velocity
| random_line_split |
test01_validity_test_SH-PSV_input_S.py | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 21 04:00:41 2016
@author: irnakat
"""
# test IOfile
import IOfile
from TFCalculator import TFCalculator as TFC
import TFDisplayTools
# validity test for SH PSV case using S wave as an input
# filename
fname = 'sampleinput_linear_elastic_1layer_halfspace.... |
TFDisplayTools.PhasePlot(theclass1,theclass3,theclass5,theclass4, \
label=['Kramer SH','Knopoff SH','Kennet SH','Knopoff PSV']) | TFDisplayTools.TFPlot(theclass1,theclass3,theclass5,theclass4, \
label=['Kramer SH','Knopoff SH','Kennet SH','Knopoff PSV'])
| random_line_split |
Gruntfile.js | module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: {
release: ["public/**"]
},
assemble: {
release: {
options: {
layoutdir: 'www/templates/layouts',
partials: ['www/templates/includ... | }]
}
},
copy: {
release: {
files: [{
expand: true,
cwd: 'bower_components/bloxui/dist/css/fonts',
src: ['./**'],
dest: 'public/css/fonts'
}]
}
},
watch: {
js: {
files: ['www/js/**/*.js'],
tasks: ['new... | src: ['www/css/evdp.css'],
dest: 'public',
ext: '-min.css' | random_line_split |
exchange.rs | //! The exchange pattern distributes pushed data between many target pushees.
use {Push, Data};
use dataflow::channels::Content;
use abomonation::Abomonation;
// TODO : Software write combining
/// Distributes records among target pushees according to a distribution function.
pub struct Exchange<T, D, P: Push<(T, Co... | let index = (((self.hash_func)(&datum)) & mask) as usize;
self.buffers[index].push(datum);
if self.buffers[index].len() == self.buffers[index].capacity() {
self.flush(index);
}
... | {
// if only one pusher, no exchange
if self.pushers.len() == 1 {
self.pushers[0].push(message);
}
else {
if let Some((ref time, ref mut data)) = *message {
// if the time isn't right, flush everything.
if self.current.as_ref().map... | identifier_body |
exchange.rs | //! The exchange pattern distributes pushed data between many target pushees.
use {Push, Data};
use dataflow::channels::Content;
use abomonation::Abomonation;
// TODO : Software write combining
/// Distributes records among target pushees according to a distribution function.
pub struct Exchange<T, D, P: Push<(T, Co... | }
} | } | random_line_split |
exchange.rs | //! The exchange pattern distributes pushed data between many target pushees.
use {Push, Data};
use dataflow::channels::Content;
use abomonation::Abomonation;
// TODO : Software write combining
/// Distributes records among target pushees according to a distribution function.
pub struct Exchange<T, D, P: Push<(T, Co... | (&mut self, message: &mut Option<(T, Content<D>)>) {
// if only one pusher, no exchange
if self.pushers.len() == 1 {
self.pushers[0].push(message);
}
else {
if let Some((ref time, ref mut data)) = *message {
// if the time isn't right, flush every... | push | identifier_name |
exchange.rs | //! The exchange pattern distributes pushed data between many target pushees.
use {Push, Data};
use dataflow::channels::Content;
use abomonation::Abomonation;
// TODO : Software write combining
/// Distributes records among target pushees according to a distribution function.
pub struct Exchange<T, D, P: Push<(T, Co... |
// as a last resort, use mod (%)
else {
for datum in data.drain(..) {
let index = (((self.hash_func)(&datum)) % self.pushers.len() as u64) as usize;
self.buffers[index].push(datum);
if self.buffe... | {
let mask = (self.pushers.len() - 1) as u64;
for datum in data.drain(..) {
let index = (((self.hash_func)(&datum)) & mask) as usize;
self.buffers[index].push(datum);
if self.buffers[index].len() == self.buf... | conditional_block |
OfficeJSLabHost.ts | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ... | (options: Labs.Core.ILabCreationOptions, callback: Labs.Core.ILabCallback<void>) {
this._labHost.create(options, callback);
}
getConfiguration(callback: Labs.Core.ILabCallback<Labs.Core.IConfiguration>) {
this._labHost.getConfiguration(callback);
}
setConfigurat... | create | identifier_name |
OfficeJSLabHost.ts | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ... |
// based on what happens here I think I want to split on which internal host I create
resolver.resolve();
};
}
getSupportedVersions(): Core.ILabHostVersionInfo[] {
return [this._version];
}
connect(versions: Labs.Core.ILabHostVe... | {
this._labHost = new RichClientOfficeJSLabsHost(
labsSettings ? labsSettings.configuration : null,
labsSettings ? labsSettings.hostVersion : null);
} | conditional_block |
OfficeJSLabHost.ts | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ... |
takeAction(type: string, options: Labs.Core.IActionOptions, callback: Labs.Core.ILabCallback<Labs.Core.IAction>);
takeAction(type: string, options: Labs.Core.IActionOptions, result: Labs.Core.IActionResult, callback: Labs.Core.ILabCallback<Labs.Core.IAction>);
takeAction(type: string, options:... | {
this._labHost.setState(state, callback);
} | identifier_body |
OfficeJSLabHost.ts | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ... | var Office: OfficeInterface;
module Labs {
export interface IPromise {
then(callback: Function);
};
export class Resolver {
private _callbacks: Function[] = [];
private _isResolved = false;
private _resolvedValue;
promise: IPromise;
constructor() {
... | random_line_split | |
serialise.rs | /* Notice: Copyright 2016, The Care Connections Initiative c.i.c.
* Author: Charlie Fyvie-Gauld (cfg@zunautica.org)
* License: GPLv3 (http://www.gnu.org/licenses/gpl-3.0.txt)
*/
use std::mem::transmute;
use ::enums::Failure;
pub trait NetSerial : Sized {
fn serialise(&self) -> Vec<u8>;
fn deserialise(bytes: &[u8... | }
}
pub fn u32_transmute_be_arr(a: &[u8]) -> u32 {
unsafe { transmute::<[u8;4], u32>([a[3], a[2], a[1], a[0]]) }
}
pub fn u32_transmute_le_arr(a: &[u8]) -> u32 {
unsafe { transmute::<[u8;4], u32>([a[0], a[1], a[2], a[3]]) }
}
pub fn array_transmute_be_u32(d: u32) -> [u8;4] {
unsafe { transmute(d.to_be()) }
}
... | v.push(*b) | random_line_split |
serialise.rs | /* Notice: Copyright 2016, The Care Connections Initiative c.i.c.
* Author: Charlie Fyvie-Gauld (cfg@zunautica.org)
* License: GPLv3 (http://www.gnu.org/licenses/gpl-3.0.txt)
*/
use std::mem::transmute;
use ::enums::Failure;
pub trait NetSerial : Sized {
fn serialise(&self) -> Vec<u8>;
fn deserialise(bytes: &[u8... |
pub fn array_transmute_le_u32(d: u32) -> [u8;4] {
unsafe { transmute(d.to_le()) }
}
pub fn byte_slice_4array(a: &[u8]) -> [u8;4] {
[ a[0], a[1], a[2], a[3] ]
}
pub fn deserialise_bool(byte: u8) -> bool {
match byte {
0 => false,
_ => true
}
}
pub fn hex_str_to_byte(src: &[u8]) -> Option<u8> {
let mut v... | {
unsafe { transmute(d.to_be()) }
} | identifier_body |
serialise.rs | /* Notice: Copyright 2016, The Care Connections Initiative c.i.c.
* Author: Charlie Fyvie-Gauld (cfg@zunautica.org)
* License: GPLv3 (http://www.gnu.org/licenses/gpl-3.0.txt)
*/
use std::mem::transmute;
use ::enums::Failure;
pub trait NetSerial : Sized {
fn serialise(&self) -> Vec<u8>;
fn deserialise(bytes: &[u8... | (byte: u8) -> bool {
match byte {
0 => false,
_ => true
}
}
pub fn hex_str_to_byte(src: &[u8]) -> Option<u8> {
let mut val = 0;
let mut factor = 16;
for i in 0 .. 2 {
val += match src[i] {
v @ 48 ... 57 => (v - 48) * factor,
v @ 65 ... 70 => (v - 55) * factor,
v @ 97 ... 102 => (v - 87) * factor... | deserialise_bool | identifier_name |
sync_deleted_instances_fix.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 fileencoding=utf-8
import json
from django.conf import settings
from django.core.management import BaseCommand
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from django.utils.translation import ugettext_lazy
from onadata.apps.log... | continue
else:
deleted_at = parse_datetime(record["_deleted_at"])
if not timezone.is_aware(deleted_at):
deleted_at = timezone.make_aware(
deleted_at, timezone.utc)
i.set_deleted(deleted_at)
| help = ugettext_lazy("Fixes deleted instances by syncing "
"deleted items from mongo.")
def handle(self, *args, **kwargs):
# Reset all sql deletes to None
Instance.objects.exclude(
deleted_at=None, xform__downloadable=True).update(deleted_at=None)
# Get... | identifier_body |
sync_deleted_instances_fix.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 fileencoding=utf-8
import json
from django.conf import settings
from django.core.management import BaseCommand
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from django.utils.translation import ugettext_lazy
from onadata.apps.log... |
i.set_deleted(deleted_at)
| deleted_at = timezone.make_aware(
deleted_at, timezone.utc) | conditional_block |
sync_deleted_instances_fix.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 fileencoding=utf-8
import json
from django.conf import settings
from django.core.management import BaseCommand
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from django.utils.translation import ugettext_lazy
from onadata.apps.log... | (BaseCommand):
help = ugettext_lazy("Fixes deleted instances by syncing "
"deleted items from mongo.")
def handle(self, *args, **kwargs):
# Reset all sql deletes to None
Instance.objects.exclude(
deleted_at=None, xform__downloadable=True).update(deleted_at=N... | Command | identifier_name |
sync_deleted_instances_fix.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 fileencoding=utf-8
import json
from django.conf import settings
from django.core.management import BaseCommand
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from django.utils.translation import ugettext_lazy
from onadata.apps.log... | uuid=record["_uuid"], xform__downloadable=True)
except Instance.DoesNotExist:
continue
else:
deleted_at = parse_datetime(record["_deleted_at"])
if not timezone.is_aware(deleted_at):
deleted_at = timezone.mak... | random_line_split | |
jsxReactTestSuite.tsx | // @jsx: preserve
declare var React: any;
declare var Component:any;
declare var Composite:any;
declare var Composite2:any;
declare var Child:any;
declare var Namespace:any;
declare var foo: any;
declare var bar: any;
declare var y:any;
declare var x:any;
declare var z:any;
declare var hasOwnProperty:any;
<div>text</... |
"baz" + "bug"
}
attr3={
"foo" + "bar" +
"baz" + "bug"
// Extra line here.
}
attr4="baz">
</div>;
(
<div>
{/* A comment at the beginning */}
{/* A second comment at the beginning */}
<span>
{/* A nested comment */}
</span>
{/* A sandwiched com... | "foo" + "bar" + | random_line_split |
test_glif_cond.py | NEST 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 2 of the License, or
# (at your option) any later version.
#
# NEST is distributed in the hope that it will be useful,
# but WITHOUT ANY WAR... |
def simulate_w_stim(self, model_params):
"""
Runs a one second simulation with different types of input stimulation.
Returns the time-steps, voltages, and collected spike times.
"""
# Create glif model to simulate
nrn = nest.Create("glif_cond", params=model_params)... | """
Clean up and initialize NEST before each test.
"""
msd = 123456
self.resol = 0.01
nest.ResetKernel()
N_vp = nest.GetKernelStatus(['total_num_virtual_procs'])[0]
pyrngs = [np.random.RandomState(s)
for s in range(msd, msd + N_vp)]
nest.... | identifier_body |
test_glif_cond.py | .
#
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see <http://www.gnu.org/licenses/>.
import unittest
import numpy as np
import nest
HAVE_GSL = nest.ll_api.sli_func("statusdict/have_gsl ::")
@unittest.skipIf(not HAVE_GSL, 'GSL is not available')
class GLIFCONDTestCa... | run() | conditional_block | |
test_glif_cond.py | NEST 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 2 of the License, or
# (at your option) any later version.
#
# NEST is distributed in the hope that it will be useful,
# but WITHOUT ANY WAR... | msd + 2 * N_vp + 1)})
def simulate_w_stim(self, model_params):
"""
Runs a one second simulation with different types of input stimulation.
Returns the time-steps, voltages, and collected spike times.
"""
# Create glif model t... | nest.SetKernelStatus({'resolution': self.resol,
'grng_seed': msd + N_vp,
'rng_seeds': range(msd + N_vp + 1, | random_line_split |
test_glif_cond.py | NEST 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 2 of the License, or
# (at your option) any later version.
#
# NEST is distributed in the hope that it will be useful,
# but WITHOUT ANY WAR... | (unittest.TestCase):
def setUp(self):
"""
Clean up and initialize NEST before each test.
"""
msd = 123456
self.resol = 0.01
nest.ResetKernel()
N_vp = nest.GetKernelStatus(['total_num_virtual_procs'])[0]
pyrngs = [np.random.RandomState(s)
... | GLIFCONDTestCase | identifier_name |
test.spec.js | describe('Home Page', () => {
it('Should load correctly', () => {
cy.visit('/')
cy.get('div.marketing-content')
.should('contain', 'Real-time Retrospectives')
}); | it('Should login and write a post', () => {
cy.get('.MuiButton-root').click();
cy.get('.MuiTabs-flexContainer > [tabindex="-1"]').click();
cy.get('.MuiInput-input').focus().type('Zelensky');
cy.get('.MuiDialogContent-root .MuiButton-root').click();
// Home page should display the user name
cy... | random_line_split | |
struct_grape_f_s_1_1___performance_operation.js | [ "_PerformanceOperation", "struct_grape_f_s_1_1___performance_operation.html#a9251cc499a0ab5c9d2fe2762ca2eb7a2", null ],
[ "FillProc", "struct_grape_f_s_1_1___performance_operation.html#ac8a4badb2cb3594ba22870efc8d68434", null ],
[ "ToString", "struct_grape_f_s_1_1___performance_operation.html#a742c658271c... | var struct_grape_f_s_1_1___performance_operation =
[ | random_line_split | |
views.py | #-*- coding:utf-8 -*-
from flask import render_template, redirect, request, url_for, flash
from flask.ext.login import login_user, logout_user, login_required, \
current_user
from . import auth
from .. import db
from ..models import User
from .forms import LoginForm, RegistrationForm
@auth.before_app_request
def ... | """登出"""
logout_user()
flash('You have been logged out.')
return redirect(url_for('main.index'))
@auth.route('/register', methods=['GET', 'POST'])
def register():
"""注册"""
form = RegistrationForm()
if form.validate_on_submit():
user = User(email=form.email.data,
... |
@auth.route('/logout')
@login_required
def logout(): | random_line_split |
views.py | #-*- coding:utf-8 -*-
from flask import render_template, redirect, request, url_for, flash
from flask.ext.login import login_user, logout_user, login_required, \
current_user
from . import auth
from .. import db
from ..models import User
from .forms import LoginForm, RegistrationForm
@auth.before_app_request
def ... | ()
if form.validate_on_submit():
user = User(email=form.email.data,
username=form.username.data,
password=form.password.data)
db.session.add(user)
db.session.commit()
return redirect(url_for('auth.login'))
return render_template('auth/regis... | tionForm | identifier_name |
views.py | #-*- coding:utf-8 -*-
from flask import render_template, redirect, request, url_for, flash
from flask.ext.login import login_user, logout_user, login_required, \
current_user
from . import auth
from .. import db
from ..models import User
from .forms import LoginForm, RegistrationForm
@auth.before_app_request
def ... | d
def logout():
"""登出"""
logout_user()
flash('You have been logged out.')
return redirect(url_for('main.index'))
@auth.route('/register', methods=['GET', 'POST'])
def register():
"""注册"""
form = RegistrationForm()
if form.validate_on_submit():
user = User(email=form.email.data,
... | if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is not None and user.verify_password(form.password.data):
login_user(user, form.remember_me.data)
return redirect(request.args.get('next') or url_for('main.index'))
flash(... | identifier_body |
views.py | #-*- coding:utf-8 -*-
from flask import render_template, redirect, request, url_for, flash
from flask.ext.login import login_user, logout_user, login_required, \
current_user
from . import auth
from .. import db
from ..models import User
from .forms import LoginForm, RegistrationForm
@auth.before_app_request
def ... | html', form=form)
@auth.route('/logout')
@login_required
def logout():
"""登出"""
logout_user()
flash('You have been logged out.')
return redirect(url_for('main.index'))
@auth.route('/register', methods=['GET', 'POST'])
def register():
"""注册"""
form = RegistrationForm()
if form.validate_on... | mail.data).first()
if user is not None and user.verify_password(form.password.data):
login_user(user, form.remember_me.data)
return redirect(request.args.get('next') or url_for('main.index'))
flash('Invalid username or password.')
return render_template('auth/login. | conditional_block |
Keyboard.js | /**
* Copyright 2019 Google LLC
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY... | else {
this.ready = Promise.resolve()
}
}
_addListeners(device){
if (!this.connectedDevices.has(device.id)){
this.connectedDevices.set(device.id, device)
device.addListener('noteon', 'all', (event) => {
this.emit('keyDown', `${event.note.name}${event.note.octave}`, event.velocity)
})
device... | {
this.ready = new Promise((done, error) => {
WebMidi.enable((e) => {
if (e){
error(e)
}
WebMidi.inputs.forEach(i => this._addListeners(i))
WebMidi.addListener('connected', (e) => {
if (e.port.type === 'input'){
this._addListeners(e.port)
}
})
WebMidi.addLis... | conditional_block |
Keyboard.js | /**
* Copyright 2019 Google LLC
* | *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
import WebMidi from 'webmidi'
import { EventEmitter } from 'events'... | * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation. | random_line_split |
Keyboard.js | /**
* Copyright 2019 Google LLC
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY... | (device){
if (!this.connectedDevices.has(device.id)){
this.connectedDevices.set(device.id, device)
device.addListener('noteon', 'all', (event) => {
this.emit('keyDown', `${event.note.name}${event.note.octave}`, event.velocity)
})
device.addListener('noteoff', 'all', (event) => {
this.emit('keyUp... | _addListeners | identifier_name |
settings-notifications.ts | import { cloneDeep } from 'lodash';
import { createPersonUpdate } from '../utils/people';
export default function(app) {
app.component('settingsNotifications', {
bindings: {
person: '<',
},
controller: class SettingsNotificationsCtrl {
public emailNotificationFrequency: 'immediately' | 'dail... | () {
const personUpdate = createPersonUpdate(this.authService.user);
personUpdate.account.settings = {
...personUpdate.account.setting,
emailNotificationFrequency: this.emailNotificationFrequency,
};
this.saving = true;
this.peopleApi.update(this.authService.u... | save | identifier_name |
settings-notifications.ts | import { cloneDeep } from 'lodash';
import { createPersonUpdate } from '../utils/people';
export default function(app) {
app.component('settingsNotifications', {
bindings: {
person: '<',
},
controller: class SettingsNotificationsCtrl {
public emailNotificationFrequency: 'immediately' | 'dail... | } | random_line_split | |
settings-notifications.ts | import { cloneDeep } from 'lodash';
import { createPersonUpdate } from '../utils/people';
export default function(app) {
app.component('settingsNotifications', {
bindings: {
person: '<',
},
controller: class SettingsNotificationsCtrl {
public emailNotificationFrequency: 'immediately' | 'dail... |
public save() {
const personUpdate = createPersonUpdate(this.authService.user);
personUpdate.account.settings = {
...personUpdate.account.setting,
emailNotificationFrequency: this.emailNotificationFrequency,
};
this.saving = true;
this.peopleApi.update... | {
$scope.$watch(
'$ctrl.authService.user.account.settings.emailNotificationFrequency',
frequency => this.emailNotificationFrequency = frequency,
);
} | identifier_body |
structsource0.rs | // On créé un type nommé `Borrowed` qui a pour attribut
// une référence d'un entier codé sur 32 bits. La référence
// doit survivre à l'instance de la structure `Borrowed`.
#[derive(Debug)]
struct Borrowed<'a>(&'a i32);
// Même combat, ces deux références doivent survivre à l'instance
// (ou aux instances) de la s... | Ref(&'a i32),
}
fn main() {
let x = 18;
let y = 15;
let single = Borrowed(&x);
let double = NamedBorrowed { x: &x, y: &y };
let reference = Either::Ref(&x);
let number = Either::Num(y);
println!("x is borrowed in {:?}", single);
println!("x and y are borrowed in {:?}", double);
... | 32),
| identifier_name |
structsource0.rs | // On créé un type nommé `Borrowed` qui a pour attribut
// une référence d'un entier codé sur 32 bits. La référence
// doit survivre à l'instance de la structure `Borrowed`.
#[derive(Debug)]
struct Borrowed<'a>(&'a i32);
// Même combat, ces deux références doivent survivre à l'instance
// (ou aux instances) de la s... | Ref(&'a i32),
}
fn main() {
let x = 18;
let y = 15;
let single = Borrowed(&x);
let double = NamedBorrowed { x: &x, y: &y };
let reference = Either::Ref(&x);
let number = Either::Num(y);
println!("x is borrowed in {:?}", single);
println!("x and y are borrowed in {:?}", double);... | Num(i32), | random_line_split |
lib.rs | pub use platform::*;
pub type Handle = *const std::os::raw::c_void;
pub type Error = Box<dyn std::error::Error>;
pub const CURRENT_PROCESS: Handle = 0 as Handle;
#[cfg(unix)]
mod platform {
use super::{Error, Handle, CURRENT_PROCESS};
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void... | if handle.is_null() {
Err(format!("{:?}", CStr::from_ptr(dlerror())).into())
} else {
Ok(handle)
}
}
pub unsafe fn free_library(handle: Handle) -> Result<(), Error> {
if dlclose(handle) == 0 {
Ok(())
} else {
Err(format!("{... | random_line_split | |
lib.rs | pub use platform::*;
pub type Handle = *const std::os::raw::c_void;
pub type Error = Box<dyn std::error::Error>;
pub const CURRENT_PROCESS: Handle = 0 as Handle;
#[cfg(unix)]
mod platform {
use super::{Error, Handle, CURRENT_PROCESS};
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void... |
}
pub unsafe fn free_library(handle: Handle) -> Result<(), Error> {
if FreeLibrary(handle) != 0 {
Ok(())
} else {
Err(format!("Could not free library (err={:08X})", GetLastError()).into())
}
}
pub unsafe fn find_symbol(handle: Handle, name: &str) -> Res... | {
Ok(handle)
} | conditional_block |
lib.rs | pub use platform::*;
pub type Handle = *const std::os::raw::c_void;
pub type Error = Box<dyn std::error::Error>;
pub const CURRENT_PROCESS: Handle = 0 as Handle;
#[cfg(unix)]
mod platform {
use super::{Error, Handle, CURRENT_PROCESS};
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void... |
pub unsafe fn find_symbol(handle: Handle, name: &str) -> Result<*const c_void, Error> {
let cname = CString::new(name).unwrap();
let ptr = GetProcAddress(handle, cname.as_ptr() as *const c_char);
if ptr.is_null() {
Err(format!("Could not find {} (err={:08X})", name, GetLastErro... | {
if FreeLibrary(handle) != 0 {
Ok(())
} else {
Err(format!("Could not free library (err={:08X})", GetLastError()).into())
}
} | identifier_body |
lib.rs | pub use platform::*;
pub type Handle = *const std::os::raw::c_void;
pub type Error = Box<dyn std::error::Error>;
pub const CURRENT_PROCESS: Handle = 0 as Handle;
#[cfg(unix)]
mod platform {
use super::{Error, Handle, CURRENT_PROCESS};
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void... | (handle: Handle) -> Result<(), Error> {
if FreeLibrary(handle) != 0 {
Ok(())
} else {
Err(format!("Could not free library (err={:08X})", GetLastError()).into())
}
}
pub unsafe fn find_symbol(handle: Handle, name: &str) -> Result<*const c_void, Error> {
le... | free_library | identifier_name |
add_ad_groups.py | #!/usr/bin/python
#
# Copyright 2014 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 b... |
if __name__ == '__main__':
# Initialize client object.
adwords_client = adwords.AdWordsClient.LoadFromStorage()
main(adwords_client, CAMPAIGN_ID)
| print ('Ad group with name \'%s\' and id \'%s\' was added.'
% (ad_group['name'], ad_group['id'])) | conditional_block |
add_ad_groups.py | #!/usr/bin/python
#
# Copyright 2014 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 b... | # limitations under the License.
"""This example adds ad groups to a given campaign.
To get ad groups, run get_ad_groups.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching... | random_line_split | |
add_ad_groups.py | #!/usr/bin/python
#
# Copyright 2014 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 b... | }, {
'operator': 'ADD',
'operand': {
'campaignId': campaign_id,
'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(),
'status': 'ENABLED',
'biddingStrategyConfiguration': {
'bids': [
{
'xsi_type': 'CpcBid',
... | ad_group_service = client.GetService('AdGroupService', version='v201406')
# Construct operations and add ad groups.
operations = [{
'operator': 'ADD',
'operand': {
'campaignId': campaign_id,
'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(),
'status': 'ENABLED',
... | identifier_body |
add_ad_groups.py | #!/usr/bin/python
#
# Copyright 2014 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 b... | (client, campaign_id):
# Initialize appropriate service.
ad_group_service = client.GetService('AdGroupService', version='v201406')
# Construct operations and add ad groups.
operations = [{
'operator': 'ADD',
'operand': {
'campaignId': campaign_id,
'name': 'Earth to Mars Cruises ... | main | identifier_name |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... | else {Inconsistent}
}
}
}
impl<T> Drop for Queue<T> {
fn drop(&mut self) {
unsafe {
let mut cur = *self.tail.get();
while !cur.is_null() {
let next = (*cur).next.load(Ordering::Relaxed);
let _: Box<Node<T>> = mem::transmute(cur);
... | {Empty} | conditional_block |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... | (&mut self) {
unsafe {
let mut cur = *self.tail.get();
while !cur.is_null() {
let next = (*cur).next.load(Ordering::Relaxed);
let _: Box<Node<T>> = mem::transmute(cur);
cur = next;
}
}
}
}
| drop | identifier_name |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... | * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or impli... | random_line_split | |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... |
/// Pushes a new value onto this queue.
pub fn push(&self, t: T) {
unsafe {
let n = Node::new(Some(t));
let prev = self.head.swap(n, Ordering::AcqRel);
(*prev).next.store(n, Ordering::Release);
}
}
/// Pops some data from this queue.
///
///... | {
let stub = unsafe { Node::new(None) };
Queue {
head: AtomicPtr::new(stub),
tail: UnsafeCell::new(stub),
}
} | identifier_body |
treeshaking_spec.ts | /**
* @license | *
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import '@angular/compiler';
import * as fs from 'fs';
import * as path from 'path';
const UTF8 = {
encoding: 'utf-8'
};
const PACKAGE = 'angular/packages/core/test/bundling/h... | * Copyright Google LLC All Rights Reserved. | random_line_split |
reopen.ts | import Ember from 'ember';
import { assertType } from './lib/assert';
type Person = typeof Person.prototype;
const Person = Ember.Object.extend({
name: '',
sayHello() {
alert(`Hello. My name is ${this.get('name')}`);
},
});
assertType<Person>(Person.reopen());
assertType<string>(Person.create().n... | assertType<number>(Reopened.c); | random_line_split | |
reopen.ts | import Ember from 'ember';
import { assertType } from './lib/assert';
type Person = typeof Person.prototype;
const Person = Ember.Object.extend({
name: '',
sayHello() {
alert(`Hello. My name is ${this.get('name')}`);
},
});
assertType<Person>(Person.reopen());
assertType<string>(Person.create().n... | () {
alert(`${this.get('goodbyeMessage')}, ${this.get('name')}`);
},
});
const person3 = Person3.create();
person3.get('name');
person3.get('goodbyeMessage');
person3.sayHello();
person3.sayGoodbye();
interface AutoResizeMixin {
resizable: true;
}
const AutoResizeMixin = Ember.Mixin.create({ resizable... | sayGoodbye | identifier_name |
reopen.ts | import Ember from 'ember';
import { assertType } from './lib/assert';
type Person = typeof Person.prototype;
const Person = Ember.Object.extend({
name: '',
sayHello() {
alert(`Hello. My name is ${this.get('name')}`);
},
});
assertType<Person>(Person.reopen());
assertType<string>(Person.create().n... | ,
});
const person3 = Person3.create();
person3.get('name');
person3.get('goodbyeMessage');
person3.sayHello();
person3.sayGoodbye();
interface AutoResizeMixin {
resizable: true;
}
const AutoResizeMixin = Ember.Mixin.create({ resizable: true });
const ResizableTextArea = Ember.TextArea.reopen(AutoResizeMixin, {
... | {
alert(`${this.get('goodbyeMessage')}, ${this.get('name')}`);
} | identifier_body |
hero-detail.component.js | System.register(['angular2/core', 'angular2/router', './hero.service'], function(exports_1) {
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;... | },
function (hero_service_1_1) {
hero_service_1 = hero_service_1_1;
}],
execute: function() {
HeroDetailComponent = (function () {
function HeroDetailComponent(_heroService, _routeParams) {
this._heroService = _h... | router_1 = router_1_1; | random_line_split |
hero-detail.component.js | System.register(['angular2/core', 'angular2/router', './hero.service'], function(exports_1) {
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;... |
HeroDetailComponent.prototype.ngOnInit = function () {
var _this = this;
var id = +this._routeParams.get('id');
this._heroService
.getHero(id)
.then(function (h) { return _this.hero = h; });
... | {
this._heroService = _heroService;
this._routeParams = _routeParams;
} | identifier_body |
hero-detail.component.js | System.register(['angular2/core', 'angular2/router', './hero.service'], function(exports_1) {
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;... | (_heroService, _routeParams) {
this._heroService = _heroService;
this._routeParams = _routeParams;
}
HeroDetailComponent.prototype.ngOnInit = function () {
var _this = this;
var id = +this._routeParams.get('i... | HeroDetailComponent | identifier_name |
pod_account.rs | .
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::*;
use state::Account;
use account_db::AccountDBMut;
use ethjson;
use types::account_diff::*;
use rlp::{self, RlpStream, Stream};
#[derive(Debug, Clone, PartialEq, Eq)]
... | balance: Diff::Born(x.balance),
nonce: Diff::Born(x.nonce),
code: Diff::Born(x.code.as_ref().expect("account is newly created; newly created accounts must be given code; all caches should remain in place; qed").clone()),
storage: x.storage.iter().map(|(k, v)| (k.clone(), Diff::Born(v.clone()))).collect(),
... | (None, Some(x)) => Some(AccountDiff { | random_line_split |
pod_account.rs | // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::*;
use state::Account;
use account_db::AccountDBMut;
use ethjson;
use types::account_diff::*;
use rlp::{self, RlpStream, Stream};
#[derive(Debug, Clone, PartialEq, Eq)]
///... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(bal={}; nonce={}; code={} bytes, #{}; storage={} items)",
self.balance,
self.nonce,
self.code.as_ref().map_or(0, |c| c.len()),
self.code.as_ref().map_or_else(H256::new, |c| c.sha3()),
self.storage.len(),
)
}
}
/// Determine difference bet... | fmt | identifier_name |
pod_account.rs | // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::*;
use state::Account;
use account_db::AccountDBMut;
use ethjson;
use types::account_diff::*;
use rlp::{self, RlpStream, Stream};
#[derive(Debug, Clone, PartialEq, Eq)]
///... |
/// Returns the RLP for this account.
pub fn rlp(&self) -> Bytes {
let mut stream = RlpStream::new_list(4);
stream.append(&self.nonce);
stream.append(&self.balance);
stream.append(&sec_trie_root(self.storage.iter().map(|(k, v)| (k.to_vec(), rlp::encode(&U256::from(&**v)).to_vec())).collect()));
stream.app... | {
PodAccount {
balance: *acc.balance(),
nonce: *acc.nonce(),
storage: acc.storage_changes().iter().fold(BTreeMap::new(), |mut m, (k, v)| {m.insert(k.clone(), v.clone()); m}),
code: acc.code().map(|x| x.to_vec()),
}
} | identifier_body |
PostsItemWrapper.tsx | import { Components, registerComponent } from '../../lib/vulcan-lib';
import { useSingle } from '../../lib/crud/withSingle';
import { Posts } from '../../lib/collections/posts';
import React from 'react';
import DragIcon from '@material-ui/icons/DragHandle';
import RemoveIcon from '@material-ui/icons/Close';
const sty... |
</PostsItem2MetaInfo>
<PostsItem2MetaInfo className={classes.meta}>
{document.baseScore} points
</PostsItem2MetaInfo>
<RemoveIcon className={classes.removeIcon} onClick={() => removeItem(document._id)} />
</div>
} else {
return <Components.Loading />
}
};
const PostsItemWra... | {
return <div className={classes.root}>
<DragIcon className={classes.dragHandle}/>
<span className={classes.title}>
<PostsTitle post={document} isLink={false}/>
</span>
<PostsItem2MetaInfo className={classes.meta}>
{document.user.displayName} | conditional_block |
PostsItemWrapper.tsx | import { Components, registerComponent } from '../../lib/vulcan-lib';
import { useSingle } from '../../lib/crud/withSingle';
import { Posts } from '../../lib/collections/posts';
import React from 'react';
import DragIcon from '@material-ui/icons/DragHandle';
import RemoveIcon from '@material-ui/icons/Close';
const sty... | fragmentName: 'PostsList',
});
if (document && !loading) {
return <div className={classes.root}>
<DragIcon className={classes.dragHandle}/>
<span className={classes.title}>
<PostsTitle post={document} isLink={false}/>
</span>
<PostsItem2MetaInfo className={classes.meta}>
... | random_line_split | |
svn_fetch.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | with pkg.stage:
with spack.config.override('config:verify_ssl', secure):
pkg.do_stage()
with working_dir(pkg.stage.source_path):
assert h() == t.revision
file_path = os.path.join(pkg.stage.source_path, t.file)
assert os.path.isdir(pkg.stage.source_pa... | """Tries to:
1. Fetch the repo using a fetch strategy constructed with
supplied args (they depend on type_of_test).
2. Check if the test_file is in the checked out repository.
3. Assert that the repository is at the revision supplied.
4. Add and remove some files, then reset the repo, and
... | identifier_body |
svn_fetch.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | (
type_of_test,
secure,
mock_svn_repository,
config,
mutable_mock_packages
):
"""Tries to:
1. Fetch the repo using a fetch strategy constructed with
supplied args (they depend on type_of_test).
2. Check if the test_file is in the checked out repository.
3.... | test_fetch | identifier_name |
svn_fetch.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | # License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
import os
import pytest
from llnl.util.filesystem import touch, working_dir
import spack.repo
... | # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public | random_line_split |
__init__.py | #!/usr/bin/env python
import re
import requests
import validators
import sys
import httplib2
import datetime
import socket
from urllib.parse import urlsplit, urljoin
from ipwhois import IPWhois
from pprint import pprint
from bs4 import BeautifulSoup, SoupStrainer
import pkg_resources
http_interface = httplib2.Http()
... |
def checkLinks(url):
try:
status, response = http_interface.request(url)
for link in BeautifulSoup(response, "html.parser", parse_only=SoupStrainer("a")):
if link.has_attr('href'):
addLink(urljoin(url,link['href']))
for link in BeautifulSoup(response, "html.pars... | links.append(url) | random_line_split |
__init__.py | #!/usr/bin/env python
import re
import requests
import validators
import sys
import httplib2
import datetime
import socket
from urllib.parse import urlsplit, urljoin
from ipwhois import IPWhois
from pprint import pprint
from bs4 import BeautifulSoup, SoupStrainer
import pkg_resources
http_interface = httplib2.Http()
... |
def checkHeaders(url):
secureURL = 0
# Determine target URL type
if url.lower().find("https:",0) == 0:
secureURL = 1
print()
print(timeStamp() + "* Checking headers")
try:
response, content = http_interface.request(url, method="GET")
if 'server' in response:
... | r = requests.get(url)
for cookie in r.cookies:
if url.lower().find("https:",0) == 0:
if cookie.secure == False:
print(timeStamp() + "!!! " + cookie.name + " set without 'Secure' flag")
if not cookie.has_nonstandard_attr('httponly') and not cookie.has_nonstandard_attr('Htt... | identifier_body |
__init__.py | #!/usr/bin/env python
import re
import requests
import validators
import sys
import httplib2
import datetime
import socket
from urllib.parse import urlsplit, urljoin
from ipwhois import IPWhois
from pprint import pprint
from bs4 import BeautifulSoup, SoupStrainer
import pkg_resources
http_interface = httplib2.Http()
... | (IP):
print()
print(timeStamp() + "* Performing WHOIS on " + IP)
obj = IPWhois(IP)
res = obj.lookup_whois()
print(timeStamp() + "- WHOIS name: " + res["nets"][0]['name'])
print(timeStamp() + "- WHOIS CIDR: " + res['asn_cidr'])
print(timeStamp() + "- More info at http://who.is/whois-ip/ip-add... | performWhoIs | identifier_name |
__init__.py | #!/usr/bin/env python
import re
import requests
import validators
import sys
import httplib2
import datetime
import socket
from urllib.parse import urlsplit, urljoin
from ipwhois import IPWhois
from pprint import pprint
from bs4 import BeautifulSoup, SoupStrainer
import pkg_resources
http_interface = httplib2.Http()
... |
if 'content-security-policy' not in response:
print(timeStamp() + "!!! Content-Security-Policy header missing")
if 'x-xss-protection' not in response:
print(timeStamp() + "!!! X-XSS-Protection header missing")
if 'set-cookie' in response:
checkCookies(url)... | print(timeStamp() + "!!! X-Frame-Options header missing") | conditional_block |
HeaderParser.js | var EventEmitter = require('events').EventEmitter,
inherits = require('util').inherits;
var StreamSearch = require('streamsearch');
var B_DCRLF = Buffer.from('\r\n\r\n'),
RE_CRLF = /\r\n/g,
RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/,
MAX_HEADER_PAIRS = 2000, // from node's http.js
MAX_HEADER_SIZE ... | self.nread += (end - start);
if (self.nread === MAX_HEADER_SIZE)
self.maxed = true;
self.buffer += data.toString('binary', start, end);
}
if (isMatch)
self._finish();
});
}
inherits(HeaderParser, EventEmitter);
HeaderParser.prototype.push = function(data) {
var r = this... | {
EventEmitter.call(this);
var self = this;
this.nread = 0;
this.maxed = false;
this.npairs = 0;
this.maxHeaderPairs = (cfg && typeof cfg.maxHeaderPairs === 'number'
? cfg.maxHeaderPairs
: MAX_HEADER_PAIRS);
this.buffer = '';
this.header = {};
this.fi... | identifier_body |
HeaderParser.js | var EventEmitter = require('events').EventEmitter,
inherits = require('util').inherits;
var StreamSearch = require('streamsearch');
var B_DCRLF = Buffer.from('\r\n\r\n'),
RE_CRLF = /\r\n/g,
RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/,
MAX_HEADER_PAIRS = 2000, // from node's http.js
MAX_HEADER_SIZE ... | (cfg) {
EventEmitter.call(this);
var self = this;
this.nread = 0;
this.maxed = false;
this.npairs = 0;
this.maxHeaderPairs = (cfg && typeof cfg.maxHeaderPairs === 'number'
? cfg.maxHeaderPairs
: MAX_HEADER_PAIRS);
this.buffer = '';
this.header = {};
t... | HeaderParser | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.