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 |
|---|---|---|---|---|
test_jail_code.py |
def assertResultOk(self, res):
"""Assert that `res` exited well (0), and had no stderr output."""
self.assertEqual(res.stderr, "")
self.assertEqual(res.status, 0)
class TestFeatures(JailCodeHelpers):
"""Test features of how `jail_code` runs Python."""
def test_hello_world(self):... | (self):
res = jailpy(code="""\
import urllib.request
print("Reading google")
u = urllib.request.urlopen("http://google.com")
google = u.read()
print(len(google))
""")
self.assertNotEqual(res.status, 0)
... | test_cant_use_network | identifier_name |
test_jail_code.py |
return result
def file_here(fname):
"""Return the full path to a file alongside this code."""
return os.path.join(os.path.dirname(__file__), fname)
class JailCodeHelpers(unittest.TestCase):
"""Assert helpers for jail_code tests."""
def setUp(self):
super(JailCodeHelpers, self).setUp()
... | result.stderr = result.stderr.decode() | conditional_block | |
test_jail_code.py |
def assertResultOk(self, res):
"""Assert that `res` exited well (0), and had no stderr output."""
self.assertEqual(res.stderr, "")
self.assertEqual(res.status, 0)
class TestFeatures(JailCodeHelpers):
"""Test features of how `jail_code` runs Python."""
def test_hello_world(self):... |
class TestLimits(JailCodeHelpers):
"""Tests of the resource limits, and changing them."""
def test_cant_use_too_much_memory(self):
# This will fail after setting the limit to 30Mb.
res = jailpy(code="print(len(bytearray(50000000)))", limits={'MEMORY': 30000000})
self.assertEqual(res.... | first = textwrap.dedent("""
with open("hello.txt", "w") as f:
f.write("Hello, second")
""")
second = textwrap.dedent("""
with open("hello.txt") as f:
print(f.read())
""")
limits = {"TIME": 1, "MEMORY": 128*1024*1024,
... | identifier_body |
checkUp.service.ts | import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { CheckUp } from '../models/checkUp';
@Injectable()
export class CheckUpService {
private prodU... |
private handleError (error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ... | {
let body = res.json();
return body || {};
} | identifier_body |
checkUp.service.ts | import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { CheckUp } from '../models/checkUp';
@Injectable()
export class CheckUpService {
private prodU... | else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
} | {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} | conditional_block |
checkUp.service.ts | import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { CheckUp } from '../models/checkUp';
@Injectable()
export class CheckUpService {
private prodU... | deleteCheckUp(id: string): Observable<void> {
const url = `${this.checkUpsUrl}/${id}`;
return this.http.delete(url, {headers: this.headers})
.map(this.extractData)
.catch(this.handleError);
};
private extractData(res: Response){
let body = res.json();
return body || {};
}
private handleError (... | random_line_split | |
checkUp.service.ts | import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { CheckUp } from '../models/checkUp';
@Injectable()
export class CheckUpService {
private prodU... | (id: string): Observable<CheckUp> {
return this.getCheckUps()
.map(checkUps => checkUps.find(checkUp => checkUp._id === id));
};
createCheckUp(checkUp: CheckUp): Observable<CheckUp> {
const url = `${this.checkUpsUrl}`;
return this.http
.post(url, JSON.stringify(checkUp), {headers: this.headers})
... | getCheckUp | identifier_name |
test_resource_class.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | self.rcm._update = mock.Mock(return_value=['fake_resource_class'])
self.assertEqual(
self.rcm.update(42, dummy='dummy resource class data'),
['fake_resource_class'])
self.rcm._update.assert_called_with(
'/v1/resource_classes/42',
{'dummy': 'dummy... |
def test_update(self): | random_line_split |
test_resource_class.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... |
def test_get(self):
self.rcm._get = mock.Mock(return_value='fake_resource_class')
self.assertEqual(self.rcm.get(42), 'fake_resource_class')
self.rcm._get.assert_called_with('/v1/resource_classes/42')
def test_list(self):
self.rcm._list = mock.Mock(return_value=['fake_resource... | super(ResourceClassManagerTest, self).setUp()
self.api = mock.Mock()
self.rcm = resource_classes.ResourceClassManager(self.api) | identifier_body |
test_resource_class.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | (self):
self.rcm._create = mock.Mock(return_value=['fake_resource_class'])
self.assertEqual(
self.rcm.create(dummy='dummy resource class data'),
['fake_resource_class'])
self.rcm._create.assert_called_with(
'/v1/resource_classes',
{'dummy': 'dumm... | test_create | identifier_name |
half_normal.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | allow_nan_stats=allow_nan_stats,
parameters=parameters,
graph_parents=[self._scale],
name=name)
@staticmethod
def _param_shapes(sample_shape):
return {"scale": ops.convert_to_tensor(sample_shape, dtype=dtypes.int32)}
@property
def scale(self):
"""Distribution parameter ... | dtype=self._scale.dtype,
reparameterization_type=distribution.FULLY_REPARAMETERIZED,
validate_args=validate_args, | random_line_split |
half_normal.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | (self):
return self.scale.shape
def _event_shape_tensor(self):
return constant_op.constant([], dtype=dtypes.int32)
def _event_shape(self):
return tensor_shape.scalar()
def _sample_n(self, n, seed=None):
shape = array_ops.concat([[n], self.batch_shape_tensor()], 0)
sampled = random_ops.rando... | _batch_shape | identifier_name |
half_normal.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
@property
def scale(self):
"""Distribution parameter for the scale."""
return self._scale
def _batch_shape_tensor(self):
return array_ops.shape(self.scale)
def _batch_shape(self):
return self.scale.shape
def _event_shape_tensor(self):
return constant_op.constant([], dtype=dtypes.int32... | return {"scale": ops.convert_to_tensor(sample_shape, dtype=dtypes.int32)} | identifier_body |
App.tsx | import React, { useState } from "react";
import { Localized } from "@fluent/react";
import { FluentDateTime } from "@fluent/bundle";
import { Hello } from "./Hello";
import { SignIn } from "./SignIn";
export function App() {
let [date] = useState(() => new Date());
return <>
<Hello />
<Localiz... |
<SignIn />
</>;
} | {"It's {$date}."}
</p>
</Localized> | random_line_split |
9F3DE783494F7FF30679A17B0C5B912834121095.js | this.NesDb = this.NesDb || {};
NesDb[ '9F3DE783494F7FF30679A17B0C5B912834121095' ] = {
"$": {
"name": "Nekketsu Kouha Kunio-kun",
"altname": "熱血硬派くにおくん",
"class": "Licensed",
"catalog": "TJC-KN",
"publisher": "Technos",
"developer": "Technos",
"region": "Japan", | "cartridge": [
{
"$": {
"system": "Famicom",
"crc": "A7D3635E",
"sha1": "9F3DE783494F7FF30679A17B0C5B912834121095",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2007-06-24"
},
"board": [
{
"$": {
"type": "HVC-UNROM",
"pcb": "HVC-UNROM-02",
"mapper": "2... | "players": "2",
"date": "1987-04-17"
}, | random_line_split |
InstrumentClone.js | // InstrumentClone.js
//
// Copyright 2018 High Fidelity, Inc.
// Created by Robin Wilson 7/5/2018
// Expands on guitarMexico.js created by Rebecca Stankus 01/31/18
//
// Entity script that plays the sound while holding the entity.
// Chooses the sound bite randomly from a list passed in.
// Takes two parameters :
//... | this.entityID = entityID;
var entityProperties = Entities.getEntityProperties(this.entityID, ["position", "name", "age"]);
this.currentPosition = entityProperties.position;
this.handNum = 0;
Script.setTimeout(function(){
if (entityProperties.name && entityProperties... | InstrumentClone.prototype = {
// ENTITY METHODS
preload: function (entityID) { | random_line_split |
InstrumentClone.js | // InstrumentClone.js
//
// Copyright 2018 High Fidelity, Inc.
// Created by Robin Wilson 7/5/2018
// Expands on guitarMexico.js created by Rebecca Stankus 01/31/18
//
// Entity script that plays the sound while holding the entity.
// Chooses the sound bite randomly from a list passed in.
// Takes two parameters :
//... |
if (this.updatePositionInterval) {
Script.clearInterval(this.updatePositionInterval);
this.updatePositionInterval = null;
}
}
// END SOUND UTILITIES
};
module.exports = {
instrumentClone: InstrumentClone
};
| {
this.injector.stop();
this.injector = null;
} | conditional_block |
printer.rs | use std::collections::HashMap;
/// Module allowing to display an AST of 'MalValue'.
use std::fmt;
use super::types::MalType::*;
use super::types::{new_str, MalHashContainer, MalValue};
lazy_static! {
static ref STR_ESCAPED_CHARS_MAP: HashMap<char, &'static str> = {
let mut m = HashMap::new();
m.in... |
fn pr_hash(
hash: &MalHashContainer,
print_readably: bool,
start: &str,
end: &str,
sep: &str,
) -> String {
let list: Vec<MalValue> = hash
.iter()
.flat_map(|(k, v)| vec![new_str(k.clone()), v.clone()])
.collect();
pr_seq(&list, print_readably, start, end, sep)
}
| {
let mut string = String::new();
string.push_str(start);
let mut first = true;
for value in seq {
if first {
first = false;
} else {
string.push_str(sep);
}
string.push_str(&value.pr_str(print_readably)[..])
}
string.push_str(end);
s... | identifier_body |
printer.rs | use std::collections::HashMap;
/// Module allowing to display an AST of 'MalValue'.
use std::fmt;
use super::types::MalType::*;
use super::types::{new_str, MalHashContainer, MalValue};
lazy_static! {
static ref STR_ESCAPED_CHARS_MAP: HashMap<char, &'static str> = {
let mut m = HashMap::new();
m.in... | }
string.push_str(&value.pr_str(print_readably)[..])
}
string.push_str(end);
string
}
fn pr_hash(
hash: &MalHashContainer,
print_readably: bool,
start: &str,
end: &str,
sep: &str,
) -> String {
let list: Vec<MalValue> = hash
.iter()
.flat_map(|(k, v)... | string.push_str(sep); | random_line_split |
printer.rs | use std::collections::HashMap;
/// Module allowing to display an AST of 'MalValue'.
use std::fmt;
use super::types::MalType::*;
use super::types::{new_str, MalHashContainer, MalValue};
lazy_static! {
static ref STR_ESCAPED_CHARS_MAP: HashMap<char, &'static str> = {
let mut m = HashMap::new();
m.in... | else {
string.push_str(sep);
}
string.push_str(&value.pr_str(print_readably)[..])
}
string.push_str(end);
string
}
fn pr_hash(
hash: &MalHashContainer,
print_readably: bool,
start: &str,
end: &str,
sep: &str,
) -> String {
let list: Vec<MalValue> = hash... | {
first = false;
} | conditional_block |
printer.rs | use std::collections::HashMap;
/// Module allowing to display an AST of 'MalValue'.
use std::fmt;
use super::types::MalType::*;
use super::types::{new_str, MalHashContainer, MalValue};
lazy_static! {
static ref STR_ESCAPED_CHARS_MAP: HashMap<char, &'static str> = {
let mut m = HashMap::new();
m.in... | (&self, print_readably: bool) -> String {
match *self {
Nil => "nil".to_string(),
True => "true".to_string(),
False => "false".to_string(),
Integer(integer) => integer.to_string(),
Str(ref string) => {
if print_readably {
... | pr_str | identifier_name |
file.js | 'use strict';
/**
* Manipulates files access
* @class {File}
*/
class File {
constructor(path) {
this.fullPath = path;
var splittedPath = path.split('/');
this.file = splittedPath.pop();
this.directory = splittedPath.join('/');
this.fs = require('fs-extra');
this.fs.ens... |
/**
* Removes the loaded file
* @return {void}
*/
remove() {
this.fs.removeSync(this.fullPath);
}
/**
* Renames the loaded file
* @param {string} newPath - path to place the new file
* @return {File}
*/
moveTo(newPath) {
this.fs.outputFileSync(ne... | {
return this.fs.readFileSync(this.fullPath, 'utf8');
} | identifier_body |
file.js | 'use strict';
/**
* Manipulates files access
* @class {File}
*/
class | {
constructor(path) {
this.fullPath = path;
var splittedPath = path.split('/');
this.file = splittedPath.pop();
this.directory = splittedPath.join('/');
this.fs = require('fs-extra');
this.fs.ensureFileSync(this.fullPath);
}
/**
* Get the full file path
... | File | identifier_name |
file.js | 'use strict';
/**
* Manipulates files access
* @class {File}
*/
class File {
constructor(path) {
this.fullPath = path;
var splittedPath = path.split('/');
this.file = splittedPath.pop();
this.directory = splittedPath.join('/');
this.fs = require('fs-extra');
this.fs.ens... | this.fs.outputFileSync(newPath, this.read());
this.remove();
return new File(newPath);
}
}
module.exports = File; | */
moveTo(newPath) { | random_line_split |
watch.js | 'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
function isOnlyChange(event) |
gulp.task('watch', ['inject'], function () {
gulp.watch([path.join(conf.paths.src, '/*.html'), 'bower.json'], ['inject']);
gulp.watch([
path.join(conf.paths.src, '/assets/styles/css/**/*.css'),
path.join(conf.paths.src, '/assets/styles/less/**/*.less')
], function(event) {
if(isOnlyChange(event)) ... | {
return event.type === 'changed';
} | identifier_body |
watch.js | 'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
function isOnlyChange(event) {
return event.type === 'changed';
}
gulp.task('watch', ['inject'], function () {
gulp.watch([path.join(conf.paths.src, '/*.html'), 'bower.... | else {
gulp.start('inject');
}
});
gulp.watch(path.join(conf.paths.src, '/app/**/*.js'), function(event) {
if(isOnlyChange(event)) {
gulp.start('scripts');
} else {
gulp.start('inject');
}
});
gulp.watch(path.join(conf.paths.src, '/app/**/*.html'), function(event) {
brow... | {
gulp.start('styles');
} | conditional_block |
watch.js | 'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
function | (event) {
return event.type === 'changed';
}
gulp.task('watch', ['inject'], function () {
gulp.watch([path.join(conf.paths.src, '/*.html'), 'bower.json'], ['inject']);
gulp.watch([
path.join(conf.paths.src, '/assets/styles/css/**/*.css'),
path.join(conf.paths.src, '/assets/styles/less/**/*.less')
], ... | isOnlyChange | identifier_name |
watch.js | 'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
function isOnlyChange(event) {
return event.type === 'changed';
}
gulp.task('watch', ['inject'], function () {
gulp.watch([path.join(conf.paths.src, '/*.html'), 'bower.... | });
}); | gulp.watch(path.join(conf.paths.src, '/app/**/*.html'), function(event) {
browserSync.reload(event.path); | random_line_split |
ObservableRenderer.tsx | import * as React from "react";
import { Observable } from "rxjs";
interface Props<T> {
observable: Observable<T>;
initialData?: T;
children: (snapshot: AsyncSnapshot<T>) => React.ReactElement;
}
function StreamRenderer<T>({
observable,
initialData,
children
}: Props<T>): React.ReactElement {
const [sna... | <T> {
constructor(
public connectionState: ConnectionState,
private _data?: T,
public error?: Error
) {}
get data() {
if (this._data === undefined) {
throw "";
}
return this._data;
}
get hasData(): boolean {
return this._data !== undefined;
}
get hasError(): boolean {... | AsyncSnapshot | identifier_name |
ObservableRenderer.tsx | import * as React from "react";
import { Observable } from "rxjs";
interface Props<T> {
observable: Observable<T>;
initialData?: T;
children: (snapshot: AsyncSnapshot<T>) => React.ReactElement;
}
function StreamRenderer<T>({
observable,
initialData,
children
}: Props<T>): React.ReactElement {
const [sna... |
return this._data;
}
get hasData(): boolean {
return this._data !== undefined;
}
get hasError(): boolean {
return this.error !== undefined;
}
}
enum ConnectionState {
none = "NONE",
waiting = "WAITING",
active = "ACTIVE",
done = "DONE"
}
export default StreamRenderer;
| {
throw "";
} | conditional_block |
ObservableRenderer.tsx | import * as React from "react";
import { Observable } from "rxjs";
interface Props<T> {
observable: Observable<T>;
initialData?: T;
children: (snapshot: AsyncSnapshot<T>) => React.ReactElement;
}
function StreamRenderer<T>({
observable,
initialData,
children
}: Props<T>): React.ReactElement | }, [observable]);
return children(snapshot);
}
class AsyncSnapshot<T> {
constructor(
public connectionState: ConnectionState,
private _data?: T,
public error?: Error
) {}
get data() {
if (this._data === undefined) {
throw "";
}
return this._data;
}
get hasData(): boolea... | {
const [snapshot, setSnapshot] = React.useState(
new AsyncSnapshot(ConnectionState.waiting, initialData, undefined)
);
React.useEffect(() => {
const subscription = observable.subscribe(
data =>
setSnapshot(new AsyncSnapshot(ConnectionState.active, data, undefined)),
error =>
... | identifier_body |
ObservableRenderer.tsx | import * as React from "react";
import { Observable } from "rxjs";
interface Props<T> {
observable: Observable<T>;
initialData?: T;
children: (snapshot: AsyncSnapshot<T>) => React.ReactElement;
}
function StreamRenderer<T>({
observable,
initialData,
children
}: Props<T>): React.ReactElement {
const [sna... | export default StreamRenderer; | random_line_split | |
col_to_cluster.py | # -*- coding: utf8
from __future__ import division, print_function
from collections import defaultdict
from matplotlib import pyplot as plt
from radar import radar_factory
from scipy import stats
from scripts import initialize_matplotlib
import numpy as np
import plac
import sys
REFERRER_ABBRV = {
'EXTERNAL':... | (features_fpath, classes):
col_dict = {
'EXTERNAL':13,
'FEATURED':14,
'INTERNAL':15,
'MOBILE':16,
'SEARCH':17,
'SOCIAL':18,
'VIRAL':19
}
to_plot = defaultdict(lambda: defaultdict(float))
sum_classes = defaultdict(float)
labels = set()
... | load_svm_file | identifier_name |
col_to_cluster.py | # -*- coding: utf8
from __future__ import division, print_function
from collections import defaultdict
from matplotlib import pyplot as plt
from radar import radar_factory
from scipy import stats
from scripts import initialize_matplotlib
import numpy as np
import plac
import sys
REFERRER_ABBRV = {
'EXTERNAL':... | '#FF7300', 'k'] * 3
colored={}
if ref:
to_use = set(REFERRER_ABBRV.values())
else:
to_use = set(CATEG_ABBRV.values())
for i, l in enumerate(to_use):
colored[l] = colors[i]
for x, y, l in zip(x_locations, bar_data, bar_labels):
c = colored[l]
... | x_locations = [1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19]
data_class = {}
data_label = {}
for data, _, class_num in data_plots:
best_idx = np.argsort(data)[::-1][:4]
best_cls = np.array(data)[best_idx]
best_lbl = np.array(labels)[best_idx]
data_class[... | identifier_body |
col_to_cluster.py | # -*- coding: utf8
from __future__ import division, print_function
from collections import defaultdict
from matplotlib import pyplot as plt
from radar import radar_factory
from scipy import stats
from scripts import initialize_matplotlib
import numpy as np
import plac
import sys
REFERRER_ABBRV = {
'EXTERNAL':... |
colors = ['b', 'g', 'm', 'r', 'y', 'c', '#A617A1', '#2B5700', 'w',
'#FF7300', 'k'] * 3
colored={}
if ref:
to_use = set(REFERRER_ABBRV.values())
else:
to_use = set(CATEG_ABBRV.values())
for i, l in enumerate(to_use):
colored[l] = colors[i]
for x, y,... | bar_data.extend(data_class[cls])
bar_labels.extend(data_label[cls]) | conditional_block |
col_to_cluster.py | # -*- coding: utf8
from __future__ import division, print_function
from collections import defaultdict
from matplotlib import pyplot as plt
from radar import radar_factory
from scipy import stats
from scripts import initialize_matplotlib
import numpy as np
import plac
import sys
REFERRER_ABBRV = {
'EXTERNAL':... |
theta = radar_factory(len(labels))
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='radar')
for data_plot, color, class_num in data_plots:
ax.plot(theta, data_plot, color=color, label='C%d'%class_num)
ax.fill(theta, data_plot, facecolor=color, alpha=0.25)
ax.s... | data_plot.append(to_plot[class_num][label] / sum_classes[class_num])
yield data_plot, color, class_num
def radar_plot(labels, data_plots, out_fpath): | random_line_split |
dependency_queue.rs | //! A graph-like structure used to represent a set of dependencies and in what
//! order they should be built.
//!
//! This structure is used to store the dependency graph and dynamically update
//! it to figure out when a dependency should be built.
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::... | (&self) -> usize {
self.dep_map.len() + self.pending.len()
}
/// Indicate that a package has been built.
///
/// This function will update the dependency queue with this information,
/// possibly allowing the next invocation of `dequeue` to return a package.
pub fn finish(&mut self, key... | len | identifier_name |
dependency_queue.rs | //! A graph-like structure used to represent a set of dependencies and in what
//! order they should be built.
//!
//! This structure is used to store the dependency graph and dynamically update
//! it to figure out when a dependency should be built.
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::... | match *self { Fresh => other, Dirty => Dirty }
}
}
impl<K: Dependency, V> DependencyQueue<K, V> {
/// Creates a new dependency queue with 0 packages.
pub fn new() -> DependencyQueue<K, V> {
DependencyQueue {
dep_map: HashMap::new(),
reverse_dep_map: HashMap::new(),
... |
impl Freshness {
pub fn combine(&self, other: Freshness) -> Freshness { | random_line_split |
mod.rs | enum method_origin {
// supertrait method invoked on "self" inside a default method
// first field is supertrait ID;
// second field is method index (relative to the *supertrait*
// method list)
method_super(ast::def_id, uint),
// fully statically resolved method
method_static(ast::def_id)... | sig: ty::FnSig {
bound_lifetime_names: opt_vec::Empty,
inputs: ~[], | random_line_split | |
mod.rs | and the infer module solves them.
*/
use driver::session;
use middle::resolve;
use middle::ty;
use util::common::time;
use util::ppaux::Repr;
use util::ppaux;
use std::hashmap::HashMap;
use std::result;
use extra::list::List;
use extra::list;
use syntax::codemap::span;
use syntax::print::pprust::*;
use syntax::{a... |
}
pub type vtable_map = @mut HashMap<ast::node_id, vtable_res>;
pub struct CrateCtxt {
// A mapping from method call sites to traits that have that method.
trait_map: resolve::TraitMap,
method_map: method_map,
vtable_map: vtable_map,
coherence_info: coherence::CoherenceInfo,
tcx: ty::ctxt
}
... | {
match *self {
vtable_static(def_id, ref tys, ref vtable_res) => {
fmt!("vtable_static(%?:%s, %s, %s)",
def_id,
ty::item_path_str(tcx, def_id),
tys.repr(tcx),
vtable_res.repr(tcx))
}
... | identifier_body |
mod.rs | vtable_static(ast::def_id, ~[ty::t], vtable_res),
/*
Dynamic vtable, comes from a parameter that has a bound on it:
fn foo<T:quux,baz,bar>(a: T) -- a's vtable would have a
vtable_param origin
The first uint is the param number (identifying T in the example),
and the second is the... | check_for_entry_fn | identifier_name | |
unquote.rs | /* Copyright (C) 2015-2016 Yutaka Kamei */
use std::string::FromUtf8Error;
const OFFSET : usize = 6;
const DIGIT : &'static [u8] = b"0123456789ABCDEFabcdef";
/// Replaces %xx escapes by their single-character equivalent.
///
/// # Examples
///
/// ```
/// use urlparse::unquote;
///
/// let s = unquote("ABC%3D123%21%... |
fn to_digit(n1: u8, n2: u8) -> Option<u8> {
let mut byte : u8 = 0;
match DIGIT.binary_search(&n1) {
Ok(_n1) => byte += if _n1 < 16 {_n1 as u8 * 16} else {(_n1 - OFFSET) as u8 * 16},
Err(_) => return None,
}
match DIGIT.binary_search(&n2) {
Ok(_n2) => byte += if _n2 < 16 {_n2 ... | {
let _s = s.as_ref().replace("+", " ");
return unquote(_s);
} | identifier_body |
unquote.rs | /* Copyright (C) 2015-2016 Yutaka Kamei */ |
const OFFSET : usize = 6;
const DIGIT : &'static [u8] = b"0123456789ABCDEFabcdef";
/// Replaces %xx escapes by their single-character equivalent.
///
/// # Examples
///
/// ```
/// use urlparse::unquote;
///
/// let s = unquote("ABC%3D123%21%20DEF%3D%23%23");
/// assert_eq!(s.ok().unwrap(), "ABC=123! DEF=##");
/// ``... |
use std::string::FromUtf8Error; | random_line_split |
unquote.rs | /* Copyright (C) 2015-2016 Yutaka Kamei */
use std::string::FromUtf8Error;
const OFFSET : usize = 6;
const DIGIT : &'static [u8] = b"0123456789ABCDEFabcdef";
/// Replaces %xx escapes by their single-character equivalent.
///
/// # Examples
///
/// ```
/// use urlparse::unquote;
///
/// let s = unquote("ABC%3D123%21%... | ,
Err(_) => return None,
}
return Some(byte);
}
#[test]
fn test_to_digit() {
assert_eq!(to_digit(b'1', b'2'), Some(0x12));
assert_eq!(to_digit(b'e', b'a'), Some(0xEA));
assert_eq!(to_digit(b'E', b'A'), Some(0xEA));
assert_eq!(to_digit(b'F', b'F'), Some(0xFF));
assert_eq!(to_digit(... | {(_n2 - OFFSET) as u8} | conditional_block |
unquote.rs | /* Copyright (C) 2015-2016 Yutaka Kamei */
use std::string::FromUtf8Error;
const OFFSET : usize = 6;
const DIGIT : &'static [u8] = b"0123456789ABCDEFabcdef";
/// Replaces %xx escapes by their single-character equivalent.
///
/// # Examples
///
/// ```
/// use urlparse::unquote;
///
/// let s = unquote("ABC%3D123%21%... | <S: AsRef<str>>(s: S) -> Result<String, FromUtf8Error> {
let _s = s.as_ref().replace("+", " ");
return unquote(_s);
}
fn to_digit(n1: u8, n2: u8) -> Option<u8> {
let mut byte : u8 = 0;
match DIGIT.binary_search(&n1) {
Ok(_n1) => byte += if _n1 < 16 {_n1 as u8 * 16} else {(_n1 - OFFSET) as u8 *... | unquote_plus | identifier_name |
fileRotate.js | persisting log messages and metadata to one or more files.
//
var FileRotate = exports.FileRotate = function (options) {
Transport.call(this, options);
//
// Helper function which throws an `Error` in the event
// that any of the rest of the arguments is present in `options`.
//
function throwIf (targe... |
if (stats) {
console.log('mtime > ' + stats.mtime);
console.log('type of > ' + typeof stats.mtime);
self._month = stats.mtime.getMonth();
self._date = stats.mtime.getDate();
}
console.log(self._month);
console.log(self._date);
var now = new Date();
... | {
if (err.code !== 'ENOENT') {
return self.emit('error', err);
}
return createAndFlush(0);
} | conditional_block |
fileRotate.js | for persisting log messages and metadata to one or more files.
//
var FileRotate = exports.FileRotate = function (options) {
Transport.call(this, options);
//
// Helper function which throws an `Error` in the event
// that any of the rest of the arguments is present in `options`.
//
function | (target /*, illegal... */) {
Array.prototype.slice.call(arguments, 1).forEach(function (name) {
if (options[name]) {
throw new Error('Cannot set ' + name + ' and ' + target + 'together');
}
});
}
if (options.filename || options.dirname) {
throwIf('filename or dirname', 'stream');
... | throwIf | identifier_name |
fileRotate.js | persisting log messages and metadata to one or more files.
//
var FileRotate = exports.FileRotate = function (options) {
Transport.call(this, options);
//
// Helper function which throws an `Error` in the event
// that any of the rest of the arguments is present in `options`.
//
function throwIf (targe... |
if (options.filename || options.dirname) {
throwIf('filename or dirname', 'stream');
this._basename = this.filename = path.basename(options.filename) || 'winston.log';
this.dirname = options.dirname || path.dirname(options.filename);
this.options = options.options || { flags: 'a' };
}
el... | {
Array.prototype.slice.call(arguments, 1).forEach(function (name) {
if (options[name]) {
throw new Error('Cannot set ' + name + ' and ' + target + 'together');
}
});
} | identifier_body |
fileRotate.js | for persisting log messages and metadata to one or more files.
//
var FileRotate = exports.FileRotate = function (options) {
Transport.call(this, options);
//
// Helper function which throws an `Error` in the event
// that any of the rest of the arguments is present in `options`.
//
function throwIf (t... | (self._date < now.getDate() && self._month <= now.getMonth()) ) {
console.log('no stats, max size, new date');
//
// If `stats.size` is greater than the `maxsize` for
// this instance then try again
//
return checkFile(self._getFile(true));
}
create... |
var now = new Date();
if (!stats || (self.maxsize && stats.size >= self.maxsize) || | random_line_split |
product.py | ##############################################################################
#
# Copyright (C) 2014 Comunitea Servicios Tecnológicos All Rights Reserved
# $Kiko Sánchez <kiko@comunitea.com>$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gen... | outlet_ok = fields.Boolean('Outlet')
order_line_id = fields.Many2one('sale.order.line', 'Order Line')
qty = fields.Float('Quantity')
percent = fields.Float('Outlet Percent') | random_line_split | |
product.py | ##############################################################################
#
# Copyright (C) 2014 Comunitea Servicios Tecnológicos All Rights Reserved
# $Kiko Sánchez <kiko@comunitea.com>$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gen... | ame = 'outlet.loss'
@api.multi
@api.depends('qty', 'price_outlet', 'price_unit')
def _get_outlet_loss(self):
for loss in self:
loss.total_lost = loss.qty*(loss.price_outlet-loss.price_unit)
product_id = fields.Many2one('product.product', 'Product')
price_unit = fields.Float('Pr... | identifier_body | |
product.py | ##############################################################################
#
# Copyright (C) 2014 Comunitea Servicios Tecnológicos All Rights Reserved
# $Kiko Sánchez <kiko@comunitea.com>$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gen... | product_id = fields.Many2one('product.product', 'Product')
price_unit = fields.Float('Price')
price_outlet = fields.Float('Outlet Price')
total_lost = fields.Float("Outlet Loss", compute=_get_outlet_loss,
store=True, readonly=True)
date_move = fields.Date('Move to outle... | ss.total_lost = loss.qty*(loss.price_outlet-loss.price_unit)
| conditional_block |
product.py | ##############################################################################
#
# Copyright (C) 2014 Comunitea Servicios Tecnológicos All Rights Reserved
# $Kiko Sánchez <kiko@comunitea.com>$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gen... | odels.Model):
_name = 'outlet.loss'
@api.multi
@api.depends('qty', 'price_outlet', 'price_unit')
def _get_outlet_loss(self):
for loss in self:
loss.total_lost = loss.qty*(loss.price_outlet-loss.price_unit)
product_id = fields.Many2one('product.product', 'Product')
price_un... | tletLoss(m | identifier_name |
test_healthcheck.py | """
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from unittest.mock import patch
import pytest
# Test against an admin app because that doesn't require setup of brand | expected_media_type = 'application/health+json'
response = client.get('/health')
assert response.status_code == 200
assert response.content_type == expected_media_type
assert response.mimetype == expected_media_type
assert response.get_json() == {
'status': 'ok',
'details': {
... | # party. After all, both admin and party apps should react the same.
def test_healthcheck_ok(client): | random_line_split |
test_healthcheck.py | """
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from unittest.mock import patch
import pytest
# Test against an admin app because that doesn't require setup of brand
# party. After all, both admin and party apps should react the same.
def test_healthcheck_... | (is_rdbms_ok_mock, client):
expected_media_type = 'application/health+json'
is_rdbms_ok_mock.return_value = False
response = client.get('/health')
assert response.status_code == 503
assert response.content_type == expected_media_type
assert response.mimetype == expected_media_type
assert ... | test_healthcheck_fail | identifier_name |
test_healthcheck.py | """
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from unittest.mock import patch
import pytest
# Test against an admin app because that doesn't require setup of brand
# party. After all, both admin and party apps should react the same.
def test_healthcheck_... | return make_client(admin_app) | identifier_body | |
dataset.py |
from collections import OrderedDict
class DataSet(object):
__slots__ = (
'events', # List of all events in this data set
'group', # Iterable containing groups of events
)
def __init__(self, query, group_function):
self.events = query.all()
if group_function is None:
... |
else:
p.pretty({
'events': self.events,
'group': self.group.keys(),
})
p.text('>')
| p.text('...') | conditional_block |
dataset.py |
from collections import OrderedDict
class DataSet(object):
__slots__ = (
'events', # List of all events in this data set
'group', # Iterable containing groups of events
)
def | (self, query, group_function):
self.events = query.all()
if group_function is None:
self.group = self.events
elif callable(group_function):
self.group = OrderedDict()
for event in self.events:
# Add this event to the group-by entries
... | __init__ | identifier_name |
dataset.py |
from collections import OrderedDict
class DataSet(object):
__slots__ = (
'events', # List of all events in this data set
'group', # Iterable containing groups of events
)
def __init__(self, query, group_function):
self.events = query.all()
if group_function is None:
... | p.text('<{0}: '.format(type(self).__name__))
if cycle:
p.text('...')
else:
p.pretty({
'events': self.events,
'group': self.group.keys(),
})
p.text('>') | identifier_body | |
dataset.py | from collections import OrderedDict
class DataSet(object):
__slots__ = (
'events', # List of all events in this data set | self.events = query.all()
if group_function is None:
self.group = self.events
elif callable(group_function):
self.group = OrderedDict()
for event in self.events:
# Add this event to the group-by entries
key = group_function(even... | 'group', # Iterable containing groups of events
)
def __init__(self, query, group_function): | random_line_split |
buying_controller.py | (self):
super(BuyingController, self).validate()
if getattr(self, "supplier", None) and not self.supplier_name:
self.supplier_name = frappe.db.get_value("Supplier", self.supplier, "supplier_name")
self.validate_items()
self.set_qty_as_per_stock_uom()
self.validate_stock_or_nonstock_items()
self.validate... | validate | identifier_name | |
buying_controller.py | _code))
def validate_negative_quantity(self, item_row, field_list):
if self.is_return:
return
item_row = item_row.as_dict()
for fieldname in field_list:
if flt(item_row[fieldname]) < 0:
frappe.throw(_("Row #{0}: {1} can not be negative for item {2}".format(item_row['idx'],
frappe.get_meta(item_r... | for d in self.get("items"):
if d.is_fixed_asset and d.asset:
asset = frappe.get_doc("Asset", d.asset)
if delete_asset and asset.docstatus == 0:
frappe.delete_doc("Asset", asset.name)
d.db_set('asset', None)
continue
if self.docstatus in [0, 1] and not asset.get(field):
asset.set(fie... | identifier_body | |
buying_controller.py | _tax_amount = flt(item_proportion * total_valuation_amount,
self.precision("item_tax_amount", item))
valuation_amount_adjustment -= item.item_tax_amount
self.round_floats_in(item)
if flt(item.conversion_factor)==0.0:
item.conversion_factor = get_conversion_factor(item.item_code, item.uom).get("... |
else:
for item in self.get("items"):
if item.bom:
item.bom = None
def create_raw_materials_supplied(self, raw_material_table):
if self.is_subcontracted=="Yes":
parent_items = []
backflush_raw_materials_based_on = frappe.db.get_single_value("Buying Settings",
"backflush_raw_materials_of_sub... | for supplied_item in self.get("supplied_items"):
if not supplied_item.reserve_warehouse:
frappe.throw(_("Reserved Warehouse is mandatory for Item {0} in Raw Materials supplied").format(frappe.bold(supplied_item.rm_item_code))) | conditional_block |
buying_controller.py | _tax_amount = flt(item_proportion * total_valuation_amount,
self.precision("item_tax_amount", item))
valuation_amount_adjustment -= item.item_tax_amount
self.round_floats_in(item)
if flt(item.conversion_factor)==0.0:
item.conversion_factor = get_conversion_factor(item.item_code, item.uom).get("... | if item.bom:
item.bom = None
def create_raw_materials_supplied(self, raw_material_table):
if self.is_subcontracted=="Yes":
parent_items = []
backflush_raw_materials_based_on = frappe.db.get_single_value("Buying Settings",
"backflush_raw_materials_of_subcontract_based_on")
if (self.doctype == '... | else:
for item in self.get("items"): | random_line_split |
Process58TestElement.py | # Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PySCAP is ... | (TestType):
MODEL_MAP = {
'tag_name': 'process58_test',
}
| Process58TestElement | identifier_name |
Process58TestElement.py | # Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PySCAP is ... | MODEL_MAP = {
'tag_name': 'process58_test',
} | identifier_body | |
Process58TestElement.py | # Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PySCAP is ... |
logger = logging.getLogger(__name__)
class Process58TestElement(TestType):
MODEL_MAP = {
'tag_name': 'process58_test',
} | from scap.model.oval_5.defs.windows.TestType import TestType | random_line_split |
map.spec.ts | import { IntegerType } from "kryo/integer";
import { MapType } from "kryo/map";
import { Ucs2StringType } from "kryo/ucs2-string";
import { registerErrMochaTests, registerMochaSuites, TestItem } from "kryo-testing";
import { QsReader } from "../../lib/qs-reader.js";
import { QsWriter } from "../../lib/qs-writer.js";
... | {
value: new Map([["a", 100], ["aa", 200]]),
io: [
{writer: QS_WRITER, reader: QS_READER, raw: "a=100&aa=200"},
],
},
];
registerMochaSuites($StringMap, items);
describe("Reader", function () {
const invalids: string[] = [
"null",
"true",... | });
const items: TestItem[] = [ | random_line_split |
fileDownloader.spec.ts | import { stubDate } from "../../../mocks/dateMock.helper"
import { FileDownloader } from "./fileDownloader"
import { FileMeta, CodeMapNode, FileSettings, BlacklistType } from "../codeCharta.model"
import { TEST_FILE_DATA, TEST_FILE_DATA_DOWNLOADED, VALID_NODE_DECORATED, VALID_EDGES_DECORATED } from "./dataMocks"
import... |
describe("downloadCurrentMap", () => {
it("should call downloadData with undecorated ExportCCFile", () => {
downloadSettingsNames = []
const expected = klona(TEST_FILE_DATA_DOWNLOADED)
expected.blacklist = []
expected.edges = []
FileDownloader.downloadCurrentMap(map, fileMeta, filesettings, downloa... | FileDownloader["downloadData"] = jest.fn()
}) | random_line_split |
SpyUtils.js | import assert from './assert'
import { isFunction } from './TestUtils'
function noop() {}
let spies = []
export function createSpy(fn, restore=noop) {
if (fn == null)
fn = noop
assert(
isFunction(fn),
'createSpy needs a function'
)
let targetFn, thrownValue, returnValue
const spy = function ... |
export function restoreSpies() {
for (let i = spies.length - 1; i >= 0; i--)
spies[i].restore()
spies = []
}
| {
return object && object.__isSpy === true
} | identifier_body |
SpyUtils.js | import assert from './assert'
import { isFunction } from './TestUtils'
function noop() {}
let spies = []
export function createSpy(fn, restore=noop) {
if (fn == null)
fn = noop
assert(
isFunction(fn),
'createSpy needs a function'
)
let targetFn, thrownValue, returnValue
const spy = function ... |
return object[methodName]
}
export function isSpy(object) {
return object && object.__isSpy === true
}
export function restoreSpies() {
for (let i = spies.length - 1; i >= 0; i--)
spies[i].restore()
spies = []
}
| {
assert(
isFunction(original),
'Cannot spyOn the %s property; it is not a function',
methodName
)
object[methodName] = createSpy(original, function () {
object[methodName] = original
})
} | conditional_block |
SpyUtils.js | import assert from './assert'
import { isFunction } from './TestUtils'
function | () {}
let spies = []
export function createSpy(fn, restore=noop) {
if (fn == null)
fn = noop
assert(
isFunction(fn),
'createSpy needs a function'
)
let targetFn, thrownValue, returnValue
const spy = function () {
spy.calls.push({
context: this,
arguments: Array.prototype.slice... | noop | identifier_name |
SpyUtils.js | import assert from './assert'
import { isFunction } from './TestUtils'
function noop() {}
let spies = []
export function createSpy(fn, restore=noop) {
if (fn == null)
fn = noop
assert(
isFunction(fn),
'createSpy needs a function'
)
let targetFn, thrownValue, returnValue
const spy = function ... | export function isSpy(object) {
return object && object.__isSpy === true
}
export function restoreSpies() {
for (let i = spies.length - 1; i >= 0; i--)
spies[i].restore()
spies = []
} | random_line_split | |
SignalCellularNoSimRounded.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime")... | }), 'SignalCellularNoSimRounded');
exports.default = _default; | var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M19 5c0-1.1-.9-2-2-2h-6.17c-.53 0-1.04.21-1.42.59L7.95 5.06 19 16.11V5zM3.09 4.44c-.39.39-.39 1.02 0 1.41L5 7.78V19c0 1.11.9 2 2 2h11.23l.91.91c.39.39 1.02.39 1.41 0 .39-.39.39-1.02 0-1.41L4.5 4.44a.9959.9959 0 0 0-1.41 0z" | random_line_split |
p5.clickable.js | // _____ _ _ _ _ _
// | ___| | (_) | | | | | |
// _ __ |___ \ ___| |_ ___| | ____ _| |__ | | ___
// | '_ \ \ \/ __| | |/ __| |/ / _` | '_ \| |/ _ \
// | |_) /\__/ / (__| | | (__| < (_| | |_) | | __/
// | .__/\____(_)___|_|_|\___|_|\_\__,_|_.__/|_|\___|
// | | w... | //This function is ran when the clickable is NOT hovered.
}
this.onPress = function(){
//This function is ran when the clickable is pressed.
}
this.onRelease = function(){
//This funcion is ran when the cursor was pressed and then
//released inside the clickable. If it was pressed inside and
//then rele... | {
this.x = x || 0; //X position of the clickable
this.y = y || 0; //Y position of the clickable
this.width = img ? img.width : 100; //Width of the clickable
this.height = img ? img.height : 50; //Height of the clickable
this.color = "#FFFFFF"; //Background color of the clickable
this.cornerRadius = 10; ... | identifier_body |
p5.clickable.js | // _____ _ _ _ _ _
// | ___| | (_) | | | | | |
// _ __ |___ \ ___| |_ ___| | ____ _| |__ | | ___
// | '_ \ \ \/ __| | |/ __| |/ / _` | '_ \| |/ _ \
// | |_) /\__/ / (__| | | (__| < (_| | |_) | | __/
// | .__/\____(_)___|_|_|\___|_|\_\__,_|_.__/|_|\___|
// | | w... | (x,y,img)
{
this.x = x || 0; //X position of the clickable
this.y = y || 0; //Y position of the clickable
this.width = img ? img.width : 100; //Width of the clickable
this.height = img ? img.height : 50; //Height of the clickable
this.color = "#FFFFFF"; //Background color of the clickable
this.cornerRad... | Clickable | identifier_name |
p5.clickable.js | // _____ _ _ _ _ _
// | ___| | (_) | | | | | |
// _ __ |___ \ ___| |_ ___| | ____ _| |__ | | ___
// | '_ \ \ \/ __| | |/ __| |/ / _` | '_ \| |/ _ \
// | |_) /\__/ / (__| | | (__| < (_| | |_) | | __/
// | .__/\____(_)___|_|_|\___|_|\_\__,_|_.__/|_|\___|
// | | w... | this.x = x;
this.y = y;
}
this.resize = function(w, h){
this.width = w;
this.height = h;
}
this.draw = function()
{
if (this.img != null)
{
image(this.img, this.x, this.y, this.width, this.height);
} else
{
fill(this.color);
stroke(this.stroke);
strokeWeight(this.strokeWeight);
rec... | random_line_split | |
dodata.py | 直接叶子写法
jsonpath="$.." + jsonpath[1:] + "[0]"
#print(jsonpath)
try:
jsonpath_expr = parse(jsonpath)
except:
return None
global jsondoc
jsondoc = json.loads(jsonstr)
for match in jsonpath_expr.find(jsondoc):
node=match
return node
##################### JSON 读取指定节点
def readjson_old(jsonstr,json... |
etrees=etree.HTML(data)
##### lxml 处理 xpath 特点
xpath=xpath.replace("html/body/","//") ### 不能写 html/body/ ,这是 firebug 的写法特点
xpaths=xpath.replace("/tbody/","/") ### 去掉所有 tbody
#print(xpaths)
ele= etrees.xpath(xpaths)
if len(ele)==0: ### 不能用 None 判断
xpaths=xpath ### 不去掉
ele= etrees.xpath(xpaths)
... |
#################################### HTML
def readhtml(data,xpath): | random_line_split |
dodata.py | 直接叶子写法
jsonpath="$.." + jsonpath[1:] + "[0]"
#print(json | = parse(jsonpath)
except:
return None
global jsondoc
jsondoc = json.loads(jsonstr)
for match in jsonpath_expr.find(jsondoc):
node=match
return node
##################### JSON 读取指定节点
def readjson_old(jsonstr,jsonpath): ##### jsonpath_rw 中文内容节点的取值有点问题, 原始方法弃用
node=jsonnode(jsonstr,json... | path)
try:
jsonpath_expr | conditional_block |
dodata.py | 直接叶子写法
jsonpath="$.." + jsonpath[1:] + "[0]"
#print(jsonpath)
try:
jsonpath_expr = parse(jsonpath)
except:
return None
global jsondoc
jsondoc = json.loads(jsonstr)
for match in jsonpath_expr.find(jsondoc):
node=match
return node
##################### JSON 读取指定节点
def readjson_old(jsonstr,json... | .xpath(xpaths)
if len(ele)==0: ### 不能用 None 判断
xpaths=xpath ### 不去掉
ele= etrees.xpath(xpaths)
#####
types="" ## 暂时只支持取 text
#####
try:
if types=="":
values=ele[0].text ### 元素的 text
else:
values=str(etrees.xpath(xpaths+ "/@" + types)[0]) ### 元素的对应属性
#print(values)
except:
#print... | ele= etrees | identifier_name |
dodata.py | 直接叶子写法
jsonpath="$.." + jsonpath[1:] + "[0]"
#print(jsonpath)
try:
jsonpath_expr = parse(jsonpath)
except:
return None
global jsondoc
jsondoc = json.loads(jsonstr)
for match in jsonpath_expr.find(jsondoc):
node=match
return node
##################### JSON 读取指定节点
def readjson_old(jsonstr,json... | ths)
ele= etrees.xpath(xpaths)
if len(ele)==0: ### 不能用 None 判断
xpaths=xpath ### 不去掉
ele= etrees.xpath(xpaths)
#####
types="" ## 暂时只支持取 text
#####
try:
if types=="":
values=ele[0].text ### 元素的 text
else:
values=str(etrees.xpath(xpaths+ "/@" + types)[0]) ### 元素的对应属性
#print(values)
... |
etrees=etree.HTML(data)
##### lxml 处理 xpath 特点
xpath=xpath.replace("html/body/","//") ### 不能写 html/body/ ,这是 firebug 的写法特点
xpaths=xpath.replace("/tbody/","/") ### 去掉所有 tbody
#print(xpa | identifier_body |
notification-hub.component.ts | import { Component, OnInit, NgZone } from '@angular/core';
import { LocalStorageService } from "app/local-storage.service";
import { Http, Response } from '@angular/http';
import { NotificationHubService } from "app/notification/notification-hub.service";
import { Router, ActivatedRoute } from "@angular/router";
@Comp... | () {
this.notApprovedAccommodations = 0;
this.notifications = [];
}
clickResolve() {
this.notifications = [];
this.router.navigate(['/not_approved_accommodations/']);
}
}
| removeAllNotifications | identifier_name |
notification-hub.component.ts | import { Component, OnInit, NgZone } from '@angular/core';
import { LocalStorageService } from "app/local-storage.service";
import { Http, Response } from '@angular/http';
import { NotificationHubService } from "app/notification/notification-hub.service";
import { Router, ActivatedRoute } from "@angular/router";
@Comp... |
});
}
public onNotification2(notif: string) {
this.ngZone.run(() => {
this.notifications.push(notif);
});
}
isNewNotifyExist() : boolean {
return this.notifications.length > 0;
}
removeAllNotifications() {
this.notApprovedAccommodations = 0;
this.notifications = [];
... | {
this.notificationHubService.sendHello()
} | conditional_block |
notification-hub.component.ts | import { Component, OnInit, NgZone } from '@angular/core';
import { LocalStorageService } from "app/local-storage.service";
import { Http, Response } from '@angular/http';
import { NotificationHubService } from "app/notification/notification-hub.service";
import { Router, ActivatedRoute } from "@angular/router";
@Comp... | this.notificationHubService.notificationReceivedNewAcc.subscribe(e => this.onNotification2(e));
}
private checkConnection(){
this.notificationHubService.connectionEstablished.subscribe(e => {this.isConnected = e;
if (e) {
this.notificationHubService.sendHello()
}
});
}
p... | }
private subscribeForNewAccommodationNotification () { | random_line_split |
notification-hub.component.ts | import { Component, OnInit, NgZone } from '@angular/core';
import { LocalStorageService } from "app/local-storage.service";
import { Http, Response } from '@angular/http';
import { NotificationHubService } from "app/notification/notification-hub.service";
import { Router, ActivatedRoute } from "@angular/router";
@Comp... |
}
| {
this.notifications = [];
this.router.navigate(['/not_approved_accommodations/']);
} | identifier_body |
test_token.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
JWT tokens (for web interface, mostly, as all peer operations function on
public key cryptography)
JWT tokens can be one of:
* Good
* Expired
* Invalid
And granting them should not take database access. They are meant to
figure out if a user is auth'd without using t... | def test_routes(self):
self.threshold = .1
tok = jwt_get(u'ten')
res = jwt_use(tok)
print(res) | class test_jwt(TimedTestCase):
| random_line_split |
test_token.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
JWT tokens (for web interface, mostly, as all peer operations function on
public key cryptography)
JWT tokens can be one of:
* Good
* Expired
* Invalid
And granting them should not take database access. They are meant to
figure out if a user is auth'd without using t... |
class test_jwt(TimedTestCase):
def test_routes(self):
self.threshold = .1
tok = jwt_get(u'ten')
res = jwt_use(tok)
print(res)
| def test_good_token(self):
"""Valid JWT Token"""
self.threshold = .32
bob = token(u'bob')
example = bob.make(u'print')
bob.check(example)
def test_expired_token(self):
"""Expire a token..."""
self.threshold = .1
a = datetime.datetime.now()
ass... | identifier_body |
test_token.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
JWT tokens (for web interface, mostly, as all peer operations function on
public key cryptography)
JWT tokens can be one of:
* Good
* Expired
* Invalid
And granting them should not take database access. They are meant to
figure out if a user is auth'd without using t... | (self):
self.threshold = .1
tok = jwt_get(u'ten')
res = jwt_use(tok)
print(res)
| test_routes | identifier_name |
executionService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (file: string, args: string[], options: exec.IOptions): TPromise<any> {
throw errors.notImplemented();
}
}
export class WinExecutionService extends AbstractExecutionService {
protected doExec(file: string, args: string[], options: exec.IOptions): TPromise<any> {
let childProcess: cp.ChildProcess;
return new... | doExec | identifier_name |
executionService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
});
}
protected doExec(file: string, args: string[], options: exec.IOptions): TPromise<any> {
throw errors.notImplemented();
}
}
export class WinExecutionService extends AbstractExecutionService {
protected doExec(file: string, args: string[], options: exec.IOptions): TPromise<any> {
let childProcess... |
return ret.then(val => val, err => {
if (!errors.isPromiseCanceledError(err)) {
throw err; | random_line_split |
executionService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | else {
objects.mixin(allEnv, cwdOrOptions.env);
cwdOrOptions.env = allEnv;
options = cwdOrOptions;
}
let key = args.concat([file, options.cwd]).reduce((p, c) => hash.combine(hash.computeMurmur2StringHashCode(c), p), 17);
if (this._executions[key]) {
this._executions[key].cancel();
delete this._ex... | {
options = {
cwd: cwdOrOptions,
env: allEnv
};
} | conditional_block |
executionService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | if (childProcess) {
childProcess.kill('SIGTERM');
}
});
}
}
export class LinuxExecutionService extends AbstractExecutionService {
private static LINUX_TERM = '/usr/bin/gnome-terminal'; // '/usr/bin/x-terminal-emulator'
private static WAIT_MESSAGE = nls.localize('linux.wait', "Press any key to continue... | {
let childProcess: cp.ChildProcess;
return new TPromise<any>((c, e, p) => {
args = [
uri.parse(require.toUrl('vs/workbench/parts/execution/electron-browser/macHelper.scpt')).fsPath,
'cd', `'${options.cwd}'`, ';',
file
].concat(args);
childProcess = cp.spawn('/usr/bin/osascript', args, optio... | identifier_body |
readmes.js | /**
* Since we moved our documentation to our website repo, we want to point to the
* website from the docs in this repo
*
* This script write the link to the website in every READMEs.
*/
const { join } = require("path");
const { readdirSync, writeFileSync } = require("fs");
const cwd = process.cwd();
const pac... | "babel-polyfill": getIssueLabelLink("pkg: polyfill"),
"babel-preset-env": getIssueLabelLink("pkg: preset-env"),
"babel-register": getIssueLabelLink("pkg: register"),
"babel-template": getIssueLabelLink("pkg: template"),
"babel-traverse": getIssueLabelLink("pkg: traverse"),
"babel-types": getIssueLabelLink("... | "babel-parser": getIssueLabelLink("pkg: babylon"),
"babel-cli": getIssueLabelLink("pkg: cli"),
"babel-core": getIssueLabelLink("pkg: core"),
"babel-generator": getIssueLabelLink("pkg: generator"), | random_line_split |
urls.py | #!/usr/bin/env python
"""
"""
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from views import *
| urlpatterns = patterns('',
url(r'^index/$', FabricIndex.as_view(), name='fabric_index'),
# Users
url(r'^access/$', FabricAccessList.as_view(), name='fabric_access'),
url(r'^access/create/$', FabricAccessCreate.as_view(), name='fabric_access_create'),
url(r'^access/(?P<pk>\d+)/$', FabricAccessDetail... | random_line_split | |
scanningPage.py | # -*- coding: utf-8 -*-
# This file is part of the Horus Project
__author__ = 'Jesús Arroyo Torrens <jesus.arroyo@bq.com>'
__copyright__ = 'Copyright (C) 2014-2015 Mundo Reader S.L.'
__license__ = 'GNU General Public License v2 http://www.gnu.org/licenses/gpl2.html'
import wx._core
from horus.gui.wizard.wizardPage i... | self.laserDict = dict(zip(_choices, choices))
self.laserLabel = wx.StaticText(self.panel, label=_("Use laser"))
self.laserComboBox = wx.ComboBox(self.panel, wx.ID_ANY,
value=_(profile.settings['use_laser']),
choice... | choices.append(_(i))
| conditional_block |
scanningPage.py | # -*- coding: utf-8 -*-
# This file is part of the Horus Project
__author__ = 'Jesús Arroyo Torrens <jesus.arroyo@bq.com>'
__copyright__ = 'Copyright (C) 2014-2015 Mundo Reader S.L.'
__license__ = 'GNU General Public License v2 http://www.gnu.org/licenses/gpl2.html'
import wx._core
from horus.gui.wizard.wizardPage i... | f status:
profile.settings['workbench'] = u'Scanning workbench'
self.GetParent().parent.workbenchUpdate(False)
self.videoView.play()
value = profile.settings['use_laser']
if value == 'Left':
self.driver.board.laser_on(0)
self.dr... | identifier_body | |
scanningPage.py | # -*- coding: utf-8 -*-
# This file is part of the Horus Project
__author__ = 'Jesús Arroyo Torrens <jesus.arroyo@bq.com>'
__copyright__ = 'Copyright (C) 2014-2015 Mundo Reader S.L.'
__license__ = 'GNU General Public License v2 http://www.gnu.org/licenses/gpl2.html'
import wx._core
from horus.gui.wizard.wizardPage i... | if useRight:
self.driver.board.laser_on(1)
else:
self.driver.board.laser_off(1)
self.ciclop_scan.set_use_left_laser(useLeft)
self.ciclop_scan.set_use_right_laser(useRight)
def get_image(self):
return self.image_capture.capture_texture()
def updat... | else:
self.driver.board.laser_off(0)
| random_line_split |
scanningPage.py | # -*- coding: utf-8 -*-
# This file is part of the Horus Project
__author__ = 'Jesús Arroyo Torrens <jesus.arroyo@bq.com>'
__copyright__ = 'Copyright (C) 2014-2015 Mundo Reader S.L.'
__license__ = 'GNU General Public License v2 http://www.gnu.org/licenses/gpl2.html'
import wx._core
from horus.gui.wizard.wizardPage i... | self):
return self.image_capture.capture_texture()
def updateStatus(self, status):
if status:
profile.settings['workbench'] = u'Scanning workbench'
self.GetParent().parent.workbenchUpdate(False)
self.videoView.play()
value = profile.settings['use_lase... | et_image( | identifier_name |
mean.rs | //! Functions for calculating mean
use std::f64::NAN;
/// Calculates arithmetic mean (AM) of data set `slice`.
///
/// # Arguments
///
/// * `slice` - collection of values
///
/// # Example
///
/// ```
/// use math::mean;
///
/// let slice = [8., 16.];
/// assert_eq!(mean::arithmetic(&slice), 12.);
/// ```
pub fn | (slice: &[f64]) -> f64 {
slice.iter().fold(0., |a, b| a + b) / slice.len() as f64
}
/// Calculate geometric mean (GM) of data set `slice`.
///
/// If the result would be imaginary, function returns `NAN`.
///
/// # Arguments
///
/// * `slice` - collection of values
///
/// # Example
///
/// ```
/// use math::mean;
//... | arithmetic | identifier_name |
mean.rs | //! Functions for calculating mean
use std::f64::NAN;
/// Calculates arithmetic mean (AM) of data set `slice`.
///
/// # Arguments
///
/// * `slice` - collection of values
///
/// # Example
///
/// ```
/// use math::mean;
///
/// let slice = [8., 16.];
/// assert_eq!(mean::arithmetic(&slice), 12.);
/// ```
pub fn arit... | geometric_8: (&[NEG_INFINITY, 1., 2., 3., 4.], NAN),
geometric_9: (&[1., 2., 3., 4., INFINITY], INFINITY),
]}
test_mean! { super::harmonic [
harmonic_1: (&[-7., -4., 1., 3., 8.], 4.692737),
harmonic_2: (&[-4., 1., 3., 8., 12.], 3.870968),
harmonic_3: (&[0., 0., 0., 0., 0.], 0.),
harmonic_4: (&[0., 4., 7.... | geometric_4: (&[0., 4., 7., 9., 17.], 0.),
geometric_5: (&[1., 2., 6., 4., 13.], 3.622738),
geometric_6: (&[1., 5., 10., 20., 25.], 7.578583),
geometric_7: (&[2., 3., 5., 7., 11.], 4.706764), | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.