file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
config.js | System.config({
"baseURL": "/",
"transpiler": "babel",
"babelOptions": {
"optional": [
"runtime"
]
},
"paths": {
"*": "*.js",
"github:*": "jspm_packages/github/*.js",
"npm:*": "jspm_packages/npm/*.js"
} | "babel": "npm:babel-core@5.2.6",
"babel-runtime": "npm:babel-runtime@5.2.6",
"chai": "npm:chai@2.3.0",
"core-js": "npm:core-js@0.9.6",
"github:jspm/nodelibs-buffer@0.1.0": {
"buffer": "npm:buffer@3.2.1"
},
"github:jspm/nodelibs-process@0.1.1": {
"process": "npm:process@0.10.1"
... | });
System.config({
"map": { | random_line_split |
layout_interface.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The high-level interface from script to layout. Using this abstract
//! interface helps reduce coupling betwee... |
pub struct ContentBoxResponse(pub Rect<Au>);
pub struct ContentBoxesResponse(pub Vec<Rect<Au>>);
pub struct NodeGeometryResponse {
pub client_rect: Rect<i32>,
}
pub struct HitTestResponse(pub UntrustedNodeAddress);
pub struct MouseOverResponse(pub Vec<UntrustedNodeAddress>);
pub struct ResolvedStyleResponse(pub O... | } | random_line_split |
layout_interface.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The high-level interface from script to layout. Using this abstract
//! interface helps reduce coupling betwee... | {
pub id: PipelineId,
pub url: Url,
pub is_parent: bool,
pub layout_pair: OpaqueScriptLayoutChannel,
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
pub constellation_chan: ConstellationChan,
pub failure: Failure,
pub script_chan: Sender<ConstellationControlMsg>,
pub image_cache_t... | NewLayoutTaskInfo | identifier_name |
map.js | function initMap() {
var latLng = new google.maps.LatLng(40.791885, -73.952581);
var styles = [
{
stylers: [
{ hue: "#541388" },
{ saturation: 0 }
]
},{
featureType: "road",
elementType: "geometry",
stylers: [
... | // );
} | random_line_split | |
map.js | function initMap() {
var latLng = new google.maps.LatLng(40.791885, -73.952581);
var styles = [
{
stylers: [
{ hue: "#541388" },
{ saturation: 0 }
]
},{
featureType: "road",
elementType: "geometry",
stylers: [
... |
var eventMarker = new google.maps.Marker({
position: latLng,
map: map,
title: "The New York Academy of Medicine",
icon: '/img/map/star.png',
animation: google.maps.Animation.DROP
});
// Add Click Event for location
google.maps.event.addListener(eventMarker, 'cl... | {
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: title,
icon: '/img/map/hotel.png',
animation: google.maps.Animation.DROP
});
// Add Click Event
google.maps.event.addListener(marker, 'click', function(... | identifier_body |
map.js | function initMap() {
var latLng = new google.maps.LatLng(40.791885, -73.952581);
var styles = [
{
stylers: [
{ hue: "#541388" },
{ saturation: 0 }
]
},{
featureType: "road",
elementType: "geometry",
stylers: [
... | (title, latLng, url, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: title,
icon: '/img/map/hotel.png',
animation: google.maps.Animation.DROP
});
// Add Click Event
google.maps.event.addListener(... | addHotelMarker | identifier_name |
fasta.py | from Bio import SeqIO
def get_proteins_for_db(fastafn, fastadelim, genefield):
"""Runs through fasta file and returns proteins accession nrs, sequences
and evidence levels for storage in lookup DB. Duplicate accessions in
fasta are accepted and removed by keeping only the last one.
"""
records = {... | (record):
fields = [x.split(':') for x in record.description.split()]
try:
return [x[1] for x in fields if x[0] == 'gene' and len(x) == 2][0]
except IndexError:
raise RuntimeError('ENSEMBL detected but cannot find gene ENSG in fasta')
def get_symbol(record, rectype, fastadelim, genefield):... | get_ensg | identifier_name |
fasta.py | from Bio import SeqIO
def get_proteins_for_db(fastafn, fastadelim, genefield):
"""Runs through fasta file and returns proteins accession nrs, sequences
and evidence levels for storage in lookup DB. Duplicate accessions in
fasta are accepted and removed by keeping only the last one.
"""
records = {... |
def get_other_gene(record, fastadelim, genefield):
return record.description.split(fastadelim)[genefield]
def get_genes_pickfdr(fastafn, outputtype, fastadelim, genefield):
"""Called by protein FDR module for both ENSG and e.g. Uniprot"""
for rec in parse_fasta(fastafn):
rtype = get_record_type... | desc = []
for part in record.description.split()[1:]:
if len(part.split('=')) > 1:
break
desc.append(part)
return ' '.join(desc) | conditional_block |
fasta.py | from Bio import SeqIO
def get_proteins_for_db(fastafn, fastadelim, genefield):
"""Runs through fasta file and returns proteins accession nrs, sequences
and evidence levels for storage in lookup DB. Duplicate accessions in
fasta are accepted and removed by keeping only the last one.
"""
records = {... |
def get_genes_pickfdr(fastafn, outputtype, fastadelim, genefield):
"""Called by protein FDR module for both ENSG and e.g. Uniprot"""
for rec in parse_fasta(fastafn):
rtype = get_record_type(rec)
if rtype == 'ensembl' and outputtype == 'ensg':
yield get_ensg(rec)
elif outpu... | return record.description.split(fastadelim)[genefield] | identifier_body |
fasta.py | from Bio import SeqIO
def get_proteins_for_db(fastafn, fastadelim, genefield):
"""Runs through fasta file and returns proteins accession nrs, sequences
and evidence levels for storage in lookup DB. Duplicate accessions in
fasta are accepted and removed by keeping only the last one.
"""
records = {... | def get_uniprot_evidence_level(record, rtype):
"""Returns uniprot protein existence evidence level for a fasta header.
Evidence levels are 1-5, but we return 5 - x since sorting still demands
that higher is better."""
if rtype != 'swiss':
return -1
for item in record.description.split():
... | random_line_split | |
input_layers.rs | use std::borrow::Cow;
use std::fmt;
use std::io::BufRead;
use std::result;
use enum_map::{Enum, EnumMap};
use failure::Error;
use tensorflow::Tensor;
use crate::features::addr;
use crate::features::lookup::LookupResult;
use crate::features::parse_addr::parse_addressed_values;
use crate::features::{BoxedLookup, Lookup... | self.realize_into(state, &mut embed_layer, &mut lookup_layers);
InputVector {
embed_layer,
lookup_layers,
}
}
/// Vectorize a parser state into the given slices.
pub fn realize_into<S>(
&self,
state: &ParserState<'_>,
embed_layer: &mu... | for (layer, &size) in &self.lookup_layer_sizes() {
lookup_layers[layer] = vec![0; size];
}
| random_line_split |
input_layers.rs | use std::borrow::Cow;
use std::fmt;
use std::io::BufRead;
use std::result;
use enum_map::{Enum, EnumMap};
use failure::Error;
use tensorflow::Tensor;
use crate::features::addr;
use crate::features::lookup::LookupResult;
use crate::features::parse_addr::parse_addressed_values;
use crate::features::{BoxedLookup, Lookup... | (EnumMap<Layer, BoxedLookup>);
impl LayerLookups {
pub fn new() -> Self {
LayerLookups(EnumMap::new())
}
pub fn insert<L>(&mut self, layer: Layer, lookup: L)
where
L: Into<Box<dyn Lookup>>,
{
self.0[layer] = BoxedLookup::new(lookup)
}
/// Get the lookup for a layer... | LayerLookups | identifier_name |
input_layers.rs | use std::borrow::Cow;
use std::fmt;
use std::io::BufRead;
use std::result;
use enum_map::{Enum, EnumMap};
use failure::Error;
use tensorflow::Tensor;
use crate::features::addr;
use crate::features::lookup::LookupResult;
use crate::features::parse_addr::parse_addressed_values;
use crate::features::{BoxedLookup, Lookup... |
pub fn lookup_layer_sizes(&self) -> EnumMap<Layer, usize> {
let mut sizes = EnumMap::new();
for layer in &self.input_layer_addrs.0 {
if let Some(lookup) = self.layer_lookups.0[(&layer.layer).into()].as_ref() {
match lookup.lookup_type() {
LookupType... | {
&self.layer_lookups
} | identifier_body |
function-external-overscroll.js | /**
* Overscroll v1.6.4
* A jQuery Plugin that emulates the iPhone scrolling experience in a browser.
* http://azoffdesign.com/overscroll
*
* Intended for use with the latest jQuery
* http://code.jquery.com/jquery-latest.js
*
* Copyright 2012, Jonathan Azoff
* Dual licensed under the MIT or GPL Version 2 li... | zIndex: 999,
hasHorizontal: true,
hasVertical: true
},
// Triggers a DOM event on the overscrolled element.
// All events are namespaced under the overscroll name
triggerEvent = function (event, target) {
target.trigger('overscroll:' + event);
},
// Utility function to return a timestamp
time =... | random_line_split | |
function-external-overscroll.js | /**
* Overscroll v1.6.4
* A jQuery Plugin that emulates the iPhone scrolling experience in a browser.
* http://azoffdesign.com/overscroll
*
* Intended for use with the latest jQuery
* http://code.jquery.com/jquery-latest.js
*
* Copyright 2012, Jonathan Azoff
* Dual licensed under the MIT or GPL Version 2 li... |
if(top + sizing.container.height > sizing.container.scrollHeight) {
top = sizing.container.scrollHeight - sizing.container.height;
}
if (thumbs.horizontal) {
ml = left * (1 + sizing.container.width / sizing.container.scrollWidth);
mt = top + sizing.thumbs.horizontal.top;
if(ml + sizing.thum... | {
left = sizing.container.scrollWidth - sizing.container.width;
} | conditional_block |
metrics_utils.ts | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {loadTimeData} from './i18n_setup.js';
/** Records |durationMs| in the |metricName| histogram. */
export function recordDuration(metricName: strin... | max: 1,
buckets: 1,
},
1);
} | random_line_split | |
metrics_utils.ts | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {loadTimeData} from './i18n_setup.js';
/** Records |durationMs| in the |metricName| histogram. */
export function recordDuration(metricName: strin... |
/**
* Records that an event has happened rather than a value in the |metricName|
* histogram.
*/
export function recordOccurence(metricName: string) {
chrome.metricsPrivate.recordValue(
{
metricName,
type: chrome.metricsPrivate.MetricTypeType.HISTOGRAM_LINEAR,
min: 1,
max: 1... | {
chrome.metricsPrivate.recordValue(
{
metricName,
type: chrome.metricsPrivate.MetricTypeType.HISTOGRAM_LINEAR,
min: 1, // Choose 1 if real min is 0.
max: 11, // Exclusive.
buckets: 12, // Numbers 0-10 and unused overflow bucket of 11.
},
value);
} | identifier_body |
metrics_utils.ts | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {loadTimeData} from './i18n_setup.js';
/** Records |durationMs| in the |metricName| histogram. */
export function | (metricName: string, durationMs: number) {
chrome.metricsPrivate.recordValue(
{
metricName,
type: chrome.metricsPrivate.MetricTypeType.HISTOGRAM_LOG,
min: 1,
max: 60000, // 60 seconds.
buckets: 100,
},
Math.floor(durationMs));
}
/**
* Records the duration b... | recordDuration | identifier_name |
libp2p-bundle.js | // eslint-disable-next-line
'use strict'
const Libp2p = require('libp2p')
const Websockets = require('libp2p-websockets')
const WebSocketStar = require('libp2p-websocket-star')
const WebRTCStar = require('libp2p-webrtc-star')
const MPLEX = require('libp2p-mplex')
const { NOISE } = require('@chainsafe/libp2p-noise')
co... | streamMuxer: [
MPLEX
],
connEncryption: [
NOISE
],
dht: KadDHT
},
config: {
peerDiscovery: {
autoDial: false,
webrtcStar: {
enabled: false
},
websocketStar: {
enabled: false
}
},
dht: {
... | wrtcstar,
wsstar,
Websockets
], | random_line_split |
libp2p-bundle.js | // eslint-disable-next-line
'use strict'
const Libp2p = require('libp2p')
const Websockets = require('libp2p-websockets')
const WebSocketStar = require('libp2p-websocket-star')
const WebRTCStar = require('libp2p-webrtc-star')
const MPLEX = require('libp2p-mplex')
const { NOISE } = require('@chainsafe/libp2p-noise')
co... | {
const wrtcstar = new WebRTCStar({id: peerInfo.id})
const wsstar = new WebSocketStar({id: peerInfo.id})
const delegatedApiOptions = {
host: '0.0.0.0',
protocol: 'http',
port: '8080'
}
return new Libp2p({
peerInfo,
peerBook,
// Lets limit the connection managers peers and have it chec... | identifier_body | |
libp2p-bundle.js | // eslint-disable-next-line
'use strict'
const Libp2p = require('libp2p')
const Websockets = require('libp2p-websockets')
const WebSocketStar = require('libp2p-websocket-star')
const WebRTCStar = require('libp2p-webrtc-star')
const MPLEX = require('libp2p-mplex')
const { NOISE } = require('@chainsafe/libp2p-noise')
co... | ({peerInfo, peerBook}) {
const wrtcstar = new WebRTCStar({id: peerInfo.id})
const wsstar = new WebSocketStar({id: peerInfo.id})
const delegatedApiOptions = {
host: '0.0.0.0',
protocol: 'http',
port: '8080'
}
return new Libp2p({
peerInfo,
peerBook,
// Lets limit the connection manager... | Libp2pBundle | identifier_name |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from setuptools.command.test import test
REQUIREMENTS = (
"six",
)
with open("README.rst", "r") as resource:
LONG_DESCRIPTION = resource.read()
# copypasted from http://pytest.org/latest/goodpractises.html
class Py... |
setup(
name="isitbullshit",
description=("Small library for verifying parsed JSONs "
"if they are bullshit or not"),
long_description=LONG_DESCRIPTION,
version="0.2.1",
author="Sergey Arkhipov",
license="MIT",
author_email="serge@aerialsounds.org",
maintainer="Sergey ... | user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
test.initialize_options(self)
self.pytest_args = None # pylint: disable=W0201
def finalize_options(self):
test.finalize_options(self)
self.test_args = [] # pylint: disable=W02... | identifier_body |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from setuptools.command.test import test
REQUIREMENTS = (
"six",
)
with open("README.rst", "r") as resource:
LONG_DESCRIPTION = resource.read()
# copypasted from http://pytest.org/latest/goodpractises.html
class Py... | author="Sergey Arkhipov",
license="MIT",
author_email="serge@aerialsounds.org",
maintainer="Sergey Arkhipov",
maintainer_email="serge@aerialsounds.org",
url="https://github.com/9seconds/isitbullshit/",
install_requires=REQUIREMENTS,
keywords="json validation jsonschema",
tests_requir... | long_description=LONG_DESCRIPTION,
version="0.2.1", | random_line_split |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from setuptools.command.test import test
REQUIREMENTS = (
"six",
)
with open("README.rst", "r") as resource:
LONG_DESCRIPTION = resource.read()
# copypasted from http://pytest.org/latest/goodpractises.html
class Py... | (self):
test.initialize_options(self)
self.pytest_args = None # pylint: disable=W0201
def finalize_options(self):
test.finalize_options(self)
self.test_args = [] # pylint: disable=W0201
self.test_suite = True # pylint: disable=W0201
def run_tests(self):
# imp... | initialize_options | identifier_name |
Subsets II.js | /**
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
*/
/... | (nums, start, end, curArr, result) {
result.push(curArr);
var i;
for (i = start; i <= end; i++) {
// skip duplicates
if (i > start && nums[i] === nums[i - 1]) {
continue;
}
curArr.push(nums[i]);
helper(nums, i + 1, end, curArr.concat(), result);
... | helper | identifier_name |
Subsets II.js | /**
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
*/
/... |
}
| {
// skip duplicates
if (i > start && nums[i] === nums[i - 1]) {
continue;
}
curArr.push(nums[i]);
helper(nums, i + 1, end, curArr.concat(), result);
curArr.pop();
} | conditional_block |
Subsets II.js | /**
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
*/
/... | {
result.push(curArr);
var i;
for (i = start; i <= end; i++) {
// skip duplicates
if (i > start && nums[i] === nums[i - 1]) {
continue;
}
curArr.push(nums[i]);
helper(nums, i + 1, end, curArr.concat(), result);
curArr.pop();
}
} | identifier_body | |
Subsets II.js | /**
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
*/
/... | });
helper(nums, 0, len - 1, [], result);
return result;
};
function helper(nums, start, end, curArr, result) {
result.push(curArr);
var i;
for (i = start; i <= end; i++) {
// skip duplicates
if (i > start && nums[i] === nums[i - 1]) {
continue;
... | nums.sort(function(a, b) {
return a - b; | random_line_split |
Intent.ts |
export class | <V> {
protected targetPromise: Promise<V>;
protected promiseValue: V;
protected promiseError: any;
protected availableFlag: boolean;
protected successfulFlag: boolean;
public constructor(promise: Promise<V>) {
this.targetPromise = promise;
// Listen to promise
this.targetPromise.then(this.onTargetFul... | Intent | identifier_name |
Intent.ts |
export class Intent<V> {
protected targetPromise: Promise<V>;
protected promiseValue: V;
protected promiseError: any;
protected availableFlag: boolean;
protected successfulFlag: boolean;
public constructor(promise: Promise<V>) {
this.targetPromise = promise;
// Listen to promise
this.targetPromise.t... |
/** Returns whether the promise is fulfilled or rejected, or false when the value is not available. */
public fulfilled(): boolean {
return (this.availableFlag && this.successfulFlag);
}
public rejected(): boolean {
return (this.availableFlag && !this.successfulFlag);
}
}
| {
return this.availableFlag;
} | identifier_body |
Intent.ts | export class Intent<V> {
protected targetPromise: Promise<V>;
protected promiseValue: V;
protected promiseError: any;
protected availableFlag: boolean; | protected successfulFlag: boolean;
public constructor(promise: Promise<V>) {
this.targetPromise = promise;
// Listen to promise
this.targetPromise.then(this.onTargetFulfilled, this.onTargetRejected);
}
protected onTargetFulfilled(result: V): void {
this.availableFlag = true;
this.successfulFlag = t... | random_line_split | |
e01-pass-struct.rs | /// Exercise 11.1: Modify the example code shown in Figure 11.4 to pass the structure between the
/// threads properly.
///
/// The cleanest solution is - I think - if the main thread is responsible
/// for both mallocing and freeing the memory, thus we don't need
/// the return value (or pthread_exit), but store the c... | () {
unsafe {
let foo = Box::new(Foo {
a: 1,
b: 2,
c: 3,
d: 4,
});
let mut tid1 = std::mem::uninitialized();
let foo_ptr = Box::into_raw(foo);
pthread_create(&mut tid1, null_mut(), thr_fn1, foo_ptr as *mut c_void).check_zero().e... | main | identifier_name |
e01-pass-struct.rs | /// Exercise 11.1: Modify the example code shown in Figure 11.4 to pass the structure between the | ///
/// The cleanest solution is - I think - if the main thread is responsible
/// for both mallocing and freeing the memory, thus we don't need
/// the return value (or pthread_exit), but store the changes in to the arg
/// variable directly.
///
/// The solution in the book works as well of course, but leaks memory.
... | /// threads properly. | random_line_split |
prev-games.tsx | import * as React from 'react'
import flowRight from 'lodash-es/flowRight'
import {translate} from 'react-i18next'
import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'
import {RouteComponentProps, withRouter} from 'react-router'
import {Container} from '../material/container'
import List from '@... | if (havePrevGame) {
return (
<Container>
<div className={classes.prevGameContainer}>
<Typography variant="display1" gutterBottom>{t('Click on an entry for details')}</Typography>
<List>
{prevGames.map((prevGame, index) => (
<PrevGame key=... | public render() {
const {havePrevGame, prevGames, t} = this.props | random_line_split |
chatmessagehandler.ts | <?xml version="1.0" ?><!DOCTYPE TS><TS language="es" sourcelanguage="en" version="2.1">
<context>
<name>ChatMessageHandler</name>
<message>
<source>Chat Messages</source>
<translation>Mensajes de chat</translation>
</message>
<message>
<source>Message from %1</source>
<tr... | </TS> | <source><Absent></source>
<translation><Ausente></translation>
</message>
</context> | random_line_split |
main.ts | var allTestFiles: string[] = []
var TEST_REGEXP = /^\/base\/dist\/test\/test\/[^\/]+\.js$/i
declare var require: any;
interface Window {
__karma__: any;
}
// Get a list of all the test files to include
Object.keys(window.__karma__.files).forEach(function (file) {
if (TEST_REGEXP.test(file) && file !== '/base/dis... | name: 'aurelia-templating-resources',
location: '/base/node_modules/aurelia-templating-resources/dist/amd',
main : 'aurelia-templating-resources'
},
{
name: 'aurelia-testing',
location: '/base/node_modules/aurelia-testing/dist/amd',
main : 'aurelia-testing'
},
{
... | { | random_line_split |
main.ts | var allTestFiles: string[] = []
var TEST_REGEXP = /^\/base\/dist\/test\/test\/[^\/]+\.js$/i
declare var require: any;
interface Window {
__karma__: any;
}
// Get a list of all the test files to include
Object.keys(window.__karma__.files).forEach(function (file) {
if (TEST_REGEXP.test(file) && file !== '/base/dis... |
started = true;
pal.initialize();
require(allTestFiles, () => window.__karma__.start());
},
paths: {
'aurelia-binding': '/base/node_modules/aurelia-binding/dist/amd/aurelia-binding',
'aurelia-bootstrapper': '/base/node_modules/aurelia-bootstrapper/dist/amd/aurelia-bootstrapper',
'aurelia-d... | {
return;
} | conditional_block |
ebrpc.py | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... | # twispread's TEBRPC.callRemote then TEBRPC will insert the tid for the call.
def __init__(self, faultCode, faultString, tid=None):
self.faultCode = faultCode
self.faultString = faultString
self.tid = tid
self.args = (faultCode, faultString)
def __repr__(self):
... |
class DFault(Exception):
"""Indicates an Datagram EBRPC fault package."""
# If you return a DFault with tid=None from within a function called via | random_line_split |
ebrpc.py | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... |
return out
def loads(data):
d = ebdecode(data)
if d['y'] == 'e':
raise Fault(d['c'], d['s']) # the server raised a fault
elif d['y'] == 'r':
# why is this return value so weird?
# because it's the way that loads works in xmlrpclib
return (d['r'],), None
elif d['y'] ... | raise Error("") | conditional_block |
ebrpc.py | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... |
def __repr__(self):
return (
"<Fault %s: %s>" %
(self.faultCode, repr(self.faultString))
)
### datagram interface
### has transaction ID as third return valuebt
### slightly different API, returns a tid as third argument in query/response
def dumpd(params, meth... | self.faultCode = faultCode
self.faultString = faultString
self.tid = tid
self.args = (faultCode, faultString) | identifier_body |
ebrpc.py | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... | (code, msg):
return ebencode({'y':'e', 'c':code, 's':msg})
def dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False):
if methodresponse and isinstance(params, TupleType):
assert len(params) == 1, "response tuple must be a singleton"
if methodname:
out = ebenc... | dump_fault | identifier_name |
pgwmodal-test.ts | /// <reference path="pgwmodal.d.ts" />
var $j: JQueryStatic;
var $z: ZeptoStatic;
function test_open(): void {
var r: boolean = $j.pgwModal({
content: 'Modal Example 1'
});
$j.pgwModal({
target: '#modalContent',
title: 'Modal title 2',
maxWidth: 800
});
$j.pgwModa... | {
$j.pgwModal == $z.pgwModal;
} | identifier_body | |
pgwmodal-test.ts | /// <reference path="pgwmodal.d.ts" />
var $j: JQueryStatic;
var $z: ZeptoStatic;
function test_open(): void {
var r: boolean = $j.pgwModal({
content: 'Modal Example 1'
});
$j.pgwModal({
target: '#modalContent',
title: 'Modal title 2',
maxWidth: 800
});
$j.pgwModa... | (): void {
$j.pgwModal == $z.pgwModal;
}
| test_equal | identifier_name |
pgwmodal-test.ts | /// <reference path="pgwmodal.d.ts" />
var $j: JQueryStatic; | var r: boolean = $j.pgwModal({
content: 'Modal Example 1'
});
$j.pgwModal({
target: '#modalContent',
title: 'Modal title 2',
maxWidth: 800
});
$j.pgwModal({
url: 'modal-test.php',
loadingContent: '<span style="text-align:center">Loading in progress</... | var $z: ZeptoStatic;
function test_open(): void { | random_line_split |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() | {
loop {
println!("\n");
println!("Hurry ! guess a number between 1 and 100 quick !!");
println!("Now quickly enter what you have guessed !");
let mut myguess = String::new();
io::stdin()
.read_line(&mut myguess)
.ok()
.expect("can not read !! I am blind again !!");
let m... | identifier_body | |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
loop {
println!("\n");
println!("Hurry ! guess a number between 1 and 100 quick !!");
println!("Now quickly enter what you have guessed !");
let mut myguess = String::new();
io::stdin()
.read_line(&mut m... |
}
println!("The secret number is: {}", secret);
}
}
| {
println!("You Win !!!");
break;
} | conditional_block |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
loop {
println!("\n");
println!("Hurry ! guess a number between 1 and 100 quick !!");
println!("Now quickly enter what you have guessed !");
let mut myguess = String::new();
io::stdin()
.read_line(&mut m... | match myguess.cmp(&secret) {
Ordering::Less => println!("Too small !!"),
Ordering::Greater => println!("Too BIG !!"),
Ordering::Equal => {
println!("You Win !!!");
break;
}
}
println!("The secret number is: {}", secret);
}
} |
let secret = rand::thread_rng().gen_range(1,101); | random_line_split |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn | () {
loop {
println!("\n");
println!("Hurry ! guess a number between 1 and 100 quick !!");
println!("Now quickly enter what you have guessed !");
let mut myguess = String::new();
io::stdin()
.read_line(&mut myguess)
.ok()
.expect("can not read !! I am blind again !!");
le... | main | identifier_name |
arm_linux_androideabi.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> Target {
let mut base = super::linux_base::opts();
base.features = "+v7".to_string();
// Many of the symbols defined in compiler-rt are also defined in libgcc. Android
// linker doesn't like that by default.
base.pre_link_args.push("-Wl,--allow-multiple-definition".to_string());
// FIXME ... | target | identifier_name |
arm_linux_androideabi.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
Target {
data_layout: "e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string(),
llvm_target: "arm-linux-androideabi".to_string(),
... | base.pre_link_args.push("-Wl,--allow-multiple-definition".to_string());
// FIXME #17437 (and #17448): Android doesn't support position dependent executables anymore.
base.position_independent_executables = false; | random_line_split |
arm_linux_androideabi.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let mut base = super::linux_base::opts();
base.features = "+v7".to_string();
// Many of the symbols defined in compiler-rt are also defined in libgcc. Android
// linker doesn't like that by default.
base.pre_link_args.push("-Wl,--allow-multiple-definition".to_string());
// FIXME #17437 (and #... | identifier_body | |
source.py | '''
|marx| offers several different source shapes. Tests in this module exercise
those sources (except ``SAOSAC``, which is heavily used in
:ref:`sect-tests.PSF` already).
'''
import shutil
import subprocess
import os
from collections import OrderedDict
from marxtest import base
title = 'Sources in |marx|'
tests = ... | '''Turn into fits files
We use the ``EXACT`` setting here to make the comparison simpler.
The default EDSER (energy-dependent sub-pixel event repositioning)
shifts photons of the same energy by a different amount for ACIS-S and
ACIS-I, which would make it harder to compare the r... | 'OutputDir': 'acisi', 'DetectorType': 'ACIS-I'}
@base.Marx2fits
def step_4(self): | random_line_split |
source.py | '''
|marx| offers several different source shapes. Tests in this module exercise
those sources (except ``SAOSAC``, which is heavily used in
:ref:`sect-tests.PSF` already).
'''
import shutil
import subprocess
import os
from collections import OrderedDict
from marxtest import base
title = 'Sources in |marx|'
tests = ... | '''ds9 images of the PSF'''
return ['''ds9 -width 800 -height 500 -log -cmap heat point.fits -pan to 4018 4141 physical -zoom 8 -saveimage {0} -exit'''.format(self.figpath(list(self.figures.keys())[0]))] | identifier_body | |
source.py | '''
|marx| offers several different source shapes. Tests in this module exercise
those sources (except ``SAOSAC``, which is heavily used in
:ref:`sect-tests.PSF` already).
'''
import shutil
import subprocess
import os
from collections import OrderedDict
from marxtest import base
title = 'Sources in |marx|'
tests = ... | (self):
'''ACIS-I'''
return {'SourceType': 'RAYFILE', 'RayFile': 'marx.output',
'OutputDir': 'acisi', 'DetectorType': 'ACIS-I'}
@base.Marx2fits
def step_4(self):
'''Turn into fits files
We use the ``EXACT`` setting here to make the comparison simpler.
Th... | step_3 | identifier_name |
source.py | '''
|marx| offers several different source shapes. Tests in this module exercise
those sources (except ``SAOSAC``, which is heavily used in
:ref:`sect-tests.PSF` already).
'''
import shutil
import subprocess
import os
from collections import OrderedDict
from marxtest import base
title = 'Sources in |marx|'
tests = ... |
jdmath_h = os.path.join(marxpath, 'include')
jdmath_a = os.path.join(marxpath, 'lib', 'libjdmath.a')
subprocess.call(['gcc', '-I' + jdmath_h, jdmath_a,
'-shared', 'point.c', '-o', 'point.so'])
@base.Marx
def step_2(self):
'''run USER source'''
... | shutil.copy(os.path.join(src, f),
os.path.join(self.basepath, f)) | conditional_block |
classes-simple.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | cat {
meows: in_x,
how_hungry: in_y
}
}
pub fn main() {
let mut nyan : cat = cat(52u, 99);
let mut kitty = cat(1000u, 2);
assert!((nyan.how_hungry == 99));
assert!((kitty.how_hungry == 2));
} | fn cat(in_x : uint, in_y : int) -> cat { | random_line_split |
classes-simple.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
let mut nyan : cat = cat(52u, 99);
let mut kitty = cat(1000u, 2);
assert!((nyan.how_hungry == 99));
assert!((kitty.how_hungry == 2));
}
| {
cat {
meows: in_x,
how_hungry: in_y
}
} | identifier_body |
classes-simple.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut nyan : cat = cat(52u, 99);
let mut kitty = cat(1000u, 2);
assert!((nyan.how_hungry == 99));
assert!((kitty.how_hungry == 2));
}
| main | identifier_name |
calendar.service.ts | import {Injectable} from '@angular/core';
import {BaThemeConfigProvider} from '../../theme';
@Injectable()
export class CalendarService {
constructor(private _baConfig:BaThemeConfigProvider) { |
let dashboardColors = this._baConfig.get().colors.dashboard;
return {
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2016-03-08',
selectable: true,
selectHelper: true,
editable: true,
eve... | }
getData() { | random_line_split |
calendar.service.ts | import {Injectable} from '@angular/core';
import {BaThemeConfigProvider} from '../../theme';
@Injectable()
export class CalendarService {
| (private _baConfig:BaThemeConfigProvider) {
}
getData() {
let dashboardColors = this._baConfig.get().colors.dashboard;
return {
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2016-03-08',
selectable: ... | constructor | identifier_name |
cyber.py | # ****************************************************************************
# Copyright 2018 The Apollo 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
#
# ht... |
def shutdown():
"""
shutdown cyber envi.
"""
return _CYBER_INIT.py_shutdown()
def is_shutdown():
"""
is cyber shutdown.
"""
return _CYBER_INIT.py_is_shutdown()
def waitforshutdown():
"""
waitforshutdown.
"""
return _CYBER_INIT.py_waitforshutdown()
# //////////////... | """
is cyber envi ok.
"""
return _CYBER_INIT.py_ok() | identifier_body |
cyber.py | # ****************************************************************************
# Copyright 2018 The Apollo 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
#
# ht... | (msg_type, rawmsgdata):
"""
Parse rawmsg from rawmsg data
Input: message type; rawmsg data
Output: a human readable form of this message.for debugging and other purposes.
"""
return _CYBER_NODE.PyChannelUtils_get_debugstring_by_msgtype_rawmsgdata(msg_type, rawmsgdata)
... | get_debugstring_rawmsgdata | identifier_name |
cyber.py | # ****************************************************************************
# Copyright 2018 The Apollo 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
#
# ht... |
class ChannelUtils(object):
@staticmethod
def get_debugstring_rawmsgdata(msg_type, rawmsgdata):
"""
Parse rawmsg from rawmsg data
Input: message type; rawmsg data
Output: a human readable form of this message.for debugging and other purposes.
"""
return _CYBER... | time.sleep(0.002) | conditional_block |
cyber.py | # ****************************************************************************
# Copyright 2018 The Apollo 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
#
# ht... | from google.protobuf.descriptor_pb2 import FileDescriptorProto
PY_CALLBACK_TYPE = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_char_p)
PY_CALLBACK_TYPE_T = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_char_p)
# init vars
CYBER_PATH = os.environ['CYBER_PATH']
CYBER_DIR = os.path.split(CYBER_PATH)[0]
sys.path.append(CYBER_PATH +... | import threading
import ctypes
| random_line_split |
index.ts | /*
MIT License
Copyright (c) 2022 Looker Data Sciences, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modi... | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
export * from './Area' | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | random_line_split |
styles.ts | import styled, { keyframes } from 'styled-components';
// Models
import { IBoxComponentProps } from '../Box/model';
import { IModalComponentProps, IModalContentComponentProps } from './model';
// Components
import { Box } from '../Box/Box';
import variables from '../_utils/globals/variables';
const overlayFadeIn = ... | /* max-height: 100vh; */
height: 100vh;
border-radius: 4px;
display: flex;
flex-direction: column;
z-index: 1400;
color: ${(props) => props.palette?.fontColors.text || variables.fontColors.text};
background: ${(props) => props.palette?.backgroundColors.white || variables.backgroundColors.white};
outline: 0px;
... | width: 100%;
max-width: 100%; | random_line_split |
database.py | # -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table... |
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == w... | self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message')) | random_line_split |
database.py | # -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table... |
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it sim... | self.db.define_table('World', Field('randomNumber', 'integer')) | conditional_block |
database.py | # -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table... | (self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_u... | __init__ | identifier_name |
database.py | # -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table... |
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgett... | return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict() | identifier_body |
kubernetesHelpers.ts | /// <reference path="../../fabric/js/fabricGlobals.ts"/>
/// <reference path="../../baseIncludes.ts"/>
/// <reference path="../../baseHelpers.ts"/>
module Kubernetes {
export var context = '/kubernetes';
export var hash = '#' + context;
export var defaultRoute = hash + '/overview';
export var pluginName = 'Kub... | var answer = "";
angular.forEach(labels, (value, key) => {
var separator = answer ? "," : "";
answer += separator + key + "=" + value;
});
return answer;
}
export function initShared($scope) {
$scope.$on("labelFilterUpdate", ($event, text) => {
var filterText = $scope.tableCon... |
/**
* Returns the labels text string using the <code>key1=value1,key2=value2,....</code> format
*/
export function labelsToString(labels) { | random_line_split |
kubernetesHelpers.ts | /// <reference path="../../fabric/js/fabricGlobals.ts"/>
/// <reference path="../../baseIncludes.ts"/>
/// <reference path="../../baseHelpers.ts"/>
module Kubernetes {
export var context = '/kubernetes';
export var hash = '#' + context;
export var defaultRoute = hash + '/overview';
export var pluginName = 'Kub... |
}
| {
$scope.$on("labelFilterUpdate", ($event, text) => {
var filterText = $scope.tableConfig.filterOptions.filterText;
if (Core.isBlank(filterText)) {
$scope.tableConfig.filterOptions.filterText = text;
} else {
var expressions = filterText.split(/\s+/);
if (expressions.any(te... | identifier_body |
kubernetesHelpers.ts | /// <reference path="../../fabric/js/fabricGlobals.ts"/>
/// <reference path="../../baseIncludes.ts"/>
/// <reference path="../../baseHelpers.ts"/>
module Kubernetes {
export var context = '/kubernetes';
export var hash = '#' + context;
export var defaultRoute = hash + '/overview';
export var pluginName = 'Kub... |
var item = collection.find((item) => { return item.id === id; });
if (item) {
$scope.json = angular.toJson(item, true);
$scope.item = item;
} else {
$scope.id = undefined;
$scope.json = '';
$scope.item = undefined;
}
}
/**
* Returns the labels text string using th... | {
return;
} | conditional_block |
kubernetesHelpers.ts | /// <reference path="../../fabric/js/fabricGlobals.ts"/>
/// <reference path="../../baseIncludes.ts"/>
/// <reference path="../../baseHelpers.ts"/>
module Kubernetes {
export var context = '/kubernetes';
export var hash = '#' + context;
export var defaultRoute = hash + '/overview';
export var pluginName = 'Kub... | ($scope) {
$scope.$on("labelFilterUpdate", ($event, text) => {
var filterText = $scope.tableConfig.filterOptions.filterText;
if (Core.isBlank(filterText)) {
$scope.tableConfig.filterOptions.filterText = text;
} else {
var expressions = filterText.split(/\s+/);
if (expressio... | initShared | identifier_name |
dev.py | from common import *
DEBUG = True
MONGODB_SETTINGS = {
'HOST': '127.0.0.1',
'PORT': 27017,
'DB': 'myhoard_dev',
'USERNAME': 'myhoard',
'PASSWORD': 'myh0@rd',
}
# Logging
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'root': {
'level': 'NOTSET',
'handlers... | 'backupCount': 64,
},
},
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s',
},
},
} | 'level': 'INFO',
'formatter': 'standard',
'filename': '/home/pat/logs/dev/myhoard.log',
'mode': 'a',
'maxBytes': 2 * 1024 * 1024, # 2MiB | random_line_split |
control.py | # -*- coding: utf-8 -*-
'''
Tulip routine libraries, based on lambda's lamlib
Author Twilight0
License summary below, for more details please read license.txt file
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License... |
c, f = query.split('.')
execute('SetFocus(%i)' % (int(c) + 100))
execute('SetFocus(%i)' % (int(f) + 200))
except:
return
def openSettings_alt():
try:
idle()
xbmcaddon.Addon().openSettings()
except:
return
def openPlaylist():
return execute('Ac... | raise Exception() | conditional_block |
control.py | # -*- coding: utf-8 -*-
'''
Tulip routine libraries, based on lambda's lamlib
Author Twilight0
License summary below, for more details please read license.txt file
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License... |
def openSettings(query=None, id=addonInfo('id')):
try:
idle()
execute('Addon.OpenSettings(%s)' % id)
if query is None:
raise Exception()
c, f = query.split('.')
execute('SetFocus(%i)' % (int(c) + 100))
execute('SetFocus(%i)' % (int(f) + 200))
except:... | return dialog.select(heading, list) | identifier_body |
control.py | # -*- coding: utf-8 -*-
'''
Tulip routine libraries, based on lambda's lamlib
Author Twilight0
License summary below, for more details please read license.txt file
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License... | return
def openPlaylist():
return execute('ActivateWindow(VideoPlaylist)')
def refresh():
return execute('Container.Refresh')
def idle():
return execute('Dialog.Close(busydialog)')
def set_view_mode(vmid):
return execute('Container.SetViewMode({0})'.format(vmid)) | try:
idle()
xbmcaddon.Addon().openSettings()
except: | random_line_split |
control.py | # -*- coding: utf-8 -*-
'''
Tulip routine libraries, based on lambda's lamlib
Author Twilight0
License summary below, for more details please read license.txt file
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License... | ():
try:
idle()
xbmcaddon.Addon().openSettings()
except:
return
def openPlaylist():
return execute('ActivateWindow(VideoPlaylist)')
def refresh():
return execute('Container.Refresh')
def idle():
return execute('Dialog.Close(busydialog)')
def set_view_mode(vmid):
r... | openSettings_alt | identifier_name |
temp.provider.spec.ts | /// <reference path="<%= toComponents %>/../../typings/index.d.ts" />
import ngModuleName from './<%= modName %>';
import {<%= upCaseName %>Provider} from './<%= name %>.provider';
import <%= upCaseName %>Service from './<%= name %>.provider';
'use strict';
let $module = angular.mock.module;
let $inject = angular.mo... |
// $log.debug.logs[0] will contain the module initialization logs
let $log;
let provider: <%= upCaseName %>Provider;
let service: <%= upCaseName %>Service;
describe('## Existence of provider', () => {
beforeEach(() => {
$module(ngModuleName, <%= fullName %>Provider => {
provider = <%= ful... | random_line_split | |
boost.py | ##
# Copyright 2009-2016 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | (self, *args, **kwargs):
"""Initialize Boost-specific variables."""
super(EB_Boost, self).__init__(*args, **kwargs)
self.objdir = None
@staticmethod
def extra_options():
"""Add extra easyconfig parameters for Boost."""
extra_vars = {
'boost_mpi': [False, "Bu... | __init__ | identifier_name |
boost.py | ##
# Copyright 2009-2016 Ghent University
#
# This file is part of EasyBuild, | # Flemish Research Foundation (FWO) (http://www.fwo.be/en)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# http://github.com/hpcugent/easybuild
#
# EasyBuild is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Licens... | # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), | random_line_split |
boost.py | ##
# Copyright 2009-2016 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... |
else:
txt = "using mpi : %s ;" % os.getenv("MPICXX")
write_file('user-config.jam', txt, append=True)
def build_step(self):
"""Build Boost with bjam tool."""
bjamoptions = " --prefix=%s" % self.objdir
# specify path for bzip2/zlib if module is loa... | raise EasyBuildError("Bailing out: only PrgEnv-gnu supported for now") | conditional_block |
boost.py | ##
# Copyright 2009-2016 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... |
def make_module_extra(self):
"""Set up a BOOST_ROOT environment variable to e.g. ease Boost handling by cmake"""
txt = super(EB_Boost, self).make_module_extra()
txt += self.module_generator.set_environment('BOOST_ROOT', self.installdir)
return txt
| """Custom sanity check for Boost."""
shlib_ext = get_shared_lib_ext()
custom_paths = {
'files': ['lib/libboost_system.%s' % shlib_ext],
'dirs': ['include/boost']
}
if self.cfg['boost_mpi']:
custom_paths["files"].append('lib/libboost_mpi.%s' % shlib_e... | identifier_body |
multi_vms_file_transfer.py | import time, os, logging
from autotest.client import utils
from autotest.client.shared import error
from virttest import remote, utils_misc
@error.context_aware
def run_multi_vms_file_transfer(test, params, env):
| """
Transfer a file back and forth between multi VMs for long time.
1) Boot up two VMs .
2) Create a large file by dd on host.
3) Copy this file to VM1.
4) Compare copied file's md5 with original file.
5) Copy this file from VM1 to VM2.
6) Compare copied file's md5 with original file.
7... | identifier_body | |
multi_vms_file_transfer.py | import time, os, logging
from autotest.client import utils
from autotest.client.shared import error
from virttest import remote, utils_misc
@error.context_aware
def run_multi_vms_file_transfer(test, params, env):
"""
Transfer a file back and forth between multi VMs for long time.
1) Boot up two VMs .
... | (session, orig_md5):
msg = "Compare copied file's md5 with original file."
error.context(msg, logging.info)
md5_cmd = "md5sum %s | awk '{print $1}'" % guest_path
s, o = session.cmd_status_output(md5_cmd)
if s:
msg = "Fail to get md5 value from guest. Output is %s" % o... | md5_check | identifier_name |
multi_vms_file_transfer.py | import time, os, logging
from autotest.client import utils
from autotest.client.shared import error
from virttest import remote, utils_misc
@error.context_aware
def run_multi_vms_file_transfer(test, params, env):
"""
Transfer a file back and forth between multi VMs for long time.
1) Boot up two VMs .
... |
tmp_dir = params.get("tmp_dir", "/tmp/")
repeat_time = int(params.get("repeat_time", "10"))
clean_cmd = params.get("clean_cmd", "rm -f")
filesize = int(params.get("filesize", 4000))
count = int(filesize / 10)
if count == 0:
count = 1
host_path = os.path.join(tmp_dir, "tmp-%s" %
... | raise error.TestError("Please set file_transfer_port, username,"
" password paramters for guest") | conditional_block |
multi_vms_file_transfer.py | import time, os, logging
from autotest.client import utils
from autotest.client.shared import error
from virttest import remote, utils_misc
@error.context_aware
def run_multi_vms_file_transfer(test, params, env):
"""
Transfer a file back and forth between multi VMs for long time.
1) Boot up two VMs .
... | t_begin = time.time()
remote.scp_between_remotes(src=ip_vm2, dst=ip_vm1, port=port,
s_passwd=password, d_passwd=password,
s_name=username, d_name=username,
s_path=guest_path, d_pa... | random_line_split | |
snap.js | var system = require('system');
var page = require('webpage').create();
var fs = require('fs');
if (system.args.length === 3) {
console.log('Usage: snap.js <some URL> <view port width> <target image name>');
phantom.exit();
}
var url = system.args[1];
var image_name = system.args[3];
var view_port_width = sys... |
// };
// If you want to set a cookie, just add your details below in the following way.
// phantom.addCookie({
// 'name': 'ckns_policy',
// 'value': '111',
// 'domain': '.bbc.co.uk'
// });
// phantom.addCookie({
// 'name': 'locserv',
// 'value': '1#l1#i=6691484:n=Oxford+Circus:h=e@w1#i=8:p=Lond... |
// You can place custom headers here, example below.
// page.customHeaders = {
// 'X-Candy-OVERRIDE': 'https://api.live.bbc.co.uk/' | random_line_split |
snap.js | var system = require('system');
var page = require('webpage').create();
var fs = require('fs');
if (system.args.length === 3) {
console.log('Usage: snap.js <some URL> <view port width> <target image name>');
phantom.exit();
}
var url = system.args[1];
var image_name = system.args[3];
var view_port_width = sys... |
});
| {
console.log('Error with page ' + url);
phantom.exit();
} | conditional_block |
main.rs | use mylib_threadpool::ThreadPool;
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().ta... | (mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
} else if buffer.starts... | handle_connection | identifier_name |
main.rs | use mylib_threadpool::ThreadPool;
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
fn main() |
fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
}... | {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().take(2) {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
println!("Shutting down.");
} | identifier_body |
main.rs | use mylib_threadpool::ThreadPool;
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().ta... | };
let contents = fs::read_to_string(filename).unwrap();
let response = format!("{}{}", status_line, contents);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
} | ("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") | random_line_split |
main.rs | use mylib_threadpool::ThreadPool;
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().ta... | ;
let contents = fs::read_to_string(filename).unwrap();
let response = format!("{}{}", status_line, contents);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
| {
("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
} | conditional_block |
utils.py | """
This file includes commonly used utilities for this app.
"""
from datetime import datetime
today = datetime.now()
year = today.year
month = today.month
day = today.day
# Following are for images upload helper functions. The first two are used for product upload for the front and back.
# The last two are used f... | conditional_block | ||
utils.py | """
This file includes commonly used utilities for this app.
"""
|
today = datetime.now()
year = today.year
month = today.month
day = today.day
# Following are for images upload helper functions. The first two are used for product upload for the front and back.
# The last two are used for design product upload for the front and back.
def front_image(instance, filename):
# file ... | from datetime import datetime
| random_line_split |
utils.py | """
This file includes commonly used utilities for this app.
"""
from datetime import datetime
today = datetime.now()
year = today.year
month = today.month
day = today.day
# Following are for images upload helper functions. The first two are used for product upload for the front and back.
# The last two are used f... | '''
NAME::
fill_category_tree
DESCRIPTION::
一般用来针对带有parent产品分类表字段的进行遍历,并生成树形结构
PARAMETERS::
:param model: 被遍历的model,具有parent属性
:param deep: 本例中,为了明确表示父子的层次关系,用短线---的多少来表示缩进
:param parent_id: 表示从哪个父类开始,=0表示从最顶层开始
:param tree: 要生成的树形tuple
RETURN::
... | identifier_body | |
utils.py | """
This file includes commonly used utilities for this app.
"""
from datetime import datetime
today = datetime.now()
year = today.year
month = today.month
day = today.day
# Following are for images upload helper functions. The first two are used for product upload for the front and back.
# The last two are used f... | (instance, filename):
# file will be uploaded to MEDIA_ROOT/product_imgs/owner_<id>/product_<id>/Y/m/d/front/<filename>
return 'product_imgs/owner_{0}/product_{1}/{2}/{3}/{4}/front/{5}'.format(instance.owner.id, instance.slug, year, month, day, filename)
def back_image(instance, filename):
# file will be u... | front_image | identifier_name |
source.rs | use std::fmt::{self, Debug, Formatter};
use url::Url;
use core::source::{Source, SourceId};
use core::GitReference;
use core::{Dependency, Package, PackageId, Summary};
use util::Config;
use util::errors::CargoResult;
use util::hex::short_hash;
use sources::PathSource;
use sources::git::utils::{GitRemote, GitRevision... | else {
(self.remote.db_at(&db_path)?, actual_rev.unwrap())
};
// Don’t use the full hash,
// to contribute less to reaching the path length limit on Windows:
// https://github.com/servo/servo/pull/14397
let short_id = db.to_short_id(actual_rev.clone()).unwrap();
... | {
self.config.shell().status(
"Updating",
format!("git repository `{}`", self.remote.url()),
)?;
trace!("updating git source `{:?}`", self.remote);
self.remote
.checkout(&db_path, &self.reference, self.config)?
} | conditional_block |
source.rs | use std::fmt::{self, Debug, Formatter};
use url::Url;
use core::source::{Source, SourceId};
use core::GitReference;
use core::{Dependency, Package, PackageId, Summary};
use util::Config;
use util::errors::CargoResult;
use util::hex::short_hash;
use sources::PathSource;
use sources::git::utils::{GitRemote, GitRevision... | url.set_path(&path);
}
// Repos generally can be accessed with or w/o '.git'
let needs_chopping = url.path().ends_with(".git");
if needs_chopping {
let last = {
let last = url.path_segments().unwrap().next_back().unwrap();
last[..last.len() - 4].to_owned()
... | url.set_scheme("https").unwrap();
let path = url.path().to_lowercase(); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.