file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
draft.py | from datetime import datetime
from xmodule.modulestore import Location, namedtuple_to_son
from xmodule.modulestore.exceptions import ItemNotFoundError
from xmodule.modulestore.inheritance import own_metadata
from xmodule.exceptions import InvalidVersionError
from xmodule.modulestore.mongo.base import MongoModuleStore
... | metadata: A nested dictionary of module metadata
"""
draft_loc = as_draft(location)
draft_item = self.get_item(location)
if not getattr(draft_item, 'is_draft', False):
self.clone_item(location, draft_loc)
if 'is_draft' in metadata:
del metadata['... | random_line_split | |
inventoryState.ts | import { ActionChartItem, ActionChart, Item } from "..";
import { mechanicsEngine } from "../controller/mechanics/mechanicsEngine";
/**
* Inventory state at one point
*/
export class InventoryState {
public weapons: ActionChartItem[] = [];
public hasBackpack: boolean = false;
public backpackItems: Act... |
return objects;
}
private addItem(aChartItem: ActionChartItem) {
const item = aChartItem.getItem();
if (!item) {
return;
}
if (item.type === Item.WEAPON) {
this.weapons.push(aChartItem);
} else if (item.type === Item.SPECIAL) {
... | {
const msg = "Wrong objectTypes: " + objectTypes;
mechanicsEngine.debugWarning(msg);
throw msg;
} | conditional_block |
inventoryState.ts | import { ActionChartItem, ActionChart, Item } from "..";
import { mechanicsEngine } from "../controller/mechanics/mechanicsEngine";
/**
* Inventory state at one point
*/
export class InventoryState {
public weapons: ActionChartItem[] = [];
public hasBackpack: boolean = false;
public backpackItems: Act... | (items: ActionChartItem[]) {
for (const item of items) {
this.addItem(item.clone());
}
}
/**
* Append to this inventory state other state
* @param s2 The state to append to this
*/
public addInventoryToThis(s2: InventoryState) {
this.weapons = this.weapon... | addItemsArray | identifier_name |
inventoryState.ts | import { ActionChartItem, ActionChart, Item } from "..";
import { mechanicsEngine } from "../controller/mechanics/mechanicsEngine";
/**
* Inventory state at one point
*/
export class InventoryState {
public weapons: ActionChartItem[] = [];
public hasBackpack: boolean = false;
public backpackItems: Act... |
}
| {
return {
weapons: this.weapons,
hasBackpack: this.hasBackpack,
backpackItems: this.backpackItems,
specialItems: this.specialItems,
beltPouch: this.beltPouch,
arrows: this.arrows,
meals: this.meals
};
} | identifier_body |
inventoryState.ts | import { ActionChartItem, ActionChart, Item } from "..";
import { mechanicsEngine } from "../controller/mechanics/mechanicsEngine";
/**
* Inventory state at one point
*/
export class InventoryState {
public weapons: ActionChartItem[] = [];
public hasBackpack: boolean = false;
public backpackItems: Act... |
return toRecover;
}
/**
* Create a inventory state from an object
* @param object The inventory state object. Must to have same properties than InventoryState
*/
public static fromObject(object: any): InventoryState {
if (!object) {
return new InventoryState();
... | random_line_split | |
users.rs | #![crate_name = "users"]
/*
* This file is part of the uutils coreutils package.
*
* (c) KokaKiwi <kokakiwi@kokakiwi.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* last synced with: whoami (GNU coreutils) 8.22 */
// All... |
fn exec(filename: &str) {
unsafe {
utmpxname(CString::new(filename).unwrap().as_ptr());
}
let mut users = vec!();
unsafe {
setutxent();
loop {
let line = getutxent();
if line == ptr::null() {
break;
}
if (*lin... | {
let mut opts = Options::new();
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!("{}", f),
};
if matches.opt_present("help") ... | identifier_body |
users.rs | #![crate_name = "users"]
/*
* This file is part of the uutils coreutils package.
*
* (c) KokaKiwi <kokakiwi@kokakiwi.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* last synced with: whoami (GNU coreutils) 8.22 */
// All... | (args: Vec<String>) -> i32 {
let mut opts = Options::new();
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!("{}", f),
};
if m... | uumain | identifier_name |
users.rs | #![crate_name = "users"]
/*
* This file is part of the uutils coreutils package.
*
* (c) KokaKiwi <kokakiwi@kokakiwi.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* last synced with: whoami (GNU coreutils) 8.22 */
// All... |
if (*line).ut_type == USER_PROCESS {
let user = String::from_utf8_lossy(CStr::from_ptr(mem::transmute(&(*line).ut_user)).to_bytes()).to_string();
users.push(user);
}
}
endutxent();
}
if users.len() > 0 {
users.sort();
pr... | {
break;
} | conditional_block |
users.rs | #![crate_name = "users"]
/*
* This file is part of the uutils coreutils package.
*
* (c) KokaKiwi <kokakiwi@kokakiwi.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* last synced with: whoami (GNU coreutils) 8.22 */
// All... | println!("");
println!("Usage:");
println!(" {} [OPTION]... [FILE]", NAME);
println!("");
println!("{}", opts.usage("Output who is currently logged in according to FILE."));
return 0;
}
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION)... | println!("{} {}", NAME, VERSION); | random_line_split |
hello_triangle.rs | extern crate bootstrap_rs as bootstrap;
extern crate polygon;
use bootstrap::window::*;
use polygon::*;
use polygon::anchor::*;
use polygon::camera::*;
use polygon::math::*;
use polygon::mesh_instance::*;
use polygon::geometry::mesh::*;
static VERTEX_POSITIONS: [f32; 12] = [
-1.0, -1.0, 0.0, 1.0,
1.0, -1.0, ... | () {
// Open a window and create the renderer instance.
let mut window = Window::new("Hello, Triangle!").unwrap();
let mut renderer = RendererBuilder::new(&window).build();
// Build a triangle mesh.
let mesh = MeshBuilder::new()
.set_position_data(Point::slice_from_f32_slice(&VERTEX_POSITIO... | main | identifier_name |
hello_triangle.rs | extern crate bootstrap_rs as bootstrap;
extern crate polygon;
use bootstrap::window::*;
use polygon::*;
use polygon::anchor::*;
use polygon::camera::*;
use polygon::math::*;
use polygon::mesh_instance::*;
use polygon::geometry::mesh::*;
static VERTEX_POSITIONS: [f32; 12] = [
-1.0, -1.0, 0.0, 1.0,
1.0, -1.0, ... |
// Send the mesh to the GPU.
let gpu_mesh = renderer.register_mesh(&mesh);
// Create an anchor and register it with the renderer.
let anchor = Anchor::new();
let anchor_id = renderer.register_anchor(anchor);
// Setup the material for the mesh.
let mut material = renderer.default_material(... | .set_indices(&INDICES)
.build()
.unwrap(); | random_line_split |
hello_triangle.rs | extern crate bootstrap_rs as bootstrap;
extern crate polygon;
use bootstrap::window::*;
use polygon::*;
use polygon::anchor::*;
use polygon::camera::*;
use polygon::math::*;
use polygon::mesh_instance::*;
use polygon::geometry::mesh::*;
static VERTEX_POSITIONS: [f32; 12] = [
-1.0, -1.0, 0.0, 1.0,
1.0, -1.0, ... | {
// Open a window and create the renderer instance.
let mut window = Window::new("Hello, Triangle!").unwrap();
let mut renderer = RendererBuilder::new(&window).build();
// Build a triangle mesh.
let mesh = MeshBuilder::new()
.set_position_data(Point::slice_from_f32_slice(&VERTEX_POSITIONS)... | identifier_body | |
TestRe.py | # -*- coding: utf-8 -*-
import re
test = '用户输入的字符串'
if re.match(r'用户', test):
print('ok')
else:
| iled')
print('a b c'.split(' '))
print(re.split(r'\s*', 'a b c'))
print(re.split(r'[\s\,\;]+', 'a,b;; c d'))
m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
print(m.group(1))
m = re.match(r'^(\S+)@(\S+.com)$', 'cysuncn@126.com')
print(m.group(2))
print(m.groups())
# <Tom Paris> tom@voyager .org
re_mail = re.com... | print('fa | conditional_block |
TestRe.py | # -*- coding: utf-8 -*-
import re
test = '用户输入的字符串'
if re.match(r'用户', test):
print('ok')
else:
print('failed')
print('a b c'.split(' '))
print(re.split(r'\s*', 'a b c'))
print(re.split(r'[\s\,\;]+', 'a,b;; c d'))
m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
print(m.group(1))
m = re.match(r'^(\S+)@(\... |
str = 'abcbacba'
# non-greed match
re = re.compile(r'a.*?a', re.S)
print(re.match(str).group()) | print(re_mail.match('<Tom Paris> tom@voyager.org').groups()) | random_line_split |
xml.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 https://mozilla.org/MPL/2.0/. */
#![allow(unrooted_must_root)]
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::trace::J... |
}
#[allow(unsafe_code)]
unsafe impl JSTraceable for XmlTokenizer<XmlTreeBuilder<Dom<Node>, Sink>> {
unsafe fn trace(&self, trc: *mut JSTracer) {
struct Tracer(*mut JSTracer);
let tracer = Tracer(trc);
impl XmlTracer for Tracer {
type Handle = Dom<Node>;
#[allow(unr... | {
&self.inner.sink.sink.base_url
} | identifier_body |
xml.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 https://mozilla.org/MPL/2.0/. */
#![allow(unrooted_must_root)]
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::trace::J... |
Ok(())
}
pub fn end(&mut self) {
self.inner.end()
}
pub fn url(&self) -> &ServoUrl {
&self.inner.sink.sink.base_url
}
}
#[allow(unsafe_code)]
unsafe impl JSTraceable for XmlTokenizer<XmlTreeBuilder<Dom<Node>, Sink>> {
unsafe fn trace(&self, trc: *mut JSTracer) {
... | {
return Err(script);
} | conditional_block |
xml.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 https://mozilla.org/MPL/2.0/. */
#![allow(unrooted_must_root)]
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::trace::J... | node.trace(self.0);
}
}
}
let tree_builder = &self.sink;
tree_builder.trace_handles(&tracer);
tree_builder.sink.trace(trc);
}
} | type Handle = Dom<Node>;
#[allow(unrooted_must_root)]
fn trace_handle(&self, node: &Dom<Node>) {
unsafe { | random_line_split |
xml.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 https://mozilla.org/MPL/2.0/. */
#![allow(unrooted_must_root)]
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::trace::J... | (&self, trc: *mut JSTracer) {
struct Tracer(*mut JSTracer);
let tracer = Tracer(trc);
impl XmlTracer for Tracer {
type Handle = Dom<Node>;
#[allow(unrooted_must_root)]
fn trace_handle(&self, node: &Dom<Node>) {
unsafe {
nod... | trace | identifier_name |
SqliteCustomFunctions.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
if __name__ == '__main__':
sys.path.append('../../')
import json
import logging
import sqlite3
from gchelpers.ip.GeoDbManager import GeoDbManager
from gchelpers.dt import DateTimeHandler
GEO_MANAGER = GeoDbManager()
def splitpath(path, ... |
def GetRegMatch(input,group,pattern):
if input is None:
return None
match = re.search(pattern, input)
result = None
if match:
result = match.group(group)
return result
def GetRegMatchArray(input,group,pattern):
hits = []
if input is None:
re... | if input is None:
return None
input = input.replace("\n", "")
input = input.replace("\r", "")
return input | identifier_body |
SqliteCustomFunctions.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
if __name__ == '__main__':
sys.path.append('../../')
import json
import logging
import sqlite3
from gchelpers.ip.GeoDbManager import GeoDbManager
from gchelpers.dt import DateTimeHandler
GEO_MANAGER = GeoDbManager()
def splitpath(path, ... | (input,group,pattern):
hits = []
if input is None:
return json.dumps(hits)
for result in re.finditer(pattern, input):
hits.append(result.group(group))
if len(hits) > 0:
return json.dumps(hits)
return json.dumps(hits)
def test1():
n = 2
fullnam... | GetRegMatchArray | identifier_name |
SqliteCustomFunctions.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
if __name__ == '__main__':
sys.path.append('../../')
import json
import logging
import sqlite3
from gchelpers.ip.GeoDbManager import GeoDbManager
from gchelpers.dt import DateTimeHandler
GEO_MANAGER = GeoDbManager()
def splitpath(path, ... |
return None
def DtFormat(dtstringin,newformat):
if dtstringin:
string_out = None
# Get object from in string
datetime_obj = DateTimeHandler.DatetimeFromString(
dtstringin
)
# Format object
string_out = DateTimeHandler.Strin... | string_out = None
# Get object from in string
datetime_obj = DateTimeHandler.DatetimeFromString(
dtstringin
)
# Timezone Conversion
new_datetime_obj = DateTimeHandler.ConvertDatetimeTz(
datetime_obj,
current_tz_str,
... | conditional_block |
SqliteCustomFunctions.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
if __name__ == '__main__':
sys.path.append('../../')
import json
import logging
import sqlite3
from gchelpers.ip.GeoDbManager import GeoDbManager
from gchelpers.dt import DateTimeHandler
GEO_MANAGER = GeoDbManager()
def splitpath(path, ... |
def test2():
n = 2
fullname = "testfolder001\\testfile088.png"
splitname = splitpath(fullname,n)
print splitname
if __name__ == '__main__':
test1()
test2() | print splitname | random_line_split |
kana.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
from jcconv import kata2hira, hira2kata
from itertools import chain
from printable import PrintableDict, PrintableList
__by_vowels = PrintableDict(**{
u'ア': u'ワラヤャマハナタサカアァ',
u'イ': u'リミヒニちシキイィ',
u'ウ': u'ルユュムフヌツスクウゥ',
... | ana(char)
if is_kata:
char = kata2hira(char)
for char in __to_mini.get(char, ''):
yield hira2kata(char) if is_kata else char
def extend_dakuten_reading(string):
if len(string) == 0:
yield ''
return
char = string[0]
for mult in kana_plus_dakuten(char):
yiel... | s_kata = is_katak | identifier_name |
kana.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
from jcconv import kata2hira, hira2kata
from itertools import chain
from printable import PrintableDict, PrintableList
__by_vowels = PrintableDict(**{
u'ア': u'ワラヤャマハナタサカアァ',
u'イ': u'リミヒニちシキイィ',
u'ウ': u'ルユュムフヌツスクウゥ',
... | except ValueError:
# Sometimes certain codepoints can't be used on a machine
pass
def char_set(value):
if isinstance(value, list) or isinstance(value, tuple):
return codepoint_range(*value)
else:
return [value]
def unipairs(lst):
return PrintableList(reduce(lambda ... | t, end):
try:
yield unichr(val)
| conditional_block |
kana.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
from jcconv import kata2hira, hira2kata
from itertools import chain
from printable import PrintableDict, PrintableList
__by_vowels = PrintableDict(**{
u'ア': u'ワラヤャマハナタサカアァ',
u'イ': u'リミヒニちシキイィ',
u'ウ': u'ルユュムフヌツスクウゥ',
... | return [value]
def unipairs(lst):
return PrintableList(reduce(lambda a, b: chain(a, b), map(char_set, lst)))
__KATAKANA = (
# Katakana: http://en.wikipedia.org/wiki/Katakana
(0x30A0, 0x30FF + 1),
(0x31F0, 0x31FF + 1),
(0x3200, 0x32FF + 1),
(0xFF00, 0xFFEF + 1),
)
__HIRAGANA = (
# ... | return codepoint_range(*value)
else: | random_line_split |
kana.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
from jcconv import kata2hira, hira2kata
from itertools import chain
from printable import PrintableDict, PrintableList
__by_vowels = PrintableDict(**{
u'ア': u'ワラヤャマハナタサカアァ',
u'イ': u'リミヒニちシキイィ',
u'ウ': u'ルユュムフヌツスクウゥ',
... | turn hira2kata(hira)
else:
return __by_dakuten.get(char, char)
def kana_plus_dakuten(char):
yield char
is_kata = is_katakana(char)
if is_kata:
char = kata2hira(char)
for char in __to_dakuten.get(char, ''):
yield hira2kata(char) if is_kata else char
def kana_plus_mini(char... | ra, hira)
re | identifier_body |
PlaceholderImage.js | import cx from 'clsx'
import PropTypes from 'prop-types'
import React from 'react'
import { customPropTypes, getElementType, getUnhandledProps, useKeyOnly } from '../../lib'
/**
* A placeholder can contain an image.
*/
function PlaceholderImage(props) |
PlaceholderImage.propTypes = {
/** An element type to render as (string or function). */
as: PropTypes.elementType,
/** Additional classes. */
className: PropTypes.string,
/** An image can modify size correctly with responsive styles. */
square: customPropTypes.every([customPropTypes.disallow(['rectangu... | {
const { className, square, rectangular } = props
const classes = cx(
useKeyOnly(square, 'square'),
useKeyOnly(rectangular, 'rectangular'),
'image',
className,
)
const rest = getUnhandledProps(PlaceholderImage, props)
const ElementType = getElementType(PlaceholderImage, props)
return <Elem... | identifier_body |
PlaceholderImage.js | import cx from 'clsx'
import PropTypes from 'prop-types'
import React from 'react'
import { customPropTypes, getElementType, getUnhandledProps, useKeyOnly } from '../../lib'
/**
* A placeholder can contain an image.
*/
function | (props) {
const { className, square, rectangular } = props
const classes = cx(
useKeyOnly(square, 'square'),
useKeyOnly(rectangular, 'rectangular'),
'image',
className,
)
const rest = getUnhandledProps(PlaceholderImage, props)
const ElementType = getElementType(PlaceholderImage, props)
retu... | PlaceholderImage | identifier_name |
PlaceholderImage.js | import cx from 'clsx'
import PropTypes from 'prop-types'
import React from 'react'
import { customPropTypes, getElementType, getUnhandledProps, useKeyOnly } from '../../lib'
/**
* A placeholder can contain an image.
*/
function PlaceholderImage(props) { | useKeyOnly(square, 'square'),
useKeyOnly(rectangular, 'rectangular'),
'image',
className,
)
const rest = getUnhandledProps(PlaceholderImage, props)
const ElementType = getElementType(PlaceholderImage, props)
return <ElementType {...rest} className={classes} />
}
PlaceholderImage.propTypes = {
... | const { className, square, rectangular } = props
const classes = cx( | random_line_split |
subprocess_py27.py | # This file is part of the Python 2.7 module subprocess.py, included here
# for compatibility with Python 2.6.
#
# It is still under the original, very open PSF license, see the original
# copyright message included below.
#
# subprocess - Subprocesses with accessible I/O streams
#
# For more information about this mod... | """
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
... | ... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n' | random_line_split |
subprocess_py27.py | # This file is part of the Python 2.7 module subprocess.py, included here
# for compatibility with Python 2.6.
#
# It is still under the original, very open PSF license, see the original
# copyright message included below.
#
# subprocess - Subprocesses with accessible I/O streams
#
# For more information about this mod... | (*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are th... | check_output | identifier_name |
subprocess_py27.py | # This file is part of the Python 2.7 module subprocess.py, included here
# for compatibility with Python 2.6.
#
# It is still under the original, very open PSF license, see the original
# copyright message included below.
#
# subprocess - Subprocesses with accessible I/O streams
#
# For more information about this mod... |
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd)
return output
| raise ValueError('stdout argument not allowed, it will be overridden.') | conditional_block |
subprocess_py27.py | # This file is part of the Python 2.7 module subprocess.py, included here
# for compatibility with Python 2.6.
#
# It is still under the original, very open PSF license, see the original
# copyright message included below.
#
# subprocess - Subprocesses with accessible I/O streams
#
# For more information about this mod... | r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen cons... | identifier_body | |
texts.js | CS.Controllers.Texts = [
{
type: "workbook-area-description",
workbookAreaClassName: "Strengths",
htmlText: "<p>Vad utmärker dig som person? Vilka styrkor använder du för att få jobbet gjort? Från vilket perspektiv ser du på tillvaron? </p><p>I det här avsnittet av Tracks kommer du att besva... | type: "workbook-area-description",
workbookAreaClassName: "ManagementStyle",
htmlText: "<p>TODO</p>"
},
{
type: "workbook-area-description",
workbookAreaClassName: "Mores",
htmlText: "<p>Ett av de enklaste och mest effektiva sätten att utvecklas mot ett mer mening... | },
{ | random_line_split |
method_info.rs | use super::Attributes;
#[derive(Debug)]
pub struct | {
pub access_flags: MethodAccessFlags,
pub name_index: u16,
pub descriptor_index: u16,
pub attrs: Attributes,
}
bitflags! {
pub flags MethodAccessFlags: u16 {
const METHOD_ACC_PUBLIC = 0x0001,
const METHOD_ACC_PRIVATE = 0x0002,
const METHOD_ACC_PROTECTED = ... | MethodInfo | identifier_name |
method_info.rs | use super::Attributes;
#[derive(Debug)]
pub struct MethodInfo {
pub access_flags: MethodAccessFlags,
pub name_index: u16,
pub descriptor_index: u16,
pub attrs: Attributes,
}
bitflags! {
pub flags MethodAccessFlags: u16 {
const METHOD_ACC_PUBLIC = 0x0001,
const METHOD_ACC_PRI... | }
pub fn is_bridge(&self) -> bool {
self.contains(METHOD_ACC_BRIDGE)
}
pub fn is_varargs(&self) -> bool {
self.contains(METHOD_ACC_VARARGS)
}
pub fn is_native(&self) -> bool {
self.contains(METHOD_ACC_NATIVE)
}
pub fn is_abstract(&self) -> bool {
self.... | random_line_split | |
test_level_types.py | from django.urls import reverse
from course_discovery.apps.api.v1.tests.test_views.mixins import APITestCase, SerializationMixin
from course_discovery.apps.core.tests.factories import USER_PASSWORD, UserFactory
from course_discovery.apps.course_metadata.models import LevelType
from course_discovery.apps.course_metadat... | def test_authentication(self):
""" Verify the endpoint requires the user to be authenticated. """
response = self.client.get(self.list_path)
assert response.status_code == 200
self.client.logout()
response = self.client.get(self.list_path)
assert response.status_code... | def setUp(self):
super().setUp()
self.user = UserFactory(is_staff=True, is_superuser=True)
self.client.login(username=self.user.username, password=USER_PASSWORD)
| random_line_split |
test_level_types.py | from django.urls import reverse
from course_discovery.apps.api.v1.tests.test_views.mixins import APITestCase, SerializationMixin
from course_discovery.apps.core.tests.factories import USER_PASSWORD, UserFactory
from course_discovery.apps.course_metadata.models import LevelType
from course_discovery.apps.course_metadat... | (self):
""" The request should return details for a single level type. """
level_type = LevelTypeFactory()
level_type.set_current_language('en')
level_type.name_t = level_type.name
level_type.save()
url = reverse('api:v1:level_type-detail', kwargs={'name': level_type.name... | test_retrieve | identifier_name |
test_level_types.py | from django.urls import reverse
from course_discovery.apps.api.v1.tests.test_views.mixins import APITestCase, SerializationMixin
from course_discovery.apps.core.tests.factories import USER_PASSWORD, UserFactory
from course_discovery.apps.course_metadata.models import LevelType
from course_discovery.apps.course_metadat... |
def test_authentication(self):
""" Verify the endpoint requires the user to be authenticated. """
response = self.client.get(self.list_path)
assert response.status_code == 200
self.client.logout()
response = self.client.get(self.list_path)
assert response.status_co... | super().setUp()
self.user = UserFactory(is_staff=True, is_superuser=True)
self.client.login(username=self.user.username, password=USER_PASSWORD) | identifier_body |
kontrtube.py | # encoding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
int_or_none,
parse_duration,
)
class KontrTubeIE(InfoExtractor):
| IE_NAME = 'kontrtube'
IE_DESC = 'KontrTube.ru - Труба зовёт'
_VALID_URL = r'http://(?:www\.)?kontrtube\.ru/videos/(?P<id>\d+)/(?P<display_id>[^/]+)/'
_TEST = {
'url': 'http://www.kontrtube.ru/videos/2678/nad-olimpiyskoy-derevney-v-sochi-podnyat-rossiyskiy-flag/',
'md5': '975a991a4926c9a85f3... | identifier_body | |
kontrtube.py | # encoding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
int_or_none,
parse_duration,
)
class | (InfoExtractor):
IE_NAME = 'kontrtube'
IE_DESC = 'KontrTube.ru - Труба зовёт'
_VALID_URL = r'http://(?:www\.)?kontrtube\.ru/videos/(?P<id>\d+)/(?P<display_id>[^/]+)/'
_TEST = {
'url': 'http://www.kontrtube.ru/videos/2678/nad-olimpiyskoy-derevney-v-sochi-podnyat-rossiyskiy-flag/',
'md5':... | KontrTubeIE | identifier_name |
kontrtube.py | # encoding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor | parse_duration,
)
class KontrTubeIE(InfoExtractor):
IE_NAME = 'kontrtube'
IE_DESC = 'KontrTube.ru - Труба зовёт'
_VALID_URL = r'http://(?:www\.)?kontrtube\.ru/videos/(?P<id>\d+)/(?P<display_id>[^/]+)/'
_TEST = {
'url': 'http://www.kontrtube.ru/videos/2678/nad-olimpiyskoy-derevney-v-sochi-... | from ..utils import (
int_or_none, | random_line_split |
kontrtube.py | # encoding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
int_or_none,
parse_duration,
)
class KontrTubeIE(InfoExtractor):
IE_NAME = 'kontrtube'
IE_DESC = 'KontrTube.ru - Труба зовёт'
_VALID_URL = r'http://(?:www\.)?kontrtube\.ru/... | ((\d+)\)<', webpage, ' comment count', fatal=False))
return {
'id': video_id,
'display_id': display_id,
'url': video_url,
'thumbnail': thumbnail,
'title': title,
'description': description,
'duration': duration,
'vi... | _none(self._search_regex(
r'Комментарии \ | conditional_block |
text.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/. */
//! Text layout.
#![deny(unsafe_code)]
use app_units::Au;
use fragment::{Fragment, ScannedTextFragmentInfo, Spec... | };
fragments.push_front(new_fragment);
}
/// Information about a text run that we're about to create. This is used in `scan_for_runs`.
struct RunInfo {
/// The text that will go in this text run.
text: String,
/// The insertion point in this text run, if applicable.
insertion_point: Option<Cha... | UnscannedTextFragmentInfo::new(string_before,
insertion_point_before))) | random_line_split |
text.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/. */
//! Text layout.
#![deny(unsafe_code)]
use app_units::Au;
use fragment::{Fragment, ScannedTextFragmentInfo, Spec... | yle: &ComputedValues, metrics: &FontMetrics) -> Au {
let font_size = style.get_font().font_size;
match style.get_inheritedbox().line_height {
line_height::T::Normal => metrics.line_gap,
line_height::T::Number(l) => font_size.scale_by(l),
line_height::T::Length(l) => l
}
}
fn split_f... | e_height_from_style(st | identifier_name |
text.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/. */
//! Text layout.
#![deny(unsafe_code)]
use app_units::Au;
use fragment::{Fragment, ScannedTextFragmentInfo, Spec... |
_ => panic!("Expected an unscanned text fragment!"),
};
let (mut start_position, mut end_position) = (0, 0);
for character in text.chars() {
// Search for the first font in this font group that contains a glyph for this
... | {
text = &text_fragment_info.text;
insertion_point = text_fragment_info.insertion_point;
} | conditional_block |
ProximityBridge.d.ts | /// <reference path="APIRequest.d.ts" />
/// <reference path="APIResponse.d.ts" />
/// <reference path="BaseSensorBridge.d.ts" />
/// <reference path="CommonUtil.d.ts" />
/// <reference path="IAdaptiveRPGroup.d.ts" />
/// <reference path="IBaseSensor.d.ts" />
/// <reference path="IProximity.d.ts" />
/**
--| ADAPTIVE RU... | * @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
declare module Adaptive {
/**
@class Adaptive.ProximityBridge
@extends Adaptive.BaseSensorBridge
Interface for Managing the Proximity operations
... | * See source code files for contributors.
Release:
| random_line_split |
ProximityBridge.d.ts | /// <reference path="APIRequest.d.ts" />
/// <reference path="APIResponse.d.ts" />
/// <reference path="BaseSensorBridge.d.ts" />
/// <reference path="CommonUtil.d.ts" />
/// <reference path="IAdaptiveRPGroup.d.ts" />
/// <reference path="IBaseSensor.d.ts" />
/// <reference path="IProximity.d.ts" />
/**
--| ADAPTIVE RU... | extends BaseSensorBridge implements IProximity {
/**
@method constructor
Default constructor.
*/
constructor();
}
}
| ProximityBridge | identifier_name |
message.js | var messaging_enabled = process.env.FH_AMQP_APP_ENABLED;
var messaging_user = process.env.FH_AMQP_USER;
var message_pass = process.env.FH_AMQP_PASS;
var messaging_nodes = process.env.FH_AMQP_NODES;
var messaging_max_cons = process.env.FH_AMQP_CONN_MAX || 10;
var messaging_vhost = process.env.FH_AMQP_VHOST;
var messag... | ;
connect(function (er, conn){
retAmqp = conn;
});
return {
"getAmqp": function (cb){
connect(cb);
},
"getAmqpManager": function (){
return amqpManager;
}
};
};
| {
if (messaging_enabled && messaging_enabled !== "false" && ! retAmqp) {
var clusterNodes = [];
var nodes = (messaging_nodes && messaging_nodes.split) ? messaging_nodes.split(",") : [];
var vhost = "";
if(messaging_vhost && messaging_vhost.trim() !== "/"){
vhost = messaging_vhost.tri... | identifier_body |
message.js | var messaging_enabled = process.env.FH_AMQP_APP_ENABLED;
var messaging_user = process.env.FH_AMQP_USER;
var message_pass = process.env.FH_AMQP_PASS;
var messaging_nodes = process.env.FH_AMQP_NODES;
var messaging_max_cons = process.env.FH_AMQP_CONN_MAX || 10;
var messaging_vhost = process.env.FH_AMQP_VHOST;
var messag... | var conf = {
"enabled": messaging_enabled,
"clusterNodes": clusterNodes,
"maxReconnectAttempts": messaging_max_cons
};
var amqpjs = require('fh-amqp-js');
amqpManager = new amqpjs.AMQPManager(conf);
amqpManager.connectToCluster();
amqpManager.on("error", fu... | node = "amqp://"+messaging_user+":"+message_pass+"@"+node+vhost;
clusterNodes.push(node);
}
| random_line_split |
message.js | var messaging_enabled = process.env.FH_AMQP_APP_ENABLED;
var messaging_user = process.env.FH_AMQP_USER;
var message_pass = process.env.FH_AMQP_PASS;
var messaging_nodes = process.env.FH_AMQP_NODES;
var messaging_max_cons = process.env.FH_AMQP_CONN_MAX || 10;
var messaging_vhost = process.env.FH_AMQP_VHOST;
var messag... | (cb){
if (messaging_enabled && messaging_enabled !== "false" && ! retAmqp) {
var clusterNodes = [];
var nodes = (messaging_nodes && messaging_nodes.split) ? messaging_nodes.split(",") : [];
var vhost = "";
if(messaging_vhost && messaging_vhost.trim() !== "/"){
vhost = messaging_vhost... | connect | identifier_name |
message.js | var messaging_enabled = process.env.FH_AMQP_APP_ENABLED;
var messaging_user = process.env.FH_AMQP_USER;
var message_pass = process.env.FH_AMQP_PASS;
var messaging_nodes = process.env.FH_AMQP_NODES;
var messaging_max_cons = process.env.FH_AMQP_CONN_MAX || 10;
var messaging_vhost = process.env.FH_AMQP_VHOST;
var messag... |
};
connect(function (er, conn){
retAmqp = conn;
});
return {
"getAmqp": function (cb){
connect(cb);
},
"getAmqpManager": function (){
return amqpManager;
}
};
};
| {
cb({"message":"messaging not enabled","code":503});
} | conditional_block |
network-records-to-devtools-log.js | // @ts-nocheck
/**
* @license Copyright 2018 The Lighthouse Authors. 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 requ... | (networkRecord, index) {
let initiator = {type: 'other'};
if (networkRecord.initiator) {
initiator = {...networkRecord.initiator};
}
return {
method: 'Network.requestWillBeSent',
params: {
requestId: getBaseRequestId(networkRecord) || `${idBase}.${index}`,
documentURL: networkRecord.doc... | getRequestWillBeSentEvent | identifier_name |
network-records-to-devtools-log.js | // @ts-nocheck
/**
* @license Copyright 2018 The Lighthouse Authors. 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 requ... |
/**
* @param {Partial<NetworkRequest>} networkRecord
* @return {LH.Protocol.RawEventMessage}
*/
function getLoadingFailedEvent(networkRecord, index) {
return {
method: 'Network.loadingFailed',
params: {
requestId: getBaseRequestId(networkRecord) || `${idBase}.${index}`,
timestamp: networkReco... | {
return {
method: 'Network.loadingFinished',
params: {
requestId: getBaseRequestId(networkRecord) || `${idBase}.${index}`,
timestamp: networkRecord.endTime || 3,
encodedDataLength: networkRecord.transferSize === undefined ?
0 : networkRecord.transferSize,
},
};
} | identifier_body |
network-records-to-devtools-log.js | // @ts-nocheck
/**
* @license Copyright 2018 The Lighthouse Authors. 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 requ... | }
if (networkRecord.fromMemoryCache) {
devtoolsLog.push(getRequestServedFromCacheEvent(networkRecord, index));
}
if (networkRecord.failed) {
devtoolsLog.push(getLoadingFailedEvent(networkRecord, index));
return;
}
devtoolsLog.push(getResponseReceivedEvent(networkRecord, inde... | return; | random_line_split |
testsuite.py | # Copyright (c) 2018 PaddlePaddle Authors. 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 app... |
for attr_name in Operator.get_op_attr_names(op_type):
if attr_name in attrs:
kwargs[attr_name] = attrs[attr_name]
return Operator(op_type, **kwargs)
def set_input(scope, op, inputs, place):
def np_value_to_fluid_value(input):
if input.dtype == np.float16:
input =... | __create_var__(out_name, out_name) | conditional_block |
testsuite.py | # Copyright (c) 2018 PaddlePaddle Authors. 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 app... | (block, output_names):
mean_inputs = list(map(block.var, output_names))
if len(mean_inputs) == 1:
loss = block.create_var(dtype=mean_inputs[0].dtype, shape=[1])
op = block.append_op(
inputs={"X": mean_inputs}, outputs={"Out": loss}, type='mean')
op.desc.infer_var_type(block.... | append_loss_ops | identifier_name |
testsuite.py | # Copyright (c) 2018 PaddlePaddle Authors. 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 app... |
for in_name, in_dup in Operator.get_op_inputs(op_type):
if in_name in inputs:
kwargs[in_name] = []
if in_dup:
sub_in = inputs[in_name]
for item in sub_in:
sub_in_name, _ = item[0], item[1]
__create_var__(in_nam... | scope.var(var_name).get_tensor()
kwargs[name].append(var_name) | identifier_body |
testsuite.py | # Copyright (c) 2018 PaddlePaddle Authors. 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 app... | '''Insert VarDesc and generate Python variable instance'''
proto_list = op_proto.inputs if is_input else op_proto.outputs
def create_var(block, name, np_list, var_proto):
dtype = None
shape = None
lod_level = None
if name not in np_list:
assert var_proto.intermed... | else:
__set_input__(in_name, inputs[in_name])
def append_input_output(block, op_proto, np_list, is_input, dtype): | random_line_split |
progress.rs | //! A simple progress meter.
//!
//! Records updates of number of files visited, and number of bytes
//! processed. When given an estimate, printes a simple periodic report of
//! how far along we think we are.
use env_logger::Builder;
use lazy_static::lazy_static;
use log::Log;
use std::{
io::{stdout, Write},
... | {
let mut value = value as f64;
let mut unit = 0;
while value > 1024.0 {
value /= 1024.0;
unit += 1;
}
static UNITS: [&str; 9] = [
"B ", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB",
];
let precision = if value < 10.0 {
3
} else if value < 10... | identifier_body | |
progress.rs | //! A simple progress meter.
//!
//! Records updates of number of files visited, and number of bytes
//! processed. When given an estimate, printes a simple periodic report of
//! how far along we think we are.
use env_logger::Builder;
use lazy_static::lazy_static;
use log::Log;
use std::{
io::{stdout, Write},
... | next_update: update_interval(false),
is_logging: false,
});
}
impl State {
/// Called to advance to the next message, sets the update time
/// appropriately.
fn next(&mut self) {
self.next_update = update_interval(self.is_logging);
}
/// Clears the visual text of the cu... | message: String::new(), | random_line_split |
progress.rs | //! A simple progress meter.
//!
//! Records updates of number of files visited, and number of bytes
//! processed. When given an estimate, printes a simple periodic report of
//! how far along we think we are.
use env_logger::Builder;
use lazy_static::lazy_static;
use log::Log;
use std::{
io::{stdout, Write},
... | (&mut self) {
self.next_update = update_interval(self.is_logging);
}
/// Clears the visual text of the current message (but not the message
/// buffer itself, so that it can be redisplayed if needed).
fn clear(&self) {
for ch in self.message.chars() {
if ch == '\n' {
... | next | identifier_name |
progress.rs | //! A simple progress meter.
//!
//! Records updates of number of files visited, and number of bytes
//! processed. When given an estimate, printes a simple periodic report of
//! how far along we think we are.
use env_logger::Builder;
use lazy_static::lazy_static;
use log::Log;
use std::{
io::{stdout, Write},
... |
}
lazy_static! {
// The current global state.
static ref STATE: Mutex<State> = Mutex::new(State {
message: String::new(),
next_update: update_interval(false),
is_logging: false,
});
}
impl State {
/// Called to advance to the next message, sets the update time
/// appropri... | {
OffsetDateTime::now_utc() + Duration::seconds(5)
} | conditional_block |
project.config.js | const NODE_ENV = process.env.NODE_ENV || 'development'
module.exports = {
/** The environment to use when building the project */
env: NODE_ENV,
/** The full path to the project's root directory */
basePath: __dirname,
/** The name of the directory containing the application source code */
srcDir: 'src',
... | 'redux',
'react-redux',
'redux-thunk',
'react-router',
],
apiProxy: {
url: 'http://47.94.172.79'
}
} | 'react-dom', | random_line_split |
processor.ts | import path from "path";
import {
CoreConfig,
WorkingDirectoryInfo,
PluginCreateOptions,
KeyGeneratorPlugin,
PublisherPlugin,
NotifierPlugin,
NotifyParams,
PluginLogger,
ComparisonResult,
} from "reg-suit-interface";
import { EventEmitter } from "events";
const compare = require("reg-cli");
const rim... |
publish(ctx: StepResultAfterActualKey): Promise<StepResultAfterPublish> {
if (this._publisher) {
return this._publisher
.publish(ctx.actualKey)
.then(result => {
this._logger.info(`Published snapshot '${ctx.actualKey}' successfully.`);
if (result.reportUrl) {
... | {
const keyForExpected = ctx.expectedKey;
if (this._publisher && keyForExpected) {
return this._publisher.fetch(keyForExpected);
} else if (!keyForExpected) {
this._logger.info("Skipped to fetch the expected data because expected key is null.");
return Promise.resolve(ctx);
} else if (... | identifier_body |
processor.ts | import path from "path";
import {
CoreConfig,
WorkingDirectoryInfo,
PluginCreateOptions,
KeyGeneratorPlugin,
PublisherPlugin,
NotifierPlugin,
NotifyParams,
PluginLogger,
ComparisonResult,
} from "reg-suit-interface";
import { EventEmitter } from "events";
const compare = require("reg-cli");
const rim... | (ctx: StepResultAfterActualKey): Promise<StepResultAfterPublish> {
if (this._publisher) {
return this._publisher
.publish(ctx.actualKey)
.then(result => {
this._logger.info(`Published snapshot '${ctx.actualKey}' successfully.`);
if (result.reportUrl) {
this._log... | publish | identifier_name |
processor.ts | import path from "path";
import {
CoreConfig,
WorkingDirectoryInfo,
PluginCreateOptions,
KeyGeneratorPlugin,
PublisherPlugin,
NotifierPlugin,
NotifyParams,
PluginLogger,
ComparisonResult,
} from "reg-suit-interface";
import { EventEmitter } from "events";
const compare = require("reg-cli");
const rim... |
getExpectedKey(): Promise<StepResultAfterExpectedKey> {
if (this._keyGenerator) {
return this._keyGenerator
.getExpectedKey()
.then(key => {
this._logger.info(`Detected the previous snapshot key: '${key}'`);
return { expectedKey: key };
})
.catch(reason =... | .then(ctx => this.notify(ctx));
} | random_line_split |
load.js | var loadState={
preload:function(){
//add a loading label on screen
var loadingLabel = game.add.text(game.width/2, 150,
'loading...', { font:'30px Arial', fill:'#ffffff'});
loadingLabel.anchor.setTo(0.5,0.5);
//display progress bar
var progressBar= game.add.sprite(game.width/2,200,'progressBar');
prog... | }; | },
create:function(){
//go to menu state
game.state.start('menu');
} | random_line_split |
serializers.py | """
Serializer for user API
"""
from rest_framework import serializers
from rest_framework.reverse import reverse
from django.template import defaultfilters
from courseware.access import has_access
from student.models import CourseEnrollment, User
from certificates.models import certificate_status_for_student, Certif... |
class CourseEnrollmentSerializer(serializers.ModelSerializer):
"""
Serializes CourseEnrollment models
"""
course = CourseOverviewField(source="course_overview", read_only=True)
certificate = serializers.SerializerMethodField()
def get_certificate(self, model):
"""Returns the informat... | course_id = unicode(course_overview.id)
request = self.context.get('request', None)
if request:
video_outline_url = reverse(
'video-summary-list',
kwargs={'course_id': course_id},
request=request
)
course_updates_url = r... | identifier_body |
serializers.py | """
Serializer for user API
"""
from rest_framework import serializers
from rest_framework.reverse import reverse
from django.template import defaultfilters
from courseware.access import has_access
from student.models import CourseEnrollment, User
from certificates.models import certificate_status_for_student, Certif... | Serializes CourseEnrollment models
"""
course = CourseOverviewField(source="course_overview", read_only=True)
certificate = serializers.SerializerMethodField()
def get_certificate(self, model):
"""Returns the information about the user's certificate in the course."""
certificate_inf... | random_line_split | |
serializers.py | """
Serializer for user API
"""
from rest_framework import serializers
from rest_framework.reverse import reverse
from django.template import defaultfilters
from courseware.access import has_access
from student.models import CourseEnrollment, User
from certificates.models import certificate_status_for_student, Certif... |
else:
return {}
class Meta(object): # pylint: disable=missing-docstring
model = CourseEnrollment
fields = ('created', 'mode', 'is_active', 'course', 'certificate')
lookup_field = 'username'
class UserSerializer(serializers.HyperlinkedModelSerializer):
"""
Ser... | return {
"url": certificate_info['download_url'],
} | conditional_block |
serializers.py | """
Serializer for user API
"""
from rest_framework import serializers
from rest_framework.reverse import reverse
from django.template import defaultfilters
from courseware.access import has_access
from student.models import CourseEnrollment, User
from certificates.models import certificate_status_for_student, Certif... | (serializers.RelatedField):
"""Custom field to wrap a CourseDescriptor object. Read-only."""
def to_representation(self, course_overview):
course_id = unicode(course_overview.id)
request = self.context.get('request', None)
if request:
video_outline_url = reverse(
... | CourseOverviewField | identifier_name |
shared_lock.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 https://mozilla.org/MPL/2.0/. */
//! Different objects protected by the same lock
use crate::str::{CssString, CssStringWriter};
use crate::styles... | /// A trait to do a deep clone of a given CSS type. Gets a lock and a read
/// guard, in order to be able to read and clone nested structures.
pub trait DeepCloneWithLock: Sized {
/// Deep clones this object.
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGu... | pub struct DeepCloneParams;
| random_line_split |
shared_lock.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 https://mozilla.org/MPL/2.0/. */
//! Different objects protected by the same lock
use crate::str::{CssString, CssStringWriter};
use crate::styles... | trait to do a deep clone of a given CSS type. Gets a lock and a read
/// guard, in order to be able to read and clone nested structures.
pub trait DeepCloneWithLock: Sized {
/// Deep clones this object.
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard,
... | eParams;
/// A | identifier_name |
mta-vs-native.js | // 2016-08-22
//
// This is the wrapper for the native side
/*
prelim: start a server from the lib dir:
python -m SimpleHTTPServer (python 2.x) (linux)
python -m http.server (python 3.x) (windows)
1a) load jquery (note: may need a real active file open for this to work)
Note: get message 'VM148:52 Uncaught (in promis... | .done(function(first_call, second_call, third_call){
console.log('all loaded');
})
.fail(function(){
console.log('load failed');
});
// Note: server now automatically starts when your run 'mta-vs'
3)
// then do a word setup so a "Theme:" appears in the status line
4) then change the theme... | random_line_split | |
rotation.rs | // Copyright 2015 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// 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 ... | () {
let a: Basis3<_> = rotation::a3();
assert!(a.concat(&a.invert()).as_matrix3().is_identity());
}
| test_invert_basis3 | identifier_name |
rotation.rs | // Copyright 2015 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// 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 ... | }
#[test]
fn test_invert_basis3() {
let a: Basis3<_> = rotation::a3();
assert!(a.concat(&a.invert()).as_matrix3().is_identity());
} | let a: Basis2<_> = rotation::a2();
assert!(a.concat(&a.invert()).as_matrix2().is_identity()); | random_line_split |
rotation.rs | // Copyright 2015 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// 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 ... |
#[test]
fn test_invert_basis3() {
let a: Basis3<_> = rotation::a3();
assert!(a.concat(&a.invert()).as_matrix3().is_identity());
}
| {
let a: Basis2<_> = rotation::a2();
assert!(a.concat(&a.invert()).as_matrix2().is_identity());
} | identifier_body |
kde.js | // Based on http://bl.ocks.org/900762 by John Firebaugh
d3.json("../data/faithful.json", function(faithful) {
data = faithful;
var w = 800,
h = 400,
x = d3.scale.linear().domain([30, 110]).range([0, w]);
bins = d3.layout.histogram().frequency(false).bins(x.ticks(60))(data),
max = d3.max(bins... | .attr("d", function(h) {
return line(kde.bandwidth(h)(d3.range(30, 110, .1)));
});
}); | random_line_split | |
sample_cli.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import asyncio
from cffi import FFI
from pprint import pprint
ffi = FFI()
ffi.cdef('''
typedef struct {
int cmd;
int version;
} ProtoHelo;
''')
ffi.cdef('''
typedef struct {
int cmd;
int msgLen;
char msg[10];
} ProtoEcho;
''')
@asyncio.coroutine
def samp... |
loop = asyncio.get_event_loop()
loop.run_until_complete(sample_cli(loop))
loop.close() | reader, writer = yield from asyncio.open_connection(
'127.0.0.1', 8888, loop=loop
)
print('Connected.')
helo = ffi.new('ProtoHelo[]', 1)
ffi.buffer(helo)[:] = yield from reader.read(ffi.sizeof(helo))
print('Received Helo: {}, {}'.format(
helo[0].cmd, helo[0].version
))
for i in range(0, 100+1):
sendMsg... | identifier_body |
sample_cli.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import asyncio
from cffi import FFI
from pprint import pprint
ffi = FFI()
ffi.cdef('''
typedef struct {
int cmd;
int version;
} ProtoHelo;
''')
ffi.cdef('''
typedef struct {
int cmd;
int msgLen;
char msg[10];
} ProtoEcho;
''')
@asyncio.coroutine
def samp... |
writer.close()
loop = asyncio.get_event_loop()
loop.run_until_complete(sample_cli(loop))
loop.close() | sendMsg = 'msg_{}'.format(i)
sendEcho = ffi.new('ProtoEcho[]', [(i, len(sendMsg), sendMsg.encode('utf-8'))])
writer.write(bytes(ffi.buffer(sendEcho)))
yield from writer.drain()
recvEcho = ffi.new('ProtoEcho[]', 1)
try:
ffi.buffer(recvEcho)[:] = yield from reader.read(ffi.sizeof(recvEcho))
except ValueEr... | conditional_block |
sample_cli.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import asyncio
from cffi import FFI
from pprint import pprint
ffi = FFI()
ffi.cdef('''
typedef struct {
int cmd;
int version;
} ProtoHelo;
''')
| } ProtoEcho;
''')
@asyncio.coroutine
def sample_cli(loop):
reader, writer = yield from asyncio.open_connection(
'127.0.0.1', 8888, loop=loop
)
print('Connected.')
helo = ffi.new('ProtoHelo[]', 1)
ffi.buffer(helo)[:] = yield from reader.read(ffi.sizeof(helo))
print('Received Helo: {}, {}'.format(
helo[0].... | ffi.cdef('''
typedef struct {
int cmd;
int msgLen;
char msg[10]; | random_line_split |
sample_cli.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import asyncio
from cffi import FFI
from pprint import pprint
ffi = FFI()
ffi.cdef('''
typedef struct {
int cmd;
int version;
} ProtoHelo;
''')
ffi.cdef('''
typedef struct {
int cmd;
int msgLen;
char msg[10];
} ProtoEcho;
''')
@asyncio.coroutine
def | (loop):
reader, writer = yield from asyncio.open_connection(
'127.0.0.1', 8888, loop=loop
)
print('Connected.')
helo = ffi.new('ProtoHelo[]', 1)
ffi.buffer(helo)[:] = yield from reader.read(ffi.sizeof(helo))
print('Received Helo: {}, {}'.format(
helo[0].cmd, helo[0].version
))
for i in range(0, 100+1):
... | sample_cli | identifier_name |
doc_test_lints.rs | //! This pass is overloaded and runs two different lints.
//!
//! - MISSING_DOC_CODE_EXAMPLES: this lint is **UNSTABLE** and looks for public items missing doctests
//! - PRIVATE_DOC_TESTS: this lint is **STABLE** and looks for private items with doctests.
use super::Pass;
use crate::clean;
use crate::clean::*;
use cr... | }
pub(crate) struct Tests {
pub(crate) found_tests: usize,
}
impl crate::doctest::Tester for Tests {
fn add_test(&mut self, _: String, config: LangString, _: usize) {
if config.rust && config.ignore == Ignore::None {
self.found_tests += 1;
}
}
}
crate fn should_have_doc_exampl... | random_line_split | |
doc_test_lints.rs | //! This pass is overloaded and runs two different lints.
//!
//! - MISSING_DOC_CODE_EXAMPLES: this lint is **UNSTABLE** and looks for public items missing doctests
//! - PRIVATE_DOC_TESTS: this lint is **STABLE** and looks for private items with doctests.
use super::Pass;
use crate::clean;
use crate::clean::*;
use cr... | <'tcx>(cx: &DocContext<'tcx>, dox: &str, item: &Item) {
let hir_id = match DocContext::as_local_hir_id(cx.tcx, item.def_id) {
Some(hir_id) => hir_id,
None => {
// If non-local, no need to check anything.
return;
}
};
let mut tests = Tests { found_tests: 0 };
... | look_for_tests | identifier_name |
doc_test_lints.rs | //! This pass is overloaded and runs two different lints.
//!
//! - MISSING_DOC_CODE_EXAMPLES: this lint is **UNSTABLE** and looks for public items missing doctests
//! - PRIVATE_DOC_TESTS: this lint is **STABLE** and looks for private items with doctests.
use super::Pass;
use crate::clean;
use crate::clean::*;
use cr... |
}
pub(crate) struct Tests {
pub(crate) found_tests: usize,
}
impl crate::doctest::Tester for Tests {
fn add_test(&mut self, _: String, config: LangString, _: usize) {
if config.rust && config.ignore == Ignore::None {
self.found_tests += 1;
}
}
}
crate fn should_have_doc_examp... | {
let dox = item.attrs.collapsed_doc_value().unwrap_or_else(String::new);
look_for_tests(self.cx, &dox, &item);
Some(self.fold_item_recur(item))
} | identifier_body |
doc_test_lints.rs | //! This pass is overloaded and runs two different lints.
//!
//! - MISSING_DOC_CODE_EXAMPLES: this lint is **UNSTABLE** and looks for public items missing doctests
//! - PRIVATE_DOC_TESTS: this lint is **STABLE** and looks for private items with doctests.
use super::Pass;
use crate::clean;
use crate::clean::*;
use cr... |
}
}
crate fn should_have_doc_example(cx: &DocContext<'_>, item: &clean::Item) -> bool {
if !cx.cache.access_levels.is_public(item.def_id.expect_def_id())
|| matches!(
*item.kind,
clean::StructFieldItem(_)
| clean::VariantItem(_)
| clean::AssocCon... | {
self.found_tests += 1;
} | conditional_block |
engine.py | """
The "engine room" of django mailer.
Methods here actually handle the sending of queued messages.
"""
from django_mailer import constants, models, settings
from lockfile import FileLock, AlreadyLocked, LockTimeout
from socket import error as SocketError
import logging
import os
import smtplib
import tempfile
impo... |
queue = get_block()
while queue:
for message in queue:
yield message
queue = get_block()
def send_all(block_size=500, backend=None):
"""
Send all non-deferred messages in the queue.
A lock file is used to ensure that this process can not be started again
while it ... | queue = models.QueuedMessage.objects.non_deferred() \
.exclude(pk__in=exclude_messages).select_related()
if block_size:
queue = queue[:block_size]
return queue | identifier_body |
engine.py | """
The "engine room" of django mailer.
Methods here actually handle the sending of queued messages.
"""
from django_mailer import constants, models, settings
from lockfile import FileLock, AlreadyLocked, LockTimeout
from socket import error as SocketError
import logging
import os
import smtplib
import tempfile
impo... | return result | random_line_split | |
engine.py | """
The "engine room" of django mailer.
Methods here actually handle the sending of queued messages.
"""
from django_mailer import constants, models, settings
from lockfile import FileLock, AlreadyLocked, LockTimeout
from socket import error as SocketError
import logging
import os
import smtplib
import tempfile
impo... |
else:
connection = get_connection()
blacklist = models.Blacklist.objects.values_list('email', flat=True)
connection.open()
for message in _message_queue(block_size, exclude_messages=exclude_messages):
result = send_queued_message(message, connection=connection,
... | connection = get_connection(backend=backend) | conditional_block |
engine.py | """
The "engine room" of django mailer.
Methods here actually handle the sending of queued messages.
"""
from django_mailer import constants, models, settings
from lockfile import FileLock, AlreadyLocked, LockTimeout
from socket import error as SocketError
import logging
import os
import smtplib
import tempfile
impo... | (queued_message, connection=None, blacklist=None,
log=True):
"""
Send a queued message, returning a response code as to the action taken.
The response codes can be found in ``django_mailer.constants``. The
response will be either ``RESULT_SKIPPED`` for a blacklisted email,
``RESULT... | send_queued_message | identifier_name |
index.d.ts | // Type definitions for sinon-chai 2.7.0
// Project: https://github.com/domenic/sinon-chai
// Definitions by: Kazi Manzur Rashid <https://github.com/kazimanzurrashid/>, Jed Mao <https://github.com/jedmao/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference type... | */
calledWith(...args: any[]): Assertion;
/**
* Returns true if call received provided arguments and no others.
*/
calledWithExactly(...args: any[]): Assertion;
/**
* Returns true if call received matching arguments (and... | random_line_split | |
speedcd.py | # coding=utf-8
"""Provider code for Speed.cd."""
from __future__ import unicode_literals
import logging
from medusa import tv
from medusa.bs4_parser import BS4Parser
from medusa.helper.common import (
convert_size,
try_int,
)
from medusa.logger.adapters.style import BraceAdapter
from medusa.providers.torren... | torrent_table = torrent_table.find('table') if torrent_table else None
torrent_rows = torrent_table('tr') if torrent_table else []
# Continue only if at least one release is found
if len(torrent_rows) < 2:
log.debug('Data returned from provider does not c... | items = []
with BS4Parser(data, 'html5lib') as html:
torrent_table = html.find('div', class_='boxContent') | random_line_split |
speedcd.py | # coding=utf-8
"""Provider code for Speed.cd."""
from __future__ import unicode_literals
import logging
from medusa import tv
from medusa.bs4_parser import BS4Parser
from medusa.helper.common import (
convert_size,
try_int,
)
from medusa.logger.adapters.style import BraceAdapter
from medusa.providers.torren... |
def login(self):
"""Login method used for logging in before doing search and torrent downloads."""
if any(dict_from_cookiejar(self.session.cookies).values()):
return True
login_params = {
'username': self.username,
'password': self.password,
}
... | """
Parse search results for items.
:param data: The raw response from a search
:param mode: The current mode used to search, e.g. RSS
:return: A list of items found
"""
# Units
units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
items = []
with BS4Par... | identifier_body |
speedcd.py | # coding=utf-8
"""Provider code for Speed.cd."""
from __future__ import unicode_literals
import logging
from medusa import tv
from medusa.bs4_parser import BS4Parser
from medusa.helper.common import (
convert_size,
try_int,
)
from medusa.logger.adapters.style import BraceAdapter
from medusa.providers.torren... |
items.append(item)
except (AttributeError, TypeError, KeyError, ValueError, IndexError):
log.exception('Failed parsing provider.')
return items
def login(self):
"""Login method used for logging in before doing search and torrent downloads."... | log.debug('Found result: {0} with {1} seeders and {2} leechers',
title, seeders, leechers) | conditional_block |
speedcd.py | # coding=utf-8
"""Provider code for Speed.cd."""
from __future__ import unicode_literals
import logging
from medusa import tv
from medusa.bs4_parser import BS4Parser
from medusa.helper.common import (
convert_size,
try_int,
)
from medusa.logger.adapters.style import BraceAdapter
from medusa.providers.torren... | (self):
"""Get the login url (post) as speed.cd keeps changing it."""
response = self.session.get(self.urls['login'])
if not response or not response.text:
log.debug('Unable to connect to provider to get login URL')
return
data = BS4Parser(response.text, 'html5lib... | login_url | identifier_name |
worker-context.ts | /**
* @license
* Copyright 2021 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
import {LanguageServiceContext} from './language-service-context.js';
import {CachingCdn} from './caching-cdn.js'; |
/**
* Acquire the existing worker instance, or create a fresh one if missing.
* If the config differs from the existing instance's config, a new WorkerContext is
* instantiated and made the new instance.
*/
export function getWorkerContext(config: WorkerConfig) {
const configCacheKey = JSON.stringify(config);
... | import {ImportMapResolver} from './import-map-resolver.js';
import {WorkerConfig} from '../shared/worker-api.js';
let workerContext: WorkerContext | undefined;
let cacheKey = ''; | random_line_split |
worker-context.ts | /**
* @license
* Copyright 2021 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
import {LanguageServiceContext} from './language-service-context.js';
import {CachingCdn} from './caching-cdn.js';
import {ImportMapResolver} from './import-map-resolver.js';
import {WorkerConfig} from '../shared/worker-api.js';
... |
}
| {
this.importMapResolver = new ImportMapResolver(config.importMap);
this.cdn = new CachingCdn(config.cdnBaseUrl ?? 'https://unpkg.com/');
this.languageServiceContext = new LanguageServiceContext();
} | identifier_body |
worker-context.ts | /**
* @license
* Copyright 2021 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
import {LanguageServiceContext} from './language-service-context.js';
import {CachingCdn} from './caching-cdn.js';
import {ImportMapResolver} from './import-map-resolver.js';
import {WorkerConfig} from '../shared/worker-api.js';
... | (config: WorkerConfig) {
this.importMapResolver = new ImportMapResolver(config.importMap);
this.cdn = new CachingCdn(config.cdnBaseUrl ?? 'https://unpkg.com/');
this.languageServiceContext = new LanguageServiceContext();
}
}
| constructor | identifier_name |
worker-context.ts | /**
* @license
* Copyright 2021 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
import {LanguageServiceContext} from './language-service-context.js';
import {CachingCdn} from './caching-cdn.js';
import {ImportMapResolver} from './import-map-resolver.js';
import {WorkerConfig} from '../shared/worker-api.js';
... |
cacheKey = configCacheKey;
workerContext = new WorkerContext(config);
return workerContext;
}
export class WorkerContext {
readonly cdn: CachingCdn;
readonly importMapResolver: ImportMapResolver;
readonly languageServiceContext: LanguageServiceContext;
constructor(config: WorkerConfig) {
this.impo... | {
return workerContext;
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.