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 |
|---|---|---|---|---|
holdingpen.controllers.js | /*
* This file is part of INSPIRE.
* Copyright (C) 2016 CERN.
*
* INSPIRE is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* ... | * In applying this license, CERN does not
* waive the privileges and immunities granted to it by virtue of its status
* as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
(function (angular) {
function HoldingPenSelectionCtrl($scope, Hotkeys, HoldingPenRecordService) {
$scope.vm.... | * along with INSPIRE; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
* | random_line_split |
holdingpen.controllers.js | /*
* This file is part of INSPIRE.
* Copyright (C) 2016 CERN.
*
* INSPIRE is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* ... |
function toggleSelection(record) {
var _data_type = record._source._workflow.data_type;
if (isChecked(record._id)) {
$scope.vm.selected_records.splice(getItemIdx(+record._id), 1);
if (_data_type in $scope.vm.selected_record_decisions) {
$scope.vm.selected_record_decisions[_d... | {
return $scope.vm.selected_records.indexOf(+id);
} | identifier_body |
holdingpen.controllers.js | /*
* This file is part of INSPIRE.
* Copyright (C) 2016 CERN.
*
* INSPIRE is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* ... | (id) {
return $scope.vm.selected_records.indexOf(+id);
}
function toggleSelection(record) {
var _data_type = record._source._workflow.data_type;
if (isChecked(record._id)) {
$scope.vm.selected_records.splice(getItemIdx(+record._id), 1);
if (_data_type in $scope.vm.selected_re... | getItemIdx | identifier_name |
holdingpen.controllers.js | /*
* This file is part of INSPIRE.
* Copyright (C) 2016 CERN.
*
* INSPIRE is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* ... |
if(record._source._extra_data === undefined || record._source._extra_data.user_action == undefined)
$scope.vm.selected_record_decisions[record._source._workflow.data_type]
.push(record._id);
}
}
});
}
}
function i... | {
$scope.vm.selected_record_decisions[
record._source._workflow.data_type] = [];
} | conditional_block |
Standby.py | ():
infobar_instance = isInfoBarInstance()
return config.usage.check_timeshift.value and infobar_instance and infobar_instance.timeshiftEnabled() and infobar_instance.timeshift_was_activated
class StandbyScreen(Screen):
def __init__(self, session, StandbyCounterIncrease=True):
self.skinName = "Standby"
Screen.... | checkTimeshiftRunning | identifier_name | |
Standby.py | InfoBarInstance()
from Screens.SleepTimerEdit import isNextWakeupTime
self.StandbyCounterIncrease = StandbyCounterIncrease
self.standbyTimeoutTimer = eTimer()
self.standbyTimeoutTimer.callback.append(self.standbyTimeout)
self.standbyStopServiceTimer = eTimer()
self.standbyStopServiceTimer.callback.append(se... |
if self.session.screen["TunerInfo"].tuner_use_mask or mediafilesInUse(self.session):
self.standbyTimeoutTimer.startLongTimer(600)
else:
RecordTimer.RecordTimerEntry.TryQuitMainloop()
def standbyWakeup(self):
self.Power()
def createSummary(self):
return StandbySummary
class Standby(StandbyScreen):
... | if duration < 0:
duration += 24 * 3600
self.standbyTimeoutTimer.startLongTimer(duration)
return | conditional_block |
Standby.py | InfoBarInstance()
from Screens.SleepTimerEdit import isNextWakeupTime
self.StandbyCounterIncrease = StandbyCounterIncrease
self.standbyTimeoutTimer = eTimer()
self.standbyTimeoutTimer.callback.append(self.standbyTimeout)
self.standbyStopServiceTimer = eTimer()
self.standbyStopServiceTimer.callback.append(se... |
class QuitMainloopScreen(Screen):
def __init__(self, session, retvalue=QUIT_SHUTDOWN):
self.skin = """<screen name="QuitMainloopScreen" position="fill" flags="wfNoBorder">
<ePixmap pixmap="icons/input_info.png" position="c-27,c-60" size="53,53" alphatest="on" />
<widget name="text" position="center,c+5" s... | skin = """
<screen position="0,0" size="132,64">
<widget source="global.CurrentTime" render="Label" position="0,0" size="132,64" font="Regular;40" halign="center">
<convert type="ClockToText" />
</widget>
<widget source="session.RecordState" render="FixedLabel" text=" " position="0,0" size="132,64" zPosition=... | identifier_body |
Standby.py | ().volumeUnMute()
def stopService(self):
self.prev_running_service = self.session.nav.getCurrentlyPlayingServiceOrGroup()
if Components.ParentalControl.parentalControl.isProtected(self.prev_running_service):
self.prev_running_service = eServiceReference(config.tv.lastservice.value)
self.session.nav.stopServi... | config.misc.RestartUI.save()
self.quitMainloop()
else: | random_line_split | |
registry.rs | we want to know
// precisely what the keys of `sources` are, so this is a mapping of key to
// what exactly the key is.
source_ids: HashMap<SourceId, (SourceId, Kind)>,
locked: HashMap<SourceId, HashMap<String, Vec<(PackageId, Vec<PackageId>)>>>,
}
#[derive(PartialEq, Eq, Clone, Copy)]
enum Kind {
... | new | identifier_name | |
registry.rs | dating the
// same git repo twice for example), but we also want to ensure that the
// loaded source is always updated.
//
// Sources with a `precise` field normally don't need to be updated because
// their contents are already on disk, but sources without a `precise` field
// almost always nee... | // Ensure the requested source_id is loaded
try!(self.ensure_loaded(dep.source_id()));
let mut ret = Vec::new();
for (id, src) in self.sources.sources_mut() { | random_line_split | |
registry.rs | !(source.get(package_ids));
ret.extend(packages.into_iter());
}
// TODO: Return earlier if fail
assert!(package_ids.len() == ret.len(),
"could not get packages from registry; ids={:?}; ret={:?}",
package_ids, ret);
Ok(ret)
}
pub fn ... | {
Ok(overrides)
} | conditional_block | |
registry.rs | have a cached `Source` for a
// precise `SourceId`, then when we add a new `SourceId` that is not precise
// we want to ensure that the underlying source is updated.
//
// This is basically a long-winded way of saying that we want to know
// precisely what the keys of `sources` are, so this is a ma... | {
let overrides = try!(self.query_overrides(dep));
let ret = if overrides.len() == 0 {
// Ensure the requested source_id is loaded
try!(self.ensure_loaded(dep.source_id()));
let mut ret = Vec::new();
for (id, src) in self.sources.sources_mut() {
... | identifier_body | |
javascript.js | var | uglify = require('gulp-uglify'),
jc = require('../jcConfig'),
paths = jc.paths;
gulp.task('js-top', function () {
var topJsScripts = [
paths.bower + '/html5shiv/dist/html5shiv.js'
];
return gulp.src(topJsScripts)
.pipe(concat("top.js"))
.pipe(uglify())
.pipe(gulp.dest(paths.assets));
});
... | gulp = require('gulp'),
concat = require('gulp-concat'), | random_line_split |
SimulateP2PNetwork.py | :\n\
\n\
python SimulateP2PNetwork.py 30 randomwalk -o output\n\
This will simulate a network of 30 vertices and use the random walk algorithm, outputs in output.csv\n\
\n\
python SimulateP2PNetwork.py 500 bfs -e 20\n\
This will simulate a network of 500 verticies, using the BFS algorithm, and run a \
new experiment (a... | for currentRun in range(numberOfRuns):
numhops, searchtime = runAlgorithm(network, startHost, endHost)
runtime.append(searchtime)
hops.append(sum(numhops))
averageRunTime = sum(runtime) / len(runtime)
averageHopLength = sum(hops) / len(hops)
# Adds li... | for currentExeriment in range(numberOfExperiments):
startHost, endHost = shuffleHostsOfInterest()
hops = []
runtime = []
spacePerHost = 32 # Estimated 32 bytes of data for the base request. | random_line_split |
SimulateP2PNetwork.py | :\n\
\n\
python SimulateP2PNetwork.py 30 randomwalk -o output\n\
This will simulate a network of 30 vertices and use the random walk algorithm, outputs in output.csv\n\
\n\
python SimulateP2PNetwork.py 500 bfs -e 20\n\
This will simulate a network of 500 verticies, using the BFS algorithm, and run a \
new experiment (a... |
# Shuffles node looking for the file, and node which has the file
def shuffleHostsOfInterest():
startNode = random.randrange(0, numberOfVertices - 1)
endNode = random.randrange(0, numberOfVertices - 1)
if (startNode == endNode):
return shuffleHostsOfInterest()
else:
return startNode,... | edges = random.randrange(numberOfVertices - 1, maxEdges(numberOfVertices))
verts = [x for x in xrange(int(numberOfVertices))]
network = random_connected_graph.random_walk(verts, edges)
network.sort_edges()
# print "Generated network containing:\n\
#%d hosts (vertices)\n\
#%d connections (edges)"... | identifier_body |
SimulateP2PNetwork.py | n\
\n\
python SimulateP2PNetwork.py 30 randomwalk -o output\n\
This will simulate a network of 30 vertices and use the random walk algorithm, outputs in output.csv\n\
\n\
python SimulateP2PNetwork.py 500 bfs -e 20\n\
This will simulate a network of 500 verticies, using the BFS algorithm, and run a \
new experiment (ass... | ():
startNode = random.randrange(0, numberOfVertices - 1)
endNode = random.randrange(0, numberOfVertices - 1)
if (startNode == endNode):
return shuffleHostsOfInterest()
else:
return startNode, endNode
# setup loading bar
print "\n\nRunning Simulations..."
trialRatio = math.ceil(numberOf... | shuffleHostsOfInterest | identifier_name |
SimulateP2PNetwork.py | n\
\n\
python SimulateP2PNetwork.py 30 randomwalk -o output\n\
This will simulate a network of 30 vertices and use the random walk algorithm, outputs in output.csv\n\
\n\
python SimulateP2PNetwork.py 500 bfs -e 20\n\
This will simulate a network of 500 verticies, using the BFS algorithm, and run a \
new experiment (ass... |
finishtime = time.time()*1000
return path, (finishtime - starttime);
if (algorithm == "lazyrandomwalk"):
hops = []
currHost = random.choice(graph.neighborSet[startHost])
start_Per_Host_Computation_Time = time.time()*1000
while (len(hops) <= maxPathLength and currHo... | path = queue.pop(0)
# get the last node from the path
currHost = path[-1]
# path found
if currHost == endHost:
finishtime = time.time()*1000
return path, (finishtime - starttime)
# enumerate all adjacent nodes, construct a new p... | conditional_block |
quick_switcher.py | #-*- coding:utf-8 -*-
"""
This file is part of OpenSesame.
OpenSesame 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.
OpenSesame is distri... |
def event_open_item(self, name):
if self.d is not None:
self.d.bump_item(name)
def init_dialog(self):
"""
desc:
Re-init the dialog.
"""
self.set_busy()
from quick_switcher_dialog.dialog import quick_switcher
self.d = quick_switcher(self.main_window)
self.set_busy(False)
def activate(s... | if self.d is not None:
if self.experiment.items._type(name) == u'inline_script':
self.d.refresh_item(name) | identifier_body |
quick_switcher.py | #-*- coding:utf-8 -*-
"""
This file is part of OpenSesame.
OpenSesame 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.
OpenSesame is distri... | (self):
self.d = None
def event_change_item(self, name):
if self.d is not None:
if self.experiment.items._type(name) == u'inline_script':
self.d.refresh_item(name)
def event_open_item(self, name):
if self.d is not None:
self.d.bump_item(name)
def init_dialog(self):
"""
desc:
Re-init th... | event_regenerate | identifier_name |
quick_switcher.py | #-*- coding:utf-8 -*-
"""
This file is part of OpenSesame.
OpenSesame 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.
OpenSesame is distri... | self.set_busy(False)
def activate(self):
"""
desc:
Pops up the quick-switcher dialog.
"""
if not hasattr(self, u'd') or self.d is None:
self.init_dialog()
self.d.items_list_widget.sortItems()
self.d.exec_() | from quick_switcher_dialog.dialog import quick_switcher
self.d = quick_switcher(self.main_window) | random_line_split |
quick_switcher.py | #-*- coding:utf-8 -*-
"""
This file is part of OpenSesame.
OpenSesame 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.
OpenSesame is distri... |
def event_purge_unused_items(self):
self.d = None
def event_regenerate(self):
self.d = None
def event_change_item(self, name):
if self.d is not None:
if self.experiment.items._type(name) == u'inline_script':
self.d.refresh_item(name)
def event_open_item(self, name):
if self.d is not None:
... | self.d.delete_item(name) | conditional_block |
pep_bookmarks.py | # Copyright (C) 2018 Philipp Hörist <philipp AT hoerist.com>
#
# This file is part of nbxmpp.
#
# 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 opt... | callback=self._process_pubsub_bookmarks,
ns=Namespace.PUBSUB_EVENT,
priority=16),
]
def _process_pubsub_bookmarks(self, _client, stanza, properties):
if not properties.is_pubsub_event:
return
if prope... | BaseModule.__init__(self, client)
self._client = client
self.handlers = [
StanzaHandler(name='message', | random_line_split |
pep_bookmarks.py | # Copyright (C) 2018 Philipp Hörist <philipp AT hoerist.com>
#
# This file is part of nbxmpp.
#
# 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 opt... | self, client):
BaseModule.__init__(self, client)
self._client = client
self.handlers = [
StanzaHandler(name='message',
callback=self._process_pubsub_bookmarks,
ns=Namespace.PUBSUB_EVENT,
priority=16),
... | _init__( | identifier_name |
pep_bookmarks.py | # Copyright (C) 2018 Philipp Hörist <philipp AT hoerist.com>
#
# This file is part of nbxmpp.
#
# 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 opt... |
@iq_request_task
def store_bookmarks(self, bookmarks):
_task = yield
self._log.info('Store Bookmarks')
self.publish(Namespace.BOOKMARKS,
build_storage_node(bookmarks),
id_='current',
options=BOOKMARK_OPTIONS,
... | task = yield
items = yield self.request_items(Namespace.BOOKMARKS, max_items=1)
raise_if_error(items)
if not items:
yield []
bookmarks = parse_bookmarks(items[0], self._log)
for bookmark in bookmarks:
self._log.info(bookmark)
yield bookmarks
| identifier_body |
pep_bookmarks.py | # Copyright (C) 2018 Philipp Hörist <philipp AT hoerist.com>
#
# This file is part of nbxmpp.
#
# 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 opt... |
properties.pubsub_event = pubsub_event
@iq_request_task
def request_bookmarks(self):
_task = yield
items = yield self.request_items(Namespace.BOOKMARKS, max_items=1)
raise_if_error(items)
if not items:
yield []
bookmarks = parse_bookmarks(items[0]... | elf._log.info(bookmark)
| conditional_block |
test_flipud.py | import unittest
import numpy | from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
@testing.parameterize(*testing.product({
'shape': [(3,), (3, 4)],
'dtype': [numpy.float16, numpy.float32, numpy.float64],
}))
class TestFlipUD(unittest.TestCase):
def setUp(self):
self.x = numpy.random... |
import chainer
from chainer.backends import cuda
from chainer import functions | random_line_split |
test_flipud.py | import unittest
import numpy
import chainer
from chainer.backends import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
@testing.parameterize(*testing.product({
'shape': [(3,), (3, 4)],
'dtype': [numpy.float16, numpy.float32... |
@attr.gpu
def test_double_backward_gpu(self):
self.check_double_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy),
cuda.to_gpu(self.ggx))
testing.run_module(__name__, __file__)
| self.check_double_backward(self.x, self.gy, self.ggx) | identifier_body |
test_flipud.py | import unittest
import numpy
import chainer
from chainer.backends import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
@testing.parameterize(*testing.product({
'shape': [(3,), (3, 4)],
'dtype': [numpy.float16, numpy.float32... | (self):
self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy))
def check_double_backward(self, x_data, y_grad, x_grad_grad):
gradient_check.check_double_backward(
functions.flipud, x_data, y_grad, x_grad_grad, dtype=numpy.float64,
atol=5e-4, rtol=5e-3)
def test_... | test_backward_gpu | identifier_name |
loadData.js | const loadData = require('../loadData')
jest.mock('fs-extra')
jest.mock('../../utils/get-closest-config', () => require('../../../mocks/get-closest-config'))
describe('load Plugins', () => {
it('should save property into context', async () => {
const result = await loadData({
data: '',
site: {},
... | expect(error.message).toBe('should pass a object to load.')
}
})
it('throws if context.src is not passed as a string', async () => {
try {
await loadData({
site: {},
})
} catch (error) {
expect(error.message).toBe('context.src must be a string.')
}
})
it('throws... | it('throws if context is not passed as an object', async () => {
try {
await loadData()
} catch (error) { | random_line_split |
App.js | import React, { Component } from 'react';
import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';
import {
Collapse,
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
NavItem,
NavLink,
Container,
Row,
Col,
Jumbotron,
Button
} from 'reactstrap';
class App extends Component... |
render() {
return (
<div>
<Navbar color="inverse" light expand="md">
<NavbarBrand href="/">reactstrap</NavbarBrand>
<NavbarToggler onClick={this.toggle} />
<Collapse isOpen={this.state.isOpen} navbar>
<Nav class... | {
this.setState({
isOpen: !this.state.isOpen
});
} | identifier_body |
App.js | import React, { Component } from 'react';
import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';
import {
Collapse,
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
NavItem,
NavLink,
Container,
Row,
Col,
Jumbotron,
Button
} from 'reactstrap';
class App extends Component... | <Navbar color="inverse" light expand="md">
<NavbarBrand href="/">reactstrap</NavbarBrand>
<NavbarToggler onClick={this.toggle} />
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="ml-auto" navbar>
... | return (
<div> | random_line_split |
App.js | import React, { Component } from 'react';
import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';
import {
Collapse,
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
NavItem,
NavLink,
Container,
Row,
Col,
Jumbotron,
Button
} from 'reactstrap';
class App extends Component... |
console.log(response)
return response.json();
})
.then(json => {
this.setState({
message: json.message,
fetching: false
});
}).catch(e => {
this.setState({
message: `API call failed: ${e}`,
fetching: false
});
... | {
throw new Error(`status ${response.status}`);
} | conditional_block |
App.js | import React, { Component } from 'react';
import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';
import {
Collapse,
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
NavItem,
NavLink,
Container,
Row,
Col,
Jumbotron,
Button
} from 'reactstrap';
class App extends Component... | () {
fetch('/api')
.then(response => {
if (!response.ok) {
throw new Error(`status ${response.status}`);
}
console.log(response)
return response.json();
})
.then(json => {
this.setState({
message: json.message,
fetching: false
... | componentDidMount | identifier_name |
urls.py | """finman URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns | conditional_block | |
urls.py | """finman URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth.views ... | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') | random_line_split |
accept.rs | // error-pattern:Worked!
extern crate nemo;
use nemo::*;
use nemo::session_types::*;
use nemo::peano::*;
fn main() {
use nemo::channels::Blocking;
struct MyProtocol;
type SendString = Send<String, End>;
type SendUsize = Send<usize, End>;
type SendIsize = Send<isize, End>;
type Orig = Choose<... |
}
impl<I: Transfers<String> + Transfers<usize> + Transfers<isize>, E: SessionType> Handler<I, E, DualSendString> for MyProtocol {
fn with(_: Channel<Self, I, E, DualSendString>) -> Defer<Self, I> {
panic!("fail")
}
}
impl<I: Transfers<String> + Transfers<usize> + Transfers... | {
this.accept().ok().unwrap()
} | identifier_body |
accept.rs | // error-pattern:Worked!
extern crate nemo;
use nemo::*;
use nemo::session_types::*;
use nemo::peano::*;
fn | () {
use nemo::channels::Blocking;
struct MyProtocol;
type SendString = Send<String, End>;
type SendUsize = Send<usize, End>;
type SendIsize = Send<isize, End>;
type Orig = Choose<SendString, Choose<SendUsize, Finally<SendIsize>>>;
type DualSendString = Recv<String, End>;
type DualSen... | main | identifier_name |
accept.rs | // error-pattern:Worked!
extern crate nemo;
use nemo::*; | fn main() {
use nemo::channels::Blocking;
struct MyProtocol;
type SendString = Send<String, End>;
type SendUsize = Send<usize, End>;
type SendIsize = Send<isize, End>;
type Orig = Choose<SendString, Choose<SendUsize, Finally<SendIsize>>>;
type DualSendString = Recv<String, End>;
type ... | use nemo::session_types::*;
use nemo::peano::*;
| random_line_split |
accept.rs | // error-pattern:Worked!
extern crate nemo;
use nemo::*;
use nemo::session_types::*;
use nemo::peano::*;
fn main() {
use nemo::channels::Blocking;
struct MyProtocol;
type SendString = Send<String, End>;
type SendUsize = Send<usize, End>;
type SendIsize = Send<isize, End>;
type Orig = Choose<... |
}
}
}
let (client1, client2) = Blocking::new::<MyProtocol>(MyProtocol, MyProtocol);
let mut client1 = client1.defer();
let mut client2 = client2.defer();
assert_eq!(false, client1.with()); // client1 chooses a protocol, sends 10, closes channel
assert_eq!(true, client... | {
panic!("fail")
} | conditional_block |
fast_thread_local.rs | // Copyright 2016 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 ... | (mut ptr: *mut u8) {
while !ptr.is_null() {
let list: Box<List> = Box::from_raw(ptr as *mut List);
for (ptr, dtor) in list.into_iter() {
dtor(ptr);
}
ptr = DTORS.get();
DTORS.set(ptr::null_mut());
}
}
}
pub unsafe extern fn... | run_dtors | identifier_name |
fast_thread_local.rs | // Copyright 2016 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 requires_move_before_drop() -> bool {
false
}
| {
ptr::drop_in_place((*ptr).inner.get());
} | conditional_block |
fast_thread_local.rs | // Copyright 2016 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 unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
// The fallback implementation uses a vanilla OS-based TLS key to track
// the list of destructors that need to be run for this thread. The key
// then has its own destructor which runs all the other destructors.
//
// Th... | {
if !mem::needs_drop::<T>() || self.dtor_registered.get() {
return
}
register_dtor(self as *const _ as *mut u8,
destroy_value::<T>);
self.dtor_registered.set(true);
} | identifier_body |
fast_thread_local.rs | // 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 http://opensource.org/licenses/MIT>, at your
// option. This file... | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT | random_line_split | |
exercice1.py | #Initialisation
from time import sleep
from NaoCommunication import *
nao=NaoControle(Nao())
# 1 - Decrire le resultat de ce morceau de code
# ...
for a in range(16):
if a%2==0:
nao.reglerCouleur(a,a*15,50,50)
else :
nao.reglerCouleur(a,255,0,0)
sleep(0.1)
for a in range(15,-1,-1):
nao.eteind... |
for a in range(0,16,1):
nao.eteindreLed(a)
sleep(0.1)
# 3 - A partir des exemples precedents, ecrire un code qui
# allume alternativement les deux leds 1 seconde chacune
# pendant 10 secondes.
| nao.allumerLed(a)
sleep(0.1) | conditional_block |
exercice1.py | #Initialisation
from time import sleep
from NaoCommunication import *
nao=NaoControle(Nao())
# 1 - Decrire le resultat de ce morceau de code
# ...
for a in range(16):
if a%2==0:
nao.reglerCouleur(a,a*15,50,50)
else :
nao.reglerCouleur(a,255,0,0)
sleep(0.1)
for a in range(15,-1,-1):
nao.eteind... | for a in range(15,-1,-1):
nao.allumerLed(a)
sleep(0.1)
for a in range(0,16,1):
nao.eteindreLed(a)
sleep(0.1)
# 3 - A partir des exemples precedents, ecrire un code qui
# allume alternativement les deux leds 1 seconde chacune
# pendant 10 secondes. | # ... | random_line_split |
upload.js | //Settings
actype = ['image/png','image/jpeg','image/jpg','image/gif']; /* Accepted mime type */
maxweight = 819200; /* Max file size in octets */
maxwidth = 150; /* Max width of the image */
maxheight = 150; /* Max height*/
//Caching variable selector
ish = $('.ish'); /* On attach element hide or show */
msgUp = $('.... | $(document).off('click', '#filesend');
$(document).on('click', '#filesend', function(e) {
//Cancel the default execution if img ready to be send to php
if($(this).hasClass('lock'))
e.preventDefault();
});
//On reset
$(document).off('click', '#reset');
$(document).on('click', '#reset', function(e) {
//Cancel ... |
//input file prevent on lock | random_line_split |
upload.js | //Settings
actype = ['image/png','image/jpeg','image/jpg','image/gif']; /* Accepted mime type */
maxweight = 819200; /* Max file size in octets */
maxwidth = 150; /* Max width of the image */
maxheight = 150; /* Max height*/
//Caching variable selector
ish = $('.ish'); /* On attach element hide or show */
msgUp = $('.... |
//Set src / preview
fileprev.attr('src', filer.result);
//Make new Image for get the width / height
var image = new Image();
image.src = filer.result;
image.onload = function() {
//Set width / height
aWidth = image.width;
aHeight = image.height;
//Check width
if(aWi... | {
msgUp.text('File type not allowed');
return;
} | conditional_block |
headers.ts | import {BaseException} from '../src/facade/exceptions';
import {isBlank} from '../src/facade/lang';
import {isListLikeIterable, iterateListLike, Map, MapWrapper, StringMapWrapper, ListWrapper,} from '../src/facade/collection';
/**
* Polyfill for [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers/Head... |
/**
* Deletes all header values for the given name.
*/
delete (name: string): void { this._headersMap.delete(name); }
forEach(fn: (values: string[], name: string, headers: Map<string, string[]>) => void): void {
this._headersMap.forEach(fn);
}
/**
* Returns first header that matches given nam... | {
var mapName = this._headersMap.get(name);
var list = isListLikeIterable(mapName) ? mapName : [];
list.push(value);
this._headersMap.set(name, list);
} | identifier_body |
headers.ts | import {BaseException} from '../src/facade/exceptions';
import {isBlank} from '../src/facade/lang';
import {isListLikeIterable, iterateListLike, Map, MapWrapper, StringMapWrapper, ListWrapper,} from '../src/facade/collection';
/**
* Polyfill for [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers/Head... | if (headers instanceof Headers) {
this._headersMap = (<Headers>headers)._headersMap;
return;
}
this._headersMap = new Map<string, string[]>();
if (isBlank(headers)) {
return;
}
// headers instanceof StringMap
StringMapWrapper.forEach(headers, (v: any, k: string) => {
... | export class Headers {
/** @internal */
_headersMap: Map<string, string[]>;
constructor(headers?: Headers|{[key: string]: any}) { | random_line_split |
headers.ts | import {BaseException} from '../src/facade/exceptions';
import {isBlank} from '../src/facade/lang';
import {isListLikeIterable, iterateListLike, Map, MapWrapper, StringMapWrapper, ListWrapper,} from '../src/facade/collection';
/**
* Polyfill for [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers/Head... | (headers?: Headers|{[key: string]: any}) {
if (headers instanceof Headers) {
this._headersMap = (<Headers>headers)._headersMap;
return;
}
this._headersMap = new Map<string, string[]>();
if (isBlank(headers)) {
return;
}
// headers instanceof StringMap
StringMapWrapper.fo... | constructor | identifier_name |
headers.ts | import {BaseException} from '../src/facade/exceptions';
import {isBlank} from '../src/facade/lang';
import {isListLikeIterable, iterateListLike, Map, MapWrapper, StringMapWrapper, ListWrapper,} from '../src/facade/collection';
/**
* Polyfill for [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers/Head... | else {
list.push(<string>value);
}
this._headersMap.set(header, list);
}
/**
* Returns values of all headers.
*/
values(): string[][] { return MapWrapper.values(this._headersMap); }
/**
* Returns string of all headers.
*/
toJSON(): {[key: string]: any} {
let serializableHeade... | {
var pushValue = (<string[]>value).join(',');
list.push(pushValue);
} | conditional_block |
main.py | Fedora/RH, so make it an error everywhere so it will
# be noticed:
import warnings
warnings.filterwarnings("error", "could not open display")
def main(script_file, cmdline):
#################################################################
## NOTE NOTE NOTE
##
## If you modify anything her... |
def parse_display_name(parser, opts, display_name):
if display_name.startswith("ssh:"):
desc = {
"type": "ssh",
"local": False
}
sshspec = display_name[len("ssh:"):]
if ":" in sshspec:
(desc["host"], desc["display"]) = sshspec.split(":", 1)
... | parser.error("invalid mode '%s'" % mode) | conditional_block |
main.py | Fedora/RH, so make it an error everywhere so it will
# be noticed:
import warnings
warnings.filterwarnings("error", "could not open display")
def main(script_file, cmdline):
#################################################################
## NOTE NOTE NOTE
##
## If you modify anything her... | (parser, opts, display_name):
if display_name.startswith("ssh:"):
desc = {
"type": "ssh",
"local": False
}
sshspec = display_name[len("ssh:"):]
if ":" in sshspec:
(desc["host"], desc["display"]) = sshspec.split(":", 1)
desc["display... | parse_display_name | identifier_name |
main.py | Fedora/RH, so make it an error everywhere so it will
# be noticed:
import warnings
warnings.filterwarnings("error", "could not open display")
def main(script_file, cmdline):
#################################################################
## NOTE NOTE NOTE
##
## If you modify anything her... |
def connect_or_fail(display_desc):
if display_desc["type"] == "ssh":
cmd = (display_desc["full_remote_xpra"]
+ ["_proxy"] + display_desc["display_as_args"])
try:
child = Popen(cmd, stdin=PIPE, stdout=PIPE)
except OSError, e:
sys.exit("Error running ss... | try:
sock.connect(target)
except socket.error, e:
sys.exit("Connection failed: %s" % (e,))
return SocketConnection(sock) | identifier_body |
main.py | Fedora/RH, so make it an error everywhere so it will
# be noticed:
import warnings
warnings.filterwarnings("error", "could not open display")
def main(script_file, cmdline):
#################################################################
## NOTE NOTE NOTE
##
## If you modify anything her... | "Perhaps try using something like 'ssh:USER@host:display'?\n")
sys.stdout.flush()
def run_client(parser, opts, extra_args):
from xpra.client import XpraClient
conn = connect_or_fail(pick_display(parser, opts, extra_args))
if opts.compression_level < 0 or opts.compression_le... | sys.stdout.write("Your ssh program appears to be asking for a username.\n" | random_line_split |
app.js | // Perform a request against the simplepushclient server
var doRequest = function doPost(type, uri, data, cb) {
var xhr = new XMLHttpRequest({mozSystem: true});
xhr.onload = function onLoad(evt) {
if (xhr.status === 200 || xhr.status === 0) {
cb(null, xhr.response);
} else {
cb(xhr.status);
... | window.PushHelper.debug = true;
window.PushHelper.listen('messages',
function(version, endPoint, callback) {
doRequest('GET', 'http://simplepushclient.eu01.aws.af.cm/api/v1/' +
version + '?client=' + endPoint, null,
function(err, data) {
if (err) {
alert('Cannot get message with ve... | random_line_split | |
app.js | // Perform a request against the simplepushclient server
var doRequest = function doPost(type, uri, data, cb) {
var xhr = new XMLHttpRequest({mozSystem: true});
xhr.onload = function onLoad(evt) {
if (xhr.status === 200 || xhr.status === 0) {
cb(null, xhr.response);
} else {
cb(xhr.status);
... |
});
});
window.PushHelper.init();
| {
alert('Register to receive push notifications');
} | conditional_block |
it.js | /**
* IT lang variables
*
* Author : Luciano Vernaschi <luciano@virgilio.it>
* Last Updated : Oct. 17th, 2006
* TinyMCE Version : 2.0.7
*/
tinyMCE.addToLang('',{
bold_desc : 'Grassetto (Ctrl+B)',
italic_desc : 'Corsivo (Ctrl+I)',
underline_desc : 'Sottolineato (Ctrl+U)',
striketrough_desc : 'Barrato',
justifyle... | cleanup_desc : 'Pulisci il codice HTML',
focus_alert : 'Fare clic su un\' istanza dell\'editor prima di eseguire questo comando',
edit_confirm : 'Vuoi usare l\'editor visuale in quest\'area di testo?',
insert_link_title : 'Inserisci o modifica link',
insert : 'Inserisci',
update : 'Modifica',
cancel : 'Annulla',
insert... | link_desc : 'Inserisci o modifica link',
unlink_desc : 'Elimina link',
image_desc : 'Inserisci o modifica immagine', | random_line_split |
build.js | const fs = require('fs')
const Log = require('log')
const browserify = require('browserify')
const babelify = require('babelify')
const errorify = require('errorify')
const cssNext = require('postcss-cssnext')
const cssModulesify = require('css-modulesify')
const exec = require('child_process').exec
const log = new Lo... | () {
b.bundle().pipe(fs.createWriteStream(`${outFile}.js`))
}
b.on('log', message => log.info(message))
b.on('error', message => log.error(message))
bundle()
})
})
| bundle | identifier_name |
build.js | const fs = require('fs')
const Log = require('log')
const browserify = require('browserify')
const babelify = require('babelify')
const errorify = require('errorify')
const cssNext = require('postcss-cssnext')
const cssModulesify = require('css-modulesify')
const exec = require('child_process').exec
const log = new Lo... |
})
files.forEach(file => {
const inFile = `${srcFolder}/${file}`
const outFile = `${buildFolder}/${fileMap[file]}`
const b = browserify({
entries: [inFile],
plugin: [
errorify
],
transform: [
[ babelify, {
presets: [
'es2015',
'... | {
throw error
} | conditional_block |
build.js | const fs = require('fs')
const Log = require('log')
const browserify = require('browserify')
const babelify = require('babelify')
const errorify = require('errorify')
const cssNext = require('postcss-cssnext')
const cssModulesify = require('css-modulesify')
const exec = require('child_process').exec
const log = new Lo... |
b.on('log', message => log.info(message))
b.on('error', message => log.error(message))
bundle()
})
})
| {
b.bundle().pipe(fs.createWriteStream(`${outFile}.js`))
} | identifier_body |
build.js | const fs = require('fs')
const Log = require('log')
const browserify = require('browserify') | const exec = require('child_process').exec
const log = new Log('info')
const fileMap = {
'index.js': 'main'
}
const files = Object.keys(fileMap)
const srcFolder = `${__dirname}/../demo`
const buildFolder = `${__dirname}/../docs`
const outFiles = files.map(file => {
return `${buildFolder}/${fileMap[file]}.js ${bu... | const babelify = require('babelify')
const errorify = require('errorify')
const cssNext = require('postcss-cssnext')
const cssModulesify = require('css-modulesify') | random_line_split |
admin.py | from django.contrib import admin
from modeltranslation.admin import TabbedTranslationAdmin
from .models import Person, Office, Tag
class PersonAdmin(TabbedTranslationAdmin):
list_display = ('name', 'surname', 'security_level', 'gender')
list_filter = ('security_level', 'tags', 'office', 'name', 'gender')
... |
copy_100.short_description = 'Copy 100 objects with random data'
class PersonStackedInline(admin.TabularInline):
model = Person
extra = 0
class OfficeAdmin(admin.ModelAdmin):
inlines = (PersonStackedInline,)
list_display = ('office', 'address')
class TagAdmin(admin.ModelAdmin):
list_displ... | item.populate() | conditional_block |
admin.py | from django.contrib import admin
from modeltranslation.admin import TabbedTranslationAdmin
from .models import Person, Office, Tag |
class PersonAdmin(TabbedTranslationAdmin):
list_display = ('name', 'surname', 'security_level', 'gender')
list_filter = ('security_level', 'tags', 'office', 'name', 'gender')
actions = ['copy_100']
def copy_100(self, request, queryset):
for item in queryset.all():
item.populate()... | random_line_split | |
admin.py | from django.contrib import admin
from modeltranslation.admin import TabbedTranslationAdmin
from .models import Person, Office, Tag
class PersonAdmin(TabbedTranslationAdmin):
list_display = ('name', 'surname', 'security_level', 'gender')
list_filter = ('security_level', 'tags', 'office', 'name', 'gender')
... | (admin.ModelAdmin):
inlines = (PersonStackedInline,)
list_display = ('office', 'address')
class TagAdmin(admin.ModelAdmin):
list_display = ('name',)
admin.site.register(Person, PersonAdmin)
admin.site.register(Office, OfficeAdmin)
admin.site.register(Tag, TagAdmin)
| OfficeAdmin | identifier_name |
admin.py | from django.contrib import admin
from modeltranslation.admin import TabbedTranslationAdmin
from .models import Person, Office, Tag
class PersonAdmin(TabbedTranslationAdmin):
|
class PersonStackedInline(admin.TabularInline):
model = Person
extra = 0
class OfficeAdmin(admin.ModelAdmin):
inlines = (PersonStackedInline,)
list_display = ('office', 'address')
class TagAdmin(admin.ModelAdmin):
list_display = ('name',)
admin.site.register(Person, PersonAdmin)
admin.site.... | list_display = ('name', 'surname', 'security_level', 'gender')
list_filter = ('security_level', 'tags', 'office', 'name', 'gender')
actions = ['copy_100']
def copy_100(self, request, queryset):
for item in queryset.all():
item.populate()
copy_100.short_description = 'Copy 100 objec... | identifier_body |
word_splitters.rs | /// #[cfg(feature = "hyphenation")] {
/// use hyphenation::{Language, Load, Standard};
/// use textwrap::{wrap, Options, WordSplitter};
///
/// let text = "Oxidation is the loss of electrons.";
/// let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
/// let options = Options::new... | (&self, word: &str) -> Vec<usize> {
match self {
WordSplitter::NoHyphenation => Vec::new(),
WordSplitter::HyphenSplitter => {
let mut splits = Vec::new();
for (idx, _) in word.match_indices('-') {
// We only use hyphens that are surrou... | split_points | identifier_name |
word_splitters.rs | #[cfg(feature = "hyphenation")] {
/// use hyphenation::{Language, Load, Standard};
/// use textwrap::{wrap, Options, WordSplitter};
///
/// let text = "Oxidation is the loss of electrons.";
/// let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
/// let options = Options::new(8)... | {
assert_iter_eq!(
split_words(vec![Word::from("foo-bar")], &WordSplitter::HyphenSplitter),
vec![Word::from("foo-"), Word::from("bar")]
);
} | identifier_body | |
word_splitters.rs | /// #[cfg(feature = "hyphenation")] {
/// use hyphenation::{Language, Load, Standard};
/// use textwrap::{wrap, Options, WordSplitter};
///
/// let text = "Oxidation is the loss of electrons.";
/// let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
/// let options = Options::new... |
#[test]
fn split_words_no_words() {
assert_iter_eq!(split_words(vec![], &WordSplitter::HyphenSplitter), vec![]);
}
#[test]
fn split_words_empty_word() {
assert_iter_eq!(
split_words(vec![Word::from(" ")], &WordSplitter::HyphenSplitter),
vec![Word::from(" ... | ($left:expr, $right:expr) => {
assert_eq!($left.collect::<Vec<_>>(), $right);
};
} | random_line_split |
Line.tsx | import * as React from 'react';
import { Shape } from '@visx/visx';
import { ScaleTime } from 'd3-scale';
import { pick } from 'ramda';
import { useAtomValue } from 'jotai/utils';
import makeStyles from '@mui/styles/makeStyles';
import { useLocaleDateTimeFormat, useMemoComponent } from '@centreon/ui';
import {
an... | annotation,
color,
}),
}}
width={iconSize}
/>
);
return useMemoComponent({
Component: (
<Annotation
header={header}
icon={icon}
marker={line}
xIcon={xIcon + xIconMargin}
{...props}
/>
),
memoProps: [annotati... | height={iconSize}
style={{
color: getIconColor({ | random_line_split |
resources.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::env;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use std::sync::{Once, ONCE_INIT, RwLoc... |
pub fn register_resources_for_tests() {
INIT.call_once(|| {
struct ResourceReader;
impl ResourceReaderMethods for ResourceReader {
fn sandbox_access_files(&self) -> Vec<PathBuf> { vec![] }
fn sandbox_access_files_dirs(&self) -> Vec<PathBuf> { vec![] }
fn read(&se... | }
static INIT: Once = ONCE_INIT; | random_line_split |
resources.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::env;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use std::sync::{Once, ONCE_INIT, RwLoc... | break;
}
path.pop();
}
path.push(file);
let mut buffer = vec![];
File::open(path).expect(&format!("Can't find file: {}", file))
.read_to_end(&mut buffer).expect... | {
let file = match file {
Resource::Preferences => "prefs.json",
Resource::BluetoothBlocklist => "gatt_blocklist.txt",
Resource::DomainList => "public_domains.txt",
Resource::HstsPreloadList => "hsts_preload.json",
... | identifier_body |
resources.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::env;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use std::sync::{Once, ONCE_INIT, RwLoc... | (res: Resource) -> Vec<u8> {
RES.read().unwrap().as_ref().expect("Resource reader not set.").read(res)
}
pub fn read_string(res: Resource) -> String {
String::from_utf8(read_bytes(res)).unwrap()
}
pub fn sandbox_access_files() -> Vec<PathBuf> {
RES.read().unwrap().as_ref().expect("Resource reader not set.... | read_bytes | identifier_name |
main.rs | // @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/pasteur
//
// This file may not be copied, modified, or distributed
// except according to those terms.
#[macro_use]
extern crate clap;
extern crate pasteur;
/// Default* cons... | {
let yaml = load_yaml!("cli.yml");
let options = clap::App::from_yaml(yaml).get_matches();
pasteur::new (
options.value_of("template").unwrap_or(DEFAULT_TEMPLATE),
options.value_of("locale").unwrap_or(DEFAULT_LOCALE),
options.value_of("style").unwrap_or(DEFAULT_STYLE),
opti... | identifier_body | |
main.rs | // @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/pasteur
//
// This file may not be copied, modified, or distributed
// except according to those terms.
#[macro_use]
extern crate clap;
extern crate pasteur;
/// Default* cons... | () {
let yaml = load_yaml!("cli.yml");
let options = clap::App::from_yaml(yaml).get_matches();
pasteur::new (
options.value_of("template").unwrap_or(DEFAULT_TEMPLATE),
options.value_of("locale").unwrap_or(DEFAULT_LOCALE),
options.value_of("style").unwrap_or(DEFAULT_STYLE),
... | main | identifier_name |
main.rs | // @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/pasteur
//
// This file may not be copied, modified, or distributed
// except according to those terms.
| extern crate pasteur;
/// Default* const arguments defined by CLI.
const DEFAULT_TEMPLATE: &'static str = "etc/templates";
const DEFAULT_LOCALE: &'static str = "etc/locales";
const DEFAULT_STYLE: &'static str = "etc/stylesheets";
const DEFAULT_CERT: &'static str = "etc/ca/cert.pem";
const DEFAULT_KEY: &'static str = ... | #[macro_use]
extern crate clap; | random_line_split |
test04-out-ds.js | var $M = require("@effectful/debugger"),
$x = $M.context,
$ret = $M.ret,
$unhandled = $M.unhandled,
$brk = $M.brk,
$lset = $M.lset,
$mcall = $M.mcall,
$m = $M.module("file.js", null, typeof module === "undefined" ? null : module, null, "$", {
__webpack_require__: typeof __webpack_require__... |
case 2:
$l[1] = $p;
$.goto = 3;
$p = ($x.call = eff)(2);
$.state = 3;
case 3:
$.goto = 4;
$mcall("log", console, $l[1] + $p);
$.state = 4;
case 4:
$.goto = 6;
$brk();
continue;
case 5:
$.goto = 6;
return $unhandled($.error);
... | case 1:
$.goto = 2;
$p = ($x.call = eff)(1);
$.state = 2; | random_line_split |
swagger-oauth.js | Dialog = $(
[
'<div class="api-popup-dialog">',
'<div class="api-popup-title">Select OAuth2.0 Scopes</div>',
'<div class="api-popup-content">',
'<p>Scopes are used to grant an application different levels of access to data on behalf of the end user. Each API may declare one or more scopes.... | checkbox.each(function(pos){
checkbox[pos].checked = false;
});
alert(token.error);
} | random_line_split | |
swagger-oauth.js | key});
}
}
}
}
}
if(window.swaggerUi.api
&& window.swaggerUi.api.info) {
appName = window.swaggerUi.api.info.title;
}
$('.api-popup-dialog').remove();
popupDialog = $(
[
'<div class="api-popup-dialog">',
'<div class="api-popup-title">Select OAuth2.0 Scop... |
function initOAuth(opts) {
var o = (opts||{});
var errors = [];
appName = (o.appName||errors.push('missing appName'));
popupMask = (o.popupMask||$('#api-common-mask'));
popupDialog = (o.popupDialog||$('.api-popup-dialog'));
clientId = (o.clientId||errors.push('missing client id'));
clientSecret = (o.cl... | {
for(key in window.swaggerUi.api.clientAuthorizations.authz){
window.swaggerUi.api.clientAuthorizations.remove(key)
}
window.enabledScopes = null;
$('.api-ic.ic-on').addClass('ic-off');
$('.api-ic.ic-on').removeClass('ic-on');
// set the info box
$('.api-ic.ic-warning').addClass('ic-error');
$('.a... | identifier_body |
swagger-oauth.js | key});
}
}
}
}
}
if(window.swaggerUi.api
&& window.swaggerUi.api.info) {
appName = window.swaggerUi.api.info.title;
}
$('.api-popup-dialog').remove();
popupDialog = $(
[
'<div class="api-popup-dialog">',
'<div class="api-popup-title">Select OAuth2.0 Scop... | (scopes, tokenUrl, OAuthSchemeKey) {
var params = {
'client_id': clientId,
'client_secret': clientSecret,
'scope': scopes.join(' '),
'grant_type': 'client_credentials'
}
$.ajax(
{
url : tokenUrl,
type: "POST",
data: params,
success:function(data, textStatu... | clientCredentialsFlow | identifier_name |
form_based_credentials_backend_unittest_base.py | # Copyright (c) 2013 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 logging
import os
import unittest
from telemetry.core import browser_finder
from telemetry.unittest import simple_mock
from telemetry.unittest imp... |
def VerifySubmit(js):
assert '.submit' in js
tab.ExpectCall('ExecuteJavaScript', _).WhenCalled(VerifySubmit)
# Checking for form still up.
tab.ExpectCall('EvaluateJavaScript', _).WillReturn(False)
backend.LoginNeeded(tab, config)
| tab = simple_mock.MockObject()
config = {'username': 'blah',
'password': 'blargh'}
tab.ExpectCall('Navigate', login_page_url)
tab.ExpectCall('EvaluateJavaScript', _).WillReturn(False)
tab.ExpectCall('EvaluateJavaScript', _).WillReturn(True)
tab.ExpectCall('EvaluateJavaScript', _).Wil... | identifier_body |
form_based_credentials_backend_unittest_base.py | # Copyright (c) 2013 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 logging
import os
import unittest
from telemetry.core import browser_finder
from telemetry.unittest import simple_mock
from telemetry.unittest imp... |
options = options_for_unittests.GetCopy()
# Login once to make sure our default profile is logged in.
with browser_finder.FindBrowser(options).Create() as b:
b.credentials.credentials_path = credentials_path
if not b.credentials.CanLogin(self._credentials_type):
return
tab = b... | logging.warning('Credentials file not found, skipping test.')
return | conditional_block |
form_based_credentials_backend_unittest_base.py | # Copyright (c) 2013 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 logging
import os
import unittest
from telemetry.core import browser_finder
from telemetry.unittest import simple_mock
from telemetry.unittest imp... | (self):
credentials_path = _GetCredentialsPath()
if not credentials_path:
logging.warning('Credentials file not found, skipping test.')
return
options = options_for_unittests.GetCopy()
with browser_finder.FindBrowser(options).Create() as b:
b.credentials.credentials_path = credentials... | testRealLoginIfPossible | identifier_name |
form_based_credentials_backend_unittest_base.py | # Copyright (c) 2013 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 logging
import os
import unittest
from telemetry.core import browser_finder
from telemetry.unittest import simple_mock
from telemetry.unittest imp... | with browser_finder.FindBrowser(options).Create() as b:
b.credentials.credentials_path = credentials_path
if not b.credentials.CanLogin(self._credentials_type):
return
ret = b.credentials.LoginNeeded(b.tabs[0], self._credentials_type)
self.assertTrue(ret)
@DisabledTest
def testR... | logging.warning('Credentials file not found, skipping test.')
return
options = options_for_unittests.GetCopy() | random_line_split |
tree.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Zhassulan Zhussupov
# Author zhzhussupovkz@gmail.com
# Tree class
import random
class Tree:
def __init__(self, world, screen, x, y):
self.world, self.pygame = world, world.pygame
self.screen = screen
model = random.choice(['tree.png', 'tree_1.pn... |
def move(self):
if self.y >= 480:
self.change()
self.y = 0
key = self.pygame.key.get_pressed()
if key[self.pygame.K_UP]:
if self.world.taxi.gear == 1:
self.y += 0.2
elif self.world.taxi.gear == 2:
self.y += 0.4... | self.screen.blit(self.image, [self.x, self.y]) | identifier_body |
tree.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Zhassulan Zhussupov
# Author zhzhussupovkz@gmail.com
# Tree class
import random
class | :
def __init__(self, world, screen, x, y):
self.world, self.pygame = world, world.pygame
self.screen = screen
model = random.choice(['tree.png', 'tree_1.png'])
self.image = self.pygame.image.load("./images/houses/" + model)
self.x, self.y = x, y
def draw(self):
s... | Tree | identifier_name |
tree.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Zhassulan Zhussupov
# Author zhzhussupovkz@gmail.com
# Tree class
import random
class Tree:
def __init__(self, world, screen, x, y):
self.world, self.pygame = world, world.pygame
self.screen = screen
model = random.choice(['tree.png', 'tree_1.pn... | elif self.world.taxi.gear == 3:
self.y += 0.5
elif self.world.taxi.gear == 4:
self.y += 0.75
def change(self):
model = random.choice(['tree.png', 'tree_1.png'])
self.image = self.pygame.image.load("./images/houses/" + model) | self.y += 0.2
elif self.world.taxi.gear == 2:
self.y += 0.4 | random_line_split |
tree.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Zhassulan Zhussupov
# Author zhzhussupovkz@gmail.com
# Tree class
import random
class Tree:
def __init__(self, world, screen, x, y):
self.world, self.pygame = world, world.pygame
self.screen = screen
model = random.choice(['tree.png', 'tree_1.pn... |
key = self.pygame.key.get_pressed()
if key[self.pygame.K_UP]:
if self.world.taxi.gear == 1:
self.y += 0.2
elif self.world.taxi.gear == 2:
self.y += 0.4
elif self.world.taxi.gear == 3:
self.y += 0.5
elif self... | self.change()
self.y = 0 | conditional_block |
mine_nrd_kernel.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... | }
assert_eq!(chain.head().unwrap().height, 8);
let key_id1 = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier();
let key_id2 = ExtKeychainPath::new(1, 2, 0, 0, 0).to_identifier();
let tx = build::transaction(
KernelFeatures::NoRecentDuplicate {
fee: 20000.into(),
relative_height: NRDRelativeHeight::new(... |
for n in 1..9 {
let key_id = ExtKeychainPath::new(1, n, 0, 0, 0).to_identifier();
let block = build_block(&chain, &keychain, &key_id, vec![]);
chain.process_block(block, Options::MINE).unwrap(); | random_line_split |
mine_nrd_kernel.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... | edge_bits,
)
.unwrap();
block
}
#[test]
fn mine_block_with_nrd_kernel_and_nrd_feature_enabled() {
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
global::set_local_nrd_enabled(true);
util::init_test_logger();
let chain_dir = ".grin.nrd_kernel";
clean_output_dir(chain_dir);
let keych... | {
let prev = chain.head_header().unwrap();
let next_header_info = consensus::next_difficulty(1, chain.difficulty_iter().unwrap());
let fee = txs.iter().map(|x| x.fee()).sum();
let reward =
reward::output(keychain, &ProofBuilder::new(keychain), key_id, fee, false).unwrap();
let mut block = Block::new(&prev, &txs... | identifier_body |
mine_nrd_kernel.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... | () {
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
global::set_local_nrd_enabled(true);
util::init_test_logger();
let chain_dir = ".grin.invalid_nrd_kernel";
clean_output_dir(chain_dir);
let keychain = ExtKeychain::from_random_seed(false).unwrap();
let pb = ProofBuilder::new(&keychain);
... | mine_invalid_block_with_nrd_kernel_and_nrd_feature_enabled_before_hf | identifier_name |
event_confirm_registration.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | (self, cr, uid, ids, context=None):
if context is None:
context = {}
registration_pool = self.pool.get('event.registration')
registration_ids = context.get('registration_ids', [])
registration_pool.do_open(cr, uid, registration_ids, context=context)
return {'type': 'i... | confirm | identifier_name |
event_confirm_registration.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
event_confirm_registration()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | if context is None:
context = {}
registration_pool = self.pool.get('event.registration')
registration_ids = context.get('registration_ids', [])
registration_pool.do_open(cr, uid, registration_ids, context=context)
return {'type': 'ir.actions.act_window_close'} | identifier_body |
event_confirm_registration.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
if 'msg' in fields:
res.update({'msg': msg})
return res
def confirm(self, cr, uid, ids, context=None):
if context is None:
context = {}
registration_pool = self.pool.get('event.registration')
registration_ids = context.get('registration_ids', [])
... | overlimit_event_ids.append(registration.event_id.id)
msg += _("Warning: The Event '%s' has reached its Maximum Limit (%s).") \
%(registration.event_id.name, register_max) | conditional_block |
event_confirm_registration.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | context = {}
registration_pool = self.pool.get('event.registration')
registration_ids = context.get('registration_ids', [])
res = super(event_confirm_registration, self).default_get(cr, uid, fields, context=context)
msg = ""
overlimit_event_ids = []
for regist... | random_line_split | |
errorOnDeprecated.test.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {wrap} from 'jest-snapshot-serializer-raw';
import {skipSuiteOnJestCircus} from '@jest/test-utils';
im... |
expect(wrap(rest)).toMatchSnapshot();
});
});
testFiles.forEach(testFile => {
const shouldPass = SHOULD_NOT_PASS_IN_JEST.has(testFile);
const expectation = `${testFile} ${shouldPass ? 'errors' : 'passes'}`;
const testName = `${expectation} when not in errorOnDeprecated mode`;
test(testName, () => {
... | {
const lineEntry = '(__tests__/defaultTimeoutInterval.test.js:10:3)';
expect(rest).toContain(`at Object.<anonymous>.test ${lineEntry}`);
rest = rest.replace(
`at Object.<anonymous>.test ${lineEntry}`,
`at Object.<anonymous> ${lineEntry}`,
);
} | conditional_block |
errorOnDeprecated.test.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {wrap} from 'jest-snapshot-serializer-raw';
import {skipSuiteOnJestCircus} from '@jest/test-utils';
im... | testFiles.forEach(testFile => {
const shouldPass = SHOULD_NOT_PASS_IN_JEST.has(testFile);
const expectation = `${testFile} ${shouldPass ? 'errors' : 'passes'}`;
const testName = `${expectation} when not in errorOnDeprecated mode`;
test(testName, () => {
const result = runJest('error-on-deprecated', [testF... | random_line_split | |
__init__.py | Parser()
QUERY_PARSER.add_argument("filter", action="append", help="Filter")
QUERY_PARSER.add_argument("order", help="Ordering", default="id")
QUERY_PARSER.add_argument("page", type=int, default=1, help="Page #")
QUERY_PARSER.add_argument("count",
type=int,
default=10... | query_filter = getattr(column, attr)(value)
return query.filter(query_filter)
def name_or_id(model, name):
"""Return an _id attribute if one exists."""
name_id = name + "_id"
if hasattr(model, name_id):
return getattr(model, name_id)
elif hasattr(model, name):
return getat... | """
Construct query based on:
attribute.operation.expression
For example:
foo.eq.42
"""
key, op, value = expression.split(".", 2)
column = getattr(model, key, None)
if isinstance(column.property, RelationshipProperty):
column = getattr(model, key + "_id", None)
if op ... | identifier_body |
__init__.py | _argument("count",
type=int,
default=1000,
help="Items per page")
# All defalut time range arguments
RANGE_PARSER = reqparse.RequestParser()
RANGE_PARSER.add_argument("start", type=int, default=0)
RANGE_PARSER.add_argument("end", type=int, d... | BaseIngestResource | identifier_name | |
__init__.py | _TOKEN is not None:
AUTH_TOKEN = AUTH_TOKEN.lower()
UUID_NAMESPACE = uuid.UUID("aeb7cf1c-a842-4592-82e9-55d2dad00150")
if "LOG_DIR" in app.config:
LOG_DIR = app.config["LOG_DIR"]
else:
LOG_DIR = "."
if "LOG_LEVEL" in app.config:
LOG_LEVEL = getattr(logging, app.config["LOG_LEVEL"].upper(), logging.DE... | restapi.add_resource(cls, endpoint) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.