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 |
|---|---|---|---|---|
htmlobjectelement.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::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementB... |
}
impl Validatable for HTMLObjectElement {}
impl VirtualMethods for HTMLObjectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwr... | {
self.form_owner()
} | identifier_body |
htmlobjectelement.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::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementB... |
}
}
}
impl HTMLObjectElementMethods for HTMLObjectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r(), self.upcast())
}
// https://html.spec.wha... | { } | conditional_block |
htmlobjectelement.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::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementB... | use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::htmlformelement::{FormControl, HTMLFormElement};
use dom::node::{Node, window_from_node};
use dom::validation::Validatable;
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use net_traits::image::b... | use dom::bindings::str::DOMString;
use dom::document::Document; | random_line_split |
make-autosuspend-rules.py | #!/usr/bin/env python3
# SPDX-License-Identifier: LGPL-2.1+
# Generate autosuspend rules for devices that have been tested to work properly
# with autosuspend by the Chromium OS team. Based on
# https://chromium.googlesource.com/chromiumos/platform2/+/master/power_manager/udev/gen_autosuspend_rules.py
|
print('# pci:v<00VENDOR>d<00DEVICE> (8 uppercase hexadecimal digits twice)')
for entry in chromiumos.gen_autosuspend_rules.PCI_IDS:
vendor, device = entry.split(':')
vendor = int(vendor, 16)
device = int(device, 16)
print('pci:v{:08X}d{:08X}*'.format(vendor, device))
print('# usb:v<VEND>p<PROD> (4 upp... | import chromiumos.gen_autosuspend_rules | random_line_split |
make-autosuspend-rules.py | #!/usr/bin/env python3
# SPDX-License-Identifier: LGPL-2.1+
# Generate autosuspend rules for devices that have been tested to work properly
# with autosuspend by the Chromium OS team. Based on
# https://chromium.googlesource.com/chromiumos/platform2/+/master/power_manager/udev/gen_autosuspend_rules.py
import chromium... |
print('# usb:v<VEND>p<PROD> (4 uppercase hexadecimal digits twice')
for entry in chromiumos.gen_autosuspend_rules.USB_IDS:
vendor, product = entry.split(':')
vendor = int(vendor, 16)
product = int(product, 16)
print('usb:v{:04X}p{:04X}*'.format(vendor, product))
print(' ID_AUTOSUSPEND=1')
| vendor, device = entry.split(':')
vendor = int(vendor, 16)
device = int(device, 16)
print('pci:v{:08X}d{:08X}*'.format(vendor, device)) | conditional_block |
image.rs | 2) -> (&::Element, (u32,u32)) {
(self, (0,0))
}
}
pub trait Buffer
{
fn dims_px(&self) -> Rect<Px>;
//fn dims_phys(&self) -> Rect<::geom::Mm>;
fn render(&self, buf: ::surface::SurfaceView);
}
impl Buffer for ::surface::Colour {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0,0,0)
}
fn render(&self, buf: ::s... | { self.bg } | conditional_block | |
image.rs | Image {
has_changed: ::std::cell::Cell::new(true),
data: i,
align_h: Align::Center,
align_v: Align::Center,
}
}
/// Set the vertical alignment of the image
pub fn set_align_v(&mut self, align: Align) {
self.align_v = align;
self.force_redraw();
}
/// Set the horizontal alignment of the image
p... |
fn render(&self, surface: ::surface::SurfaceView, force: bool) {
if force || self.has_changed.get() {
let (i_w, i_h) = self.dims_px();
let x = self.align_h.get_ofs(i_w, surface.width());
let y = self.align_h.get_ofs(i_h, surface.height());
let subsurf = surface.slice( Rect::new(Px(x), Px(y), Px(!0), Px... | {
// Don't care
false
} | identifier_body |
image.rs | Image {
has_changed: ::std::cell::Cell::new(true),
data: i,
align_h: Align::Center,
align_v: Align::Center,
}
}
/// Set the vertical alignment of the image
pub fn set_align_v(&mut self, align: Align) {
self.align_v = align;
self.force_redraw();
}
/// Set the horizontal alignment of the image
... | pub struct RasterBiA
{
bg: ::surface::Colour,
fg: ::surface::Colour,
width: usize,
data: Vec<bool>, // TODO: Use BitVec or similar
alpha: Vec<u8>,
}
impl RasterBiA
{
pub fn new_img<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour, bg: ::surface::Colour) -> Result<Image<Self>,LoadError> {
Self::new(path... | }
}
/// Raster two-colour image with alpha | random_line_split |
image.rs | <T: Buffer>
{
has_changed: ::std::cell::Cell<bool>,
align_v: Align,
align_h: Align,
data: T,
}
impl Align
{
fn get_ofs(&self, item: u32, avail: u32) -> u32 {
if item >= avail {
return 0;
}
match self
{
&Align::Left => 0,
&Align::Center => avail / 2 - item / 2,
&Align::Right => avail - item,
}
... | Image | identifier_name | |
strict_https_loader.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
from thumbor.loaders import http_loader
from tornado.concurrent impor... |
return http_loader.validate(context, url, normalize_url_func=_normalize_url)
def return_contents(response, url, callback, context):
return http_loader.return_contents(response, url, callback, context)
@return_future
def load(context, url, callback):
return http_loader.load_sync(context, url, callback,... | return False | conditional_block |
strict_https_loader.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
from thumbor.loaders import http_loader
from tornado.concurrent impor... |
@return_future
def load(context, url, callback):
return http_loader.load_sync(context, url, callback, normalize_url_func=_normalize_url)
def encode(string):
return http_loader.encode(string)
| return http_loader.return_contents(response, url, callback, context) | identifier_body |
strict_https_loader.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
from thumbor.loaders import http_loader
from tornado.concurrent impor... | if url.startswith('http:'):
url = url.replace('http:', 'https:', 1)
return url if url.startswith('https://') else 'https://%s' % url
def validate(context, url):
if url.startswith('http://'):
return False
return http_loader.validate(context, url, normalize_url_func=_normalize_url)
d... |
def _normalize_url(url):
url = http_loader.quote_url(unquote(url)) | random_line_split |
strict_https_loader.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
from thumbor.loaders import http_loader
from tornado.concurrent impor... | (url):
url = http_loader.quote_url(unquote(url))
if url.startswith('http:'):
url = url.replace('http:', 'https:', 1)
return url if url.startswith('https://') else 'https://%s' % url
def validate(context, url):
if url.startswith('http://'):
return False
return http_loader.validate... | _normalize_url | identifier_name |
lib.rs | extern crate gitignore;
extern crate libc;
use std::ffi::CStr;
use std::ffi::CString;
use std::mem;
use std::path::{Path, PathBuf};
use std::string::FromUtf8Error;
#[repr(C)]
pub struct RubyArray {
len: libc::size_t,
data: *const libc::c_void,
}
impl RubyArray {
fn from_vec<T>(vec: Vec<T>) -> RubyArr... | (path_ptr: *const libc::c_char) -> RubyArray {
let path_string = ptr_to_string(path_ptr).unwrap();
let path = Path::new(&*path_string).to_path_buf();
let gitignore_path = path.join(".gitignore");
let file = gitignore::File::new(&gitignore_path).unwrap();
let files = file.included_files().unwrap();... | included_files | identifier_name |
lib.rs | extern crate gitignore;
extern crate libc;
use std::ffi::CStr;
use std::ffi::CString;
use std::mem;
use std::path::{Path, PathBuf};
use std::string::FromUtf8Error;
#[repr(C)]
pub struct RubyArray {
len: libc::size_t,
data: *const libc::c_void,
}
impl RubyArray {
fn from_vec<T>(vec: Vec<T>) -> RubyArr... | let path_string = ptr_to_string(path_ptr).unwrap();
let path = Path::new(&*path_string).to_path_buf();
let gitignore_path = path.join(".gitignore");
let file = gitignore::File::new(&gitignore_path).unwrap();
let files = file.included_files().unwrap();
RubyArray::from_vec(paths_to_ptrs(files))
... | pub extern "C" fn included_files(path_ptr: *const libc::c_char) -> RubyArray { | random_line_split |
notebook_exporter.py | """
@file
@brief Customer notebook exporters.
"""
import os
from textwrap import indent
from traitlets import default
from traitlets.config import Config
from jinja2 import DictLoader
from nbconvert.exporters import RSTExporter
from nbconvert.filters.pandoc import convert_pandoc
def convert_pandoc_rst(source, from_fo... | # -*- coding: utf-8 -*- | random_line_split | |
notebook_exporter.py | # -*- coding: utf-8 -*-
"""
@file
@brief Customer notebook exporters.
"""
import os
from textwrap import indent
from traitlets import default
from traitlets.config import Config
from jinja2 import DictLoader
from nbconvert.exporters import RSTExporter
from nbconvert.filters.pandoc import convert_pandoc
def convert_pa... | c = Config({
'ExtractOutputPreprocessor': {
'enabled': True,
'output_filename_template': '{unique_key}_{cell_index}_{index}{extension}'
},
'HighlightMagicsPreprocessor': {
'enabled': True
},
})
c.merge(super(... | identifier_body | |
notebook_exporter.py | # -*- coding: utf-8 -*-
"""
@file
@brief Customer notebook exporters.
"""
import os
from textwrap import indent
from traitlets import default
from traitlets.config import Config
from jinja2 import DictLoader
from nbconvert.exporters import RSTExporter
from nbconvert.filters.pandoc import convert_pandoc
def convert_pa... |
if 'var update_menu = function() {' in source:
return "\n\n.. contents::\n :local:\n\n"
return "\n\n.. raw:: html\n\n" + indent(source, prefix=' ')
class UpgradedRSTExporter(RSTExporter):
"""
Exports :epkg:`rst` documents.
Overwrites `RSTExporter <https://github.com/jupyter/
nbc... | return source # pragma: no cover | conditional_block |
notebook_exporter.py | # -*- coding: utf-8 -*-
"""
@file
@brief Customer notebook exporters.
"""
import os
from textwrap import indent
from traitlets import default
from traitlets.config import Config
from jinja2 import DictLoader
from nbconvert.exporters import RSTExporter
from nbconvert.filters.pandoc import convert_pandoc
def convert_pa... | (self):
return '.rst'
@default('template_name')
def _template_name_default(self):
return 'rst'
@property
def default_config(self):
c = Config({
'ExtractOutputPreprocessor': {
'enabled': True,
'output_filename_template': '{unique_key}_... | _file_extension_default | identifier_name |
get_exif.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2013 Jérémie DECOCK (http://www.jdhp.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including withou... | :
"""Main function"""
img = Image.open("test.jpeg")
# Print the image's EXIF metadata dictionary indexed by EXIF numeric tags
exif_data_num_dict = img._getexif()
print exif_data_num_dict
# Print the image's EXIF metadata dictionary indexed by EXIF tag name strings
exif_data_str_dict = {PI... | in() | identifier_name |
get_exif.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2013 Jérémie DECOCK (http://www.jdhp.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including withou... |
def main():
"""Main function"""
img = Image.open("test.jpeg")
# Print the image's EXIF metadata dictionary indexed by EXIF numeric tags
exif_data_num_dict = img._getexif()
print exif_data_num_dict
# Print the image's EXIF metadata dictionary indexed by EXIF tag name strings
exif_data_str... | import PIL.ExifTags | random_line_split |
get_exif.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2013 Jérémie DECOCK (http://www.jdhp.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including withou... | in()
| conditional_block | |
get_exif.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2013 Jérémie DECOCK (http://www.jdhp.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including withou... | if __name__ == '__main__':
main()
| "Main function"""
img = Image.open("test.jpeg")
# Print the image's EXIF metadata dictionary indexed by EXIF numeric tags
exif_data_num_dict = img._getexif()
print exif_data_num_dict
# Print the image's EXIF metadata dictionary indexed by EXIF tag name strings
exif_data_str_dict = {PIL.ExifTa... | identifier_body |
test_pd_client.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use grpcio::EnvBuilder;
use kvproto::metapb::*;
use pd_client::{PdClient, RegionInfo, RegionStat, RpcClient};
use security::{SecurityConfig, SecurityManager};
use test_pd::{mocker::*, util::*, Server as MockServer};
use tikv_util::config::ReadableDurat... |
// Clean up the fail point.
fail::remove(pd_client_reconnect_fp);
handle.join().unwrap();
}
// Reconnection will be speed limited.
#[test]
fn test_reconnect_limit() {
let pd_client_reconnect_fp = "pd_client_reconnect";
let (_server, client) = new_test_server_and_client(ReadableDuration::secs(100)... | {
panic!("pd client2 is blocked");
} | conditional_block |
test_pd_client.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use grpcio::EnvBuilder;
use kvproto::metapb::*;
use pd_client::{PdClient, RegionInfo, RegionStat, RpcClient};
use security::{SecurityConfig, SecurityManager};
use test_pd::{mocker::*, util::*, Server as MockServer};
use tikv_util::config::ReadableDurat... | request!(client => block_on(get_region_by_id(0))),
request!(client => block_on(region_heartbeat(0, Region::default(), Peer::default(), RegionStat::default(), None))),
request!(client => block_on(ask_split(Region::default()))),
request!(client => block_on(ask_batch_split(Region::default()... | {
let (_server, client) = new_test_server_and_client(ReadableDuration::millis(100));
let client = Arc::new(client);
let pd_client_reconnect_fp = "pd_client_reconnect";
// It contains all interfaces of PdClient.
let test_funcs: Vec<(_, Box<dyn FnOnce() + Send>)> = vec;
}
| random_line_split |
store.js | import lowerCaseFirst from 'lower-case-first';
import {handles} from 'marty';
import Override from 'override-decorator';
function addHandlers(ResourceStore) {
const {constantMappings} = this;
return class ResourceStoreWithHandlers extends ResourceStore {
@Override
@handles(constantMappings.getMany.done)
... |
return super.fetch(options);
}
};
}
export default function extendStore(
ResourceStore,
{
useFetch = true,
...options
}
) {
ResourceStore = this::addHandlers(ResourceStore, options);
if (useFetch) {
ResourceStore = this::addFetch(ResourceStore, options);
}
return ResourceStore... | {
const baseLocally = options.locally;
options.locally = function refreshLocally() {
if (refresh) {
refresh = false;
return undefined;
} else {
return this::baseLocally();
}
};
} | conditional_block |
store.js | import lowerCaseFirst from 'lower-case-first';
import {handles} from 'marty';
import Override from 'override-decorator';
function addHandlers(ResourceStore) {
const {constantMappings} = this;
return class ResourceStoreWithHandlers extends ResourceStore {
@Override
@handles(constantMappings.getMany.done)
... |
[getMany](options, {refresh} = {}) {
return this.fetch({
id: `c${this.collectionKey(options)}`,
locally: () => this.localGetMany(options),
remotely: () => this.remoteGetMany(options),
refresh
});
}
[refreshMany](options) {
return this[getMany](options, {r... | {
return this.app[actionsKey];
} | identifier_body |
store.js | import lowerCaseFirst from 'lower-case-first';
import {handles} from 'marty';
import Override from 'override-decorator';
function addHandlers(ResourceStore) {
const {constantMappings} = this;
return class ResourceStoreWithHandlers extends ResourceStore {
@Override
@handles(constantMappings.getMany.done)
... | (
ResourceStore,
{
actionsKey = `${lowerCaseFirst(this.name)}Actions`
}
) {
const {methodNames, name, plural} = this;
const {getMany, getSingle} = methodNames;
const refreshMany = `refresh${plural}`;
const refreshSingle = `refresh${name}`;
return class ResourceStoreWithFetch extends ResourceStore ... | addFetch | identifier_name |
function.py | # coding=utf-8
#默认参数
# 定义默认参数要牢记一点:默认参数必须指向不变对象
# 默认值是列表、字典或大部分类的实例等易变的对象的时候又有所不同。例如,下面的函数在后续调用过程中会累积传给它的参数:
def f1(a, L=[]):
L.append(a)
return L
print(f1(1)) | print(f1(3))
# 如果你不想默认值在随后的调用中共享,可以像这样编写函数:
def f2(a, L=None):
if L is None:
L = []
L.append(a)
return L
print(f2(1))
print(f2(2))
print(f2(3))
# 可变参数---可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。
# 在参数前加上星号 *
def calc_sum(*numbers):
sum = 0
for i in numbers:
sum += i
return... | print(f1(2)) | random_line_split |
function.py | # coding=utf-8
#默认参数
# 定义默认参数要牢记一点:默认参数必须指向不变对象
# 默认值是列表、字典或大部分类的实例等易变的对象的时候又有所不同。例如,下面的函数在后续调用过程中会累积传给它的参数:
def f1(a, L=[]):
L.append(a)
return L
print(f1(1))
print(f1(2))
print(f1(3))
# 如果你不想默认值在随后的调用中共享,可以像这样编写函数:
def f2(a, L=None):
if L is None:
L = []
L.append(a)
return L
print(f2(... | r:', kw)
person('Michael', 30)
person('Bob', 35, city='Beijing')
person('Adam', 45, gender='M', job='Engineer')
# 参数列表的分拆
# 1. *-操作符将参数从列表或元组中分拆开来
# 2. **-操作符让字典传递关键字参数
args = [3, 6]
print(list(range(*args)))
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack', 24, **extra)
# 文档字符串
def my_function():
""... | e, 'othe | conditional_block |
function.py | # coding=utf-8
#默认参数
# 定义默认参数要牢记一点:默认参数必须指向不变对象
# 默认值是列表、字典或大部分类的实例等易变的对象的时候又有所不同。例如,下面的函数在后续调用过程中会累积传给它的参数:
def f1(a, L=[]):
L.append(a)
return L
print(f1(1))
print(f1(2))
print(f1(3))
# 如果你不想默认值在随后的调用中共享,可以像这样编写函数:
def f2(a, L=None):
if L is None:
L = []
L.append(a)
return L
print(f2(... | n('Michael', 30)
person('Bob', 35, city='Beijing')
person('Adam', 45, gender='M', job='Engineer')
# 参数列表的分拆
# 1. *-操作符将参数从列表或元组中分拆开来
# 2. **-操作符让字典传递关键字参数
args = [3, 6]
print(list(range(*args)))
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack', 24, **extra)
# 文档字符串
def my_function():
"""Do nothing, bu... | ):
print('name:', name, 'age:', age, 'other:', kw)
perso | identifier_body |
function.py | # coding=utf-8
#默认参数
# 定义默认参数要牢记一点:默认参数必须指向不变对象
# 默认值是列表、字典或大部分类的实例等易变的对象的时候又有所不同。例如,下面的函数在后续调用过程中会累积传给它的参数:
def f1(a, L=[]):
L.append(a)
return L
print(f1(1))
print(f1(2))
print(f1(3))
# 如果你不想默认值在随后的调用中共享,可以像这样编写函数:
def f2(a, L=None):
if L is None:
L = []
L | ppend(a)
return L
print(f2(1))
print(f2(2))
print(f2(3))
# 可变参数---可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。
# 在参数前加上星号 *
def calc_sum(*numbers):
sum = 0
for i in numbers:
sum += i
return sum
print(calc_sum(1, 2, 3))
# 如果参数本身就是一个list或者tuple,则在list或者tuple前加一个*号,变为可变参数传入
num_tuple = (1, 2, 3,... | .a | identifier_name |
sequence.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/.
*/
//! Utilities for paquet sequencing
use std::cmp::*;
use std::iter::Step;
use std::num::{Zero, One};
#[derive... | Some(val) => self.0 = val,
None => self.0 = I::zero()
};
self.0.clone()
}
pub fn stepu(&mut self) { let _ = self.step(); }
}
#[test]
fn test_step_incr() {
let mut seq = Sequence::new(0 as u8);
assert_eq!(0, seq.0);
seq.step();
assert_eq!(1, seq.0);
s... | match self.0.step(&I::one()) { | random_line_split |
sequence.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/.
*/
//! Utilities for paquet sequencing
use std::cmp::*;
use std::iter::Step;
use std::num::{Zero, One};
#[derive... | (&mut self) -> I {
match self.0.step(&I::one()) {
Some(val) => self.0 = val,
None => self.0 = I::zero()
};
self.0.clone()
}
pub fn stepu(&mut self) { let _ = self.step(); }
}
#[test]
fn test_step_incr() {
let mut seq = Sequence::new(0 as u8);
assert_eq!(... | step | identifier_name |
sequence.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/.
*/
//! Utilities for paquet sequencing
use std::cmp::*;
use std::iter::Step;
use std::num::{Zero, One};
#[derive... |
}
#[test]
fn test_step_incr() {
let mut seq = Sequence::new(0 as u8);
assert_eq!(0, seq.0);
seq.step();
assert_eq!(1, seq.0);
seq.step();
assert_eq!(2, seq.0);
seq.step();
assert_eq!(3, seq.0);
seq.step();
assert_eq!(4, seq.0)
}
#[test]
fn test_step_cycle() {
use std::u8;
... | { let _ = self.step(); } | identifier_body |
0009_auto__del_field_event_date.py | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
|
def backwards(self, orm):
# User chose to not deal with backwards NULL issues for 'Event.date'
raise RuntimeError("Cannot reverse this migration. 'Event.date' and its values cannot be restored.")
# The following code is provided here to aid in writing a correct migration # ... | def forwards(self, orm):
# Deleting field 'Event.date'
db.delete_column(u'photocontest_event', 'date')
| random_line_split |
0009_auto__del_field_event_date.py | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
| u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'photocon... | def forwards(self, orm):
# Deleting field 'Event.date'
db.delete_column(u'photocontest_event', 'date')
def backwards(self, orm):
# User chose to not deal with backwards NULL issues for 'Event.date'
raise RuntimeError("Cannot reverse this migration. 'Event.date' and its values cann... | identifier_body |
0009_auto__del_field_event_date.py | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class | (SchemaMigration):
def forwards(self, orm):
# Deleting field 'Event.date'
db.delete_column(u'photocontest_event', 'date')
def backwards(self, orm):
# User chose to not deal with backwards NULL issues for 'Event.date'
raise RuntimeError("Cannot reverse this migration. 'Event.d... | Migration | identifier_name |
dropboxFilePicker.ts | import { FilePicker } from "./Webamp";
interface DropboxFile {
link: string;
name: string;
}
// Requires Dropbox's Chooser to be loaded on the page
function genAudioFileUrlsFromDropbox(): Promise<DropboxFile[]> |
const dropboxFilePicker: FilePicker = {
contextMenuName: "Dropbox...",
filePicker: async () => {
alert(
`Dropbox integration is currently disabled. See https://github.com/captbaritone/webamp/issues/750 for more information.`
);
// https://github.com/captbaritone/webamp/issues/750
const files ... | {
return new Promise((resolve, reject) => {
// @ts-ignore
if (window.Dropbox == null) {
reject();
}
// @ts-ignore
window.Dropbox.choose({
success: resolve,
error: reject,
linkType: "direct",
folderselect: false,
multiselect: true,
extensions: ["video", "au... | identifier_body |
dropboxFilePicker.ts | import { FilePicker } from "./Webamp";
interface DropboxFile {
link: string;
name: string;
}
// Requires Dropbox's Chooser to be loaded on the page
function genAudioFileUrlsFromDropbox(): Promise<DropboxFile[]> {
return new Promise((resolve, reject) => {
// @ts-ignore
if (window.Dropbox == null) |
// @ts-ignore
window.Dropbox.choose({
success: resolve,
error: reject,
linkType: "direct",
folderselect: false,
multiselect: true,
extensions: ["video", "audio"],
});
});
}
const dropboxFilePicker: FilePicker = {
contextMenuName: "Dropbox...",
filePicker: async () ... | {
reject();
} | conditional_block |
dropboxFilePicker.ts | import { FilePicker } from "./Webamp";
interface DropboxFile {
link: string;
name: string;
}
// Requires Dropbox's Chooser to be loaded on the page
function | (): Promise<DropboxFile[]> {
return new Promise((resolve, reject) => {
// @ts-ignore
if (window.Dropbox == null) {
reject();
}
// @ts-ignore
window.Dropbox.choose({
success: resolve,
error: reject,
linkType: "direct",
folderselect: false,
multiselect: true,
... | genAudioFileUrlsFromDropbox | identifier_name |
dropboxFilePicker.ts | import { FilePicker } from "./Webamp";
interface DropboxFile {
link: string;
name: string;
}
// Requires Dropbox's Chooser to be loaded on the page
function genAudioFileUrlsFromDropbox(): Promise<DropboxFile[]> {
return new Promise((resolve, reject) => {
// @ts-ignore
if (window.Dropbox == null) {
... | const dropboxFilePicker: FilePicker = {
contextMenuName: "Dropbox...",
filePicker: async () => {
alert(
`Dropbox integration is currently disabled. See https://github.com/captbaritone/webamp/issues/750 for more information.`
);
// https://github.com/captbaritone/webamp/issues/750
const files =... | random_line_split | |
problem-005.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
// 2520 is the smallest number that can be divided by each of the numbers
// from 1 to 10 without any remainder.
//
// What is the smallest positive number that is evenly divisible by all of
// the numbers from 1... | }
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn correct() {
assert_eq!(232792560, solution());
}
#[bench]
fn bench(b: &mut Bencher) {
b.iter(|| solution());
}
} | }
fn main() {
println!("The smallest positive integer divisible by all of [1,20] is {}", solution()); | random_line_split |
problem-005.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
// 2520 is the smallest number that can be divided by each of the numbers
// from 1 to 10 without any remainder.
//
// What is the smallest positive number that is evenly divisible by all of
// the numbers from 1... | () {
assert_eq!(232792560, solution());
}
#[bench]
fn bench(b: &mut Bencher) {
b.iter(|| solution());
}
}
| correct | identifier_name |
problem-005.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
// 2520 is the smallest number that can be divided by each of the numbers
// from 1 to 10 without any remainder.
//
// What is the smallest positive number that is evenly divisible by all of
// the numbers from 1... |
}
}
return n;
}
fn main() {
println!("The smallest positive integer divisible by all of [1,20] is {}", solution());
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn correct() {
assert_eq!(232792560, solution());
}
#[bench]
fn bench(b: &m... | {
all_divisible = false;
break;
} | conditional_block |
problem-005.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
// 2520 is the smallest number that can be divided by each of the numbers
// from 1 to 10 without any remainder.
//
// What is the smallest positive number that is evenly divisible by all of
// the numbers from 1... |
#[bench]
fn bench(b: &mut Bencher) {
b.iter(|| solution());
}
}
| {
assert_eq!(232792560, solution());
} | identifier_body |
setup.py | #
# Copyright 2016 Dohop hf.
#
# 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, ... | """
from setuptools import setup, find_packages
# 2 step 'with open' to be python2.6 compatible
with open('requirements.txt') as requirements:
with open('test_requirements.txt') as test_requirements:
setup(
name='supervisor-logstash-notifier',
version='0.2.5',
packages... | """
Setup script for building supervisor-logstash-notifier | random_line_split |
list.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("List", inherited=True) %>
${help... | gujarati gurmukhi kannada khmer lao malayalam mongolian
myanmar oriya persian telugu thai tibetan cjk-earthly-branch
cjk-heavenly-stem lower-greek hiragana hiragana-iroha katakana
katakana-iroha""",
gecko_con... | // [1]: http://dev.w3.org/csswg/css-counter-styles/
${helpers.single_keyword("list-style-type", """
disc none circle square decimal lower-alpha upper-alpha disclosure-open disclosure-closed
""", extra_servo_values="""arabic-indic bengali cambodian cjk-decimal devanagari | random_line_split |
list.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("List", inherited=True) %>
${help... | {
None,
Url(Url),
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
SpecifiedValue::None => dest.write_str("none"),
SpecifiedValue::Url(ref url) => url.to_css(dest),
... | SpecifiedValue | identifier_name |
list.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("List", inherited=True) %>
${help... |
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(vec![
("\u{201c}".to_owned(), "\u{201d}".to_owned()),
("\u{2018}".to_owned(), "\u{2019}".to_owned()),
])
}
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<Specifie... | {
let mut first = true;
for pair in &self.0 {
if !first {
try!(dest.write_str(" "));
}
first = false;
try!(Token::QuotedString(Cow::from(&*pair.0)).to_css(dest));
try!(dest.write_str(" "));
... | identifier_body |
modules.js | // Copyright 2013 Traceur Authors.
//
// 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 ... |
toModule() {
var oldName = refererUrl;
refererUrl = this.name;
try {
return this.func.call(this.self);
} finally {
refererUrl = oldName
}
}
}
function registerModule(name, func, self) {
var url = resolveUrl(refererUrl, name);
modules[url] = new Pending... | {
this.name = name;
this.func = func;
this.self = self;
} | identifier_body |
modules.js | // Copyright 2013 Traceur Authors.
//
// 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 ... |
var refererUrl = './';
function setRefererUrl(url) {
refererUrl = url || './';
}
function getRefererUrl() {
return refererUrl;
}
class PendingModule {
constructor(name, func, self) {
this.name = name;
this.func = func;
this.self = self;
}
toModule() {
var oldN... |
var modules = Object.create(null); | random_line_split |
modules.js | // Copyright 2013 Traceur Authors.
//
// 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 ... | () {
var oldName = refererUrl;
refererUrl = this.name;
try {
return this.func.call(this.self);
} finally {
refererUrl = oldName
}
}
}
function registerModule(name, func, self) {
var url = resolveUrl(refererUrl, name);
modules[url] = new PendingModule(name, ... | toModule | identifier_name |
select_feature.py | __author__ = 'LiGe'
#encoding:utf-8
import networkx as nx
import matplotlib.pyplot as plot
from file_to_graph import file_to_mat
def build_graph(mat):
| sub_graph= nx.strongly_connected_component_subgraphs(G)
for line in sub_graph:
print nx.degree(line)
#pos =nx.circular_layout(G)
#plot.title('the orginal graph with pos')
#nx.draw(G,pos,with_label=True,node_size=300)
#plot.show()
nx.draw(line, with_label=Tr... | G=nx.DiGraph()#创建空图
for i in range(0,mat.shape[0]):
G.add_node(i)#创造节点
for i in range(0,mat.shape[0]):
for j in range(0,mat.shape[1]):
if mat[i,j]==1:
G.add_edge(i,j)#加一条有向边
#print nx.in_degree(G,0)
#print nx.out_degree(G)
#print nx.degree(G)
... | identifier_body |
select_feature.py | __author__ = 'LiGe'
#encoding:utf-8
import networkx as nx
import matplotlib.pyplot as plot
from file_to_graph import file_to_mat
def build_graph(mat):
G=nx.DiGraph()#创建空图
for i in range(0,mat.shape[0]):
G.add_node(i)#创造节点
for i in range(0,mat.shape[0]):
for j in range(0,mat.shape... | ':
file='benapi_renew/mmc.exe.txt'
mat=file_to_mat(file)
build_graph(mat)
| #pos =nx.circular_layout(G)
#plot.title('the orginal graph with pos')
#nx.draw(G,pos,with_label=True,node_size=300)
#plot.show()
nx.draw(line, with_label=True)
plot.show()
if __name__=='__main__ | conditional_block |
select_feature.py | __author__ = 'LiGe'
#encoding:utf-8
import networkx as nx
import matplotlib.pyplot as plot
from file_to_graph import file_to_mat
def | (mat):
G=nx.DiGraph()#创建空图
for i in range(0,mat.shape[0]):
G.add_node(i)#创造节点
for i in range(0,mat.shape[0]):
for j in range(0,mat.shape[1]):
if mat[i,j]==1:
G.add_edge(i,j)#加一条有向边
#print nx.in_degree(G,0)
#print nx.out_degree(G)
#print nx.... | build_graph | identifier_name |
select_feature.py | __author__ = 'LiGe'
#encoding:utf-8
import networkx as nx
import matplotlib.pyplot as plot
from file_to_graph import file_to_mat
def build_graph(mat):
G=nx.DiGraph()#创建空图
for i in range(0,mat.shape[0]):
G.add_node(i)#创造节点
for i in range(0,mat.shape[0]):
for j in range(0,mat.shape... | print nx.closeness_centrality(G)
#print nx.diameter(G)
print nx.average_shortest_path_length(G)
# print nx.average_clustering(G)
sub_graph= nx.strongly_connected_component_subgraphs(G)
for line in sub_graph:
print nx.degree(line)
#pos =nx.circular_layout(G)
#plot.t... | random_line_split | |
organization.js | import Controller from '@ember/controller';
import modal from '../utils/modal';
import i18n from '../utils/i18n';
import session from '../utils/session';
import persistence from '../utils/persistence';
import CoughDrop from '../app';
import { later as runLater } from '@ember/runloop';
export default Controller.extend(... | var user_name = this.get('masquerade_user_name');
var _this = this;
this.store.findRecord('user', user_name).then(function(u) {
var data = session.restore();
data.original_user_name = data.user_name;
data.as_user_id = user_name;
data.user_name = user_name;... | if(this.get('model.admin') && this.get('model.permissions.manage')) { | random_line_split |
models.py | from django.db import models
class TimeStampedModel(models.Model):
|
class Caller(TimeStampedModel):
name = models.CharField(max_length=30)
phone_number = models.CharField(max_length=15)
question_num = models.IntegerField(default=0)
start_num = models.IntegerField(default=0)
end_num = models.IntegerField(default=0)
start_fresh = models.BooleanField(default=True... | created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True | identifier_body |
models.py | from django.db import models
class TimeStampedModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Caller(TimeStampedModel):
name = models.CharField(max_length=30)
phone_number = models.Cha... | (TimeStampedModel):
num = models.IntegerField()
question_text = models.CharField(max_length=1600)
def __str__(self):
return self.question_text[:100] + '...'
class Choice(TimeStampedModel):
question = models.ForeignKey(Question, related_name='choices')
choice_text = models.CharField(max_le... | Question | identifier_name |
models.py | from django.db import models
class TimeStampedModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
| end_num = models.IntegerField(default=0)
start_fresh = models.BooleanField(default=True)
intro_text = models.CharField(max_length=1600)
outro_text = models.CharField(max_length=1600)
def __str__(self):
return self.name
class Question(TimeStampedModel):
num = models.IntegerField()
... | class Caller(TimeStampedModel):
name = models.CharField(max_length=30)
phone_number = models.CharField(max_length=15)
question_num = models.IntegerField(default=0)
start_num = models.IntegerField(default=0) | random_line_split |
setup.py | from setuptools import find_packages, setup
from auspost_pac import __version__ as version
setup(
name='python-auspost-pac',
version=version, | install_requires=[
'cached_property',
'frozendict',
'requests',
],
packages=find_packages(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD Licens... | license='BSD',
author='Sam Kingston',
author_email='sam@sjkwi.com.au',
description='Python API for Australia Post\'s Postage Assessment Calculator (pac).',
url='https://github.com/sjkingo/python-auspost-pac', | random_line_split |
wm_touch.py | '''
Support for WM_TOUCH messages (Windows platform)
================================================
'''
__all__ = ('WM_MotionEventProvider', 'WM_MotionEvent')
import os
from kivy.input.providers.wm_common import WNDPROC, \
SetWindowLong_WndProc_wrapper, RECT, POINT, WM_TABLET_QUERYSYSTEMGESTURE, \
QUERYSYST... | if t.event_type == 'end' and t.id in self.touches:
touch = self.touches[t.id]
touch.move([x, y, t.size()])
touch.update_time_end()
dispatch_fn('end', touch)
del self.touches[t.id]
def stop(self)... | try:
t = self.touch_events.pop()
except:
break
# adjust x,y to window coordinates (0.0 to 1.0)
x = (t.screen_x() - x_offset) / usable_w
y = 1.0 - (t.screen_y() - y_offset) / usable_h
# actually disp... | conditional_block |
wm_touch.py | '''
Support for WM_TOUCH messages (Windows platform)
================================================
'''
__all__ = ('WM_MotionEventProvider', 'WM_MotionEvent')
import os
from kivy.input.providers.wm_common import WNDPROC, \
SetWindowLong_WndProc_wrapper, RECT, POINT, WM_TABLET_QUERYSYSTEMGESTURE, \
QUERYSYST... | (MotionEventProvider):
def start(self):
global Window
if not Window:
from kivy.core.window import Window
self.touch_events = deque()
self.touches = {}
self.uid = 0
# get window handle, and register to receive WM_TOUCH mes... | WM_MotionEventProvider | identifier_name |
wm_touch.py | '''
Support for WM_TOUCH messages (Windows platform)
================================================
'''
__all__ = ('WM_MotionEventProvider', 'WM_MotionEvent')
import os
from kivy.input.providers.wm_common import WNDPROC, \
SetWindowLong_WndProc_wrapper, RECT, POINT, WM_TABLET_QUERYSYSTEMGESTURE, \
QUERYSYST... |
def depack(self, args):
self.shape = ShapeRect()
self.sx, self.sy = args[0], args[1]
self.shape.width = args[2][0]
self.shape.height = args[2][1]
self.size = self.shape.width * self.shape.height
super().depack(args)
def __str__(self):
args = (self.id, s... | kwargs.setdefault('is_touch', True)
kwargs.setdefault('type_id', 'touch')
super().__init__(*args, **kwargs)
self.profile = ('pos', 'shape', 'size') | identifier_body |
wm_touch.py | '''
Support for WM_TOUCH messages (Windows platform)
================================================
'''
__all__ = ('WM_MotionEventProvider', 'WM_MotionEvent')
import os
from kivy.input.providers.wm_common import WNDPROC, \
SetWindowLong_WndProc_wrapper, RECT, POINT, WM_TABLET_QUERYSYSTEMGESTURE, \
QUERYSYST... |
class WM_MotionEvent(MotionEvent):
'''MotionEvent representing the WM_MotionEvent event.
Supports pos, shape and size profiles.
'''
__attrs__ = ('size', )
def __init__(self, *args, **kwargs):
kwargs.setdefault('is_touch', True)
kwargs.setdefault('type_id', 'touch')
super... |
Window = None
| random_line_split |
utils.ts | /**
* 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... |
const isGroup = Array.isArray((options[0] || {}).options);
const flatOptions = isGroup
? (options as GroupedOptionsType<OptionType>).flatMap(x => x.options || [])
: (options as OptionsType<OptionType>);
const find = (val: OptionType) => {
const realVal = (value || {}).hasOwnProperty(valueKey)
... | {
return [];
} | conditional_block |
utils.ts | /**
* 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... | * Find Option value that matches a possibly string value.
*
* Translate possible string values to `OptionType` objects, fallback to value
* itself if cannot be found in the options list.
*
* Always returns an array.
*/
export function findValue<OptionType extends OptionTypeBase>(
value: ValueType<OptionType> |... | import { OptionsType as AntdOptionsType } from './Select';
/** | random_line_split |
utils.ts | /**
* 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... | (search: string, options: AntdOptionsType) {
const searchOption = search.trim().toLowerCase();
return options.find(opt => {
const { label, value } = opt;
const labelText = String(label);
const valueText = String(value);
return (
valueText.toLowerCase().includes(searchOption) ||
labelText... | hasOption | identifier_name |
utils.ts | /**
* 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... | {
const searchOption = search.trim().toLowerCase();
return options.find(opt => {
const { label, value } = opt;
const labelText = String(label);
const valueText = String(value);
return (
valueText.toLowerCase().includes(searchOption) ||
labelText.toLowerCase().includes(searchOption)
)... | identifier_body | |
support_data.py | from __future__ import division
from bs4 import BeautifulSoup
import urllib2
import re
def url_request(url):
hdr = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36',
'Accept':'*/*'}
request = urllib2.Request(url, headers=hd... | mcm = None
if 'N/A' in mcm_entry.text:
mcm = 1
elif '*' in mcm_entry.text:
url = base_url + link['href']
response = url_request(url)
support_html = response.read()
mcm = get_support_info(support_html)
else:
try:
... | header = bs.find('th', text = re.compile(search_phrase))
support_headers = header.find_next_siblings('th')
mcm_col = -1
for i in range(len(support_headers)):
if support_headers[i].text == 'MCM':
## print "header_location: " + str(i + 1)
mcm_col = i + 1
break
ta... | identifier_body |
support_data.py | from __future__ import division
from bs4 import BeautifulSoup
import urllib2
import re
def url_request(url):
hdr = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36',
'Accept':'*/*'}
request = urllib2.Request(url, headers=hd... |
else:
print "OH NO: " + skill_name
url = 'http://pathofexile.gamepedia.com/Skills'
base_url = 'http://pathofexile.gamepedia.com'
response = url_request(url)
sk_html = response.read()
bs = BeautifulSoup(sk_html)
support_dict = {}
find_supports(bs, 'Strength Support Gems', 'str', suppo... | support_dict[skill_name] = (attr_tag, mcm) | conditional_block |
support_data.py | from __future__ import division
from bs4 import BeautifulSoup
import urllib2
import re
def url_request(url):
hdr = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36',
'Accept':'*/*'}
request = urllib2.Request(url, headers=hd... | link = r.find('a')
if link == None:
continue
skill_name = link.text.strip()
print skill_name
row_entries = r.find_all('td')
mcm_entry = row_entries[mcm_col]
mcm = None
if 'N/A' in mcm_entry.text:
mcm = 1
elif '*' in mcm_entr... | base_url = 'http://pathofexile.gamepedia.com/'
support_list = []
for r in rows: | random_line_split |
support_data.py | from __future__ import division
from bs4 import BeautifulSoup
import urllib2
import re
def url_request(url):
hdr = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36',
'Accept':'*/*'}
request = urllib2.Request(url, headers=hd... | (skill_name, skill_tag_and_costs):
row = skill_name + "|"
attr_tag = skill_tag_and_costs[0]
mana_mults = skill_tag_and_costs[1]
row += attr_tag + "|"
if type(mana_mults) is list:
for t in mana_mults:
row += str(t[0]) + "-" + str(t[1]) + ","
row = row[:-1]
else:
... | support_skill_row | identifier_name |
row_polymorphism.rs | use gluon::{ | };
use crate::support::make_vm;
#[macro_use]
mod support;
test_expr! { polymorphic_field_access,
r#"
let f record = record.x
f { y = 1, x = 123 }
"#,
123
}
test_expr! { polymorphic_record_unpack,
r#"
let f record =
let { x, y } = record
x #Int- y
f { y = 1, z = 0, x = 123 }
"#,
122
}
#[test]
fn polymorphic... | vm::api::{FunctionRef, Hole, OpaqueValue},
Thread, ThreadExt, | random_line_split |
row_polymorphism.rs | use gluon::{
vm::api::{FunctionRef, Hole, OpaqueValue},
Thread, ThreadExt,
};
use crate::support::make_vm;
#[macro_use]
mod support;
test_expr! { polymorphic_field_access,
r#"
let f record = record.x
f { y = 1, x = 123 }
"#,
123
}
test_expr! { polymorphic_record_unpack,
r#"
let f record =
let { x, y } =... |
// FIXME Add this test back when order no longer matters for fields
// test_expr! { prelude different_order_on_fields,
// r#"
// let x =
// if False then
// { x = 1, y = "a" }
// else
// { y = "b", x = 2 }
// x.y
// "#,
// String::from("a")
// }
//
| {
let _ = ::env_logger::try_init();
let vm = make_vm();
let child = vm.new_thread().unwrap();
vm.run_expr::<OpaqueValue<&Thread, Hole>>("", "import! std.function")
.unwrap();
let result = child.run_expr::<FunctionRef<fn(i32) -> i32>>(
"test",
r#"
let function = impo... | identifier_body |
row_polymorphism.rs | use gluon::{
vm::api::{FunctionRef, Hole, OpaqueValue},
Thread, ThreadExt,
};
use crate::support::make_vm;
#[macro_use]
mod support;
test_expr! { polymorphic_field_access,
r#"
let f record = record.x
f { y = 1, x = 123 }
"#,
123
}
test_expr! { polymorphic_record_unpack,
r#"
let f record =
let { x, y } =... | () {
let _ = ::env_logger::try_init();
let vm = make_vm();
let child = vm.new_thread().unwrap();
vm.run_expr::<OpaqueValue<&Thread, Hole>>("", "import! std.function")
.unwrap();
let result = child.run_expr::<FunctionRef<fn(i32) -> i32>>(
"test",
r#"
let function = i... | polymorphic_record_access_from_child_thread | identifier_name |
stylesheet_set.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/. */
//! A centralized set of stylesheets for a document.
use dom::TElement;
use invalidation::stylesheets::Stylesheet... |
/// Returns whether the given set has changed from the last flush.
pub fn has_changed(&self) -> bool {
self.dirty
}
/// Flush the current set, unmarking it as dirty, and returns an iterator
/// over the new stylesheet list.
pub fn flush<E>(
&mut self,
document_element:... | {
debug!("StylesheetSet::set_author_style_disabled");
if self.author_style_disabled == disabled {
return;
}
self.author_style_disabled = disabled;
self.dirty = true;
self.invalidations.invalidate_fully();
} | identifier_body |
stylesheet_set.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/. */
//! A centralized set of stylesheets for a document.
use dom::TElement;
use invalidation::stylesheets::Stylesheet... | &sheet,
guard
);
self.entries.insert(0, StylesheetSetEntry { sheet });
self.dirty = true;
}
/// Insert a given stylesheet before another stylesheet in the document.
pub fn insert_stylesheet_before(
&mut self,
stylist: &Stylist,
sheet: ... | self.invalidations.collect_invalidations_for(
stylist, | random_line_split |
stylesheet_set.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/. */
//! A centralized set of stylesheets for a document.
use dom::TElement;
use invalidation::stylesheets::Stylesheet... |
self.author_style_disabled = disabled;
self.dirty = true;
self.invalidations.invalidate_fully();
}
/// Returns whether the given set has changed from the last flush.
pub fn has_changed(&self) -> bool {
self.dirty
}
/// Flush the current set, unmarking it as dirty, ... | {
return;
} | conditional_block |
stylesheet_set.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/. */
//! A centralized set of stylesheets for a document.
use dom::TElement;
use invalidation::stylesheets::Stylesheet... | (
&mut self,
stylist: &Stylist,
sheet: S,
guard: &SharedRwLockReadGuard,
) {
debug!("StylesheetSet::remove_stylesheet");
self.remove_stylesheet_if_present(&sheet);
self.dirty = true;
self.invalidations.collect_invalidations_for(
stylist,
... | remove_stylesheet | identifier_name |
cli.rs | //! Provides the CLI option parser
//!
//! Used to parse the argv/config file into a struct that
//! the server can consume and use as configuration data.
use docopt::Docopt;
static USAGE: &'static str = "
Usage: statsd [options]
statsd --help
Options:
-h, --help Print help information.
-p, --p... | {
pub flag_port: u16,
pub flag_admin_port: u16,
pub flag_admin_host: String,
pub flag_flush_interval: u64,
pub flag_console: bool,
pub flag_graphite: bool,
pub flag_graphite_port: u16,
pub flag_graphite_host: String,
pub flag_help: bool,
}
pub fn parse_args() -> Args {
let args... | Args | identifier_name |
cli.rs | //! Provides the CLI option parser
//!
//! Used to parse the argv/config file into a struct that
//! the server can consume and use as configuration data.
use docopt::Docopt;
static USAGE: &'static str = "
Usage: statsd [options]
statsd --help
Options:
-h, --help Print help information.
-p, --p... | --graphite-port=<p> The port graphite/carbon is running on. [default: 2003].
--graphite-host=<p> The host graphite/carbon is running on. [default: 127.0.0.1]
--admin-host=<p> The host to bind the management server on. [default: 127.0.0.1]
--admin-port=<p> The port to bind the management server to.... | --graphite Enable the graphite backend. | random_line_split |
setup.py | # -*- coding: utf-8 -*-
from distutils.core import setup
from setuptools import find_packages
LONGDOC = """
A very simple python library, used to format datetime with *** time ago statement.
Install
pip install timeago
Usage
import timeago, datetime
d = datetime.datetime.now() + datetime.timedelta(seconds = 60... | author_email = 'i@hust.cc',
url = 'https://github.com/hustcc/timeago',
license = 'MIT',
install_requires = [],
classifiers = [
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Natural Language :: Chinese (Simplified)',
'Programming L... | setup(name = 'timeago',
version = '1.0.7',
description = 'A very simple python library, used to format datetime with `*** time ago` statement. eg: "3 hours ago".',
long_description = LONGDOC,
author = 'hustcc', | random_line_split |
execute.py | # This file is part of Pimlico
# Copyright (C) 2020 Mark Granroth-Wilding
# Licensed under the GNU LGPL v3.0 - https://www.gnu.org/licenses/lgpl-3.0.en.html
from builtins import str
from builtins import zip
from pimlico.core.external.java import Py4JInterface, JavaProcessError
from pimlico.core.modules.execute import ... |
# Don't parse the parse trees, since OpenNLP does that for us, straight from the text
executor.input_corpora[0].raw_data = True
ModuleExecutor = multiprocessing_executor_factory(
process_document, preprocess_fn=preprocess, worker_set_up_fn=worker_set_up, worker_tear_down_fn=worker_tear_down
)
| executor.log.info("Allow up to %d seconds for each coref job" % executor.info.options["timeout"]) | conditional_block |
execute.py | # This file is part of Pimlico
# Copyright (C) 2020 Mark Granroth-Wilding
# Licensed under the GNU LGPL v3.0 - https://www.gnu.org/licenses/lgpl-3.0.en.html
from builtins import str
from builtins import zip
from pimlico.core.external.java import Py4JInterface, JavaProcessError
from pimlico.core.modules.execute import ... |
def worker_tear_down(worker):
worker.interface.stop()
def preprocess(executor):
if executor.info.options["timeout"] is not None:
executor.log.info("Allow up to %d seconds for each coref job" % executor.info.options["timeout"])
# Don't parse the parse trees, since OpenNLP does that for us, strai... | worker.interface = start_interface(worker.info) | identifier_body |
execute.py | # This file is part of Pimlico
# Copyright (C) 2020 Mark Granroth-Wilding
# Licensed under the GNU LGPL v3.0 - https://www.gnu.org/licenses/lgpl-3.0.en.html
from builtins import str
from builtins import zip
from pimlico.core.external.java import Py4JInterface, JavaProcessError
from pimlico.core.modules.execute import ... | (worker, archive, filename, doc):
interface = worker.interface
# Resolve coreference, passing in PTB parse trees as strings
coref_result = interface.gateway.entry_point.resolveCoreference(doc)
if coref_result is None:
# Coref failed, return an invalid doc
# Fetch all output from stdout a... | process_document | identifier_name |
execute.py | # This file is part of Pimlico
# Copyright (C) 2020 Mark Granroth-Wilding
# Licensed under the GNU LGPL v3.0 - https://www.gnu.org/licenses/lgpl-3.0.en.html
from builtins import str
from builtins import zip
from pimlico.core.external.java import Py4JInterface, JavaProcessError
from pimlico.core.modules.execute import ... | # Coref failed, return an invalid doc
# Fetch all output from stdout and stderr
stdout = _get_full_queue(interface.stdout_queue)
stderr = _get_full_queue(interface.stderr_queue)
return InvalidDocument(
u"opennlp_coref", u"Error running coref\nJava stdout:\n%s\nJava st... | interface = worker.interface
# Resolve coreference, passing in PTB parse trees as strings
coref_result = interface.gateway.entry_point.resolveCoreference(doc)
if coref_result is None: | random_line_split |
onlinehelp.py | # -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""Online Help Plugin"""
from spyderlib.qt.QtCore import Signal
import os.path as osp
# Local imports
from spyderlib.baseconfig import get_conf_path, ... | Online Help Plugin
"""
sig_option_changed = Signal(str, object)
CONF_SECTION = 'onlinehelp'
LOG_PATH = get_conf_path('.onlinehelp')
def __init__(self, parent):
self.main = parent
PydocBrowser.__init__(self, parent)
SpyderPluginMixin.__init__(self, parent)
... | random_line_split | |
onlinehelp.py | # -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""Online Help Plugin"""
from spyderlib.qt.QtCore import Signal
import os.path as osp
# Local imports
from spyderlib.baseconfig import get_conf_path, ... | self):
"""
Return the widget to give focus to when
this plugin's dockwidget is raised on top-level
"""
self.url_combo.lineEdit().selectAll()
return self.url_combo
def closing_plugin(self, cancelable=False):
"""Perform actions before parent ma... | et_focus_widget( | identifier_name |
onlinehelp.py | # -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""Online Help Plugin"""
from spyderlib.qt.QtCore import Signal
import os.path as osp
# Local imports
from spyderlib.baseconfig import get_conf_path, ... |
else:
history = []
return history
def save_history(self):
"""Save history to a text file in user home directory"""
file(self.LOG_PATH, 'w').write("\n".join( \
[ unicode( self.url_combo.itemText(index) )
for index in range(self.url... | istory = [line.replace('\n','')
for line in file(self.LOG_PATH, 'r').readlines()]
| conditional_block |
onlinehelp.py | # -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""Online Help Plugin"""
from spyderlib.qt.QtCore import Signal
import os.path as osp
# Local imports
from spyderlib.baseconfig import get_conf_path, ... |
#------ SpyderPluginWidget API ---------------------------------------------
def get_plugin_title(self):
"""Return widget title"""
return _('Online help')
def get_focus_widget(self):
"""
Return the widget to give focus to when
this plugin's dockwid... | ""DockWidget visibility has changed"""
SpyderPluginMixin.visibility_changed(self, enable)
if enable and not self.is_server_running():
self.initialize()
| identifier_body |
qa_random.py | #!/usr/bin/env python
#
# Copyright 2006,2007,2010,2015 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at ... | for k in range(num_tests):
values[k] = rndm.ran1()
for value in values:
self.assertLess(value, 1)
self.assertGreaterEqual(value, 0)
# Check reseed method (init with time and seed as fix number)
def test_2(self):
num = 5
rndm0 = gr.random(42);... | def test_1(self):
num_tests = 10000
values = np.zeros(num_tests)
rndm = gr.random() | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.