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 |
|---|---|---|---|---|
JoinRuleDropdown.tsx | /*
Copyright 2021 The Matrix.org Foundation C.I.C. |
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is ... | random_line_split | |
setupenv_windows.py | #-----------------------------------------------------------------------------
# Copyright (c) 2013, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this softwa... |
try:
__import__(k)
print 'Already installed... %s' % k
# Module is not available - install it.
except ImportError:
# If not url or module name then look for installers in download area.
if not v[0].startswith('http') and v[0].endswith('exe'):
... | continue | conditional_block |
setupenv_windows.py | #-----------------------------------------------------------------------------
# Copyright (c) 2013, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this softwa... |
_PACKAGES = {
'docutils': ['docutils'],
'jinja2': ['jinja2'],
'sphinx': ['sphinx'],
'pytz': ['pytz'],
'IPython': ['IPython'],
# 'modulename': 'pypi_name_or_url_or_path'
'MySQLdb': ['MySQL-python-*%s-py%s.exe' % (py_arch(), PYVER)],
'numpy': ['numpy-unoptimized-*%s-py%s.exe' % (py_arch... | """
.exe installers of Python modules contain architecture name in filename.
"""
mapping = {'32bit': 'win32', '64bit': 'win-amd64'}
arch = platform.architecture()[0]
return mapping[arch] | identifier_body |
setupenv_windows.py | #-----------------------------------------------------------------------------
# Copyright (c) 2013, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this softwa... |
if __name__ == '__main__':
main() | try:
easy_install.main(['--no-deps', '--always-unzip', f])
except Exception:
print ' %s installation failed' % k | random_line_split |
setupenv_windows.py | #-----------------------------------------------------------------------------
# Copyright (c) 2013, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this softwa... | ():
"""
.exe installers of Python modules contain architecture name in filename.
"""
mapping = {'32bit': 'win32', '64bit': 'win-amd64'}
arch = platform.architecture()[0]
return mapping[arch]
_PACKAGES = {
'docutils': ['docutils'],
'jinja2': ['jinja2'],
'sphinx': ['sphinx'],
'py... | py_arch | identifier_name |
coherence-overlap-downstream-inherent.rs | // Copyright 2017 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 ... | {} | identifier_body | |
coherence-overlap-downstream-inherent.rs | // Copyright 2017 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 A<T, X>(T, X);
impl<X, T> A<T, X> where T: Bar<X> { fn f(&self) {} }
//~^ ERROR E0592
impl<X> A<i32, X> { fn f(&self) {} }
fn main() {} | trait Bar<X> {} | random_line_split |
coherence-overlap-downstream-inherent.rs | // Copyright 2017 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 ... | (&self) { } }
trait Bar<X> {}
struct A<T, X>(T, X);
impl<X, T> A<T, X> where T: Bar<X> { fn f(&self) {} }
//~^ ERROR E0592
impl<X> A<i32, X> { fn f(&self) {} }
fn main() {}
| dummy | identifier_name |
pasterapp.py | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import logging
import os
import pkg_resources
import sys
import ConfigParser
from paste.deploy import loadapp, loadwsgi
SERVER = loadwsgi.SERVER
from gunicorn.app.base import Application
fr... | (PasterBaseApplication):
def __init__(self, app, gcfg=None, host="127.0.0.1", port=None, *args, **kwargs):
self.cfg = Config()
self.app = app
self.callable = None
gcfg = gcfg or {}
cfgfname = gcfg.get("__file__")
if cfgfname is not None:
self.cfgurl ... | PasterServerApplication | identifier_name |
pasterapp.py | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import logging
import os
import pkg_resources
import sys
import ConfigParser
from paste.deploy import loadapp, loadwsgi
SERVER = loadwsgi.SERVER
from gunicorn.app.base import Application
fr... |
return cfg
def configure_logging(self):
if hasattr(self, "cfgfname"):
self.logger = logging.getLogger('gunicorn')
# from paste.script.command
parser = ConfigParser.ConfigParser()
parser.read([self.cfgfname])
if parser.has_section('logger... | if k not in self.cfg.settings:
continue
cfg[k] = v | conditional_block |
pasterapp.py | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import logging
import os
import pkg_resources
import sys
import ConfigParser
from paste.deploy import loadapp, loadwsgi
SERVER = loadwsgi.SERVER
from gunicorn.app.base import Application
fr... | super(PasterBaseApplication, self).configure_logging()
class PasterApplication(PasterBaseApplication):
def init(self, parser, opts, args):
if len(args) != 1:
parser.error("No application name specified.")
cfgfname = os.path.normpath(os.path.join(os.getcwd(), args[0]))
... |
config_file = os.path.abspath(self.cfgfname)
fileConfig(config_file, dict(__file__=config_file,
here=os.path.dirname(config_file)))
return | random_line_split |
pasterapp.py | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import logging
import os
import pkg_resources
import sys
import ConfigParser
from paste.deploy import loadapp, loadwsgi
SERVER = loadwsgi.SERVER
from gunicorn.app.base import Application
fr... | for k, v in lc.items():
if k not in self.cfg.settings:
continue
cfg[k] = v
return cfg
def configure_logging(self):
if hasattr(self, "cfgfname"):
self.logger = logging.getLogger('gunicorn')
# from paste.script.command
... | def app_config(self):
cx = loadwsgi.loadcontext(SERVER, self.cfgurl, relative_to=self.relpath)
gc, lc = cx.global_conf.copy(), cx.local_conf.copy()
cfg = {}
host, port = lc.pop('host', ''), lc.pop('port', '')
if host and port:
cfg['bind'] = '%s:%s' % (host, p... | identifier_body |
ModuleWithExportedAndNonExportedImportAlias.js | //// [ModuleWithExportedAndNonExportedImportAlias.ts]
module A {
export interface Point {
x: number;
y: number;
}
interface Point3d extends Point {
z: number;
}
}
module B {
export class | {
constructor(public start: A.Point, public end: A.Point) { }
}
}
module Geometry {
export import Points = A;
import Lines = B;
export var Origin: Points.Point = { x: 0, y: 0 };
// this is valid since B.Line _is_ visible outside Geometry
export var Unit: Lines.Line = new Lines.Line(O... | Line | identifier_name |
ModuleWithExportedAndNonExportedImportAlias.js | //// [ModuleWithExportedAndNonExportedImportAlias.ts]
module A {
export interface Point {
x: number;
y: number;
}
interface Point3d extends Point {
z: number;
}
}
module B {
export class Line {
constructor(public start: A.Point, public end: A.Point) { }
}
}
mo... |
return Line;
})();
B.Line = Line;
})(B || (B = {}));
var Geometry;
(function (Geometry) {
var Lines = B;
Geometry.Origin = { x: 0, y: 0 };
Geometry.Unit = new Lines.Line(Geometry.Origin, { x: 1, y: 0 });
})(Geometry || (Geometry = {}));
var p;
var p;
var p = Geometry.Origin;
v... | {
this.start = start;
this.end = end;
} | identifier_body |
ModuleWithExportedAndNonExportedImportAlias.js | //// [ModuleWithExportedAndNonExportedImportAlias.ts]
module A {
export interface Point {
x: number;
y: number;
}
interface Point3d extends Point {
z: number;
}
}
module B {
export class Line {
constructor(public start: A.Point, public end: A.Point) { }
}
}
mo... | var line = Geometry.Lines.Line;
//// [ModuleWithExportedAndNonExportedImportAlias.js]
var B;
(function (B) {
var Line = (function () {
function Line(start, end) {
this.start = start;
this.end = end;
}
return Line;
})();
B.Line = Line;
})(B || (... | var line = Geometry.Unit;
// not expected to work since non are exported | random_line_split |
window.py | from gi.repository import Gtk, Gdk, GdkPixbuf
(TARGET_ENTRY_TEXT, TARGET_ENTRY_PIXBUF) = range(2)
(COLUMN_TEXT, COLUMN_PIXBUF) = range(2)
DRAG_ACTION = Gdk.DragAction.COPY
class DragDropWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Drag and Drop")
vbox = Gtk.Box(orien... |
def on_drag_data_received(self, widget, drag_context, x,y, data,info, time):
if info == TARGET_ENTRY_TEXT:
text = data.get_text()
print("Received text: %s" % text)
elif info == TARGET_ENTRY_PIXBUF:
pixbuf = data.get_pixbuf()
width = pixbuf.get_width... | Gtk.Label.__init__(self, "Drop something on me!")
self.drag_dest_set(Gtk.DestDefaults.ALL, [], DRAG_ACTION)
self.connect("drag-data-received", self.on_drag_data_received) | identifier_body |
window.py | from gi.repository import Gtk, Gdk, GdkPixbuf
(TARGET_ENTRY_TEXT, TARGET_ENTRY_PIXBUF) = range(2)
(COLUMN_TEXT, COLUMN_PIXBUF) = range(2)
DRAG_ACTION = Gdk.DragAction.COPY
class DragDropWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Drag and Drop")
vbox = Gtk.Box(orien... | (Gtk.IconView):
def __init__(self):
Gtk.IconView.__init__(self)
self.set_text_column(COLUMN_TEXT)
self.set_pixbuf_column(COLUMN_PIXBUF)
model = Gtk.ListStore(str, GdkPixbuf.Pixbuf)
self.set_model(model)
self.add_item("Item 1", "image-missing")
self.add_item(... | DragSourceIconView | identifier_name |
window.py | from gi.repository import Gtk, Gdk, GdkPixbuf
(TARGET_ENTRY_TEXT, TARGET_ENTRY_PIXBUF) = range(2)
(COLUMN_TEXT, COLUMN_PIXBUF) = range(2)
DRAG_ACTION = Gdk.DragAction.COPY
class DragDropWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Drag and Drop")
vbox = Gtk.Box(orien... |
def add_item(self, text, icon_name):
pixbuf = Gtk.IconTheme.get_default().load_icon(icon_name, 16, 0)
self.get_model().append([text, pixbuf])
class DropArea(Gtk.Label):
def __init__(self):
Gtk.Label.__init__(self, "Drop something on me!")
self.drag_dest_set(Gtk.DestDefaults.... | pixbuf = self.get_model().get_value(selected_iter, COLUMN_PIXBUF)
data.set_pixbuf(pixbuf) | conditional_block |
window.py | from gi.repository import Gtk, Gdk, GdkPixbuf
(TARGET_ENTRY_TEXT, TARGET_ENTRY_PIXBUF) = range(2)
(COLUMN_TEXT, COLUMN_PIXBUF) = range(2)
DRAG_ACTION = Gdk.DragAction.COPY
class DragDropWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Drag and Drop")
vbox = Gtk.Box(orien... |
class DropArea(Gtk.Label):
def __init__(self):
Gtk.Label.__init__(self, "Drop something on me!")
self.drag_dest_set(Gtk.DestDefaults.ALL, [], DRAG_ACTION)
self.connect("drag-data-received", self.on_drag_data_received)
def on_drag_data_received(self, widget, drag_context, x,y, data,in... | self.get_model().append([text, pixbuf])
| random_line_split |
htmlselectelement.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 dom::attr::{Attr, AttrValue};
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::binding... | (&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r())
}
// Note: this function currently only exists for union.html.
// https://html.spec.whatwg.org/multipage/#dom-select-add
fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _... | Validity | identifier_name |
htmlselectelement.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 dom::attr::{Attr, AttrValue};
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::binding... | impl HTMLSelectElementMethods for HTMLSelectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r())
}
// Note: this function currently only exists for union.html... | }
}
| random_line_split |
htmlselectelement.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 dom::attr::{Attr, AttrValue};
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::binding... | else {
node.check_disabled_attribute();
}
}
fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue {
match local_name {
&atom!("size") => AttrValue::from_u32(value, DEFAULT_SELECT_SIZE),
_ => self.super_type().unwrap().parse_plain_... | {
node.check_ancestors_disabled_state_for_form_control();
} | conditional_block |
htmlselectelement.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 dom::attr::{Attr, AttrValue};
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::binding... |
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
let node = NodeCast::from_ref(self);
node.check_ancestors_disabled_state_for_form_control();
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
... | {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if attr.local_name() == &atom!(disabled) {
let node = NodeCast::from_ref(self);
match mutation {
AttributeMutation::Set(_) => {
node.set_disabled_state(true);
n... | identifier_body |
date.rs | use std::fmt;
use std::str::FromStr;
use time::Tm;
use header::{Header, HeaderFormat};
use header::parsing::from_one_raw_str;
use header::parsing::tm_from_str;
// Egh, replace as soon as something better than time::Tm exists.
/// The `Date` header field.
#[derive(Copy, PartialEq, Clone, Debug)]
pub struct Date(pub Tm)... |
}
bench_header!(imf_fixdate, Date, { vec![b"Sun, 07 Nov 1994 08:48:37 GMT".to_vec()] });
bench_header!(rfc_850, Date, { vec![b"Sunday, 06-Nov-94 08:49:37 GMT".to_vec()] });
bench_header!(asctime, Date, { vec![b"Sun Nov 6 08:49:37 1994".to_vec()] });
| {
tm_from_str(s).map(Date).ok_or(())
} | identifier_body |
date.rs | use std::fmt;
use std::str::FromStr;
use time::Tm;
use header::{Header, HeaderFormat};
use header::parsing::from_one_raw_str;
use header::parsing::tm_from_str;
// Egh, replace as soon as something better than time::Tm exists.
/// The `Date` header field.
#[derive(Copy, PartialEq, Clone, Debug)]
pub struct Date(pub Tm)... | "Date"
}
fn parse_header(raw: &[Vec<u8>]) -> Option<Date> {
from_one_raw_str(raw)
}
}
impl HeaderFormat for Date {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let tm = self.0;
let tm = match tm.tm_utcoff {
0 => tm,
_ => tm.to... | deref!(Date => Tm);
impl Header for Date {
fn header_name() -> &'static str { | random_line_split |
date.rs | use std::fmt;
use std::str::FromStr;
use time::Tm;
use header::{Header, HeaderFormat};
use header::parsing::from_one_raw_str;
use header::parsing::tm_from_str;
// Egh, replace as soon as something better than time::Tm exists.
/// The `Date` header field.
#[derive(Copy, PartialEq, Clone, Debug)]
pub struct Date(pub Tm)... | (&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let tm = self.0;
let tm = match tm.tm_utcoff {
0 => tm,
_ => tm.to_utc(),
};
fmt::Display::fmt(&tm.rfc822(), fmt)
}
}
impl FromStr for Date {
type Err = ();
fn from_str(s: &str) -> Result<Date, ()> {
... | fmt_header | identifier_name |
Home.js | 'use strict';
//var burst = require('burst-node');
//var controls = burst.core.controls;
var News = require('../models/News');
/**
* Home - Home page controller
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* The constructor, defined by Burst-Node core, inits two instance attribut... |
this.res.setTitle('Home page');
this.res.send('news', news);
};
/**
* Postrender - Executed once the page is rendered
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Proceed actions that are not required for page rendering, such as database
* insertions or statistic-purpose a... | content: "Foobar is a foo to make Barfoo fooing like a bar.",
});
news.views++; | random_line_split |
main.py | #!/usr/bin/python
## globals
primes_set = set()
primes_list = []
def | (n):
limit = int(round(sqrt(n)))
i = 2
while True:
if i > limit:
return True
if n % i == 0:
return False
def find_prime_permutations(n):
"find the prime permutations including n"
global primes_set
assert n >= 1000 and n <= 9999
perm_set = set()
s... | is_prime | identifier_name |
main.py | #!/usr/bin/python
## globals
primes_set = set()
primes_list = []
def is_prime(n):
limit = int(round(sqrt(n)))
i = 2
while True:
if i > limit:
return True
if n % i == 0:
return False
def find_prime_permutations(n):
"find the prime permutations including n"
... | for l in xrange(4):
if l == i or l == j or l == k:
continue
s2 = s[i] + s[j] + s[k] + s[l]
n2 = int(s2)
if n2 in primes_set:
perm_set.add(n2)
return perm_set
def find_ari... | continue | random_line_split |
main.py | #!/usr/bin/python
## globals
primes_set = set()
primes_list = []
def is_prime(n):
|
def find_prime_permutations(n):
"find the prime permutations including n"
global primes_set
assert n >= 1000 and n <= 9999
perm_set = set()
s = str(n)
for i in xrange(4):
for j in xrange(4):
if j == i:
continue
for k in xrange(4):
... | limit = int(round(sqrt(n)))
i = 2
while True:
if i > limit:
return True
if n % i == 0:
return False | identifier_body |
main.py | #!/usr/bin/python
## globals
primes_set = set()
primes_list = []
def is_prime(n):
limit = int(round(sqrt(n)))
i = 2
while True:
if i > limit:
return True
if n % i == 0:
return False
def find_prime_permutations(n):
"find the prime permutations including n"
... |
print repr(solutions)
| solutions.add(result) | conditional_block |
shader_compiler_util.ts | /**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
export function getOutputLogicalCoordinatesFromFlatIndexByUniform(
coords: string[], shape: number[], index = 'index'): string {
const strides = util.computeStrides(shape);
return strides
.map((_, i) => {
const line1 = `int ${coords[i]} = ${index} / outShapeStrides[${i}]`;
const line2 = ... | {
const strides = util.computeStrides(shape);
return strides
.map((stride, i) => {
const line1 = `int ${coords[i]} = ${index} / ${stride}`;
const line2 = i === strides.length - 1 ?
`int ${coords[i + 1]} = ${index} - ${coords[i]} * ${stride}` :
`index -= ${coords[i]} * $... | identifier_body |
shader_compiler_util.ts | /**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | const indicesArray = coords.map((_, i) => i);
const strides = symbolicallyComputeStrides(indicesArray, variableName);
return strides
.map((_, i) => {
const line1 = `int ${coords[i]} = ${index} / ${strides[i]}`;
const line2 = i === strides.length - 1 ?
`int ${coords[i + 1]} = ${in... | coords: string[], variableName: string, index = 'index'): string { | random_line_split |
shader_compiler_util.ts | /**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | (shape: [number, number, number]): string {
const strides = util.computeStrides(shape).map(d => d.toString());
return `
int getFlatIndex(ivec3 coords) {
return coords.x * ${strides[0]} + coords.y * ${strides[1]} + coords.z;
}
`;
}
export function getFlatIndexFrom3DOutput(): string {
return `
int getFl... | getFlatIndexFrom3D | identifier_name |
shader_compiler_util.ts | /**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
return strides;
}
export function getLogicalCoordinatesFromFlatIndexByUniform(
coords: string[], variableName: string, index = 'index'): string {
const indicesArray = coords.map((_, i) => i);
const strides = symbolicallyComputeStrides(indicesArray, variableName);
return strides
.map((_, i) => {
... | {
strides[i] = `(${strides[i + 1]} * ${shape[i + 1]})`;
} | conditional_block |
stock.py | f = open('./twstock.tmp', 'w')
f.write(date_str)
def loadDate(self):
try:
f = open('./twstock.tmp', 'r')
date_str = f.readline()
#default set to 4 PM
return datetime.datetime.strptime(date_str + " 16:00:00", "%m/%d/%Y %H:%M:%S")
except IOErro... | #no such key. insert it
df = pd.concat([df, row])
df.to_csv('bystock/' + stockid + '.csv')
#print df
except IOError:
print('stock id: {} not exist'.format(stockid))
row.to_csv('bystock/' + stockid + '.csv')
def prepcsv(self, csv):
... | #key already exist. skip it
except KeyError: | random_line_split |
stock.py | = open('./twstock.tmp', 'w')
f.write(date_str)
def loadDate(self):
try:
f = open('./twstock.tmp', 'r')
date_str = f.readline()
#default set to 4 PM
return datetime.datetime.strptime(date_str + " 16:00:00", "%m/%d/%Y %H:%M:%S")
except IOError:... |
PE=float(row[15])
try:
OP=float(row[5])
CP=float(row[8])
HP=float(row[6])
LP=float(row[7])
except ValueError:
OP=None
... | DF=0
RD=0 | conditional_block |
stock.py | = open('./twstock.tmp', 'w')
f.write(date_str)
def loadDate(self):
try:
f = open('./twstock.tmp', 'r')
date_str = f.readline()
#default set to 4 PM
return datetime.datetime.strptime(date_str + " 16:00:00", "%m/%d/%Y %H:%M:%S")
except IOError:... | (self, stockid, row, date):
try:
date_str = date.strftime("%Y-%m-%d")
df = pd.DataFrame.from_csv('bystock/' + stockid + '.csv')
#check if there is a key
df.loc[date_str].count()
#key already exist. skip it
except KeyError:
#no su... | insertToStock | identifier_name |
stock.py | .write(date_str)
def loadDate(self):
try:
f = open('./twstock.tmp', 'r')
date_str = f.readline()
#default set to 4 PM
return datetime.datetime.strptime(date_str + " 16:00:00", "%m/%d/%Y %H:%M:%S")
except IOError:
return datetime.datetime.s... | one_day = timedelta(days=1)
stop_date = start_date + one_day * days
expect_date = start_date + one_day * (days + expect)
today = datetime.date.today()
res = 0
if stop_date > today:
return None, None
try:
start_date_str = start_date.strftime("%Y-%m-... | identifier_body | |
Line.tsx | import * as React from 'react';
import { presetPrimaryColors } from '@ant-design/colors';
import { ProgressGradient, ProgressProps, StringGradients } from './progress';
import { validProgress, getSuccessPercent } from './utils';
import { DirectionType } from '../config-provider';
interface LineProps extends ProgressPr... | ? {
backgroundColor: trailColor,
}
: undefined;
const percentStyle = {
width: `${validProgress(percent)}%`,
height: strokeWidth || (size === 'small' ? 6 : 8),
borderRadius: strokeLinecap === 'square' ? 0 : '',
...backgroundProps,
} as React.CSSProperties;
const successPerce... |
const trailStyle = trailColor | random_line_split |
Line.tsx | import * as React from 'react';
import { presetPrimaryColors } from '@ant-design/colors';
import { ProgressGradient, ProgressProps, StringGradients } from './progress';
import { validProgress, getSuccessPercent } from './utils';
import { DirectionType } from '../config-provider';
interface LineProps extends ProgressPr... |
});
tempArr = tempArr.sort((a, b) => a.key - b.key);
return tempArr.map(({ key, value }) => `${value} ${key}%`).join(', ');
};
/**
* Then this man came to realize the truth: Besides six pence, there is the moon. Besides bread and
* butter, there is the bug. And... Besides women, there is the code.
*
* @exam... | {
tempArr.push({
key: formattedKey,
value: gradients[key],
});
} | conditional_block |
run_list_handling.py | from sqlalchemy import and_
from DBtransfer import *
from zlib import *
#retrun compressed
def generateFromDB(DBSession, InternData, tmp_name) :
run_list=[]
user_data = DBSession.query(InternData).filter(InternData.timestamp == tmp_name)
for data in user_data :
if not data.run in run_list :
run_list.append(da... | (run_list, params) :
list_of_used_runs = []
runs = decompressList(run_list)
for i in range(0, len(runs)) :
if runs[i] in params :
list_of_used_runs.append(runs[i])
return list_of_used_runs
# input not compressed
# output InternData objects
def rowsToFill(DBSession, InternData, tmp_name, used_runs) :
user... | usedRuns | identifier_name |
run_list_handling.py | from sqlalchemy import and_
from DBtransfer import *
from zlib import *
#retrun compressed
def generateFromDB(DBSession, InternData, tmp_name) :
run_list=[]
user_data = DBSession.query(InternData).filter(InternData.timestamp == tmp_name)
for data in user_data :
if not data.run in run_list :
run_list.append(da... |
# input not compressed
# output InternData objects
def rowsToFill(DBSession, InternData, tmp_name, used_runs) :
users_rows = getUserRows(DBSession, InternData, tmp_name)
rows = []
for row in users_rows :
if row.run in used_runs :
rows.append(row)
return rows
#input compressed, not compressed
def throughOu... | list_of_used_runs = []
runs = decompressList(run_list)
for i in range(0, len(runs)) :
if runs[i] in params :
list_of_used_runs.append(runs[i])
return list_of_used_runs | identifier_body |
run_list_handling.py | from sqlalchemy import and_
from DBtransfer import *
from zlib import *
#retrun compressed
def generateFromDB(DBSession, InternData, tmp_name) :
run_list=[]
user_data = DBSession.query(InternData).filter(InternData.timestamp == tmp_name)
for data in user_data :
if not data.run in run_list :
|
return compressList(run_list)
def getknown_runsAndrun_list(DBSession, Mass_specData, InternData, tmp_name) : #CR: rename to splitKnownAndTodo
#~ knownRuns = [] # devide runs from upload into known runs (in DB) ...
#~ runList = [] #...and the usual run_list, to get data from these runs
#CR:
runs_in_upload =... | run_list.append(data.run) | conditional_block |
run_list_handling.py | from sqlalchemy import and_
from DBtransfer import *
from zlib import *
#retrun compressed
def generateFromDB(DBSession, InternData, tmp_name) :
run_list=[]
user_data = DBSession.query(InternData).filter(InternData.timestamp == tmp_name)
for data in user_data :
if not data.run in run_list :
run_list.append(da... | return []
#
def compressList(list) :
return compress('$$'.join(list))
#input compressed
def decompressList(run_list) :
return decompress(run_list).split('$$') | rl.pop(rl.index(run))
if len(rl) > 0 :
return compressList(rl)
else : | random_line_split |
osmc_bluetooth.py | import connman
import bluetooth
import systemd
import sys
import pexpect
import json
RUNNING_IN_KODI = True
# XBMC Modules
try:
import xbmc
import xbmcgui
import xbmcaddon
except:
RUNNING_IN_KODI = False
DEVICE_PATH = 'org.bluez.Device1'
PAIRING_AGENT = 'osmc_bluetooth_agent.py'
BLUETOOTH_SERVICE ... | deviceAlias = get_device_property(deviceAddress, 'Alias')
returnValue = handleAgentInteraction(deviceAlias, return_value , messages)
if returnValue:
if returnValue == 'NO_PIN_ENTERED':
return False
sendStr = ... | script_path = scriptBasePath + PAIRING_AGENT
script = str.join(' ', [sys.executable, script_path,deviceAddress])
child = pexpect.spawn(script)
paired = False
while True:
try:
index = child.expect(['@EOL'], timeout=None)
split = child.before.split('SOL@')
if le... | identifier_body |
osmc_bluetooth.py | import connman
import bluetooth
import systemd
import sys
import pexpect
import json
RUNNING_IN_KODI = True
# XBMC Modules
try:
import xbmc
import xbmcgui
import xbmcaddon
except:
RUNNING_IN_KODI = False
DEVICE_PATH = 'org.bluez.Device1'
PAIRING_AGENT = 'osmc_bluetooth_agent.py'
BLUETOOTH_SERVICE ... |
else:
connman.toggle_technology_state('bluetooth', state)
def get_adapter_property(key):
return bluetooth.get_adapter_property(key)
def set_adapter_property(key, value):
bluetooth.set_adapter_property(key, value)
def is_discovering():
return bluetooth.get_adapter_property('Discovering')
... | if not systemd.is_service_running(BLUETOOTH_SERVICE):
systemd.toggle_service(BLUETOOTH_SERVICE, state)
connman.toggle_technology_state('bluetooth', state) | conditional_block |
osmc_bluetooth.py | import connman
import bluetooth
import systemd
import sys
import pexpect
import json
RUNNING_IN_KODI = True
# XBMC Modules
try:
import xbmc
import xbmcgui
import xbmcaddon
except:
RUNNING_IN_KODI = False
DEVICE_PATH = 'org.bluez.Device1'
PAIRING_AGENT = 'osmc_bluetooth_agent.py'
BLUETOOTH_SERVICE ... | (deviceAddress):
return bluetooth.get_device_property(deviceAddress, 'Trusted')
def set_device_trusted(deviceAddress, value):
set_device_property(deviceAddress,'Trusted', value)
def is_device_connected(deviceAddress):
return bluetooth.get_device_property(deviceAddress, 'Connected')
def connect_device(... | is_device_trusted | identifier_name |
osmc_bluetooth.py | import connman
import bluetooth
import systemd
import sys
import pexpect
import json
RUNNING_IN_KODI = True
# XBMC Modules
try:
import xbmc
import xbmcgui
import xbmcaddon
except:
RUNNING_IN_KODI = False
DEVICE_PATH = 'org.bluez.Device1'
PAIRING_AGENT = 'osmc_bluetooth_agent.py'
BLUETOOTH_SERVICE ... |
def log(message):
msg_str='OSMC_BLUETOOTH - ' + str(message)
if RUNNING_IN_KODI:
xbmc.log(msg_str, level=xbmc.LOGDEBUG)
else:
print(msg_str)
def is_bluetooth_available():
return connman.is_technology_available('bluetooth')
def is_bluetooth_enabled():
connman_status = connman.i... | PEXPECT_EOL = '@EOL' | random_line_split |
smallest-hello-world.rs | // Copyright 2013-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-MI... |
#[lang = "fail_fmt"] fn fail_fmt() -> ! { loop {} }
#[start]
#[no_stack_check]
fn main(_: int, _: *const *const u8) -> int {
unsafe {
let (ptr, _): (*const u8, uint) = transmute("Hello!\0");
puts(ptr);
}
return 0;
}
| {} | identifier_body |
smallest-hello-world.rs | // Copyright 2013-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-MI... | (_: int, _: *const *const u8) -> int {
unsafe {
let (ptr, _): (*const u8, uint) = transmute("Hello!\0");
puts(ptr);
}
return 0;
}
| main | identifier_name |
smallest-hello-world.rs | // Copyright 2013-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-MI... | let (ptr, _): (*const u8, uint) = transmute("Hello!\0");
puts(ptr);
}
return 0;
} | fn main(_: int, _: *const *const u8) -> int {
unsafe { | random_line_split |
user-settings.resolve.ts | import { Injectable } from "@angular/core";
import { CrudResolve } from "../../crud/common/crud-resolve";
import { FeathersService } from "../../services/feathers.service";
import { ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router";
import { CommonService } from "../../services/common.service";
impor... |
}
| {
return Observable.create((observer) => {
this.feathersService.get(this.commonService.getIDCurrentUser(), USER_SETTINGS_SERVICE_NAME)
.subscribe((res: Response) => {
observer.next(res.json());
observer.complete();
}, err => {
... | identifier_body |
user-settings.resolve.ts | import { Injectable } from "@angular/core";
import { CrudResolve } from "../../crud/common/crud-resolve";
import { FeathersService } from "../../services/feathers.service";
import { ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router";
import { CommonService } from "../../services/common.service";
impor... | (private commonService: CommonService,
private feathersService: FeathersService) {
super();
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return Observable.create((observer) => {
this.feathersService.get(this.commonService.getIDCurrentUser(),... | constructor | identifier_name |
user-settings.resolve.ts | import { Injectable } from "@angular/core";
import { CrudResolve } from "../../crud/common/crud-resolve";
import { FeathersService } from "../../services/feathers.service"; | import { CommonService } from "../../services/common.service";
import { USER_SETTINGS_SERVICE_NAME } from "./user-settings.service";
import { Observable } from "rxjs";
import { Response } from "@angular/http";
@Injectable()
export class UserSettingsResolve extends CrudResolve {
constructor(private commonService: ... | import { ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router"; | random_line_split |
linux_cgroup_test.py | #!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import os
import os.path
import pathlib
import platform
import unittest
from .lib.testcase import IntegrationTestCase
if plat... |
class LinuxCgroupTest(IntegrationTestCase):
def test_parse_proc_file(self) -> None:
proc_file_content = (
b"0::/user.slice/user-6986.slice/session-33.scope/init.scope\n"
)
self.assertEqual(
LinuxCgroup._parse_proc_file(proc_file_content),
b"/user.slice/... | def is_cgroup_v2_mounted():
return False | conditional_block |
linux_cgroup_test.py | #!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import os
import os.path
import pathlib
import platform
import unittest
from .lib.testcase import IntegrationTestCase
if plat... | b"12:cpuacct:/user.slice/user-2233.slice/session-163872.scope\n"
b"11:freezer:/\n"
b"10:hugetlb:/\n"
b"9:blkio:/user.slice/user-2233.slice/session-163872.scope\n"
b"8:cpuset:/\n"
b"7:pids:/user.slice/user-2233.slice/session-163872.scope\n"
... |
def test_parsing_proc_file_with_multiple_cgroups_v1_hierarchies_fails(self) -> None:
proc_file_content = ( | random_line_split |
linux_cgroup_test.py | #!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import os
import os.path
import pathlib
import platform
import unittest
from .lib.testcase import IntegrationTestCase
if plat... |
@unittest.skipIf(
not is_cgroup_v2_mounted(),
"T36934106: Fix EdenFS systemd integration tests for cgroups v1",
)
def test_cgroup_from_current_process_includes_current_process_id(self) -> None:
cgroup = LinuxCgroup.from_current_process()
self.assertIn(os.getpid(), cgroup.qu... | cgroup = LinuxCgroup(b"/user.slice/user-6986.slice/session-13.scope/init.scope")
self.assertEqual(
cgroup.sys_fs_cgroup_path,
pathlib.PosixPath(
"/sys/fs/cgroup//user.slice/user-6986.slice/session-13.scope/init.scope"
),
) | identifier_body |
linux_cgroup_test.py | #!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import os
import os.path
import pathlib
import platform
import unittest
from .lib.testcase import IntegrationTestCase
if plat... | (self) -> None:
path = pathlib.PosixPath("/sys/fs/cgroup/system.slice")
cgroup = LinuxCgroup.from_sys_fs_cgroup_path(path)
self.assertEqual(cgroup.name, b"/system.slice")
def test_sys_fs_cgroup_path(self) -> None:
cgroup = LinuxCgroup(b"/user.slice/user-6986.slice/session-13.scope/i... | test_cgroup_from_sys_fs_cgroup_path | identifier_name |
result.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
let bad_err: Result<isize, &'static str> = Err("Unrecoverable mess.");
let _ : isize = bad_err.unwrap_or_else(handler);
}
#[test]
pub fn test_expect_ok() {
let ok: Result<isize, &'static str> = Ok(100);
assert_eq!(ok.expect("Unexpected error"), 100);
}
#[test]
#[should_panic(expected="Got expe... | {
panic!("BadBad")
} | conditional_block |
result.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 ... |
#[test]
fn test_unwrap_or_else() {
fn handler(msg: &'static str) -> isize {
if msg == "I got this." {
50
} else {
panic!("BadBad")
}
}
let ok: Result<isize, &'static str> = Ok(100);
let ok_err: Result<isize, &'static str> = Err("I got this.");
asse... | {
let ok: Result<isize, &'static str> = Ok(100);
let ok_err: Result<isize, &'static str> = Err("Err");
assert_eq!(ok.unwrap_or(50), 100);
assert_eq!(ok_err.unwrap_or(50), 50);
} | identifier_body |
result.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 ... | fn test_or_else() {
assert_eq!(op1().or_else(|_| Ok::<isize, &'static str>(667)).unwrap(), 666);
assert_eq!(op1().or_else(|e| Err::<isize, &'static str>(e)).unwrap(), 666);
assert_eq!(op2().or_else(|_| Ok::<isize, &'static str>(667)).unwrap(), 667);
assert_eq!(op2().or_else(|e| Err::<isize, &'static st... | assert_eq!(op2().or(Err("bad")).unwrap_err(), "bad");
}
#[test] | random_line_split |
result.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 ... | () -> Result<isize, &'static str> { Err("sadface") }
#[test]
fn test_and() {
assert_eq!(op1().and(Ok(667)).unwrap(), 667);
assert_eq!(op1().and(Err::<i32, &'static str>("bad")).unwrap_err(),
"bad");
assert_eq!(op2().and(Ok(667)).unwrap_err(), "sadface");
assert_eq!(op2().and(Err::<i32,&... | op2 | identifier_name |
disjoint_set.py | """
Disjoint set.
| """
class Node:
def __init__(self, data: int) -> None:
self.data = data
self.rank: int
self.parent: Node
def make_set(x: Node) -> None:
"""
Make x as a set.
"""
# rank is the distance from x to its' parent
# root's rank is 0
x.rank = 0
x.paren... | Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure
| random_line_split |
disjoint_set.py | """
Disjoint set.
Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure
"""
class Node:
def __init__(self, data: int) -> None:
self.data = data
self.rank: int
self.parent: Node
def make_set(x: Node) -> None:
"""
Make x as a set.
"""
... | () -> None:
"""
>>> test_disjoint_set()
"""
vertex = [Node(i) for i in range(6)]
for v in vertex:
make_set(v)
union_set(vertex[0], vertex[1])
union_set(vertex[1], vertex[2])
union_set(vertex[3], vertex[4])
union_set(vertex[3], vertex[5])
for node0 in vertex... | test_disjoint_set | identifier_name |
disjoint_set.py | """
Disjoint set.
Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure
"""
class Node:
def __init__(self, data: int) -> None:
self.data = data
self.rank: int
self.parent: Node
def make_set(x: Node) -> None:
"""
Make x as a set.
"""
... |
raise ValueError(f"{node.data} is not in {sets}")
def test_disjoint_set() -> None:
"""
>>> test_disjoint_set()
"""
vertex = [Node(i) for i in range(6)]
for v in vertex:
make_set(v)
union_set(vertex[0], vertex[1])
union_set(vertex[1], vertex[2])
union_set(ver... | if node.data in s:
return s | conditional_block |
disjoint_set.py | """
Disjoint set.
Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure
"""
class Node:
def __init__(self, data: int) -> None:
|
def make_set(x: Node) -> None:
"""
Make x as a set.
"""
# rank is the distance from x to its' parent
# root's rank is 0
x.rank = 0
x.parent = x
def union_set(x: Node, y: Node) -> None:
"""
Union of two sets.
set with bigger rank should be parent, so that the
... | self.data = data
self.rank: int
self.parent: Node | identifier_body |
types.rs | KernelPrintable {
pub features: String,
pub fee_shift: u8,
pub fee: u64,
pub lock_height: u64,
pub excess: String,
pub excess_sig: String,
}
impl TxKernelPrintable {
pub fn from_txkernel(k: &core::TxKernel) -> TxKernelPrintable {
let features = k.features.as_string();
let (fee_fields, lock_height) = match k... | {
let hex_output = "{\
\"output_type\":\"Coinbase\",\
\"commit\":\"083eafae5d61a85ab07b12e1a51b3918d8e6de11fc6cde641d54af53608aa77b9f\",\
\"spent\":false,\
\"proof\":null,\
\"proof_hash\":\"ed6ba96009b86173bade6a9227ed60422916593fa32dd6d78b25b7a4eeef4946\",\
\"block_height\":0,\
\"merkle_p... | identifier_body | |
types.rs | HashSetNode {
hash: elem.0.to_hex(),
});
}
return_vec
}
pub fn get_last_n_kernel(chain: &chain::Chain, distance: u64) -> Vec<TxHashSetNode> {
let mut return_vec = Vec::new();
let last_n = chain.get_last_n_kernel(distance);
for elem in last_n {
return_vec.push(TxHashSetNode {
hash: elem.0.to_h... | MmrIndex,
}
struct OutputPrintableVisitor;
impl<'de> serde::de::Visitor<'de> for OutputPrintableVisitor {
type Value = OutputPrintable;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a print able Output")
}
fn visit_map<A>(self, mut map: A) -> ... | Spent,
Proof,
ProofHash,
BlockHeight,
MerkleProof, | random_line_split |
types.rs | (tip: chain::Tip) -> Tip {
Tip {
height: tip.height,
last_block_pushed: tip.last_block_h.to_hex(),
prev_block_to_last: tip.prev_block_h.to_hex(),
total_difficulty: tip.total_difficulty.to_num(),
}
}
}
/// Status page containing different server information
#[derive(Serialize, Deserialize, Debug, Clone... | from_tip | identifier_name | |
noImplicitReturnUndefined.ts | import * as es from 'estree'
import { stripIndent } from 'common-tags'
import { IError } from '../types/error'
import { Rule } from '../types/static'
export class NoImplicitReturnUndefinedError implements IError {
constructor(public node: es.ReturnStatement) {}
get location() {
return this.node.loc!
}
ex... |
}
}
}
export default noImplicitReturnUndefined
| {
return []
} | conditional_block |
noImplicitReturnUndefined.ts | import * as es from 'estree'
import { stripIndent } from 'common-tags'
import { IError } from '../types/error'
import { Rule } from '../types/static'
export class NoImplicitReturnUndefinedError implements IError {
constructor(public node: es.ReturnStatement) {}
get location() {
return this.node.loc!
}
ex... | }
export default noImplicitReturnUndefined | }
} | random_line_split |
noImplicitReturnUndefined.ts | import * as es from 'estree'
import { stripIndent } from 'common-tags'
import { IError } from '../types/error'
import { Rule } from '../types/static'
export class NoImplicitReturnUndefinedError implements IError {
constructor(public node: es.ReturnStatement) {}
get location() {
return this.node.loc!
}
ex... |
}
}
export default noImplicitReturnUndefined
| {
if (!node.argument) {
return [new NoImplicitReturnUndefinedError(node)]
} else {
return []
}
} | identifier_body |
noImplicitReturnUndefined.ts | import * as es from 'estree'
import { stripIndent } from 'common-tags'
import { IError } from '../types/error'
import { Rule } from '../types/static'
export class NoImplicitReturnUndefinedError implements IError {
constructor(public node: es.ReturnStatement) {}
get | () {
return this.node.loc!
}
explain() {
return 'Missing value in return statement'
}
elaborate() {
return stripIndent`
This return statement is missing a value.
For instance, to return the value 42, you can write
return 42;
`
}
}
const noImplicitReturnUndefined: Rule<e... | location | identifier_name |
move_base_force_cancel.py | #! /usr/bin/env python
import rospy
import actionlib
from move_base_msgs.msg import MoveBaseActionGoal
from actionlib_msgs.msg import GoalID
class ForceCancel(object):
|
def shutdown(self):
rospy.loginfo("cancel job finished")
rospy.sleep(1)
pass
if __name__ == "__main__":
fc = ForceCancel('force_cancel', False, 5)
| def __init__(self, nodename="force_cancel", is_newnode=True, repetition=10):
self.repetition = rospy.get_param("~repetition", repetition)
if is_newnode:
rospy.init_node(name=nodename, anonymous=False)
rospy.on_shutdown(self.shutdown)
pub = rospy.Publisher("move_base/canc... | identifier_body |
move_base_force_cancel.py | #! /usr/bin/env python
import rospy
import actionlib
from move_base_msgs.msg import MoveBaseActionGoal
from actionlib_msgs.msg import GoalID
class ForceCancel(object):
def __init__(self, nodename="force_cancel", is_newnode=True, repetition=10):
self.repetition = rospy.get_param("~repetition", repetition)
... |
r.sleep()
counter += 1
def callback(self, msg):
self.id = msg.goal_id.id
def shutdown(self):
rospy.loginfo("cancel job finished")
rospy.sleep(1)
pass
if __name__ == "__main__":
fc = ForceCancel('force_cancel', False, 5) | random_line_split | |
move_base_force_cancel.py | #! /usr/bin/env python
import rospy
import actionlib
from move_base_msgs.msg import MoveBaseActionGoal
from actionlib_msgs.msg import GoalID
class ForceCancel(object):
def __init__(self, nodename="force_cancel", is_newnode=True, repetition=10):
self.repetition = rospy.get_param("~repetition", repetition)
... |
pub = rospy.Publisher("move_base/cancel", GoalID, queue_size=1)
sub = rospy.Subscriber("move_base/goal", MoveBaseActionGoal, self.callback, queue_size=1)
rospy.wait_for_message("move_base/goal", MoveBaseActionGoal, 60)
r = rospy.Rate(1)
counter = 0
while not rospy.is_sh... | rospy.init_node(name=nodename, anonymous=False)
rospy.on_shutdown(self.shutdown) | conditional_block |
move_base_force_cancel.py | #! /usr/bin/env python
import rospy
import actionlib
from move_base_msgs.msg import MoveBaseActionGoal
from actionlib_msgs.msg import GoalID
class | (object):
def __init__(self, nodename="force_cancel", is_newnode=True, repetition=10):
self.repetition = rospy.get_param("~repetition", repetition)
if is_newnode:
rospy.init_node(name=nodename, anonymous=False)
rospy.on_shutdown(self.shutdown)
pub = rospy.Publisher("... | ForceCancel | identifier_name |
test.ts | import { ElementFinder, browser, by, element } from 'protractor';
describe('angularjs homepage todo list', function () { //Suite in Jasmine
it('should add a todo', function () { // Test in Jasmine
browser.get('https://angularjs.org'); // Entering application url in browser
// Enter text under TODO
... | });
});
}); | random_line_split | |
person.js | import {
PERSON_REQUEST, PERSON_SUCCESS, PERSON_FAILURE, PERSON_CLEAN,
PERSON_UPDATE, PERSON_DELETE
} from '../constants/PersonActionTypes';
import PersonSchemas from '../models/PersonSchemas';
import {CALL_API} from '../middleware/api';
function fetchPersonList(pageNo) {
return {
entity: 'personPagination',... | }
| identifier_body | |
person.js | import {
PERSON_REQUEST, PERSON_SUCCESS, PERSON_FAILURE, PERSON_CLEAN,
PERSON_UPDATE, PERSON_DELETE
} from '../constants/PersonActionTypes';
import PersonSchemas from '../models/PersonSchemas';
import {CALL_API} from '../middleware/api';
function fetchPersonList(pageNo) {
return {
entity: 'personPagination',... | person
};
}
//删除
export function deletePerson(id) {
return {
type: PERSON_DELETE,
id
};
} | random_line_split | |
person.js | import {
PERSON_REQUEST, PERSON_SUCCESS, PERSON_FAILURE, PERSON_CLEAN,
PERSON_UPDATE, PERSON_DELETE
} from '../constants/PersonActionTypes';
import PersonSchemas from '../models/PersonSchemas';
import {CALL_API} from '../middleware/api';
function fetchPersonList(pageNo) {
return {
entity: 'personPagination',... | st(pageNo));
};
}
//清空数据
export function cleanPersonList() {
return {
type: PERSON_CLEAN,
entity: 'personPagination',
clean: true
}
}
//修改
export function updatePerson(person) {
return {
type: PERSON_UPDATE,
person
};
}
//删除
export function deletePerson(id) {
return {
type: PERSON... | urn dispatch(fetchPersonLi | conditional_block |
person.js | import {
PERSON_REQUEST, PERSON_SUCCESS, PERSON_FAILURE, PERSON_CLEAN,
PERSON_UPDATE, PERSON_DELETE
} from '../constants/PersonActionTypes';
import PersonSchemas from '../models/PersonSchemas';
import {CALL_API} from '../middleware/api';
function fetchPersonList(pageNo) {
return {
entity: 'personPagination',... | entity: 'personPagination',
clean: true
}
}
//修改
export function updatePerson(person) {
return {
type: PERSON_UPDATE,
person
};
}
//删除
export function deletePerson(id) {
return {
type: PERSON_DELETE,
id
};
}
| ERSON_CLEAN,
| identifier_name |
htmlbodyelement.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 dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventH... |
#[dom_struct]
pub struct HTMLBodyElement {
htmlelement: HTMLElement
}
impl HTMLBodyElementDerived for EventTarget {
fn is_htmlbodyelement(&self) -> bool {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLBodyElementTypeId))
}
}
impl HTMLBodyElement {
fn new_inherited(localName: DOMSt... | random_line_split | |
htmlbodyelement.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 dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventH... | {
htmlelement: HTMLElement
}
impl HTMLBodyElementDerived for EventTarget {
fn is_htmlbodyelement(&self) -> bool {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLBodyElementTypeId))
}
}
impl HTMLBodyElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document... | HTMLBodyElement | identifier_name |
htmlbodyelement.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 dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventH... |
fn after_set_attr(&self, attr: JSRef<Attr>) {
match self.super_type() {
Some(ref s) => s.after_set_attr(attr),
_ => (),
}
let name = attr.local_name().as_slice();
if name.starts_with("on") {
static FORWARDED_EVENTS: &'static [&'static str] =
... | {
let element: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(element as &VirtualMethods)
} | identifier_body |
iterable.ts | import { invariant, addHiddenFinalProp } from './utils';
// inspired by https://github.com/leebyron/iterall/
declare var Symbol;
function iteratorSymbol() : string
{
// @todo: return value isn't clear: bool and string?
return (typeof Symbol === "function" && Symbol.iterator) || "@@iterator";
}
export const ... | addHiddenFinalProp(protoType, iteratorSymbol(), iteratorFactory);
} // declareIterator() | random_line_split | |
iterable.ts | import { invariant, addHiddenFinalProp } from './utils';
// inspired by https://github.com/leebyron/iterall/
declare var Symbol;
function iteratorSymbol() : string
{
// @todo: return value isn't clear: bool and string?
return (typeof Symbol === "function" && Symbol.iterator) || "@@iterator";
}
export const ... | <T>(a_array: T[]): T[] & Iterator<T>
{
// mw: TODO: this should be removed in the next major version of MobX
// returning an array for entries(), values() etc for maps was a
// mis-interpretation of the specs..
invariant(a_array[IS_ITERATING_MARKER] !== true, "Illegal state: cannot recycle array as iterator");... | arrayAsIterator | identifier_name |
iterable.ts | import { invariant, addHiddenFinalProp } from './utils';
// inspired by https://github.com/leebyron/iterall/
declare var Symbol;
function iteratorSymbol() : string
{
// @todo: return value isn't clear: bool and string?
return (typeof Symbol === "function" && Symbol.iterator) || "@@iterator";
}
export const ... |
return a_array as any;
} // arrayAsIterator()
export function declareIterator<T>(protoType, iteratorFactory: () => Iterator<T>)
{
addHiddenFinalProp(protoType, iteratorSymbol(), iteratorFactory);
} // declareIterator()
| {
// mw: TODO: this should be removed in the next major version of MobX
// returning an array for entries(), values() etc for maps was a
// mis-interpretation of the specs..
invariant(a_array[IS_ITERATING_MARKER] !== true, "Illegal state: cannot recycle array as iterator");
addHiddenFinalProp(a_array, IS_ITE... | identifier_body |
lib.rs | obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the Lice... |
/// Wrapper around a termination signal [`oneshot::Sender`] and the [`JoinHandle`] of the associated
/// background task, created by [`background`].
pub struct Background<T> {
term_tx: oneshot::Sender<()>,
join_handle: JoinHandle<T>,
}
impl<T> Background<T> {
/// Sends the termination signal to the backg... | {
port_check::free_local_port().expect("could not pick free local port")
} | identifier_body |
lib.rs | obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the Lice... | {
pub elapsed: Duration,
pub response: Response,
}
pub async fn make_request(port: u16, request_body: &[u8]) -> TestResult {
let uri = format!("http://localhost:{}/", port);
// Create client
let mut client = oak_functions_client::Client::new(&uri, |_config| Ok(()))
.await
.expect(... | TestResult | identifier_name |
lib.rs | may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the ... | port_check::free_local_port().expect("could not pick free local port")
}
/// Wrapper around a termination signal [`oneshot::Sender`] and the [`JoinHandle`] of the associated
/// background task, created by [`background`].
pub struct Background<T> {
term_tx: oneshot::Sender<()>,
join_handle: JoinHandle<T>,
... | }
pub fn free_port() -> u16 { | random_line_split |
polygon.d.ts | declare namespace AMap {
namespace Polygon {
interface EventMap<I = Polygon> extends PathOverlay.EventMap<I> { }
interface Options<ExtraData = any> extends PathOverlay.Options<ExtraData> {
/**
* 多边形轮廓线的节点坐标数组
*/
path?: LocationValue[] | LocationValue... | /**
* 修改多边形属性
* @param options 属性
*/
setOptions(options: Polygon.Options<ExtraData>): void;
/**
* 获取多边形的属性
*/
getOptions(): Partial<
this extends Omit<Ellipse, keyof Polygon> ? Ellipse.GetOptionsResult<ExtraData> :
this... | /**
* 获取多边形轮廓线节点数组
*/
getPath(): LngLat[] | LngLat[][]; | random_line_split |
polygon.d.ts | declare namespace AMap {
namespace Polygon {
interface EventMap<I = Polygon> extends PathOverlay.EventMap<I> { }
interface Options<ExtraData = any> extends PathOverlay.Options<ExtraData> {
/**
* 多边形轮廓线的节点坐标数组
*/
path?: LocationValue[] | LocationValue... | constructor(options?: Polygon.Options<ExtraData>);
/**
* 设置多边形轮廓线节点数组
* @param path 轮廓线节点
*/
setPath(path: LocationValue[] | LocationValue[][]): void;
/**
* 获取多边形轮廓线节点数组
*/
getPath(): LngLat[] | LngLat[][];
/**
* 修改多边形属性
... | identifier_name | |
common.rs |
macro_rules! enum_number {
($name:ident { $($variant:ident = $value:expr, )* }) => {
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum $name {
$($variant = $value,)*
}
impl serde::Serialize for $name {
fn s... | use chrono::NaiveDate;
use std::fmt;
/// A common type for toornament dates.
pub type Date = NaiveDate; | random_line_split | |
common.rs | use chrono::NaiveDate;
use std::fmt;
/// A common type for toornament dates.
pub type Date = NaiveDate;
macro_rules! enum_number {
($name:ident { $($variant:ident = $value:expr, )* }) => {
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum $name {... | {
/// Minimum team size
pub min: i64,
/// Maximum team size
pub max: i64,
}
enum_number!(MatchResultSimple {
Win = 1,
Draw = 2,
Loss = 3,
});
| TeamSize | identifier_name |
gcncirc.py | from __future__ import print_function
from __future__ import absolute_import
import re
from pyingest.config.utils import u2asc
from .default import DefaultParser
from .author_names import AuthorNames
from .entity_convert import EntityConverter
head_dict = {'TITLE:': 'journal', 'NUMBER:': 'volume', 'SUBJECT:': 'title',... |
def make_publication(self):
base_string = 'GRB Coordinates Network, Circular Service, No. '
self.data_dict['publication'] = base_string + self.data_dict['volume']
self.data_dict['page'] = '1'
def split_authors_abstract(self):
# This could be used to extract affils and apply th... | year = self.data_dict['pubdate'][0:4]
bibcode = 'GCN.'
self.data_dict['volume'] = self.data_dict['volume'].ljust(5, '.')
volume = self.data_dict['volume'].ljust(9, '.') + '1'
try:
init = u2asc(self.data_dict['authors'][0][0])
except Exception as err:
print... | identifier_body |
gcncirc.py | from __future__ import print_function
from __future__ import absolute_import
import re
from pyingest.config.utils import u2asc
from .default import DefaultParser
from .author_names import AuthorNames
from .entity_convert import EntityConverter
head_dict = {'TITLE:': 'journal', 'NUMBER:': 'volume', 'SUBJECT:': 'title',... |
auths = []
affils = []
while body[0] != '' and ':' not in body[0]:
auths.append(body.pop(0).strip())
auths.append(body.pop(0).strip())
auth_delimiter = u'| '
auth_string = ' '.join(auths)
auth_string = re.sub(r'\s+\((.*?)\)', ',', auth_string)
... | body.pop(0) | conditional_block |
gcncirc.py | from __future__ import print_function
from __future__ import absolute_import
import re
from pyingest.config.utils import u2asc
from .default import DefaultParser
from .author_names import AuthorNames
from .entity_convert import EntityConverter
head_dict = {'TITLE:': 'journal', 'NUMBER:': 'volume', 'SUBJECT:': 'title',... | (self):
# This could be used to extract affils and apply them to authors,
# but the process of doing so is unwieldy. I'm leaving code that
# was my initial try but commented out.
body = self.data_dict['abstract']
while body[0] == '':
body.pop(0)
auths = []
... | split_authors_abstract | identifier_name |
gcncirc.py | from __future__ import print_function
from __future__ import absolute_import
import re
from pyingest.config.utils import u2asc
from .default import DefaultParser
from .author_names import AuthorNames
from .entity_convert import EntityConverter
head_dict = {'TITLE:': 'journal', 'NUMBER:': 'volume', 'SUBJECT:': 'title',... | auth_delimiter = u'| '
auth_string = ' '.join(auths)
auth_string = re.sub(r'\s+\((.*?)\)', ',', auth_string)
auth_string = re.sub(r'[ ,]and\s', ',', auth_string)
auth_string = re.sub(r'on behalf of', ',', auth_string)
auth_string = re.sub(r'reports?', ',', auth_string)
... | while body[0] != '' and ':' not in body[0]:
auths.append(body.pop(0).strip())
auths.append(body.pop(0).strip()) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.