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 |
|---|---|---|---|---|
lcd_display.py | self.pressed:
self.multiple_pressed = False
def next_event(self):
"""
Return (remaining, key) where remaining is the number of seconds
(float) until the key repeat event should be sent, or None if no
events are pending.
"""
if len(self.pressed) != 1 or ... | """
| identifier_name | |
lcd_display.py | _LCD_DATA = 31 # data = [col, row] + text
CMD_GPO = 34 # data = [pin(0-12), value(0-100)]
# sent from device
CMD_KEY_ACTIVITY = 0x80
CMD_ACK = 0x40 # in high two bits ie. & 0xc0
CURSOR_NONE = 0
CURSOR_BLINKING_BLOCK = 1
CURSOR_UNDERSCORE = 2
CURSOR_BLINKING_BLOCK_UNDERSCORE = 3
CU... | self.pressed[key] = time.time()
def release(self, key):
if key not in self.pressed:
return # ignore extra release events
del self.pressed[key]
if not self.pressed:
self.multiple_pressed = False
def next_event(self):
"""
Return (remaining, ke... | .multiple_pressed = True
| conditional_block |
lcd_display.py |
def get_cols_rows(self):
return self.DISPLAY_SIZE
class CFLCDScreen(LCDScreen):
"""
Common methods for Crystal Fontz LCD displays
"""
KEYS = [None, # no key with code 0
'up_press', 'down_press', 'left_press',
'right_press', 'enter_press', 'exit_press',
'up_releas... | pass | identifier_body | |
setup.py | # Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8')... | setup(
name='melody_scripter',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='0.0.8',
description='Melody Scripter, for parsing melod... | random_line_split | |
function_def.rs | // http://rosettacode.org/wiki/Function_definition
use std::ops::Mul;
// Function taking 2 ints, multply them and return the value
fn multiply(x: i32, y: i32) -> i32 {
// In Rust a statement is a expression. An expression at the end of a
// function without semicolon is a return expression
x * y //equivalent "r... | fn test_multiply_gen() {
assert_eq!(multiply_gen(2i32,2), 4);
}
#[test]
fn test_multiply() {
assert_eq!(multiply(2i32,2), 4);
}
#[cfg(not(test))]
fn main() {
println!("2 multiply 4 = {}", multiply(2i32,4));
println!("2.0 multiply 4.0 = {}", multiply_gen(2.0f32, 4.0));
println!("5.0 multiply 7.0 is {}", mult... | random_line_split | |
function_def.rs | // http://rosettacode.org/wiki/Function_definition
use std::ops::Mul;
// Function taking 2 ints, multply them and return the value
fn multiply(x: i32, y: i32) -> i32 {
// In Rust a statement is a expression. An expression at the end of a
// function without semicolon is a return expression
x * y //equivalent "r... | () {
assert_eq!(multiply(2i32,2), 4);
}
#[cfg(not(test))]
fn main() {
println!("2 multiply 4 = {}", multiply(2i32,4));
println!("2.0 multiply 4.0 = {}", multiply_gen(2.0f32, 4.0));
println!("5.0 multiply 7.0 is {}", multiply_gen(5.0 as f32, 7.0 as f32));
}
| test_multiply | identifier_name |
function_def.rs | // http://rosettacode.org/wiki/Function_definition
use std::ops::Mul;
// Function taking 2 ints, multply them and return the value
fn multiply(x: i32, y: i32) -> i32 {
// In Rust a statement is a expression. An expression at the end of a
// function without semicolon is a return expression
x * y //equivalent "r... |
#[cfg(not(test))]
fn main() {
println!("2 multiply 4 = {}", multiply(2i32,4));
println!("2.0 multiply 4.0 = {}", multiply_gen(2.0f32, 4.0));
println!("5.0 multiply 7.0 is {}", multiply_gen(5.0 as f32, 7.0 as f32));
}
| {
assert_eq!(multiply(2i32,2), 4);
} | identifier_body |
transact.rs | //! Implementation of reversible insertions on maps and sets.
//!
//! These utility data structures are useful when several hashmaps/hashsets need to be kept
//! synchronized. For instance, maps a data structure needs to be added to maps `a`, `b`, `c`
//! but the entire operation needs to be cancelled if there is a col... | Entry::Vacant(entry) => {
entry.insert(v);
keys.push(k)
}
}
}
match conflict {
None =>
Ok(InsertInMap {
map: map,
keys: keys,
commit... | match map.entry(k.clone()) {
Entry::Occupied(_) => {
conflict = Some(k);
break;
}, | random_line_split |
transact.rs | //! Implementation of reversible insertions on maps and sets.
//!
//! These utility data structures are useful when several hashmaps/hashsets need to be kept
//! synchronized. For instance, maps a data structure needs to be added to maps `a`, `b`, `c`
//! but the entire operation needs to be cancelled if there is a col... |
}
}
/// Commit the transaction. Once this is done, the value may be dropped without cancelling
/// the insertion.
pub fn commit(mut self) {
self.committed = true
}
}
impl<'a, K, V> Drop for InsertInMap<'a, K, V> where K:'a + Clone + Hash + Eq, V: 'a {
/// If this object is dro... | {
// We need to rollback everything we have inserted so far.
for k in keys {
map.remove(&k);
}
Err(k)
} | conditional_block |
transact.rs | //! Implementation of reversible insertions on maps and sets.
//!
//! These utility data structures are useful when several hashmaps/hashsets need to be kept
//! synchronized. For instance, maps a data structure needs to be added to maps `a`, `b`, `c`
//! but the entire operation needs to be cancelled if there is a col... | {
InsertInMap::start(&mut map, vec![(6, 6), (7, 7), (8, 8)]).unwrap();
// Transaction is not committed.
assert_eq!(map, reference_map);
}
println!("Inserting and committing");
{
{
let transaction = InsertInMap::start(&mut map, vec![(6, 6), (7, 7), (8, 8)]).un... | {
println!("Initializing a map");
let mut map = HashMap::new();
for i in 1..6 {
map.insert(i, i);
}
let reference_map = map.clone();
println!("Failing to insert due to collision");
{
if let Err(i) = InsertInMap::start(&mut map, vec![(6, 6), (7, 7), (8, 8), (4, 10)]) {
... | identifier_body |
transact.rs | //! Implementation of reversible insertions on maps and sets.
//!
//! These utility data structures are useful when several hashmaps/hashsets need to be kept
//! synchronized. For instance, maps a data structure needs to be added to maps `a`, `b`, `c`
//! but the entire operation needs to be cancelled if there is a col... | <'a, K, V> where K: 'a + Clone + Hash + Eq, V: 'a {
map: &'a mut HashMap<K, V>,
committed: bool,
keys: Vec<K>,
}
impl<'a, K, V> InsertInMap<'a, K, V> where K:'a + Clone + Hash + Eq, V: 'a {
/// Insert (key, value) pairs in a map, reversibly, and without overwriting.
///
/// If one of the keys `k... | InsertInMap | identifier_name |
processor.py | raise omero.ApiUsageException(None, None, "Already activated")
self.stdout = open(str(self.stdout_path), "w")
self.stderr = open(str(self.stderr_path), "w")
self.popen = self.Popen(
self.command(),
cwd=str(self.dir), env=self.env(),
stdout=self.stdout, stder... |
#
# popen methods
#
def status(self, msg = ""):
if self.isRunning():
self.rcode = self.popen.poll()
self.logger.info("%s : %s", self, msg)
@perf
@remoted
def poll(self, current = None):
"""
Checks popen.poll() (if active) and notifies all callb... | """
Remove all known files and finally the temporary directory.
If other files exist, an exception will be raised.
"""
try:
remove_path(self.dir)
except:
self.logger.error("Failed to remove dir %s" % self.dir, exc_info=True) | identifier_body |
processor.py | )",
self.pid, self.uuid, exc_info=True)
d_stop = time.time()
elapsed = int(self.stopped - self.started)
d_elapsed = int(d_stop - d_start)
self.status("Lived %ss. Deactivation took %ss." % (elapsed, d_elapsed))
@locked
def isActive(self):
"""
Test... | random_line_split | ||
processor.py | raise omero.ApiUsageException(None, None, "Already activated")
self.stdout = open(str(self.stdout_path), "w")
self.stderr = open(str(self.stderr_path), "w")
self.popen = self.Popen(
self.command(),
cwd=str(self.dir), env=self.env(),
stdout=self.stdout, stder... |
if self.params:
out_format = self.params.stdoutFormat
err_format = self.params.stderrFormat
else:
out_format = "text/plain"
err_format = out_format
self._upload(client, self.stdout_path, "stdout", out_format)
self._upload(client, self.st... | self.logger.error(
"No client: Cannot upload output for pid=%s (%s)",
self.pid, self.uuid)
return | conditional_block |
processor.py | Service().getEventContext().groupId
handle = WithGroup(client.sf.createJobHandle(), gid)
try:
status = self.final_status
if status is None:
status = (self.rcode == 0 and "Finished" or "Error")
handle.attach(long(self.properties["omero.job"]))
... | check | identifier_name | |
feature_bip68_sequence.py | 2 = CTransaction()
tx2.nVersion = 2
sequence_value = sequence_value & 0x7fffffff
tx2.vin = [CTxIn(COutPoint(tx1_id, 0), nSequence=sequence_value)]
tx2.vout = [CTxOut(int(value-self.relayfee*COIN), CScript([b'a']))]
tx2.rehash()
assert_raises_rpc_error(-26, NOT_FINAL_ERRO... |
return tx
test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=True)
test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=False)
# Now mine some blocks, but make sure tx2 doesn't get mined.
# Use prioritisetransaction to lower the effecti... | node.sendrawtransaction(ToHex(tx)) | conditional_block |
feature_bip68_sequence.py | tx2 = CTransaction()
tx2.nVersion = 2
sequence_value = sequence_value & 0x7fffffff
tx2.vin = [CTxIn(COutPoint(tx1_id, 0), nSequence=sequence_value)]
tx2.vout = [CTxOut(int(value-self.relayfee*COIN), CScript([b'a']))]
tx2.rehash()
assert_raises_rpc_error(-26, NOT_FINAL_E... |
# 50% chance we enable sequence locks
if random.randint(0,1):
using_sequence_locks = True
# 10% of the time, make the input sequence value pass
input_will_pass = (random.randint(1,10) == 1)
sequence_value =... | sequence_value = 0xfffffffe # this disables sequence locks | random_line_split |
feature_bip68_sequence.py | mempool
assert_raises_rpc_error(-26, NOT_FINAL_ERROR, node.sendrawtransaction, ToHex(tx))
else:
# sendrawtransaction should succeed if the tx is not in the mempool
node.sendrawtransaction(ToHex(tx))
return tx
test_nonzero_locks(tx2, self... | inputs = [ ]
outputs = { self.nodes[1].getnewaddress() : 1.0 }
rawtx = self.nodes[1].createrawtransaction(inputs, outputs)
rawtxfund = self.nodes[1].fundrawtransaction(rawtx)['hex']
tx = FromHex(CTransaction(), rawtxfund)
tx.nVersion = 2
tx_signed = self.nodes[1].signrawt... | identifier_body | |
feature_bip68_sequence.py | (self):
# Create some unconfirmed inputs
new_addr = self.nodes[0].getnewaddress()
self.nodes[0].sendtoaddress(new_addr, 2) # send 2 BTC
utxos = self.nodes[0].listunspent(0, 0)
assert(len(utxos) > 0)
utxo = utxos[0]
tx1 = CTransaction()
value = int(satos... | test_disable_flag | identifier_name | |
test_config.py | import textwrap
from unittest import mock
from unittest.mock import call
import pytest
from flask_forecaster.config import Config, ConfigError, parse_vcap, require
@mock.patch('flask_forecaster.config.os.getenv')
def test_require_success(getenv):
|
@mock.patch('flask_forecaster.config.os.getenv')
def test_require_failure(getenv):
getenv.side_effect = ConfigError
with pytest.raises(ConfigError):
require('hello')
getenv.assert_called_once_with('hello')
@mock.patch('flask_forecaster.config.os.getenv')
class TestConfig:
def test_unrecog... | getenv.return_value = 'world'
assert require('hello') == 'world'
getenv.assert_called_once_with('hello') | identifier_body |
test_config.py | import textwrap
from unittest import mock
from unittest.mock import call
import pytest
from flask_forecaster.config import Config, ConfigError, parse_vcap, require
@mock.patch('flask_forecaster.config.os.getenv')
def test_require_success(getenv):
getenv.return_value = 'world'
assert require('hello') == 'wo... | assert result == 'postgres://somepath'
_require.assert_any_call('VCAP_SERVICES')
_require.assert_any_call('POSTGRES_SERVICE') | 'POSTGRES_SERVICE',
(0, 'credentials', 'uri'),
)
| random_line_split |
test_config.py | import textwrap
from unittest import mock
from unittest.mock import call
import pytest
from flask_forecaster.config import Config, ConfigError, parse_vcap, require
@mock.patch('flask_forecaster.config.os.getenv')
def | (getenv):
getenv.return_value = 'world'
assert require('hello') == 'world'
getenv.assert_called_once_with('hello')
@mock.patch('flask_forecaster.config.os.getenv')
def test_require_failure(getenv):
getenv.side_effect = ConfigError
with pytest.raises(ConfigError):
require('hello')
get... | test_require_success | identifier_name |
test_config.py | import textwrap
from unittest import mock
from unittest.mock import call
import pytest
from flask_forecaster.config import Config, ConfigError, parse_vcap, require
@mock.patch('flask_forecaster.config.os.getenv')
def test_require_success(getenv):
getenv.return_value = 'world'
assert require('hello') == 'wo... |
@mock.patch('flask_forecaster.config.require')
def test_parse_vcap(_require):
required = dict(
VCAP_SERVICES=textwrap.dedent(
"""
{
"elephantsql-dev": [
{
"name": "elephantsql-dev-c6c60",
"label": "elephantsql-dev",
... | parse_vcap.assert_called_once_with(
'POSTGRES_SERVICE',
(0, 'credentials', 'uri'),
) | conditional_block |
__openerp__.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licens... | "Serv. Tecnol. Avanzados - Pedro M. Baeza",
"contributors": [
"Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>",
"Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>",
"Ana Juaristi <ajuaristio@gmail.com>",
],
"category": "Manufacturing",
"website": "http://www.odoomr... | "product_variants_no_automatic_creation",
"mrp_production_editable_scheduled_products",
],
"author": "OdooMRP team,"
"AvanzOSC," | random_line_split |
test_sql.py | #
# GeoCoon - GIS data analysis library based on Pandas and Shapely
#
# Copyright (C) 2014 by Artur Wroblewski <wrobell@pld-linux.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ve... |
# vim: sw=4:et:ai
| """
Test SQL data frame read
"""
points = Point(1, 1), Point(2, 2), Point(3, 3)
data = {
'a': PointSeries([p.wkb for p in points]),
'b': list(range(3)),
}
data = GeoDataFrame(data)
data = data[['a', 'b']]
f_sql.return_value = data
... | identifier_body |
test_sql.py | #
# GeoCoon - GIS data analysis library based on Pandas and Shapely
#
# Copyright (C) 2014 by Artur Wroblewski <wrobell@pld-linux.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ve... | (self, f_sql):
"""
Test SQL data frame read
"""
points = Point(1, 1), Point(2, 2), Point(3, 3)
data = {
'a': PointSeries([p.wkb for p in points]),
'b': list(range(3)),
}
data = GeoDataFrame(data)
data = data[['a', 'b']]
f_sq... | test_read_sql | identifier_name |
test_sql.py | #
# GeoCoon - GIS data analysis library based on Pandas and Shapely
#
# Copyright (C) 2014 by Artur Wroblewski <wrobell@pld-linux.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ve... |
# vim: sw=4:et:ai | self.assertEqual(Point, type(result.a[0]))
self.assertEqual(3, len(result.index))
self.assertTrue(all([1, 2, 3] == result.a.x))
self.assertTrue(all([1, 2, 3] == result.a.y)) | random_line_split |
mod.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | //- #[cfg(target_os = "fuchsia")] pub mod fuchsia;
//-
//- #[cfg(any(target_os = "redox", unix))]
//- #[stable(feature = "rust1", since = "1.0.0")]
//- pub use sys::ext as unix;
//-
//- #[cfg(windows)]
//- #[stable(feature = "rust1", since = "1.0.0")]
//- pub u... | //- #[cfg(target_os = "emscripten")] pub mod emscripten; | random_line_split |
mod.rs | /*!
In order to draw, you need to provide a source of indices which is used to link the vertices
together into *primitives*.
There are eleven types of primitives, each one with a corresponding struct:
- `PointsList`
- `LinesList`
- `LinesListAdjacency`
- `LineStrip`
- `LineStripAdjacency`
- `TrianglesList`
- `... |
}
/// List of available primitives.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrimitiveType {
///
Points,
///
LinesList,
///
LinesListAdjacency,
///
LineStrip,
///
LineStripAdjacency,
///
TrianglesList,
///
TrianglesListAdjacency,
///
Triangl... | {
match self {
&IndicesSource::IndexBuffer { ref buffer, .. } => buffer.get_primitives_type(),
&IndicesSource::Buffer { primitives, .. } => primitives,
&IndicesSource::NoIndices { primitives } => primitives,
}
} | identifier_body |
mod.rs | /*!
In order to draw, you need to provide a source of indices which is used to link the vertices
together into *primitives*.
There are eleven types of primitives, each one with a corresponding struct:
- `PointsList`
- `LinesList`
- `LinesListAdjacency`
- `LineStrip`
- `LineStripAdjacency`
- `TrianglesList`
- `... | /// Don't use indices. Assemble primitives by using the order in which the vertices are in
/// the vertices source.
NoIndices {
/// Type of primitives contained in the vertex source.
primitives: PrimitiveType,
},
}
impl<'a, T> IndicesSource<'a, T> where T: Index {
/// Returns the ty... | /// Number of elements in the buffer to use.
length: usize,
},
| random_line_split |
mod.rs | /*!
In order to draw, you need to provide a source of indices which is used to link the vertices
together into *primitives*.
There are eleven types of primitives, each one with a corresponding struct:
- `PointsList`
- `LinesList`
- `LinesListAdjacency`
- `LineStrip`
- `LineStripAdjacency`
- `TrianglesList`
- `... | (&self) -> gl::types::GLenum {
*self as gl::types::GLenum
}
}
/// An index from the index buffer.
pub unsafe trait Index: Copy + Send + 'static {
/// Returns the `IndexType` corresponding to this type.
fn get_type() -> IndexType;
}
unsafe impl Index for u8 {
fn get_type() -> IndexType {
... | to_glenum | identifier_name |
test_upcoming_elections_api.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from mock import patch, Mock
from datetime import date, timedelta
from django.conf import settings
from django.utils.six.moves.urllib_parse import urljoin
from nose.plugins.attrib import attr
from django_webtest import WebTest
from candidates.tests.f... |
elif url == urljoin(settings.MAPIT_BASE_URL, '/postcode/cb28rq'):
status_code = 404
json_result = {
"code": 404,
"error": "No Postcode matches the given query."
}
elif url == urljoin(settings.MAPIT_BASE_URL, '/postcode/foobar'):
status_code = 400
... | status_code = 200
json_result = se240ag_result | conditional_block |
test_upcoming_elections_api.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from mock import patch, Mock
from datetime import date, timedelta
from django.conf import settings
from django.utils.six.moves.urllib_parse import urljoin
from nose.plugins.attrib import attr
from django_webtest import WebTest
from candidates.tests.f... | import se240ag_result, sw1a1aa_result
from compat import text_type
def fake_requests_for_mapit(url):
"""Return reduced MapIt output for some known URLs"""
if url == urljoin(settings.MAPIT_BASE_URL, '/postcode/sw1a1aa'):
status_code = 200
json_result = sw1a1aa_result
elif url == urljoi... | from elections.uk.tests.mapit_postcode_results \ | random_line_split |
test_upcoming_elections_api.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from mock import patch, Mock
from datetime import date, timedelta
from django.conf import settings
from django.utils.six.moves.urllib_parse import urljoin
from nose.plugins.attrib import attr
from django_webtest import WebTest
from candidates.tests.f... | london_assembly = ParliamentaryChamberExtraFactory.create(
slug='london-assembly', base__name='London Assembly'
)
lac_area_type = AreaTypeFactory.create(name='LAC')
gla_area_type = AreaTypeFactory.create(name='GLA')
area_extra_lac = AreaExtraFactory.create(
... | def setUp(self):
super(TestUpcomingElectionsAPI, self).setUp()
def test_empty_results(self, mock_requests):
mock_requests.get.side_effect = fake_requests_for_mapit
response = self.app.get('/upcoming-elections/?postcode=SW1A+1AA')
output = response.json
self.assertEqual(outp... | identifier_body |
test_upcoming_elections_api.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from mock import patch, Mock
from datetime import date, timedelta
from django.conf import settings
from django.utils.six.moves.urllib_parse import urljoin
from nose.plugins.attrib import attr
from django_webtest import WebTest
from candidates.tests.f... | (self, mock_requests):
mock_requests.get.side_effect = fake_requests_for_mapit
response = self.app.get('/upcoming-elections/?postcode=SE24+0AG')
output = response.json
self.assertEqual(output, [])
def test_results_for_upcoming_elections(self, mock_requests):
one_day = timed... | test_results_for_past_elections | identifier_name |
file.js | /**
* File
*
* @author Tijme Gommers <t.gommers@jetcat.nl>
* @package server.helpers
*/
module.exports = {
/**
* @var Object
*/
fs: require('fs'),
/**
* File exists
*
* @param string Path to the file
* @return boolean exists
*/ | {
try {
var stats = module.exports.fs.statSync(file);
return true;
} catch(e) {
return false;
}
},
/**
* Create a file
*
* @param string Path to the file
* @param string Content of the file
* @return boolean created
*... | exists: function(file) | random_line_split |
main.js | ////////////////////////////////////////////////////////////////////////////////
// //
// DEMO - 8 ZONES OF 1 x 1 meter //
// The zones were previously defined with the Quuppa SPD ... | (z) {
if (z < 1.2) {
return "green";
} else if (z < 1.8) {
return "yellow";
} else {
return "red";
}
}
// this function changes the background color of the visited zone
function getTagZone() {
$.ajax( {
type: 'GET',
url: SERVER_IP + SERVER_NAME_QPE + 'getTagPosition?version=2&tag=' + TAG_... | getColor | identifier_name |
main.js | ////////////////////////////////////////////////////////////////////////////////
// //
// DEMO - 8 ZONES OF 1 x 1 meter //
// The zones were previously defined with the Quuppa SPD ... | else if (z < 1.8) {
return "yellow";
} else {
return "red";
}
}
// this function changes the background color of the visited zone
function getTagZone() {
$.ajax( {
type: 'GET',
url: SERVER_IP + SERVER_NAME_QPE + 'getTagPosition?version=2&tag=' + TAG_ID,
dataType: "json",
// if the reques... | {
return "green";
} | conditional_block |
main.js | ////////////////////////////////////////////////////////////////////////////////
// //
// DEMO - 8 ZONES OF 1 x 1 meter //
// The zones were previously defined with the Quuppa SPD ... | console.log("INFO: user is moving from " + lastZCoordinate + " to " + newZCoordinate);
lastZCoordinate = newZCoordinate;
}
} else {
// test if the user has moved to another zone
var id = '#' + lastVisitedZone;
console.log("INFO: user ... | // if yes, compute the background color
if (!(minZ < newZCoordinate && maxZ > newZCoordinate)) {
var id = '#' + lastVisitedZone;
$(id).css({ fill: getColor(newZCoordinate) });
| random_line_split |
main.js | ////////////////////////////////////////////////////////////////////////////////
// //
// DEMO - 8 ZONES OF 1 x 1 meter //
// The zones were previously defined with the Quuppa SPD ... |
// this function changes the background color of the visited zone
function getTagZone() {
$.ajax( {
type: 'GET',
url: SERVER_IP + SERVER_NAME_QPE + 'getTagPosition?version=2&tag=' + TAG_ID,
dataType: "json",
// if the request is successful, update weather station data table
success:function(data... | {
if (z < 1.2) {
return "green";
} else if (z < 1.8) {
return "yellow";
} else {
return "red";
}
} | identifier_body |
request-test.js | var http = require('http');
var express = require('express');
var htmlToJson = require('../lib/htmlToJson');
describe('htmlToJson.request', function () {
it('should take request library options and a filter, then return parsed results based on the response body', function (done) {
var app = express();
var se... | var val = 999;
htmlToJson.request({
uri: 'http://localhost:' + port,
qs: {
val: val
}
}, {
'val': function ($doc) {
return +$doc.find('#val').text();
}
}, function (err, result) {
result.val.should.equal(val);
server.cl... |
server.listen(port, function () { | random_line_split |
zunionstore.test.ts | import { createNodeRedisClient } from "../../../src";
import { fuzzify } from "../../fuzzify";
const client = createNodeRedisClient();
beforeAll(async () => {
await client.ping();
});
beforeEach(async () => {
await client.flushall(); | outputs.r0 = await client.zadd("zset1", [1, "one"]);
outputs.r1 = await client.zadd("zset1", [2, "two"]);
outputs.r2 = await client.zadd("zset2", [1, "one"]);
outputs.r3 = await client.zadd("zset2", [2, "two"]);
outputs.r4 = await client.zadd("zset2", [3, "three"]);
// @ts-expect-error (not smar... | });
test("docs/redis-doc/commands/zunionstore.md example 1", async () => {
const outputs: Record<string, unknown> = {};
| random_line_split |
row.js | /**
* Copyright (c) 2014 Guyon Roche
*
* 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, modify, merge, ... | () {
return this.style.border;
},
set border(value) {
return this._applyStyle('border', value);
},
get fill() {
return this.style.fill;
},
set fill(value) {
return this._applyStyle('fill', value);
},
get hidden() {
return !!this._hidden;
},
set hidden(value) {
... | border | identifier_name |
row.js | /**
* Copyright (c) 2014 Guyon Roche
*
* 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, modify, merge, ... |
this.hidden = value.hidden;
this.outlineLevel = value.outlineLevel || 0;
this.style = value.style || {};
}
}; | {
delete this.height;
} | conditional_block |
row.js | /**
* Copyright (c) 2014 Guyon Roche
*
* 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, modify, merge, ... |
// =========================================================================
get model() {
var cells = [];
var min = 0;
var max = 0;
_.each(this._cells, function (cell) {
if (cell.type != Enums.ValueType.Null) {
var cellModel = cell.model;
if (cellModel) {
... | },
| random_line_split |
row.js | /**
* Copyright (c) 2014 Guyon Roche
*
* 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, modify, merge, ... | ,
// get the min and max column number for the non-null cells in this row or null
get dimensions() {
var min = 0;
var max = 0;
_.each(this._cells, function (cell) {
if (cell.type != Enums.ValueType.Null) {
if (!min || (min > cell.col)) {
min = cell.col;
}
... | {
return _.some(this._cells, function (cell) {
return cell.type != Enums.ValueType.Null;
});
} | identifier_body |
main.rs | extern crate rusoto_core;
extern crate rusoto_rds;
use std::{thread, time};
use rusoto_rds::{Rds, RdsClient, CreateDBInstanceMessage, DescribeDBInstancesMessage};
use rusoto_core::{DefaultCredentialsProvider, Region, default_tls_client};
fn | () {
let database_instance_name = "rusototester2";
let credentials = DefaultCredentialsProvider::new().expect("Couldn't create AWS credentials provider.");
// Security groups in the default VPC will need modification to let you access this from the internet:
let rds_client = RdsClient::new(default_tls... | main | identifier_name |
main.rs | extern crate rusoto_core;
extern crate rusoto_rds;
use std::{thread, time};
use rusoto_rds::{Rds, RdsClient, CreateDBInstanceMessage, DescribeDBInstancesMessage};
use rusoto_core::{DefaultCredentialsProvider, Region, default_tls_client};
fn main() | };
println!("Going to make the database instance.");
let db_call_result = rds_client.create_db_instance(&create_db_instance_request);
if db_call_result.is_err() {
// This `unwrap` on the `err()` call will show us the error we know is there:
println!("Didn't successfully make the DB inst... | {
let database_instance_name = "rusototester2";
let credentials = DefaultCredentialsProvider::new().expect("Couldn't create AWS credentials provider.");
// Security groups in the default VPC will need modification to let you access this from the internet:
let rds_client = RdsClient::new(default_tls_cl... | identifier_body |
main.rs | extern crate rusoto_core;
extern crate rusoto_rds;
use std::{thread, time};
use rusoto_rds::{Rds, RdsClient, CreateDBInstanceMessage, DescribeDBInstancesMessage};
use rusoto_core::{DefaultCredentialsProvider, Region, default_tls_client};
fn main() {
let database_instance_name = "rusototester2";
let credentia... | ,
};
}
let endpoint_address = endpoint.address.expect("Endpoint address not available");
let endpoint_port = endpoint.port.expect("Endpoint port not available");
println!("\n\nendpoint: {:?}", format!("{}:{}", endpoint_address, endpoint_port));
}
| {
println!("Waiting for db to be available...");
thread::sleep(ten_seconds);
continue;
} | conditional_block |
main.rs | extern crate rusoto_core;
extern crate rusoto_rds;
use std::{thread, time};
use rusoto_rds::{Rds, RdsClient, CreateDBInstanceMessage, DescribeDBInstancesMessage};
use rusoto_core::{DefaultCredentialsProvider, Region, default_tls_client};
fn main() {
let database_instance_name = "rusototester2";
let credentia... | endpoint = endpoint_result.clone();
break;
},
None => {
println!("Waiting for db to be available...");
thread::sleep(ten_seconds);
continue;
},
};
}
let endpoint_address = endpoint.addres... | .db_instances.expect("Didn't get a result for DB instances request")[0].endpoint {
Some(ref endpoint_result) => { | random_line_split |
if28.py | from polyphony import testbench
def g(x):
if x == 0:
return 0
return 1
def h(x):
if x == 0:
pass
def f(v, i, j, k):
if i == 0:
|
elif i == 1:
return v
elif i == 2:
h(g(j) + g(k))
return v
elif i == 3:
for m in range(j):
v += 2
return v
else:
for n in range(i):
v += 1
return v
def if28(code, r1, r2, r3, r4):
if code == 0:
return f(r1, r2... | return v | conditional_block |
if28.py | from polyphony import testbench
def g(x):
if x == 0:
return 0
return 1
def | (x):
if x == 0:
pass
def f(v, i, j, k):
if i == 0:
return v
elif i == 1:
return v
elif i == 2:
h(g(j) + g(k))
return v
elif i == 3:
for m in range(j):
v += 2
return v
else:
for n in range(i):
v += 1
... | h | identifier_name |
if28.py | from polyphony import testbench
def g(x):
if x == 0:
return 0
return 1
def h(x):
if x == 0:
pass
def f(v, i, j, k):
if i == 0:
return v
elif i == 1:
return v
elif i == 2:
h(g(j) + g(k))
return v
elif i == 3:
for m in range(j):
... |
@testbench
def test():
assert 1 == if28(0, 1, 1, 0, 0)
assert 2 == if28(0, 2, 0, 0, 0)
assert 3 == if28(0, 3, 1, 0, 0)
assert 4 == if28(0, 4, 2, 0, 0)
assert 5 == if28(0, 5, 2, 1, 1)
assert 6 == if28(0, 6, 2, 2, 2)
assert 7 == if28(0, 7, 3, 0, 0)
assert 10 == if28(0, 8, 3, 1, 1)
a... | if code == 0:
return f(r1, r2, r3, r4)
return 0 | identifier_body |
if28.py | from polyphony import testbench
def g(x):
if x == 0:
return 0
return 1
def h(x):
if x == 0:
pass
def f(v, i, j, k):
if i == 0:
return v
elif i == 1:
return v
elif i == 2:
h(g(j) + g(k))
return v
elif i == 3:
for m in range(j):
... | assert 7 == if28(0, 7, 3, 0, 0)
assert 10 == if28(0, 8, 3, 1, 1)
assert 13 == if28(0, 9, 3, 2, 2)
assert 14 == if28(0, 10, 4, 0, 0)
test() | assert 6 == if28(0, 6, 2, 2, 2) | random_line_split |
get_bus_pullups.py | #!/usr/bin/env python
"""
================================================
ABElectronics IO Pi Tests | test get_bus_pullups function
Requires python smbus to be installed
For Python 2 install with: sudo apt-get install python-smbus
For Python 3 install with: sudo apt-get install python3-smbus
run with: python3 get_b... | ():
"""
Main program function
"""
passed = True
iopi = IOPi(0x20, False) # new iopi object without initialisation
for a in range(1, 65536):
iopi.set_bus_pullups(a)
x = iopi.get_bus_pullups()
if x != a:
passed = False
break
iopi.set_bus_... | main | identifier_name |
get_bus_pullups.py | #!/usr/bin/env python
"""
================================================
ABElectronics IO Pi Tests | test get_bus_pullups function
Requires python smbus to be installed
For Python 2 install with: sudo apt-get install python-smbus
For Python 3 install with: sudo apt-get install python3-smbus
run with: python3 get_b... | if passed is False:
print("Test Failed")
else:
print("Test Passed")
if __name__ == "__main__":
main()
| """
Main program function
"""
passed = True
iopi = IOPi(0x20, False) # new iopi object without initialisation
for a in range(1, 65536):
iopi.set_bus_pullups(a)
x = iopi.get_bus_pullups()
if x != a:
passed = False
break
iopi.set_bus_pullups(... | identifier_body |
get_bus_pullups.py | #!/usr/bin/env python
"""
================================================
ABElectronics IO Pi Tests | test get_bus_pullups function
Requires python smbus to be installed
For Python 2 install with: sudo apt-get install python-smbus
For Python 3 install with: sudo apt-get install python3-smbus
run with: python3 get_b... |
if passed is False:
print("Test Failed")
else:
print("Test Passed")
if __name__ == "__main__":
main()
| iopi.set_bus_pullups(a)
x = iopi.get_bus_pullups()
if x != a:
passed = False
break
iopi.set_bus_pullups(a)
x = iopi.get_bus_pullups()
if x != a:
passed = False
break | conditional_block |
get_bus_pullups.py | #!/usr/bin/env python
"""
================================================
ABElectronics IO Pi Tests | test get_bus_pullups function
Requires python smbus to be installed
For Python 2 install with: sudo apt-get install python-smbus
For Python 3 install with: sudo apt-get install python3-smbus
run with: python3 get_b... | x = iopi.get_bus_pullups()
if x != a:
passed = False
break
if passed is False:
print("Test Failed")
else:
print("Test Passed")
if __name__ == "__main__":
main() | if x != a:
passed = False
break
iopi.set_bus_pullups(a) | random_line_split |
jquery-gstree.js | treeprefix + 'indent'; // class for expander handles
var treeexpanderclass = treeprefix + 'expander'; // class for expander handles
var treeexpandedclass = treeprefix + 'expander-expanded'; // class for expander when expanded
var treecollapsedclass = treeprefix + 'expander-co... | (elem){
$(elem).removeClass(nodeparentcollapsedclass);
// $(elem).animate({opacity: 1}, 300); // todo: custom callout
}
function getNodeDepth(elem){
return parseInt($(elem).data(datadepthattr),10);
}
function getChildrenByDepth(elem){
// children are all nodes until nextsibling of equal OR LOWER depth
var nextsi... | showChildRow | identifier_name |
jquery-gstree.js | eprefix + 'indent'; // class for expander handles
var treeexpanderclass = treeprefix + 'expander'; // class for expander handles
var treeexpandedclass = treeprefix + 'expander-expanded'; // class for expander when expanded
var treecollapsedclass = treeprefix + 'expander-collap... |
function getChildrenByDepth(elem){
// children are all nodes until nextsibling of equal OR LOWER depth
var nextsibling = getNextSiblingByDepth(elem);
var children = elem.nextUntil(nextsibling);
return children;
}
/**
* get the first previous parentclass with lower depth
*/
function getParentByDepth(elem){
... | {
return parseInt($(elem).data(datadepthattr),10);
} | identifier_body |
jquery-gstree.js | treeprefix + 'indent'; // class for expander handles
var treeexpanderclass = treeprefix + 'expander'; // class for expander handles
var treeexpandedclass = treeprefix + 'expander-expanded'; // class for expander when expanded
var treecollapsedclass = treeprefix + 'expander-co... | }
});
}
function showChildRow(elem){
$(elem).removeClass(nodeparentcollapsedclass);
// $(elem).animate({opacity: 1}, 300); // todo: custom callout
}
function getNodeDepth(elem){
return parseInt($(elem).data(datadepthattr),10);
}
function getChildrenByDepth(elem){
// children are all nodes until nextsibling o... | if(!parentHidden && !parentCollapsed){
showChildRow(elem); | random_line_split |
index.d.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.
*/
/// <reference types="node" />
import EventEmitter from 'events';
import { Config } from '@jest/types';
import... | extends EventEmitter {
private _buildPromise;
private _cachePath;
private _changeInterval?;
private _console;
private _options;
private _watchers;
private _whitelist;
private _worker;
constructor(options: Options);
static getCacheFilePath(tmpdir: Config.Path, name: string, ...ex... | HasteMap | identifier_name |
index.d.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.
*/
/// <reference types="node" />
import EventEmitter from 'events';
import { Config } from '@jest/types';
import... | *
* // Modules can be targeted to a specific platform based on the file name.
* // Example: platform.ios.js and Platform.android.js will both map to the same
* // `Platform` module. The platform should be specified during resolution.
* type ModuleMapItem = {[platform: string]: ModuleMetaData};
*
* //
* type Mod... | * size: number, // size of the file in bytes.
* visited: boolean, // whether the file has been parsed or not.
* dependencies: Array<string>, // all relative dependencies of this file.
* sha1: ?string, // SHA-1 of the file, if requested via options.
* }; | random_line_split |
nmaptocsv.py | map6'), IP.group('ip_only_nmap6')]
IP_str = unique_match_from_list(IP_potential_match)
FQDN_potential_match = [IP.group('fqdn_nmap5'), IP.group('fqdn_nmap6')]
FQDN_str = unique_match_from_list(FQDN_potential_match)
new_host = Host(IP_str, FQDN_st... | csv_header = [format_item.upper() for format_item in splitted_options_format]
spamwriter.writerow(csv_header) | conditional_block | |
nmaptocsv.py | REASON\s*)?(?P<version>VERSION$)?')
#-- Port finding
p_port_without_reason = re.compile(r'^(?P<number>[\d]+)\/(?P<protocol>tcp|udp)\s+(?:open|open\|filtered)\s+(?P<service>[\w\S]*)(?:\s*(?P<version>.*))?$')
p_port_with_reason = re.compile(r'^(?P<number>[\d]+)\/(?P<protocol>tcp|udp)\s+(?:open|open\|filtered)\s+(?P<serv... |
def num_to_dottedquad(n):
"""
Convert long int IP to dotted quad string
"""
return socket.inet_ntoa(struct.pack('!L',n))
def unique_match_from_list(list):
"""
Check the list for a potential pattern match
@param list : a list of potential matching groups
@rtyp... | """
Convert decimal dotted quad string IP to long integer
"""
return struct.unpack('!L',socket.inet_aton(ip))[0] | identifier_body |
nmaptocsv.py | REASON\s*)?(?P<version>VERSION$)?')
#-- Port finding
p_port_without_reason = re.compile(r'^(?P<number>[\d]+)\/(?P<protocol>tcp|udp)\s+(?:open|open\|filtered)\s+(?P<service>[\w\S]*)(?:\s*(?P<version>.*))?$')
p_port_with_reason = re.compile(r'^(?P<number>[\d]+)\/(?P<protocol>tcp|udp)\s+(?:open|open\|filtered)\s+(?P<serv... | return str(self.network_distance)
# Setters
def set_fqdn(self, fqdn):
self.fqdn = fqdn
def set_rdns_record(self, rdns_record):
self.rdns = rdns_record
def set_os(self, os):
self.os = os
def set_mac(self, mac_address, mac_address_vendor = ''):
... | def get_mac_address_vendor(self):
return str(self.mac_address_vendor)
def get_network_distance(self): | random_line_split |
nmaptocsv.py | REASON\s*)?(?P<version>VERSION$)?')
#-- Port finding
p_port_without_reason = re.compile(r'^(?P<number>[\d]+)\/(?P<protocol>tcp|udp)\s+(?:open|open\|filtered)\s+(?P<service>[\w\S]*)(?:\s*(?P<version>.*))?$')
p_port_with_reason = re.compile(r'^(?P<number>[\d]+)\/(?P<protocol>tcp|udp)\s+(?:open|open\|filtered)\s+(?P<serv... | :
def __init__(self, ip, fqdn=''):
self.ip_dottedquad = ip
self.ip_num = dottedquad_to_num(ip)
self.fqdn = fqdn
self.rdns = ''
self.ports = []
self.os = ''
self.mac_address = ''
self.mac_address_vendor = ''
self.network_distance = ''
... | Host | identifier_name |
esnext.async-iterator.as-indexed-pairs.js | import { createIterator } from '../helpers/helpers';
QUnit.test('AsyncIterator#asIndexedPairs', assert => { |
assert.isFunction(asIndexedPairs);
assert.arity(asIndexedPairs, 0);
assert.name(asIndexedPairs, 'asIndexedPairs');
assert.looksNative(asIndexedPairs);
assert.nonEnumerable(AsyncIterator.prototype, 'asIndexedPairs');
asIndexedPairs.call(createIterator(['a', 'b', 'c'])).toArray().then(it => {
assert.sam... | assert.expect(10);
const async = assert.async();
const { asIndexedPairs } = AsyncIterator.prototype; | random_line_split |
fields.py | # -*- coding: utf-8 -*-
"""Field classes.
Includes all fields from `marshmallow.fields` in addition to a custom
`Nested` field and `DelimitedList`.
All fields can optionally take a special `location` keyword argument, which tells webargs
where to parse the request argument from. ::
args = {
'active': fie... | (self, value, attr, data):
try:
ret = (
value
if ma.utils.is_iterable_but_not_string(value)
else value.split(self.delimiter)
)
except AttributeError:
self.fail('invalid')
return super(DelimitedList, self)._deseri... | _deserialize | identifier_name |
fields.py | # -*- coding: utf-8 -*-
"""Field classes.
Includes all fields from `marshmallow.fields` in addition to a custom
`Nested` field and `DelimitedList`.
All fields can optionally take a special `location` keyword argument, which tells webargs
where to parse the request argument from. ::
args = {
'active': fie... | self.fail('invalid')
return super(DelimitedList, self)._deserialize(ret, attr, data) | else value.split(self.delimiter)
)
except AttributeError: | random_line_split |
fields.py | # -*- coding: utf-8 -*-
"""Field classes.
Includes all fields from `marshmallow.fields` in addition to a custom
`Nested` field and `DelimitedList`.
All fields can optionally take a special `location` keyword argument, which tells webargs
where to parse the request argument from. ::
args = {
'active': fie... |
class Nested(ma.fields.Nested):
"""Same as `marshmallow.fields.Nested`, except can be passed a dictionary as
the first argument, which will be converted to a `marshmallow.Schema`.
"""
def __init__(self, nested, *args, **kwargs):
if isinstance(nested, dict):
nested = argmap2schema... | __all__.append(each)
globals()[each] = getattr(ma.fields, each) | conditional_block |
fields.py | # -*- coding: utf-8 -*-
"""Field classes.
Includes all fields from `marshmallow.fields` in addition to a custom
`Nested` field and `DelimitedList`.
All fields can optionally take a special `location` keyword argument, which tells webargs
where to parse the request argument from. ::
args = {
'active': fie... |
class DelimitedList(ma.fields.List):
"""Same as `marshmallow.fields.List`, except can load from either a list or
a delimited string (e.g. "foo,bar,baz").
:param Field cls_or_instance: A field class or instance.
:param str delimiter: Delimiter between values.
:param bool as_string: Dump values to ... | if isinstance(nested, dict):
nested = argmap2schema(nested)
super(Nested, self).__init__(nested, *args, **kwargs) | identifier_body |
ffi.rs | use std::default::Default;
use std::ffi::CStr;
use std::str;
use libc::{c_int, c_double, c_char, c_void, uint64_t};
#[link(name = "sigar")]
extern {
// SIGAR_DECLARE(int) sigar_open(sigar_t **sigar);
pub fn sigar_open(sigar: *mut *mut sigar_t) -> c_int;
// SIGAR_DECLARE(int) sigar_close(sigar_t *sigar);
... | pub ram: uint64_t,
pub total: uint64_t,
pub used: uint64_t,
pub free: uint64_t,
pub actual_used: uint64_t,
pub actual_free: uint64_t,
pub used_percent: c_double,
pub free_percent: c_double
}
impl Default for sigar_mem_t {
fn default() -> sigar_mem_t {
sigar_mem_t {
... | random_line_split | |
ffi.rs | use std::default::Default;
use std::ffi::CStr;
use std::str;
use libc::{c_int, c_double, c_char, c_void, uint64_t};
#[link(name = "sigar")]
extern {
// SIGAR_DECLARE(int) sigar_open(sigar_t **sigar);
pub fn sigar_open(sigar: *mut *mut sigar_t) -> c_int;
// SIGAR_DECLARE(int) sigar_close(sigar_t *sigar);
... | {
pub user: uint64_t,
pub sys: uint64_t,
pub nice: uint64_t,
pub idle: uint64_t,
pub wait: uint64_t,
pub irq: uint64_t,
pub soft_irq: uint64_t,
pub stolen: uint64_t,
pub total: uint64_t,
}
impl Default for sigar_cpu_t {
fn default() -> sigar_cpu_t {
sigar_cpu_t {
... | sigar_cpu_t | identifier_name |
ffi.rs | use std::default::Default;
use std::ffi::CStr;
use std::str;
use libc::{c_int, c_double, c_char, c_void, uint64_t};
#[link(name = "sigar")]
extern {
// SIGAR_DECLARE(int) sigar_open(sigar_t **sigar);
pub fn sigar_open(sigar: *mut *mut sigar_t) -> c_int;
// SIGAR_DECLARE(int) sigar_close(sigar_t *sigar);
... | {
unsafe {
let ptr = sigar_strerror(sigar, code);
let bytes = CStr::from_ptr(ptr).to_bytes();
str::from_utf8(bytes).ok().expect("Invalid UTF8 string").to_string()
}
} | identifier_body | |
locking.py | # This file is part of the qpopplerview package.
#
# Copyright (c) 2010 - 2014 by Wilbert Berendsen
#
# 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 2
# of the License, or (at yo... | (document):
"""Returns a threading.RLock instance for the given Poppler.Document.
Use:
with lock(document):
do_something
"""
with _lock:
try:
return _locks[document]
except KeyError:
res = _locks[document] = threading.RLock()
... | lock | identifier_name |
locking.py | # This file is part of the qpopplerview package.
#
# Copyright (c) 2010 - 2014 by Wilbert Berendsen
# | # 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 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... | random_line_split | |
locking.py | # This file is part of the qpopplerview package.
#
# Copyright (c) 2010 - 2014 by Wilbert Berendsen
#
# 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 2
# of the License, or (at yo... | """Returns a threading.RLock instance for the given Poppler.Document.
Use:
with lock(document):
do_something
"""
with _lock:
try:
return _locks[document]
except KeyError:
res = _locks[document] = threading.RLock()
return res | identifier_body | |
annotations_line2d.py | _patch().contains(event)
if drag[0]:
#Make sure no other annotation are dragging.
# wait=False means no block. True if a successful lock.
if DraggableAnnotationLine2D._drag_lock.acquire(False):
# Record the mouse button
... | index):
"""
The default function to take a Line2D artist and index and generate a
string for the annotation box.
"""
xy=line.get_xydata()[index]
return '{0}[{1}]:\nx={2:.9}\ny:{3:.9}'.format(line.get_label(),index,xy[0],xy[1])
def _onpick(self,event... | ne_str(self, line, | identifier_name |
annotations_line2d.py | _patch().contains(event)
if drag[0]:
#Make sure no other annotation are dragging.
# wait=False means no block. True if a successful lock.
if DraggableAnnotationLine2D._drag_lock.acquire(False):
# Record the mouse button
... | else:
lines=[]
for line in lines:
line.set_picker(self.tolerance)
# Make sure the callbacks are enabled for the parent canvas
enable_callbacks(artist)
def annotate(self, line, index, text=None):
"""
Makes... | e for ax in artist.get_axes() for line in ax.get_lines() if not line.pickable()]
| conditional_block |
annotations_line2d.py | if self.button == 1:
# Left-click. Move the annotation while pointing at the same data.
# Get the starting position of the artist in points (relative to data point)
self.drag_start_text_points = self.ref_artist.get_position()
# Get the inverted transform so we can conver... | random_line_split | ||
annotations_line2d.py | ().contains(event)
if drag[0]:
#Make sure no other annotation are dragging.
# wait=False means no block. True if a successful lock.
if DraggableAnnotationLine2D._drag_lock.acquire(False):
# Record the mouse button
self.b... |
def on_release(self,event):
"""
Called when the mouse button is released, whether or not this was picked.
We extend this function so that we are guaranteed to release the thread lock.
"""
# Call the original
super().on_release(event)
#Everyone tries to remo... | en the mouse button is released, if this was picked in the first place."""
#print('Finalize',self.id)
if self.button == 2 and self.formatter is not None:
# Print out annotation text for the user to copy/paste
self.print_annotation()
elif self.button == 3:
# De... | identifier_body |
schemas.py | changes.
- an explicit *role* argument is required
- the *ordered* parameter defaults to True
"""
schema_as_json = super(JSLSchemaBase, self).get_schema(role, ordered)
# Set schema title based on the definition ID and active role
try:
options = self.Options
... |
for modname, versions in schemas_to_versions.items():
for version in versions:
yield SchemaRef(modname, version)
def load_all_jsl_definitions(self):
"""Return all JSL definitions from modules in `self.schema_mod_fqn`.
The result is a dictionary that maps Schema... | mod = importlib.import_module('.'.join([self.schema_mod_fqn, modname]))
schemas_to_versions[modname] = []
role_in_development = getattr(mod, "_ROLE_IN_DEVELOPMENT", None)
for attr in dir(mod):
if attr.startswith('ROLE_v'):
# Omi... | conditional_block |
schemas.py | changes.
- an explicit *role* argument is required
- the *ordered* parameter defaults to True
"""
schema_as_json = super(JSLSchemaBase, self).get_schema(role, ordered)
# Set schema title based on the definition ID and active role
try:
options = self.Options
... |
class AbstractSchemaLibrary(object, metaclass=abc.ABCMeta):
"""Abstract class for schema."""
def load_schema(self, schema_ref):
"""Load and parse specified schema from the library."""
try:
schema_data = self.read_binary_schema(schema_ref)
except Exception as exc:
... | """Failed to import schema from module."""
def __init__(self, mod):
"""Initialize object."""
self.mod = mod
def __str__(self):
"""Represent as a string."""
return "Can't import schema from module {}".format(self.mod) | identifier_body |
schemas.py | , self.attribute)
class SchemaImportError(ImportError):
"""Failed to import schema from module."""
def __init__(self, mod):
"""Initialize object."""
self.mod = mod
def __str__(self):
"""Represent as a string."""
return "Can't import schema from module {}".format(self.mod)... | random_line_split | ||
schemas.py | changes.
- an explicit *role* argument is required
- the *ordered* parameter defaults to True
"""
schema_as_json = super(JSLSchemaBase, self).get_schema(role, ordered)
# Set schema title based on the definition ID and active role
try:
options = self.Options
... | (self, mod):
"""Initialize object."""
self.mod = mod
def __str__(self):
"""Represent as a string."""
return "Can't import schema from module {}".format(self.mod)
class AbstractSchemaLibrary(object, metaclass=abc.ABCMeta):
"""Abstract class for schema."""
def load_schema(s... | __init__ | identifier_name |
sql.js | ;
case "int":
case "tinyint":
case "smallint":
case "bigint":
case "boolean":
Ti.API.warn("\"" + type + "\" is not a valid sqlite field, using INTEGER instead");
case "integer":
type = "INTEGER";
break;
case "doubl... | (config) {
var dbFile = config.adapter.db_file, table = config.adapter.collection_name, rx = /^([\/]{0,1})([^\/]+)\.[^\/]+$/, match = dbFile.match(rx);
if (match === null) throw "Invalid sql database filename \"" + dbFile + "\"";
var dbName = config.adapter.db_name = match[2];
Ti.API.debug("Installing s... | installDatabase | identifier_name |
sql.js | ;
case "int":
case "tinyint":
case "smallint":
case "bigint":
case "boolean":
Ti.API.warn("\"" + type + "\" is not a valid sqlite field, using INTEGER instead");
case "integer":
type = "INTEGER";
break;
case "doubl... | var rs = db.execute(sql), len = 0, values = [];
while (rs.isValidRow()) {
var o = {}, fc = 0;
fc = _.isFunction(rs.fieldCount) ? rs.fieldCount() : rs.fieldCount;
_.times(fc, function(c) {
var fn = rs.fieldName(c);
o[fn] = rs.fieldByName... | }();
break;
case "read":
var sql = opts.query || "SELECT * FROM " + table;
db = Ti.Database.open(dbName); | random_line_split |
sql.js | ;
case "int":
case "tinyint":
case "smallint":
case "bigint":
case "boolean":
Ti.API.warn("\"" + type + "\" is not a valid sqlite field, using INTEGER instead");
case "integer":
type = "INTEGER";
break;
case "doubl... | q.push("?");
}
var sqlInsert = "INSERT INTO " + table + " (" + names.join(",") + ") VALUES (" + q.join(",") + ");", sqlId = "SELECT last_insert_rowid();";
db = Ti.Database.open(dbName);
db.execute("BEGIN;");
db.execute(sqlInsert, values);
... | {
var table = model.config.adapter.collection_name, columns = model.config.columns, dbName = model.config.adapter.db_name || ALLOY_DB_DEFAULT, resp = null, db;
switch (method) {
case "create":
resp = function() {
var attrObj = {};
if (!model.id) if (model.idAttribute === AL... | identifier_body |
status.rs | // Copyright (C) 2015, Alberto Corona <ac@albertocorona.com>
// All rights reserved. This file is part of rpf, distributed under the
// BSD 3-Clause license. For full terms please see the LICENSE file.
use utils::PathMod;
use utils::Styled;
use utils::Color;
use std::path::PathBuf;
use utils::Prog;
/// Enum used fo... | (&self, mesg: T, item: PathBuf) {
println!("{}{} {}", item.as_str().paint(Color::Red),
":".paint(Color::Red), mesg.as_ref().paint(Color::Red));
&self.exit(ExitStatus::Error);
}
}
| path_error | identifier_name |
status.rs | // Copyright (C) 2015, Alberto Corona <ac@albertocorona.com>
// All rights reserved. This file is part of rpf, distributed under the
// BSD 3-Clause license. For full terms please see the LICENSE file.
use utils::PathMod;
use utils::Styled;
use utils::Color;
use std::path::PathBuf;
use utils::Prog;
/// Enum used fo... |
/// Used for errors when working with paths, works similar to `error`
fn path_error(&self, mesg: T, item: PathBuf);
}
impl <T: AsRef<str>> Exit<T> for Prog {
fn error(&self, mesg: T, status: ExitStatus) {
println!("{}{} {}", self.name.paint(Color::Red), ":".paint(Color::Red),
mesg.as_ref()... | ///
/// let prog = Prog { name: "test", vers: "0.1.0", yr: "2015" };
/// prog.error("Some kind of error occured!".to_string(), ExitStatus::Error);
/// ```
fn error(&self, mesg: T, status: ExitStatus); | random_line_split |
status.rs | // Copyright (C) 2015, Alberto Corona <ac@albertocorona.com>
// All rights reserved. This file is part of rpf, distributed under the
// BSD 3-Clause license. For full terms please see the LICENSE file.
use utils::PathMod;
use utils::Styled;
use utils::Color;
use std::path::PathBuf;
use utils::Prog;
/// Enum used fo... |
fn path_error(&self, mesg: T, item: PathBuf) {
println!("{}{} {}", item.as_str().paint(Color::Red),
":".paint(Color::Red), mesg.as_ref().paint(Color::Red));
&self.exit(ExitStatus::Error);
}
}
| {
println!("{}{} {}", self.name.paint(Color::Red), ":".paint(Color::Red),
mesg.as_ref().paint(Color::Red));
&self.exit(status);
} | identifier_body |
0046_auto_20200221_1735.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-02-21 17:35 | import sentry.db.models.fields.foreignkey
class Migration(migrations.Migration):
# This flag is used to mark that a migration shouldn't be automatically run in
# production. We set this to True for operations that we think are risky and want
# someone from ops to run manually and monitor.
# General ad... | from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations
import django.db.models.deletion | random_line_split |
0046_auto_20200221_1735.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-02-21 17:35
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations
import django.db.models.deletion
import sentry.db.models.fields.foreignkey
class | (migrations.Migration):
# This flag is used to mark that a migration shouldn't be automatically run in
# production. We set this to True for operations that we think are risky and want
# someone from ops to run manually and monitor.
# General advice is that if in doubt, mark your migration as `is_danger... | Migration | identifier_name |
0046_auto_20200221_1735.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-02-21 17:35
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations
import django.db.models.deletion
import sentry.db.models.fields.foreignkey
class Migration(migrations.Migration):
# This flag is used... | model_name='exporteddata',
name='user',
field=sentry.db.models.fields.foreignkey.FlexibleForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL),
),
]
| is_dangerous = False
# This flag is used to decide whether to run this migration in a transaction or not.
# By default we prefer to run in a transaction, but for migrations where you want
# to `CREATE INDEX CONCURRENTLY` this needs to be set to False. Typically you'll
# want to create an index concurre... | identifier_body |
EditNewsWindow.js | /**
*
*/
Ext.define('RODAdmin.view.cms.news.EditNewsWindow', {
extend : 'RODAdmin.view.common.WindowForm',
alias : 'widget.newsedit',
height : '60%',
width : '60%',
requires : ['RODAdmin.util.Util'],
layout : {
type : 'fit',
// align : 'stretch'
},
config: {
cnode: {}
},
initComponent : functio... | type : 'vbox',
align : 'stretch'
},
defaults : {
afterLabelTextTpl : RODAdmin.util.Util.required,
// anchor : '100%',
xtype : 'textfield',
allowBlank : false,
// layout : {
// type : 'vbox',
//// columns:2
// align : 'stretch'
// ... | bodyPadding : 5,
layout : { | random_line_split |
text.rs | DecorationUnderline};
use servo_util::range::Range;
/// Creates a TextRenderBox from a range and a text run.
pub fn adapt_textbox_with_range(mut base: RenderBoxBase, run: @TextRun, range: Range)
-> TextRenderBox {
debug!("Creating textbox with span: (strlen=%u, off=%u, len=%u) of t... | () -> TextRunScanner {
TextRunScanner {
clump: Range::empty(),
}
}
pub fn scan_for_runs(&mut self, ctx: &LayoutContext, flow: &mut FlowContext) {
{
let inline = flow.imm_inline();
// FIXME: this assertion fails on wikipedia, but doesn't seem
... | new | identifier_name |
text.rs | DecorationUnderline};
use servo_util::range::Range;
/// Creates a TextRenderBox from a range and a text run.
pub fn adapt_textbox_with_range(mut base: RenderBoxBase, run: @TextRun, range: Range)
-> TextRenderBox {
debug!("Creating textbox with span: (strlen=%u, off=%u, len=%u) of t... | pub fn scan_for_runs(&mut self, ctx: &LayoutContext, flow: &mut FlowContext) {
{
let inline = flow.imm_inline();
// FIXME: this assertion fails on wikipedia, but doesn't seem
// to cause problems.
// assert!(inline.boxes.len() > 0);
debug!("TextRun... | random_line_split | |
text.rs | DecorationUnderline};
use servo_util::range::Range;
/// Creates a TextRenderBox from a range and a text run.
pub fn adapt_textbox_with_range(mut base: RenderBoxBase, run: @TextRun, range: Range)
-> TextRenderBox {
debug!("Creating textbox with span: (strlen=%u, off=%u, len=%u) of t... |
pub fn scan_for_runs(&mut self, ctx: &LayoutContext, flow: &mut FlowContext) {
{
let inline = flow.imm_inline();
// FIXME: this assertion fails on wikipedia, but doesn't seem
// to cause problems.
// assert!(inline.boxes.len() > 0);
debug!("TextR... | {
TextRunScanner {
clump: Range::empty(),
}
} | identifier_body |
text.rs | DecorationUnderline};
use servo_util::range::Range;
/// Creates a TextRenderBox from a range and a text run.
pub fn adapt_textbox_with_range(mut base: RenderBoxBase, run: @TextRun, range: Range)
-> TextRenderBox {
debug!("Creating textbox with span: (strlen=%u, off=%u, len=%u) of t... | ,
(true, true) => {
let old_box = in_boxes[self.clump.begin()];
let text = old_box.raw_text();
let font_style = old_box.font_style();
let underline = has_underline(old_box.text_decoration());
// TODO(#115): Use the actual CSS ... | {
debug!("TextRunScanner: pushing single non-text box in range: %?", self.clump);
out_boxes.push(in_boxes[self.clump.begin()]);
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.