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 |
|---|---|---|---|---|
icon-dropdown-menu.tsx | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
import PopupMenu from 'components/popup-menu';
import * as React from 'react';
import { classWithModifiers } from 'utils/css';
import { SlateCo... |
this.props.onSelect(target.dataset.id ?? '');
};
}
| {
return;
} | conditional_block |
configureReducer.js | import app from './app/reducer';
import auth from './auth/reducer';
import config from './config/reducer';
import device from './device/reducer';
import intl from './intl/reducer';
import todos from './todos/reducer';
import ui from './ui/reducer';
import users from './users/reducer';
import messages from './messages/... | (initialState, platformReducers) {
let reducer = combineReducers({
...platformReducers,
app,
auth,
config,
device,
fields,
firebase,
intl,
routing,
todos,
ui,
users,
messages,
events,
bio
});
// The power of higher-order reducers, http://slides.com/omn... | configureReducer | identifier_name |
configureReducer.js | import app from './app/reducer';
import auth from './auth/reducer';
import config from './config/reducer';
import device from './device/reducer';
import intl from './intl/reducer';
import todos from './todos/reducer';
import ui from './ui/reducer';
import users from './users/reducer';
import messages from './messages/... | // The power of higher-order reducers, http://slides.com/omnidan/hor
reducer = resetStateOnSignOut(reducer, initialState);
reducer = updateStateOnStorageLoad(reducer);
return reducer;
}
| {
let reducer = combineReducers({
...platformReducers,
app,
auth,
config,
device,
fields,
firebase,
intl,
routing,
todos,
ui,
users,
messages,
events,
bio
});
| identifier_body |
configureReducer.js | import app from './app/reducer';
import auth from './auth/reducer';
import config from './config/reducer';
import device from './device/reducer';
import intl from './intl/reducer';
import todos from './todos/reducer';
import ui from './ui/reducer';
import users from './users/reducer';
import messages from './messages/... |
return reducer(state, action);
};
export default function configureReducer(initialState, platformReducers) {
let reducer = combineReducers({
...platformReducers,
app,
auth,
config,
device,
fields,
firebase,
intl,
routing,
todos,
ui,
users,
messages,
events,... | {
// Preserve state without sensitive data.
state = {
app: state.app,
config: initialState.config,
device: initialState.device,
intl: initialState.intl,
routing: state.routing // Routing state has to be reused.
};
} | conditional_block |
configureReducer.js | import app from './app/reducer';
import auth from './auth/reducer';
import config from './config/reducer';
import device from './device/reducer';
import intl from './intl/reducer';
import todos from './todos/reducer';
import ui from './ui/reducer';
import users from './users/reducer';
import messages from './messages/... | ...platformReducers,
app,
auth,
config,
device,
fields,
firebase,
intl,
routing,
todos,
ui,
users,
messages,
events,
bio
});
// The power of higher-order reducers, http://slides.com/omnidan/hor
reducer = resetStateOnSignOut(reducer, initialState);
re... | return reducer(state, action);
};
export default function configureReducer(initialState, platformReducers) {
let reducer = combineReducers({ | random_line_split |
en-MH.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... |
export default [
'en-MH',
[['a', 'p'], ['AM', 'PM'], u],
[['AM', 'PM'], u, u],
[
['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
],
... | {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
} | identifier_body |
en-MH.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... | 'October', 'November', 'December'
]
],
u,
[['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']],
0,
[6, 0],
['M/d/yy', 'MMM d, y', 'MMMM d, y', 'EEEE, MMMM d, y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
['{1}, {0}', u, '{1} \'at\' {0}', u],
['.', ',', ';', '%', '+',... | [
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', | random_line_split |
en-MH.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... | (n: number): number {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
export default [
'en-MH',
[['a', 'p'], ['AM', 'PM'], u],
[['AM', 'PM'], u, u],
[
['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Th... | plural | identifier_name |
geometry.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 euclid::{Rect, Point3D};
/*
A naive port of "An Efficient and Robust Ray–Box Intersection Algorithm"
from h... | if inv_direction.z < 0.0 {
1
} else {
0
},
];
let parameters = [
Point3D::new(rect.origin.x, rect.origin.y, 0.0),
Point3D::new(rect.origin.x + rect.size.width,
rect.origin.y + rect.size.height,
0.0),
]... | 0
},
| conditional_block |
geometry.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 euclid::{Rect, Point3D};
/*
A naive port of "An Efficient and Robust Ray–Box Intersection Algorithm"
from h... | ay_origin: Point3D<f32>,
ray_end: Point3D<f32>,
rect: Rect<f32>) -> bool {
let mut dir = ray_end - ray_origin;
let len = ((dir.x*dir.x) + (dir.y*dir.y) + (dir.z*dir.z)).sqrt();
dir.x = dir.x / len;
dir.y = dir.y / len;
dir.z = dir.z / len;
le... | y_intersects_rect(r | identifier_name |
geometry.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 euclid::{Rect, Point3D};
/*
A naive port of "An Efficient and Robust Ray–Box Intersection Algorithm"
from h... | } else {
0
},
];
let parameters = [
Point3D::new(rect.origin.x, rect.origin.y, 0.0),
Point3D::new(rect.origin.x + rect.size.width,
rect.origin.y + rect.size.height,
0.0),
];
let mut tmin = (parameters[sign[0]].x - ra... | let mut dir = ray_end - ray_origin;
let len = ((dir.x*dir.x) + (dir.y*dir.y) + (dir.z*dir.z)).sqrt();
dir.x = dir.x / len;
dir.y = dir.y / len;
dir.z = dir.z / len;
let inv_direction = Point3D::new(1.0/dir.x, 1.0/dir.y, 1.0/dir.z);
let sign = [
if inv_direction.x < 0.0 {
... | identifier_body |
geometry.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 euclid::{Rect, Point3D};
/*
A naive port of "An Efficient and Robust Ray–Box Intersection Algorithm"
from h... | let t0 = 0.0;
let t1 = len;
(tmin < t1) && (tmax > t0)
*/
}
/*
pub fn circle_contains_rect(circle_center: &Point2D<f32>,
radius: f32,
rect: &Rect<f32>) -> bool {
let dx = (circle_center.x - rect.origin.x).max(rect.origin.x + rect.size.width - circle_... | random_line_split | |
must_use.rs | _utils::{match_def_path, must_use_attr, return_ty, trait_ref_of_method};
use super::{DOUBLE_MUST_USE, MUST_USE_CANDIDATE, MUST_USE_UNIT};
pub(super) fn check_item(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
let attrs = cx.tcx.hir().attrs(item.hir_id());
let attr = must_use_attr(attrs);
if let hir... | hir::TyKind::Tup(tys) => tys.is_empty(),
hir::TyKind::Never => true,
_ => false,
},
}
}
fn has_mutable_arg(cx: &LateContext<'_>, body: &hir::Body<'_>) -> bool {
let mut tys = DefIdSet::default();
body.params.iter().any(|param| is_mutable_pat(cx, param.pat, &mut t... | match decl.output {
hir::FnRetTy::DefaultReturn(_) => true,
hir::FnRetTy::Return(ty) => match ty.kind { | random_line_split |
must_use.rs | ::{match_def_path, must_use_attr, return_ty, trait_ref_of_method};
use super::{DOUBLE_MUST_USE, MUST_USE_CANDIDATE, MUST_USE_UNIT};
pub(super) fn check_item(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
let attrs = cx.tcx.hir().attrs(item.hir_id());
let attr = must_use_attr(attrs);
if let hir::Item... | (cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
if let hir::ImplItemKind::Fn(ref sig, ref body_id) = item.kind {
let is_public = cx.access_levels.is_exported(item.def_id);
let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
let attrs = cx.tcx.hir().attrs(item.hir_i... | check_impl_item | identifier_name |
must_use.rs | tcx hir::ImplItem<'_>) {
if let hir::ImplItemKind::Fn(ref sig, ref body_id) = item.kind {
let is_public = cx.access_levels.is_exported(item.def_id);
let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
let attrs = cx.tcx.hir().attrs(item.hir_id());
let attr = must_use... | {
use hir::ExprKind::{Field, Index, Path};
match e.kind {
Path(QPath::Resolved(_, path)) => !matches!(path.res, Res::Local(_)),
Path(_) => true,
Field(inner, _) | Index(inner, _) => is_mutated_static(inner),
_ => false,
}
} | identifier_body | |
dst-bad-coerce1.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
struct Foo;
trait Bar {}
pub fn main() {
// With a vec of ints.
let f1 = Fat { ptr: [1, 2, 3] };
let f2: &Fat<[int, ..3]> = &f1;
let f3: &Fat<[uint]> = f2;
//~^ ERROR mismatched types: expected `&Fat<[uint]>`, found `&Fat<[int, ..3]>`
// With a trait.
let f1 = Fat { ptr: Foo };
let ... | // Attempt to change the type as well as unsizing.
struct Fat<Sized? T> {
ptr: T | random_line_split |
dst-bad-coerce1.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ;
trait Bar {}
pub fn main() {
// With a vec of ints.
let f1 = Fat { ptr: [1, 2, 3] };
let f2: &Fat<[int, ..3]> = &f1;
let f3: &Fat<[uint]> = f2;
//~^ ERROR mismatched types: expected `&Fat<[uint]>`, found `&Fat<[int, ..3]>`
// With a trait.
let f1 = Fat { ptr: Foo };
let f2: &Fat<Foo>... | Foo | identifier_name |
rust-picotcp-dhcpd.rs | #![feature(globs)]
extern crate libc;
extern crate picotcp;
use picotcp::pico_ip4;
use picotcp::pico_ip6;
use picotcp::pico_dhcp_server::*;
fn main() {
/* Initialize stack */
let pico = picotcp::stack::new();
let my_ip_addr = pico_ip4::new("192.168.2.150");
let my_netmask = pico_ip4::new("255.255.255... |
dhcp_server_initiate(&mut settings);
pico.stack_loop();
} | server_ip: my_ip_addr,
netmask: my_netmask,
flags: 0
}; | random_line_split |
rust-picotcp-dhcpd.rs | #![feature(globs)]
extern crate libc;
extern crate picotcp;
use picotcp::pico_ip4;
use picotcp::pico_ip6;
use picotcp::pico_dhcp_server::*;
fn | () {
/* Initialize stack */
let pico = picotcp::stack::new();
let my_ip_addr = pico_ip4::new("192.168.2.150");
let my_netmask = pico_ip4::new("255.255.255.0");
let my_ip6_addr = pico_ip6 { addr:[0xaa, 0xaa, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] }; // Constructor is still WIP...
let my_6_net... | main | identifier_name |
rust-picotcp-dhcpd.rs | #![feature(globs)]
extern crate libc;
extern crate picotcp;
use picotcp::pico_ip4;
use picotcp::pico_ip6;
use picotcp::pico_dhcp_server::*;
fn main() | pool_start: dhcp_start.clone(),
pool_next: dhcp_start,
pool_end: dhcp_end,
lease_time: 0,
dev: pico_dev_eth,
s: 0,
server_ip: my_ip_addr,
netmask: my_netmask,
flags: 0
};
dhcp_server_initiate(&mut settings);
pico.stack_loop();
}
| {
/* Initialize stack */
let pico = picotcp::stack::new();
let my_ip_addr = pico_ip4::new("192.168.2.150");
let my_netmask = pico_ip4::new("255.255.255.0");
let my_ip6_addr = pico_ip6 { addr:[0xaa, 0xaa, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] }; // Constructor is still WIP...
let my_6_netmas... | identifier_body |
configuration.test.js | 'use strict';
const chai = require('chai'),
expect = chai.expect,
config = require('../config/config'),
Support = require('./support'),
dialect = Support.getTestDialect(),
Sequelize = Support.Sequelize,
fs = require('fs'),
path = require('path');
if (dialect === 'sqlite') {
var sqlite3 = require('sqli... | if (dialect === 'sqlite') {
// SQLite doesn't require authentication and `select 1 as hello` is a valid query, so this should be fulfilled not rejected for it.
return expect(seq.query('select 1 as hello')).to.eventually.be.fulfilled;
}
return expect(seq.query('select 1 as hello')).to.e... | expect(true).to.be.true;
return;
}
const seq = new Sequelize(config[dialect].database, config[dialect].username, 'fakepass123', { logging: false, host: config[dialect].host, port: 1, dialect }); | random_line_split |
configuration.test.js | 'use strict';
const chai = require('chai'),
expect = chai.expect,
config = require('../config/config'),
Support = require('./support'),
dialect = Support.getTestDialect(),
Sequelize = Support.Sequelize,
fs = require('fs'),
path = require('path');
if (dialect === 'sqlite') |
describe(Support.getTestDialectTeaser('Configuration'), () => {
describe('Connections problems should fail with a nice message', () => {
it('when we don\'t have the correct server details', () => {
const seq = new Sequelize(config[dialect].database, config[dialect].username, config[dialect].password, { st... | {
var sqlite3 = require('sqlite3'); // eslint-disable-line
} | conditional_block |
meson_post_install.py | #!/usr/bin/env python3
import os
import pathlib
import sysconfig
import compileall
import subprocess
| destdir = os.environ.get('DESTDIR', '')
if not destdir:
print('Compiling gsettings schemas...')
subprocess.call(['glib-compile-schemas', str(datadir / 'glib-2.0' / 'schemas')])
print('Updating icon cache...')
subprocess.call(['gtk-update-icon-cache', '-qtf', str(datadir / 'icons' / 'hicolor')])
p... | prefix = pathlib.Path(os.environ.get('MESON_INSTALL_PREFIX', '/usr/local'))
datadir = prefix / 'share' | random_line_split |
meson_post_install.py | #!/usr/bin/env python3
import os
import pathlib
import sysconfig
import compileall
import subprocess
prefix = pathlib.Path(os.environ.get('MESON_INSTALL_PREFIX', '/usr/local'))
datadir = prefix / 'share'
destdir = os.environ.get('DESTDIR', '')
if not destdir:
|
print('Compiling python bytecode...')
moduledir = sysconfig.get_path('purelib', vars={'base': str(prefix)})
compileall.compile_dir(destdir + os.path.join(moduledir, 'eidisi'), optimize=2)
| print('Compiling gsettings schemas...')
subprocess.call(['glib-compile-schemas', str(datadir / 'glib-2.0' / 'schemas')])
print('Updating icon cache...')
subprocess.call(['gtk-update-icon-cache', '-qtf', str(datadir / 'icons' / 'hicolor')])
print('Updating desktop database...')
subprocess.call(['up... | conditional_block |
test_cloud_memorystore_system.py | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | @provide_gcp_context(GCP_MEMORYSTORE)
def setUp(self):
super().setUp()
self.create_gcs_bucket(GCP_BUCKET_NAME, location="europe-north1")
@provide_gcp_context(GCP_MEMORYSTORE)
def test_run_example_dag_memorystore_redis(self):
self.run_dag('gcp_cloud_memorystore_redis', CLOUD_DAG_... | System tests for Google Cloud Memorystore operators
It use a real service.
"""
| random_line_split |
test_cloud_memorystore_system.py | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | (self):
self.run_dag('gcp_cloud_memorystore_memcached', CLOUD_DAG_FOLDER)
@provide_gcp_context(GCP_MEMORYSTORE)
def tearDown(self):
self.delete_gcs_bucket(GCP_BUCKET_NAME)
super().tearDown()
| test_run_example_dag_memorystore_memcached | identifier_name |
test_cloud_memorystore_system.py | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | def tearDown(self):
self.delete_gcs_bucket(GCP_BUCKET_NAME)
super().tearDown()
| """
System tests for Google Cloud Memorystore operators
It use a real service.
"""
@provide_gcp_context(GCP_MEMORYSTORE)
def setUp(self):
super().setUp()
self.create_gcs_bucket(GCP_BUCKET_NAME, location="europe-north1")
@provide_gcp_context(GCP_MEMORYSTORE)
def test_run_ex... | identifier_body |
huge-largest-array.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
assert_eq!(size_of::<[u8; (1 << 47) - 1]>(), (1 << 47) - 1);
} | identifier_body | |
huge-largest-array.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
assert_eq!(size_of::<[u8; (1 << 47) - 1]>(), (1 << 47) - 1);
}
| main | identifier_name |
huge-largest-array.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // except according to those terms.
// run-pass
use std::mem::size_of;
#[cfg(target_pointer_width = "32")]
pub fn main() {
assert_eq!(size_of::<[u8; (1 << 31) - 1]>(), (1 << 31) - 1);
}
#[cfg(target_pointer_width = "64")]
pub fn main() {
assert_eq!(size_of::<[u8; (1 << 47) - 1]>(), (1 << 47) - 1);
} | random_line_split | |
subselect.py | import re
from unittest import TestCase
def mark_quoted_strings(sql):
"""Mark all quoted strings in the SOQL by '@' and get them as params,
with respect to all escaped backslashes and quotes.
"""
pm_pattern = re.compile(r"'[^\\']*(?:\\[\\'][^\\']*)*'")
bs_pattern = re.compile(r"\\([\\'])")
out_... |
def transform_except_subselect(sql, func):
"""Call a func on every part of SOQL query except nested (SELECT ...)"""
start = 0
out = []
while sql.find('(SELECT', start) > -1:
pos = sql.find('(SELECT', start)
out.append(func(sql[start:pos]))
start, pos = find_closing_parenthesis(... | assert level > 0
level -= 1
if level == 0:
closing = match.end()
return opening, closing | conditional_block |
subselect.py | import re
from unittest import TestCase
def | (sql):
"""Mark all quoted strings in the SOQL by '@' and get them as params,
with respect to all escaped backslashes and quotes.
"""
pm_pattern = re.compile(r"'[^\\']*(?:\\[\\'][^\\']*)*'")
bs_pattern = re.compile(r"\\([\\'])")
out_pattern = re.compile("^[-!()*+,.:<=>\w\s]*$")
start = 0
... | mark_quoted_strings | identifier_name |
subselect.py | import re
from unittest import TestCase
def mark_quoted_strings(sql):
"""Mark all quoted strings in the SOQL by '@' and get them as params,
with respect to all escaped backslashes and quotes.
"""
pm_pattern = re.compile(r"'[^\\']*(?:\\[\\'][^\\']*)*'")
bs_pattern = re.compile(r"\\([\\'])")
out_... | Starts search at the position startpos.
Returns tuple of positions (opening, closing) if search succeeds, otherwise None.
"""
pattern = re.compile(r'[()]')
level = 0
opening = 0
for match in pattern.finditer(sql, startpos):
par = match.group()
if par == '(':
if le... | def find_closing_parenthesis(sql, startpos):
"""Find the pair of opening and closing parentheses.
| random_line_split |
subselect.py | import re
from unittest import TestCase
def mark_quoted_strings(sql):
"""Mark all quoted strings in the SOQL by '@' and get them as params,
with respect to all escaped backslashes and quotes.
"""
pm_pattern = re.compile(r"'[^\\']*(?:\\[\\'][^\\']*)*'")
bs_pattern = re.compile(r"\\([\\'])")
out_... |
class ReplaceQuotedStringsTest(TestCase):
def test_subst_quoted_strings(self):
def inner(sql, expected):
result = mark_quoted_strings(sql)
self.assertEqual(result, expected)
self.assertEqual(subst_quoted_strings(*result), sql)
inner("where x=''", ("where x=@", ... | sql = "SELECT a, (SELECT x, (SELECT p FROM q) FROM y) FROM b"
func = lambda x: '*transfomed*'
expected = "*transfomed*(SELECT x, (SELECT p FROM q) FROM y)*transfomed*"
self.assertEqual(transform_except_subselect(sql, func), expected) | identifier_body |
timeline.js | function(head, req) {
var ddoc = this,
path = require("vendor/couchapp/lib/path").init(req);
send('{"dateTimeFormat": "iso8601", "events": [');
var sep = "";
while(row = getRow()) {
var doc = row.doc;
var coordinates = null;
if (doc.Latitude && doc.Longit... |
var event = {
start: date_parts[0] + "T" + date_parts[1],
title: doc.Type,
description: summary,
link: path.show("report", doc._id),
coordinates: coordinates,
id: doc._id,
long_... | {
summary = (doc.Summary.replace(/<(.|\n)*?>/g, '').substring(0,350) + '...');
} | conditional_block |
timeline.js | function(head, req) {
var ddoc = this,
path = require("vendor/couchapp/lib/path").init(req);
send('{"dateTimeFormat": "iso8601", "events": [');
var sep = "";
while(row = getRow()) {
var doc = row.doc; |
if (doc.Latitude && doc.Longitude) {
coordinates = [parseFloat(doc.Longitude), parseFloat(doc.Latitude)];
var date_parts = doc.Date.split(" ");
var summary = '';
if (doc.Summary && doc.Summary.length <= 350) {
summary = doc.Summary;
... |
var coordinates = null; | random_line_split |
delete.py | from logbook import Logger
from ..core.local import get_current_conf
from ..core.connection import autoccontext
from .. import db
from datetime import timedelta, datetime
log = Logger(__name__)
def | ():
conf = get_current_conf()
with autoccontext(commit=True) as conn:
before = db.get_query_count(conn)
db.del_inactive_queries(
conn,
before=datetime.utcnow() - timedelta(days=conf['TORABOT_DELETE_INACTIVE_QUERIES_BEFORE_DAYS']),
limit=conf['TORABOT_DELETE_IN... | del_inactive_queries | identifier_name |
delete.py | from logbook import Logger
from ..core.local import get_current_conf
from ..core.connection import autoccontext
from .. import db
from datetime import timedelta, datetime
log = Logger(__name__)
def del_inactive_queries():
conf = get_current_conf()
with autoccontext(commit=True) as conn:
before = db.... | conn,
before=datetime.utcnow() - timedelta(days=conf['TORABOT_DELETE_INACTIVE_QUERIES_BEFORE_DAYS']),
limit=conf['TORABOT_DELETE_INACTIVE_QUERIES_LIMIT']
)
after = db.get_query_count(conn)
log.info('delete inactive queries, from {} to {}, deleted {}', before, ... | random_line_split | |
delete.py | from logbook import Logger
from ..core.local import get_current_conf
from ..core.connection import autoccontext
from .. import db
from datetime import timedelta, datetime
log = Logger(__name__)
def del_inactive_queries():
conf = get_current_conf()
with autoccontext(commit=True) as conn:
before = db.... | conf = get_current_conf()
with autoccontext(commit=True) as conn:
before = db.get_change_count(conn)
db.del_old_changes(
conn,
before=datetime.utcnow() - timedelta(days=conf['TORABOT_DELETE_OLD_CHANGES_BEFORE_DAYS']),
limit=conf['TORABOT_DELETE_OLD_CHANGES_LIMIT']... | identifier_body | |
jenkins_discovery.py | #!/usr/bin/env python
# Jenkins server UDP based discovery
# Based on original work by Gordon McGregor gordon.mcgregor@verilab.com
#
# Author Aske Olsson aske.olsson@switch-gears.dk
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.application.inter... | # print datagram
try:
xml = str.lower(datagram)
root = ET.fromstring(xml)
# Check if we received a datagram from another Jenkins/Hudson instance
if root.tag == 'hudson' or root.tag == 'jenkins':
for url in root.findall('url'):
# print "Jenkins url:", url.text
if not url.text in... | def datagramReceived(self, datagram, address): | random_line_split |
jenkins_discovery.py | #!/usr/bin/env python
# Jenkins server UDP based discovery
# Based on original work by Gordon McGregor gordon.mcgregor@verilab.com
#
# Author Aske Olsson aske.olsson@switch-gears.dk
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.application.inter... | discovery = JenkinsDiscovery()
reactor.listenMulticast(UDP_PORT, discovery)
refresh = task.LoopingCall(discovery.refreshList)
refresh.start(DELAY)
reactor.run() | conditional_block | |
jenkins_discovery.py | #!/usr/bin/env python
# Jenkins server UDP based discovery
# Based on original work by Gordon McGregor gordon.mcgregor@verilab.com
#
# Author Aske Olsson aske.olsson@switch-gears.dk
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.application.inter... |
def refreshList(self):
# print 'Refreshing list...'
self.instances = {}
self.ping()
def ping(self):
self.transport.write(self.ping_str, (MULTICAST_ADDR, UDP_PORT))
def datagramReceived(self, datagram, address):
# print datagram
try:
xml = str.lower(datagram)
root = ET.fr... | self.transport.joinGroup(MULTICAST_ADDR) | identifier_body |
jenkins_discovery.py | #!/usr/bin/env python
# Jenkins server UDP based discovery
# Based on original work by Gordon McGregor gordon.mcgregor@verilab.com
#
# Author Aske Olsson aske.olsson@switch-gears.dk
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.application.inter... | (self):
self.instances = {}
self.ping_str = 'Hello Jenkins, Where are you'
def startProtocol(self):
# print 'Host discovery: listening'
self.transport.joinGroup(MULTICAST_ADDR)
def refreshList(self):
# print 'Refreshing list...'
self.instances = {}
self.ping()
def ping(self):
... | __init__ | identifier_name |
brightcovePlayer.py | import httplib
from pyamf import AMF0, AMF3
from pyamf import remoting
from pyamf.remoting.client import RemotingService
height = 1080
def build_amf_request(const, playerID, videoPlayer, publisherID):
|
def get_clip_info(const, playerID, videoPlayer, publisherID, playerKey):
conn = httplib.HTTPConnection("c.brightcove.com")
envelope = build_amf_request(const, playerID, videoPlayer, publisherID)
conn.request("POST", "/services/messagebroker/amf?playerKey=" + playerKey, str(remoting.encode(envelope).read()... | env = remoting.Envelope(amfVersion=3)
env.bodies.append(
(
"/1",
remoting.Request(
target="com.brightcove.player.runtime.PlayerMediaFacade.findMediaById",
body=[const, playerID, videoPlayer, publisherID],
envelope=env
)
... | identifier_body |
brightcovePlayer.py | import httplib
from pyamf import AMF0, AMF3
from pyamf import remoting
from pyamf.remoting.client import RemotingService
height = 1080
def build_amf_request(const, playerID, videoPlayer, publisherID):
env = remoting.Envelope(amfVersion=3)
env.bodies.append(
(
"/1",
remotin... |
def play(const, playerID, videoPlayer, publisherID, playerKey):
rtmpdata = get_clip_info(const, playerID, videoPlayer, publisherID, playerKey)
streamName = ""
streamUrl = rtmpdata['FLVFullLengthURL'];
for item in sorted(rtmpdata['renditions'], key=lambda item:item['frameHeight'], reverse=False):
... | envelope = build_amf_request(const, playerID, videoPlayer, publisherID)
conn.request("POST", "/services/messagebroker/amf?playerKey=" + playerKey, str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
response = conn.getresponse().read()
response = remoting.decode(response).bodie... | random_line_split |
brightcovePlayer.py | import httplib
from pyamf import AMF0, AMF3
from pyamf import remoting
from pyamf.remoting.client import RemotingService
height = 1080
def build_amf_request(const, playerID, videoPlayer, publisherID):
env = remoting.Envelope(amfVersion=3)
env.bodies.append(
(
"/1",
remotin... | (const, playerID, videoPlayer, publisherID, playerKey):
rtmpdata = get_clip_info(const, playerID, videoPlayer, publisherID, playerKey)
streamName = ""
streamUrl = rtmpdata['FLVFullLengthURL'];
for item in sorted(rtmpdata['renditions'], key=lambda item:item['frameHeight'], reverse=False):
st... | play | identifier_name |
brightcovePlayer.py | import httplib
from pyamf import AMF0, AMF3
from pyamf import remoting
from pyamf.remoting.client import RemotingService
height = 1080
def build_amf_request(const, playerID, videoPlayer, publisherID):
env = remoting.Envelope(amfVersion=3)
env.bodies.append(
(
"/1",
remotin... |
streamName = streamName + rtmpdata['displayName']
return [streamName, streamUrl];
| streamUrl = item['defaultURL'] | conditional_block |
logger_setup.py | '''
logger_setup.py customizes the app's logging module. Each time an event is
logged the logger checks the level of the event (eg. debug, warning, info...).
If the event is above the approved threshold then it goes through. The handlers
do the same thing; they output to a file/shell if the event level is above their
t... |
# Wrap the application logger with structlog to format the output
logger = wrap_logger(
app.logger,
processors=[
add_fields,
JSONRenderer(indent=None)
]
) | file_handler = RotatingFileHandler(filename=app.config['LOG_FILENAME'],
maxBytes=app.config['LOG_MAXBYTES'],
backupCount=app.config['LOG_BACKUPS'],
mode='a',
encodi... | conditional_block |
logger_setup.py | '''
logger_setup.py customizes the app's logging module. Each time an event is
logged the logger checks the level of the event (eg. debug, warning, info...).
If the event is above the approved threshold then it goes through. The handlers
do the same thing; they output to a file/shell if the event level is above their
t... |
# Add a handler to write log messages to a file
if app.config.get('LOG_FILE'):
file_handler = RotatingFileHandler(filename=app.config['LOG_FILENAME'],
maxBytes=app.config['LOG_MAXBYTES'],
backupCount=app.config['LOG_BACKUPS'],
... | ''' Add custom fields to each record. '''
now = dt.datetime.now()
#event_dict['timestamp'] = TZ.localize(now, True).astimezone(pytz.utc).isoformat()
event_dict['timestamp'] = TZ.localize(now, True).astimezone\
(pytz.timezone(app.config['TIMEZONE'])).strftime(app.config['TIME_FMT'])
event_dict['l... | identifier_body |
logger_setup.py | '''
logger_setup.py customizes the app's logging module. Each time an event is
logged the logger checks the level of the event (eg. debug, warning, info...).
If the event is above the approved threshold then it goes through. The handlers
do the same thing; they output to a file/shell if the event level is above their
t... | (pytz.timezone(app.config['TIMEZONE'])).strftime(app.config['TIME_FMT'])
event_dict['level'] = level
if request:
try:
#event_dict['ip_address'] = request.headers['X-Forwarded-For'].split(',')[0].strip()
event_dict['ip_address'] = request.headers.get('X-Forwarded-For', req... | now = dt.datetime.now()
#event_dict['timestamp'] = TZ.localize(now, True).astimezone(pytz.utc).isoformat()
event_dict['timestamp'] = TZ.localize(now, True).astimezone\ | random_line_split |
logger_setup.py | '''
logger_setup.py customizes the app's logging module. Each time an event is
logged the logger checks the level of the event (eg. debug, warning, info...).
If the event is above the approved threshold then it goes through. The handlers
do the same thing; they output to a file/shell if the event level is above their
t... | (_, level, event_dict):
''' Add custom fields to each record. '''
now = dt.datetime.now()
#event_dict['timestamp'] = TZ.localize(now, True).astimezone(pytz.utc).isoformat()
event_dict['timestamp'] = TZ.localize(now, True).astimezone\
(pytz.timezone(app.config['TIMEZONE'])).strftime(app.config['T... | add_fields | identifier_name |
beamsearch_runner.py | from typing import Callable, List, Dict, Optional
import numpy as np
from typeguard import check_argument_types
from neuralmonkey.model.model_part import ModelPart
from neuralmonkey.decoders.beam_search_decoder import (BeamSearchDecoder,
SearchStepOutput)
from ne... |
self._rank = rank
self._all_encoders = all_encoders
self._bs_outputs = bs_outputs
self._vocabulary = vocabulary
self._postprocess = postprocess
self.result = None # type: Optional[ExecutionResult]
def next_to_execute(self) -> NextExecute:
return self._all_... | all_encoders: List[ModelPart],
bs_outputs: SearchStepOutput,
vocabulary: Vocabulary,
postprocess: Optional[Callable]) -> None: | random_line_split |
beamsearch_runner.py | from typing import Callable, List, Dict, Optional
import numpy as np
from typeguard import check_argument_types
from neuralmonkey.model.model_part import ModelPart
from neuralmonkey.decoders.beam_search_decoder import (BeamSearchDecoder,
SearchStepOutput)
from ne... |
def beam_search_runner_range(output_series: str,
decoder: BeamSearchDecoder,
max_rank: int = None,
postprocess: Callable[
[List[str]], List[str]]=None
) -> List[BeamSear... | return None | identifier_body |
beamsearch_runner.py | from typing import Callable, List, Dict, Optional
import numpy as np
from typeguard import check_argument_types
from neuralmonkey.model.model_part import ModelPart
from neuralmonkey.decoders.beam_search_decoder import (BeamSearchDecoder,
SearchStepOutput)
from ne... |
self._rank = rank
self._postprocess = postprocess
def get_executable(self,
compute_losses: bool = False,
summaries: bool = True) -> BeamSearchExecutable:
return BeamSearchExecutable(
self._rank, self.all_coders, self._decoder.outpu... | raise ValueError(
("Rank of output hypothesis must be between 1 and the beam "
"size ({}), was {}.").format(decoder.beam_size, rank)) | conditional_block |
beamsearch_runner.py | from typing import Callable, List, Dict, Optional
import numpy as np
from typeguard import check_argument_types
from neuralmonkey.model.model_part import ModelPart
from neuralmonkey.decoders.beam_search_decoder import (BeamSearchDecoder,
SearchStepOutput)
from ne... | (BaseRunner):
def __init__(self,
output_series: str,
decoder: BeamSearchDecoder,
rank: int = 1,
postprocess: Callable[[List[str]], List[str]] = None) -> None:
super(BeamSearchRunner, self).__init__(output_series, decoder)
check_argu... | BeamSearchRunner | identifier_name |
pgconf.py | authentication_timeout', 'ms', 2500)
"""
import os
import os.path
import re
# Max recursion level for postgresql.conf include directives.
# The max value is 10 in the postgres code, so it's the same here.
MAX_RECURSION_LEVEL=10
def readfile(filename='postgresql.conf', defaultpath=None):
"""
Read postgresql.c... |
fp = open(filename)
try:
dictionary = gucdict()
dictionary.populate(fp, filename)
return dictionary
except Exception:
raise
finally:
fp.close()
class gucdict(dict):
"""
A container for settings from a postgresql.conf file.
Behaves as an ordinary d... | if defaultpath is None:
defaultpath = os.getcwd()
filename = os.path.normpath(os.path.join(defaultpath, filename)) | conditional_block |
pgconf.py | authentication_timeout', 'ms', 2500)
"""
import os
import os.path
import re
# Max recursion level for postgresql.conf include directives.
# The max value is 10 in the postgres code, so it's the same here.
MAX_RECURSION_LEVEL=10
def readfile(filename='postgresql.conf', defaultpath=None):
"""
Read postgresql.c... | (self):
"""
Interpret the value as an integer. Returns an int or long.
"""
try:
return int(self.value, 0)
except ValueError:
raise self.ConfigurationError('Value should be integer.')
def float(self):
"""
Interpret the value as floatin... | int | identifier_name |
pgconf.py | authentication_timeout', 'ms', 2500)
"""
import os
import os.path
import re
# Max recursion level for postgresql.conf include directives.
# The max value is 10 in the postgres code, so it's the same here.
MAX_RECURSION_LEVEL=10
def readfile(filename='postgresql.conf', defaultpath=None):
"""
Read postgresql.c... |
def kB(self):
"""
Interpret the value as an amount of memory. Returns an int or long,
in units of 1024 bytes.
"""
try:
m = 1
t = re.split('(kB|MB|GB)', self.value)
if len(t) > 1:
i = ['kB', 'MB', 'GB'].index(t[1])
... | """
Interpret the value as floating point. Returns a float.
"""
try:
return float(self.value)
except ValueError:
raise self.ConfigurationError('Value should be floating point.') | identifier_body |
pgconf.py | ('authentication_timeout', 'ms', 2500)
"""
import os
import os.path
import re
# Max recursion level for postgresql.conf include directives.
# The max value is 10 in the postgres code, so it's the same here.
MAX_RECURSION_LEVEL=10
def readfile(filename='postgresql.conf', defaultpath=None):
"""
Read postgresql... |
linenumber = 0
for line in lines:
linenumber += 1
m = _setpat.match(line)
if m:
name, value, pos = m.group(1), m.group(3), m.start(3)
if name == 'include':
try:
# Remove the ' from th... | into our dictionary.
'''
if recurLevel == MAX_RECURSION_LEVEL:
raise Exception('could not open configuration file "%s": maximum nesting depth exceeded' % filename) | random_line_split |
sagas.ts | import { put, takeLatest, all, call } from 'redux-saga/effects'
import request from 'ROOT_SOURCE/utils/request'
import { Action4All } from 'ROOT_SOURCE/utils/types'
import { CURRENT_PAGE, PAGE_SIZE, TOTAL, RESPONSE_DESTRUST_KEY,
RESPONSE_LIST_DESTRUST_KEY } from 'ROOT_SOURCE/base/BaseConfig'
import {
LIST__UP... | a
yield put({ type: LIST__UPDATE_FORM_DATA, payload: {
..._formData,
[TOTAL]: resultBody[TOTAL],
} })
// 更新tableData
yield put({ type: LIST__UPDATE_TABLE_DATA, payload: {
dataSource: resultBody[RESPONSE_LIST_DESTRUST_KEY],
} })
}
export default function* asyncSaga... | / 更新formDat | conditional_block |
sagas.ts | import { put, takeLatest, all, call } from 'redux-saga/effects'
import request from 'ROOT_SOURCE/utils/request'
import { Action4All } from 'ROOT_SOURCE/utils/types'
import { CURRENT_PAGE, PAGE_SIZE, TOTAL, RESPONSE_DESTRUST_KEY,
RESPONSE_LIST_DESTRUST_KEY } from 'ROOT_SOURCE/base/BaseConfig'
import {
LIST__UP... | {[PAGE_SIZE]: 10, [CURRENT_PAGE]: 1},
action.payload,
)
// 请求server数据
let result = yield call(request.post, '/asset/getAsset', _formData)
if (!result) { return; }
// 解构server结果
let resultBody = result[RESPONSE_DESTRUST_KEY]
if (!resultBody) { return; ... |
function* submitFormAsync(action: Action4All) {
// 初始化antd-table-pagination
let _formData = Object.assign( | random_line_split |
product-list.ts | import { Component } from '@angular/core';
import { NavController, Keyboard } from 'ionic-angular';
import { OvhRequestService } from '../../../services/ovh-request/ovh-request.service';
import { categoryEnum } from '../../../config/constants';
import { Subscription } from 'rxjs/Subscription';
import { AnalyticsService... | .subscribe(
(products) => {
this.products = products;
this.sortProducts();
},
null,
() => this.loading = false
);
}
sortProducts() {
if (!this.search) {
this.productsFiltered = this.products;
} else {
this.productsFiltered = this.p... | random_line_split | |
product-list.ts | import { Component } from '@angular/core';
import { NavController, Keyboard } from 'ionic-angular';
import { OvhRequestService } from '../../../services/ovh-request/ovh-request.service';
import { categoryEnum } from '../../../config/constants';
import { Subscription } from 'rxjs/Subscription';
import { AnalyticsService... | {
loading: boolean = true;
search: string;
products: Array<string> = [];
productsFiltered: Array<string> = [];
category: any = categoryEnum.DOMAIN;
categoryKeys: Array<string> = Object.keys(categoryEnum).filter((category) => category !== 'PROJECT');
categoryEnum: any = categoryEnum;
subscribtion: Subsc... | ProductListPage | identifier_name |
product-list.ts | import { Component } from '@angular/core';
import { NavController, Keyboard } from 'ionic-angular';
import { OvhRequestService } from '../../../services/ovh-request/ovh-request.service';
import { categoryEnum } from '../../../config/constants';
import { Subscription } from 'rxjs/Subscription';
import { AnalyticsService... |
}
| {
this.keyboard.close();
} | identifier_body |
product-list.ts | import { Component } from '@angular/core';
import { NavController, Keyboard } from 'ionic-angular';
import { OvhRequestService } from '../../../services/ovh-request/ovh-request.service';
import { categoryEnum } from '../../../config/constants';
import { Subscription } from 'rxjs/Subscription';
import { AnalyticsService... | else {
this.productsFiltered = this.products.filter((product) => product.toLowerCase().indexOf(this.search.toLowerCase()) !== -1);
}
}
moreInfos(serviceName: string) {
this.navController.push(this.category.page, { serviceName });
}
closeKeyboard(): void {
this.keyboard.close();
}
}
| {
this.productsFiltered = this.products;
} | conditional_block |
fileUploadHandler.js | import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
import { Tracker } from 'meteor/tracker';
import { UploadFS } from 'meteor/jalik:ufs';
import { FileUploadBase } from '../../lib/FileUploadBase';
import { Uploads, Avatars } from '../../../models';
new UploadFS.Store({
collectio... | if (store) {
return new FileUploadBase(store, meta, file);
}
console.error('Invalid file store', directive);
};
Tracker.autorun(function() {
if (Meteor.userId()) {
document.cookie = `rc_uid=${ escape(Meteor.userId()) }; path=/`;
document.cookie = `rc_token=${ escape(Accounts._storedLoginToken()) }; path=/`;
... | random_line_split | |
fileUploadHandler.js | import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
import { Tracker } from 'meteor/tracker';
import { UploadFS } from 'meteor/jalik:ufs';
import { FileUploadBase } from '../../lib/FileUploadBase';
import { Uploads, Avatars } from '../../../models';
new UploadFS.Store({
collectio... |
console.error('Invalid file store', directive);
};
Tracker.autorun(function() {
if (Meteor.userId()) {
document.cookie = `rc_uid=${ escape(Meteor.userId()) }; path=/`;
document.cookie = `rc_token=${ escape(Accounts._storedLoginToken()) }; path=/`;
}
});
| {
return new FileUploadBase(store, meta, file);
} | conditional_block |
mailbox.py | ")
return self.collection.set_mbox_attr("flags", flags)
def getUIDValidity(self):
"""
Return the unique validity identifier for this mailbox.
:return: unique validity identifier
:rtype: int
"""
return self.collection.get_mbox_attr("created")
def getUID(... |
return d
return defer.succeed(messages_asked)
def _filter_msg_seq(self, messages_asked):
"""
Filter a message sequence returning only the ones that do exist in the
collection.
:param messages_asked: IDs of the messages.
:type messages_asked: Message... | d = self.collection.all_uid_iter()
d.addCallback(set_last_seq) | conditional_block |
mailbox.py | (object):
"""
A Soledad-backed IMAP mailbox.
Implements the high-level method needed for the Mailbox interfaces.
The low-level database methods are contained in the generic
MessageCollection class. We receive an instance of it and it is made
accessible in the `collection` attribute.
"""
... | IMAPMailbox | identifier_name | |
mailbox.py | tuple")
return self.collection.set_mbox_attr("flags", flags)
def getUIDValidity(self):
"""
Return the unique validity identifier for this mailbox.
:return: unique validity identifier
:rtype: int
"""
return self.collection.get_mbox_attr("created")
def g... | Returns the number of messages with the 'Unseen' flag.
:return: count of messages flagged `unseen`
:rtype: int
"""
return self.collection.count_unseen()
def getRecentCount(self):
"""
Returns the number of messages with the 'Recent' flag.
:return: co... | return self.collection.count()
def getUnseenCount(self):
""" | random_line_split |
mailbox.py | _last_uid(last_uid):
messages_asked.last = last_uid
return messages_asked
def set_last_seq(all_uid):
messages_asked.last = len(all_uid)
return messages_asked
if not messages_asked.last:
try:
iter(messages_asked)
ex... | """
Sets the flags of one or more messages.
:param messages: The identifiers of the messages to set the flags
:type messages: A MessageSet object with the list of messages requested
:param flags: The flags to set, unset, or add.
:type flags: sequence of str
:param mode... | identifier_body | |
namespaced-enum-glob-import-no-impls.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | } | m::bar(); //~ ERROR unresolved name `m::bar` | random_line_split |
namespaced-enum-glob-import-no-impls.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {}
pub fn bar(&self) {}
}
}
mod m {
pub use m2::Foo::*;
}
pub fn main() {
use m2::Foo::*;
foo(); //~ ERROR unresolved name `foo`
m::foo(); //~ ERROR unresolved name `m::foo`
bar(); //~ ERROR unresolved name `bar`
m::bar(); //~ ERROR unresolved name `m::bar`
}
| foo | identifier_name |
dashboard.js | console.log(URL_FILE_SERVER);
var lastID = 0;
var getLastId = function() {
return lastID;
};
var loadNextFile = function() { | url: URL_FILE_SERVER + getLastId(),
dataType: 'json',
method: "GET",
success: function(result) {
console.log(result)
lastID = parseInt(result.lastId);
$('#conteudo').append(result.html);
if ($("#conteudo .imagem").length <= 10) {
... | console.log(URL_FILE_SERVER + lastID);
$.ajax({ | random_line_split |
dashboard.js | console.log(URL_FILE_SERVER);
var lastID = 0;
var getLastId = function() {
return lastID;
};
var loadNextFile = function() {
console.log(URL_FILE_SERVER + lastID);
$.ajax({
url: URL_FILE_SERVER + getLastId(),
dataType: 'json',
method: "GET",
success: function(result) {
... |
},
error: function(e) {
console.log("ERROR:");
console.log(e);
}
})
};
$(function() {
if ($("#conteudo .imagem").length <= 1) {
loadNextFile();
}
var win = $(window);
// Each time the user scrolls
win.scroll(function() {
// End o... | {
loadNextFile();
} | conditional_block |
plugin.py | import StringIO
class Plugin(object):
|
if cls.ANGULAR_MODULE:
out.write("""
<script>var manuskriptPluginsList = manuskriptPluginsList || [];\n
manuskriptPluginsList.push("%s");</script>\n""" % cls.ANGULAR_MODULE)
return out.getvalue()
| ANGULAR_MODULE = None
JS_FILES = []
CSS_FILES = []
@classmethod
def PlugIntoApp(cls, app):
pass
@classmethod
def GenerateHTML(cls, root_url="/"):
out = StringIO.StringIO()
for js_file in cls.JS_FILES:
js_file = js_file.lstrip("/")
out.write('<sc... | identifier_body |
plugin.py | import StringIO
class Plugin(object):
ANGULAR_MODULE = None
JS_FILES = []
CSS_FILES = []
@classmethod
def PlugIntoApp(cls, app):
pass
@classmethod
def GenerateHTML(cls, root_url="/"):
out = StringIO.StringIO()
for js_file in cls.JS_FILES:
|
for css_file in cls.CSS_FILES:
css_file = css_file.lstrip("/")
out.write('<link rel="stylesheet" href="%s%s"></link>\n' % (
root_url, css_file))
if cls.ANGULAR_MODULE:
out.write("""
<script>var manuskriptPluginsList = manuskriptPluginsList || [];\n
... | js_file = js_file.lstrip("/")
out.write('<script src="%s%s"></script>\n' % (root_url, js_file)) | conditional_block |
plugin.py | import StringIO
class Plugin(object):
ANGULAR_MODULE = None
JS_FILES = []
CSS_FILES = []
@classmethod
def PlugIntoApp(cls, app):
pass
@classmethod | for js_file in cls.JS_FILES:
js_file = js_file.lstrip("/")
out.write('<script src="%s%s"></script>\n' % (root_url, js_file))
for css_file in cls.CSS_FILES:
css_file = css_file.lstrip("/")
out.write('<link rel="stylesheet" href="%s%s"></link>\n' % (
... | def GenerateHTML(cls, root_url="/"):
out = StringIO.StringIO() | random_line_split |
plugin.py | import StringIO
class Plugin(object):
ANGULAR_MODULE = None
JS_FILES = []
CSS_FILES = []
@classmethod
def | (cls, app):
pass
@classmethod
def GenerateHTML(cls, root_url="/"):
out = StringIO.StringIO()
for js_file in cls.JS_FILES:
js_file = js_file.lstrip("/")
out.write('<script src="%s%s"></script>\n' % (root_url, js_file))
for css_file in cls.CSS_FILES:
... | PlugIntoApp | identifier_name |
Row.ts | import Cell, { ISerializedCell } from './Cell';
import { MODE } from '../store/types';
export interface ISerializedRow {
active: boolean;
cells: ISerializedCell[];
index: number;
}
export default class Row {
private cells: Cell[];
private index: number;
private active: boolean;
private constructor(previo... | (): Row {
const row = new Row(this);
row.cells = this.cells.map(c => c.clearNotes());
return row;
}
}
| clearCandidates | identifier_name |
Row.ts | import Cell, { ISerializedCell } from './Cell';
import { MODE } from '../store/types';
export interface ISerializedRow {
active: boolean;
cells: ISerializedCell[];
index: number;
}
export default class Row {
private cells: Cell[];
private index: number;
private active: boolean;
private constructor(previo... |
public getIndex(): number {
return this.index;
}
public toggleCell(index: number, column: number): Row {
if (this.index !== index && !this.active) {
return this;
}
const row = new Row(this);
if (this.active) {
if (this.index === index) {
row.cells = this.cells.map(c => ... | {
const row = new Row(this);
row.cells = this.cells.map(c => c.validate());
return row;
} | identifier_body |
Row.ts | import Cell, { ISerializedCell } from './Cell';
import { MODE } from '../store/types';
export interface ISerializedRow {
active: boolean;
cells: ISerializedCell[];
index: number;
}
export default class Row {
private cells: Cell[];
private index: number;
private active: boolean;
private constructor(previo... | if (!this.active) {
return this;
}
const row = new Row(this);
row.cells = this.cells.map(c => c.removeDigit());
return row;
}
public clearCandidates(): Row {
const row = new Row(this);
row.cells = this.cells.map(c => c.clearNotes());
return row;
}
} | random_line_split | |
Row.ts | import Cell, { ISerializedCell } from './Cell';
import { MODE } from '../store/types';
export interface ISerializedRow {
active: boolean;
cells: ISerializedCell[];
index: number;
}
export default class Row {
private cells: Cell[];
private index: number;
private active: boolean;
private constructor(previo... |
return row;
}
public isActive(): boolean {
return this.active;
}
public setDigit(digit: number, mode: MODE): Row {
if (!this.active) {
return this;
}
const row = new Row(this);
row.cells = this.cells.map(c => c.setDigit(digit, mode));
return row;
}
public removeDigit():... | {
row.active = true;
row.cells = this.cells.map(c => (c.getColumn() === column ? c.setActive(true) : c));
} | conditional_block |
fortios_api_firewall_ippool.py | #!/usr/bin/python
#
# Ansible module for managing Fortigate devices via API
# (c) 2017, Will Wagner <willwagner602@gmail.com> and Eugene Opredelennov <eoprede@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print... |
if __name__ == "__main__":
main()
| forti_api = API(system_global_api_args)
forti_api.apply_configuration_to_endpoint() | identifier_body |
fortios_api_firewall_ippool.py | #!/usr/bin/python
#
# Ansible module for managing Fortigate devices via API
# (c) 2017, Will Wagner <willwagner602@gmail.com> and Eugene Opredelennov <eoprede@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print... | main() | conditional_block | |
fortios_api_firewall_ippool.py | #!/usr/bin/python
#
# Ansible module for managing Fortigate devices via API
# (c) 2017, Will Wagner <willwagner602@gmail.com> and Eugene Opredelennov <eoprede@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print... | description: k/v pairs of parameters passed into module and sent to the device for changes
returned: always
type: list
existing:
description: k/v pairs of existing configuration
returned: always
type: list
end_state:
description: k/v pairs of configuration after module execution
return... | random_line_split | |
fortios_api_firewall_ippool.py | #!/usr/bin/python
#
# Ansible module for managing Fortigate devices via API
# (c) 2017, Will Wagner <willwagner602@gmail.com> and Eugene Opredelennov <eoprede@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print... | ():
forti_api = API(system_global_api_args)
forti_api.apply_configuration_to_endpoint()
if __name__ == "__main__":
main()
| main | identifier_name |
BugIcon.tsx | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... | ({ className, fill = 'currentColor', size }: IconProps) {
return (
<Icon className={className} size={size}>
<path
d="M8.01 10.9885h1v-5h-1v5zm3-2h1.265l.46.771.775-.543-.733-1.228H11.01v-.316l2-2.343v-2.341h-1v1.972l-1 1.172v-1.144h-.029c-.101-.826-.658-1.52-1.436-1.853l1.472-1.349-.676-.736-1.831 1... | BugIcon | identifier_name |
BugIcon.tsx | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Bost... | * version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of | random_line_split |
BugIcon.tsx | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... | {
return (
<Icon className={className} size={size}>
<path
d="M8.01 10.9885h1v-5h-1v5zm3-2h1.265l.46.771.775-.543-.733-1.228H11.01v-.316l2-2.343v-2.341h-1v1.972l-1 1.172v-1.144h-.029c-.101-.826-.658-1.52-1.436-1.853l1.472-1.349-.676-.736-1.831 1.678-1.831-1.678-.676.736 1.472 1.349c-.778.333-1.335 1.... | identifier_body | |
model.js | , or otherwise obtained. This `model` function is
// intended to be applicable for describing purely theoretical models of a
// phenomenon as well as real-time measurements of a phenomenon.
//
// "Measuring" a moment is left to the `measure_moment` function. Each
// model has to (re)implement this f... |
_model.register = function(view) {
var view_found = views.indexOf(view);
if (view_found === -1) {
views.push(view);
views.forEach(function(v) { if(v.update_all) v.update_all();});
}
};
_model.get_views_of_type = function(view_type) {
return views.fil... | _model.update_all_views = update_all_views; | random_line_split |
model.js | = {};
_model.add_action = function( action ) {
_model.actions[action.name] = action;
_model.actions[action.name].install = function() {
return action.callback(_model);
};
};
if (config.actions) {
var add_action = function(action_name) {
_model.add_act... | ments.len | identifier_name | |
model.js | model.actions[action.name].install = function() {
return action.callback(_model);
};
};
if (config.actions) {
var add_action = function(action_name) {
_model.add_action(config.actions[action_name]);
};
Object.keys(config.actions).forEach(add_action);
}... | 1) {
step = size;
}
return step;
}
_model.step_size = step_size; | identifier_body | |
model.js | , or otherwise obtained. This `model` function is
// intended to be applicable for describing purely theoretical models of a
// phenomenon as well as real-time measurements of a phenomenon.
//
// "Measuring" a moment is left to the `measure_moment` function. Each
// model has to (re)implement this f... | _model.toggle_action = function( action_name ) {
if (_model.actions[action_name]) {
_model.actions[action_name].enabled =
!_model.action[action_name].enabled;
}
};
// ## Coordinating quantities
//
// All quantities that describe the phenomenon be... | _model.actions[action_name].enabled = true;
}
};
| conditional_block |
credentials-in-url.https.window.js | // META: script=/service-workers/service-worker/resources/test-helpers.sub.js
// META: script=resources/utils.js
'use strict';
// "If parsedURL includes credentials, then throw a TypeError."
// https://fetch.spec.whatwg.org/#dom-request
// (Added by https://github.com/whatwg/fetch/issues/26).
// "A URL includes creden... | return bgFetch.fetch(uniqueTag(), 'https://example.com');
}, 'fetch without credentials in URL should register ok');
backgroundFetchTest((t, bgFetch) => {
return promise_rejects(
t, new TypeError(),
bgFetch.fetch(uniqueTag(), 'https://username:password@example.com'));
}, 'fetch with username and passwo... | random_line_split | |
result-info-native-replay-summary.py | #!/usr/bin/env python
# Copyright (c) 2016, Daniel Liew
# This file is covered by the license in LICENSE-SVCB.txt
# vim: set sw=4 ts=4 softtabstop=4 expandtab:
"""
Read a result info describing a set of KLEE test case replays.
"""
from load_klee_runner import add_KleeRunner_to_module_search_path
from load_klee_analysis... | for error in error_list:
print(error)
# Now emit as YAML
#as_yaml = yaml.dump(program_to_coverage_info, default_flow_style=False)
#pargs.output_yaml.write(as_yaml)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv)) | if ty == nativeanalysis.analyse.TimeoutError and pargs.dump_timeouts: | random_line_split |
result-info-native-replay-summary.py | #!/usr/bin/env python
# Copyright (c) 2016, Daniel Liew
# This file is covered by the license in LICENSE-SVCB.txt
# vim: set sw=4 ts=4 softtabstop=4 expandtab:
"""
Read a result info describing a set of KLEE test case replays.
"""
from load_klee_runner import add_KleeRunner_to_module_search_path
from load_klee_analysis... | if resultInfoMisc is None:
_logger.error('Expected result info to have misc data')
return 1
if resultInfoMisc['runner'] != 'NativeReplay':
_logger.error('Expected runner to have been NativeReplay but was "{}"'.format(
resultInfoMisc['runner']))
return 1
errorType... | parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('result_info_file',
help='Result info file',
type=argparse.FileType('r'))
parser.add_argument('--dump-unknowns',
dest='dump_unknowns',
action='store_true')
parser.add_arg... | identifier_body |
result-info-native-replay-summary.py | #!/usr/bin/env python
# Copyright (c) 2016, Daniel Liew
# This file is covered by the license in LICENSE-SVCB.txt
# vim: set sw=4 ts=4 softtabstop=4 expandtab:
"""
Read a result info describing a set of KLEE test case replays.
"""
from load_klee_runner import add_KleeRunner_to_module_search_path
from load_klee_analysis... | (args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('result_info_file',
help='Result info file',
type=argparse.FileType('r'))
parser.add_argument('--dump-unknowns',
dest='dump_unknowns',
action='store_true')
pa... | main | identifier_name |
result-info-native-replay-summary.py | #!/usr/bin/env python
# Copyright (c) 2016, Daniel Liew
# This file is covered by the license in LICENSE-SVCB.txt
# vim: set sw=4 ts=4 softtabstop=4 expandtab:
"""
Read a result info describing a set of KLEE test case replays.
"""
from load_klee_runner import add_KleeRunner_to_module_search_path
from load_klee_analysis... |
# Now emit as YAML
#as_yaml = yaml.dump(program_to_coverage_info, default_flow_style=False)
#pargs.output_yaml.write(as_yaml)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
| print(error) | conditional_block |
syntax_iterators.py | from typing import Union, Iterator
from ...symbols import NOUN, PROPN, PRON
from ...errors import Errors
from ...tokens import Doc, Span
def noun_chunks(doclike: Union[Doc, Span]) -> Iterator[Span]:
"""
Detect base noun phrases from a dependency parse. Works on both Doc and Span.
"""
# fmt: off
l... |
SYNTAX_ITERATORS = {"noun_chunks": noun_chunks}
| head = word.head
while head.dep == conj and head.head.i < head.i:
head = head.head
# If the head is an NP, and we're coordinated to it, we're an NP
if head.dep in np_deps:
prev_end = word.right_edge.i
yield word.left_edge.i, word.right_... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.