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 |
|---|---|---|---|---|
currency_getter.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2009 CamptoCamp. All rights reserved.
# @author Nicolas Bessi
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Publi... | 'BG_SIBANK_getter',
'BG_UNICRDT_getter',
]
if class_name in allowed:
exec "from .update_service_%s import %s" % (class_name.replace('_getter', ''), class_name)
class_def = eval(class_name)
_logger.info("from .update_service_%s import %s: class_... | 'CA_BOC_getter',
'RO_BNR_getter',
'BG_CUSTOMS_getter', | random_line_split |
currency_getter.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2009 CamptoCamp. All rights reserved.
# @author Nicolas Bessi
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Publi... | (self):
return 'Abstract Method'
def __repr__(self):
return 'Abstract Method'
class UnknowClassError(Exception):
def __str__(self):
return 'Unknown Class'
def __repr__(self):
return 'Unknown Class'
class UnsuportedCurrencyError(Exception):
def __init__(self, value):... | __str__ | identifier_name |
currency_getter.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2009 CamptoCamp. All rights reserved.
# @author Nicolas Bessi
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Publi... |
class UnsuportedCurrencyError(Exception):
def __init__(self, value):
self.curr = value
def __str__(self):
return 'Unsupported currency %s' % self.curr
def __repr__(self):
return 'Unsupported currency %s' % self.curr
class Currency_getter_factory():
"""Factory pattern class... | return 'Unknown Class' | identifier_body |
$autoplay.js | /**
* @file 自动播放插件
* @import widget/slider/slider.js
*/
(function( gmu, $ ) {
$.extend( true, gmu.Slider, {
options: {
/**
* @property {Boolean} [autoPlay=true] 是否开启自动播放
* @namespace options
* @for Slider
* @uses Slider.autoplay
... | );
})( gmu, gmu.$ ); | conditional_block | |
$autoplay.js | /**
* @file 自动播放插件
* @import widget/slider/slider.js
*/
(function( gmu, $ ) {
$.extend( true, gmu.Slider, {
options: {
/** | * @namespace options
* @for Slider
* @uses Slider.autoplay
*/
autoPlay: true,
/**
* @property {Number} [interval=4000] 自动播放的间隔时间(毫秒)
* @namespace options
* @for Slider
* @uses Slider.autoplay
... | * @property {Boolean} [autoPlay=true] 是否开启自动播放 | random_line_split |
index.ts | /*******************************************************************************
* ___ _ ____ ____
* / _ \ _ _ ___ ___| |_| _ \| __ )
* | | | | | | |/ _ \/ __| __| | | | _ \
* | |_| | |_| | __/\__ \ |_| |_| | |_) |
* \__\_\\__,_|\___||___/\__|____/|____/
*
* Copyright (c... | *
******************************************************************************/
import { css, keyframes } from "styled-components"
const spin = keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`
export const spinAnimation = css`
animation: ${spin} 1.5s cubic-bezie... | * See the License for the specific language governing permissions and
* limitations under the License. | random_line_split |
swipe-back.js | import { assign, swipeShouldReset } from '../util/util';
import { GESTURE_GO_BACK_SWIPE } from '../gestures/gesture-controller';
import { SlideEdgeGesture } from '../gestures/slide-edge-gesture';
import { NativeRafDebouncer } from '../util/debouncer';
export class SwipeBackGesture extends SlideEdgeGesture {
constru... |
}
//# sourceMappingURL=swipe-back.js.map | {
const currentStepValue = (slide.distance / slide.max);
const isResetDirecction = slide.velocity < 0;
const isMovingFast = Math.abs(slide.velocity) > 0.4;
const isInResetZone = Math.abs(slide.delta) < Math.abs(slide.max) * 0.5;
const shouldComplete = !swipeShouldReset(isResetDir... | identifier_body |
swipe-back.js | import { assign, swipeShouldReset } from '../util/util';
import { GESTURE_GO_BACK_SWIPE } from '../gestures/gesture-controller';
import { SlideEdgeGesture } from '../gestures/slide-edge-gesture';
import { NativeRafDebouncer } from '../util/debouncer';
export class SwipeBackGesture extends SlideEdgeGesture {
constru... | priority: 20,
disableScroll: true
})
}, options));
this._nav = _nav;
}
canStart(ev) {
return (this._nav.canSwipeBack() &&
super.canStart(ev));
}
onSlideBeforeStart(ev) {
this._nav.swipeBackStart();
}
onSlide(... | zone: false,
threshold: 0,
debouncer: new NativeRafDebouncer(),
gesture: gestureCtlr.createGesture({
name: GESTURE_GO_BACK_SWIPE, | random_line_split |
swipe-back.js | import { assign, swipeShouldReset } from '../util/util';
import { GESTURE_GO_BACK_SWIPE } from '../gestures/gesture-controller';
import { SlideEdgeGesture } from '../gestures/slide-edge-gesture';
import { NativeRafDebouncer } from '../util/debouncer';
export class SwipeBackGesture extends SlideEdgeGesture {
constru... | (slide, ev) {
const currentStepValue = (slide.distance / slide.max);
const isResetDirecction = slide.velocity < 0;
const isMovingFast = Math.abs(slide.velocity) > 0.4;
const isInResetZone = Math.abs(slide.delta) < Math.abs(slide.max) * 0.5;
const shouldComplete = !swipeShouldRese... | onSlideEnd | identifier_name |
GcsArtifactEditor.tsx | import { cloneDeep, isNil } from 'lodash';
import React from 'react';
import { ArtifactTypePatterns } from 'core/artifact';
import { IArtifactEditorProps, IArtifactKindConfig } from 'core/domain';
import { StageConfigField } from 'core/pipeline';
import { SpelText } from 'core/widgets';
import { singleFieldArtifactEd... |
private onReferenceChange = (reference: string) => {
if (isNil(reference)) {
return;
}
const clonedArtifact = cloneDeep(this.props.artifact);
clonedArtifact.reference = reference;
if (reference.indexOf('#') >= 0) {
const split = reference.split('#');
clonedA... | {
super(props, TYPE);
} | identifier_body |
GcsArtifactEditor.tsx | import { cloneDeep, isNil } from 'lodash';
import React from 'react';
import { ArtifactTypePatterns } from 'core/artifact';
import { IArtifactEditorProps, IArtifactKindConfig } from 'core/domain';
import { StageConfigField } from 'core/pipeline';
import { SpelText } from 'core/widgets';
import { singleFieldArtifactEd... | (props: IArtifactEditorProps) {
super(props, TYPE);
}
private onReferenceChange = (reference: string) => {
if (isNil(reference)) {
return;
}
const clonedArtifact = cloneDeep(this.props.artifact);
clonedArtifact.reference = reference;
if (reference.indexOf('#') >= 0... | constructor | identifier_name |
GcsArtifactEditor.tsx | import { cloneDeep, isNil } from 'lodash';
import React from 'react';
import { ArtifactTypePatterns } from 'core/artifact';
import { IArtifactEditorProps, IArtifactKindConfig } from 'core/domain';
import { StageConfigField } from 'core/pipeline';
import { SpelText } from 'core/widgets';
import { singleFieldArtifactEd... |
public render() {
return (
<StageConfigField label="Object path" helpKey="pipeline.config.expectedArtifact.defaultGcs.reference">
<SpelText
placeholder="gs://bucket/path/to/file"
value={this.props.artifact.reference}
onChange={this.onReferenceChange}
... | clonedArtifact.name = reference;
}
this.props.onChange(clonedArtifact);
}; | random_line_split |
GcsArtifactEditor.tsx | import { cloneDeep, isNil } from 'lodash';
import React from 'react';
import { ArtifactTypePatterns } from 'core/artifact';
import { IArtifactEditorProps, IArtifactKindConfig } from 'core/domain';
import { StageConfigField } from 'core/pipeline';
import { SpelText } from 'core/widgets';
import { singleFieldArtifactEd... |
const clonedArtifact = cloneDeep(this.props.artifact);
clonedArtifact.reference = reference;
if (reference.indexOf('#') >= 0) {
const split = reference.split('#');
clonedArtifact.name = split[0];
clonedArtifact.version = split[1];
} else {
clonedArtifact.name =... | {
return;
} | conditional_block |
server_web.py | # A basic web server using sockets
import socket
PORT = 8090
MAX_OPEN_REQUESTS = 5
def | (clientsocket):
print(clientsocket)
data = clientsocket.recv(1024)
print(data)
web_contents = "<h1>Received</h1>"
f = open("myhtml.html", "r")
web_contents = f.read()
f.close()
web_headers = "HTTP/1.1 200"
web_headers += "\n" + "Content-Type: text/html"
web_headers += "\n" + "Content-Length:... | process_client | identifier_name |
server_web.py | # A basic web server using sockets
import socket
PORT = 8090
MAX_OPEN_REQUESTS = 5
def process_client(clientsocket):
print(clientsocket)
data = clientsocket.recv(1024)
print(data)
web_contents = "<h1>Received</h1>"
f = open("myhtml.html", "r")
web_contents = f.read()
f.close()
web_headers = "HTT... | except socket.error:
print("Problemas using port %i. Do you have permission?" % PORT) | random_line_split | |
server_web.py | # A basic web server using sockets
import socket
PORT = 8090
MAX_OPEN_REQUESTS = 5
def process_client(clientsocket):
print(clientsocket)
data = clientsocket.recv(1024)
print(data)
web_contents = "<h1>Received</h1>"
f = open("myhtml.html", "r")
web_contents = f.read()
f.close()
web_headers = "HTT... |
except socket.error:
print("Problemas using port %i. Do you have permission?" % PORT)
| print ("Waiting for connections at %s %i" % (hostname, PORT))
(clientsocket, address) = serversocket.accept()
# now do something with the clientsocket
# in this case, we'll pretend this is a non threaded server
process_client(clientsocket) | conditional_block |
server_web.py | # A basic web server using sockets
import socket
PORT = 8090
MAX_OPEN_REQUESTS = 5
def process_client(clientsocket):
|
# create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# bind the socket to a public host, and a well-known port
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
# Let's use better the local interface name
hostname = "10.1... | print(clientsocket)
data = clientsocket.recv(1024)
print(data)
web_contents = "<h1>Received</h1>"
f = open("myhtml.html", "r")
web_contents = f.read()
f.close()
web_headers = "HTTP/1.1 200"
web_headers += "\n" + "Content-Type: text/html"
web_headers += "\n" + "Content-Length: %i" % len(str.encod... | identifier_body |
conf.py | # -*- coding: utf-8 -*-
#
# pyspark documentation build configuration file, created by
# sphinx-quickstart on Thu Aug 28 15:17:47 2014.
#
# This file is execfile()d with the current directory set to its | #
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shutil
import errno
# If extensions (or modules to document with autodoc) are in another dir... | # containing dir. | random_line_split |
conf.py | # -*- coding: utf-8 -*-
#
# pyspark documentation build configuration file, created by
# sphinx-quickstart on Thu Aug 28 15:17:47 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# A... |
try:
os.mkdir("%s/reference/pyspark.pandas/api" % os.path.dirname(
os.path.abspath(__file__)))
except OSError as e:
if e.errno != errno.EEXIST:
raise
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it he... | raise | conditional_block |
conf.py | # -*- coding: utf-8 -*-
#
# pyspark documentation build configuration file, created by
# sphinx-quickstart on Thu Aug 28 15:17:47 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# A... | (app):
# The app.add_javascript() is deprecated.
getattr(app, "add_js_file", getattr(app, "add_javascript"))('copybutton.js')
# Skip sample endpoint link (not expected to resolve)
linkcheck_ignore = [r'https://kinesis.us-east-1.amazonaws.com']
| setup | identifier_name |
conf.py | # -*- coding: utf-8 -*-
#
# pyspark documentation build configuration file, created by
# sphinx-quickstart on Thu Aug 28 15:17:47 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# A... |
# Skip sample endpoint link (not expected to resolve)
linkcheck_ignore = [r'https://kinesis.us-east-1.amazonaws.com']
| getattr(app, "add_js_file", getattr(app, "add_javascript"))('copybutton.js') | identifier_body |
cost.py | from neon.transforms.cost import Cost
class MulticlsSVMLoss(Cost):
|
class L1SVMLoss(Cost):
def __init__(self, C=10):
self.C = C
def __call__(self, y, t):
return self.C * self.be.sum(self.be.square(self.be.maximum(0, 1 - y * (t * 2 - 1)))) * 0.5 / y.shape[0]
def bprop(self, y, t):
return - self.C * (t * 2 - 1) * self.be.maximum(0, 1 - y * (t * 2 ... | def __init__(self, delta=1.):
self.delta = delta
def __call__(self, y, t):
T = self.be.empty_like(y)
T[:] = self.be.max(y * t, axis=0)
# T = self.be.array(self.be.max(y * t, axis=0).asnumpyarray(), y.shape[0], axis=0)
margin = self.be.square(self.be.maximum(0, y - T + self.d... | identifier_body |
cost.py | from neon.transforms.cost import Cost
class MulticlsSVMLoss(Cost):
def __init__(self, delta=1.):
self.delta = delta
def __call__(self, y, t):
T = self.be.empty_like(y)
T[:] = self.be.max(y * t, axis=0)
# T = self.be.array(self.be.max(y * t, axis=0).asnumpyarray(), y.shape[0], ... | (Cost):
def __init__(self, C=10):
self.C = C
def __call__(self, y, t):
return self.C * self.be.sum(self.be.square(self.be.maximum(0, 1 - y * (t * 2 - 1)))) * 0.5 / y.shape[0]
def bprop(self, y, t):
return - self.C * (t * 2 - 1) * self.be.maximum(0, 1 - y * (t * 2 - 1)) / self.be.bs... | L1SVMLoss | identifier_name |
cost.py | from neon.transforms.cost import Cost
class MulticlsSVMLoss(Cost):
def __init__(self, delta=1.):
self.delta = delta
def __call__(self, y, t):
T = self.be.empty_like(y)
T[:] = self.be.max(y * t, axis=0)
# T = self.be.array(self.be.max(y * t, axis=0).asnumpyarray(), y.shape[0], ... | def __call__(self, y, t):
return self.C * self.be.sum(self.be.square(self.be.maximum(0, 1 - y * (t * 2 - 1)))) * 0.5 / y.shape[0]
def bprop(self, y, t):
return - self.C * (t * 2 - 1) * self.be.maximum(0, 1 - y * (t * 2 - 1)) / self.be.bsz / y.shape[0] | random_line_split | |
youtube-searched-for.js | 'use strict';
var React = require('react');
var mui = require('material-ui');
var SvgIcon = mui.SvgIcon;
var createClass = require('create-react-class');
var ActionYoutubeSearchedFor = createClass({
displayName: 'ActionYoutubeSearchedFor',
render: function render() {
return React.createElement(
SvgIco... | module.exports = ActionYoutubeSearchedFor; | random_line_split | |
irc.rs | use config;
use std::thread;
use nyaa::Nyaa;
use message_handler::{MessageHandlerBuilder,MessageHandler};
use colors;
use lib::log::Logger;
use lib::connection::Connection;
use lib::commands::Commands;
use std::sync::{Arc,Mutex,mpsc};
pub struct Irc{
con: Connection,
}
impl Irc{
pub fn new(con: Connection)->I... |
}
| {
let mut logger = match Logger::new("logs.txt"){
Ok(l) =>l,
Err(_) =>return false,
};
let cd = match config::ConfigData::new("config.json"){
Ok(a) =>a,
Err(err) =>{
match err{
config::ConfigErr::Parse=>{logger... | identifier_body |
irc.rs | use config;
use std::thread;
use nyaa::Nyaa;
use message_handler::{MessageHandlerBuilder,MessageHandler};
use colors;
use lib::log::Logger;
use lib::connection::Connection;
use lib::commands::Commands;
use std::sync::{Arc,Mutex,mpsc};
pub struct Irc{
con: Connection,
}
impl Irc{
pub fn new(con: Connection)->I... | Ok(a) =>a,
Err(_) =>{
logger.add("Could not clone the socket. Error: ");
return false
}
};
let (tx, rx) = mpsc::channel();
let delay = cd.nyaa.delay;
let channels = cd.channels;
thread::spawn(move || {
... | let mut sock = match self.con.socket_clone(){ | random_line_split |
irc.rs | use config;
use std::thread;
use nyaa::Nyaa;
use message_handler::{MessageHandlerBuilder,MessageHandler};
use colors;
use lib::log::Logger;
use lib::connection::Connection;
use lib::commands::Commands;
use std::sync::{Arc,Mutex,mpsc};
pub struct Irc{
con: Connection,
}
impl Irc{
pub fn new(con: Connection)->I... | (&mut self)->bool{
let mut logger = match Logger::new("logs.txt"){
Ok(l) =>l,
Err(_) =>return false,
};
let cd = match config::ConfigData::new("config.json"){
Ok(a) =>a,
Err(err) =>{
match err{
config::ConfigEr... | start | identifier_name |
irc.rs | use config;
use std::thread;
use nyaa::Nyaa;
use message_handler::{MessageHandlerBuilder,MessageHandler};
use colors;
use lib::log::Logger;
use lib::connection::Connection;
use lib::commands::Commands;
use std::sync::{Arc,Mutex,mpsc};
pub struct Irc{
con: Connection,
}
impl Irc{
pub fn new(con: Connection)->I... |
let mut sock = match self.con.socket_clone(){
Ok(a) =>a,
Err(_) =>{
logger.add("Could not clone the socket. Error: ");
return false
}
};
let (tx, rx) = mpsc::channel();
let delay = cd.nyaa.delay;
let channels =... | {
logger.add("Could not load commands from redis");
} | conditional_block |
Pdf.js | import { HTTPError } from 'utils/APIConnector'
import * as AWS from 'utils/AWS'
import * as Config from 'utils/Config'
import * as Data from 'utils/Data'
import { mkSearch } from 'utils/NamedRoutes'
import { PreviewData, PreviewError } from '../types'
import * as utils from './utils'
export const detect = utils.extIs... |
// eslint-disable-next-line no-console
console.warn('error loading pdf preview', { ...e })
// eslint-disable-next-line no-console
console.error(e)
throw e
}
}
export const Loader = function PdfLoader({ handle, children }) {
const endpoint = Config.use().binaryApiGatewayEndpoint
const sign = ... | {
if (e.json.text?.match(utils.GLACIER_ERROR_RE)) {
throw PreviewError.Archived({ handle })
}
throw PreviewError.Forbidden({ handle })
} | conditional_block |
Pdf.js | import { HTTPError } from 'utils/APIConnector'
import * as AWS from 'utils/AWS'
import * as Config from 'utils/Config'
import * as Data from 'utils/Data'
import { mkSearch } from 'utils/NamedRoutes'
import { PreviewData, PreviewError } from '../types'
import * as utils from './utils'
export const detect = utils.extIs... | ({ endpoint, sign, handle }) {
try {
const url = sign(handle)
const search = mkSearch({
url,
input: 'pdf',
output: 'raw',
size: 'w1024h768',
})
const r = await fetch(`${endpoint}/thumbnail${search}`)
if (r.status >= 400) {
const text = await r.text()
throw new H... | loadPdf | identifier_name |
Pdf.js | import { HTTPError } from 'utils/APIConnector'
import * as AWS from 'utils/AWS'
import * as Config from 'utils/Config'
import * as Data from 'utils/Data'
import { mkSearch } from 'utils/NamedRoutes'
import { PreviewData, PreviewError } from '../types'
import * as utils from './utils'
export const detect = utils.extIs... | const endpoint = Config.use().binaryApiGatewayEndpoint
const sign = AWS.Signer.useS3Signer()
const data = Data.use(loadPdf, { endpoint, sign, handle })
return children(utils.useErrorHandling(data.result, { handle, retry: data.fetch }))
} | throw e
}
}
export const Loader = function PdfLoader({ handle, children }) { | random_line_split |
Pdf.js | import { HTTPError } from 'utils/APIConnector'
import * as AWS from 'utils/AWS'
import * as Config from 'utils/Config'
import * as Data from 'utils/Data'
import { mkSearch } from 'utils/NamedRoutes'
import { PreviewData, PreviewError } from '../types'
import * as utils from './utils'
export const detect = utils.extIs... |
export const Loader = function PdfLoader({ handle, children }) {
const endpoint = Config.use().binaryApiGatewayEndpoint
const sign = AWS.Signer.useS3Signer()
const data = Data.use(loadPdf, { endpoint, sign, handle })
return children(utils.useErrorHandling(data.result, { handle, retry: data.fetch }))
}
| {
try {
const url = sign(handle)
const search = mkSearch({
url,
input: 'pdf',
output: 'raw',
size: 'w1024h768',
})
const r = await fetch(`${endpoint}/thumbnail${search}`)
if (r.status >= 400) {
const text = await r.text()
throw new HTTPError(r, text)
}
c... | identifier_body |
GridStoreAdapter.js | /**
GridStoreAdapter
Stores files in Mongo using GridStore
Requires the database adapter to be based on mongoclient
@flow weak
*/
import { MongoClient, GridStore, Db} from 'mongodb';
import { FilesAdapter } from './FilesAdapter';
import defaults from '../../defaults';
export cl... |
return this._connectionPromise;
}
// For a given config object, filename, and data, store a file
// Returns a promise
createFile(filename: string, data) {
return this._connect().then(database => {
const gridStore = new GridStore(database, filename, 'w');
return gridStore.open();
}).the... | {
this._connectionPromise = MongoClient.connect(this._databaseURI);
} | conditional_block |
GridStoreAdapter.js | /**
GridStoreAdapter
Stores files in Mongo using GridStore
Requires the database adapter to be based on mongoclient
@flow weak
*/
import { MongoClient, GridStore, Db} from 'mongodb';
import { FilesAdapter } from './FilesAdapter';
import defaults from '../../defaults';
export cl... | return gridStore.open();
});
});
}
}
export default GridStoreAdapter; |
getFileStream(filename: string) {
return this._connect().then(database => {
return GridStore.exist(database, filename).then(() => {
const gridStore = new GridStore(database, filename, 'r'); | random_line_split |
GridStoreAdapter.js | /**
GridStoreAdapter
Stores files in Mongo using GridStore
Requires the database adapter to be based on mongoclient
@flow weak
*/
import { MongoClient, GridStore, Db} from 'mongodb';
import { FilesAdapter } from './FilesAdapter';
import defaults from '../../defaults';
export cl... |
// For a given config object, filename, and data, store a file
// Returns a promise
createFile(filename: string, data) {
return this._connect().then(database => {
const gridStore = new GridStore(database, filename, 'w');
return gridStore.open();
}).then(gridStore => {
return gridStore.... | {
if (!this._connectionPromise) {
this._connectionPromise = MongoClient.connect(this._databaseURI);
}
return this._connectionPromise;
} | identifier_body |
GridStoreAdapter.js | /**
GridStoreAdapter
Stores files in Mongo using GridStore
Requires the database adapter to be based on mongoclient
@flow weak
*/
import { MongoClient, GridStore, Db} from 'mongodb';
import { FilesAdapter } from './FilesAdapter';
import defaults from '../../defaults';
export cl... | (filename: string, data) {
return this._connect().then(database => {
const gridStore = new GridStore(database, filename, 'w');
return gridStore.open();
}).then(gridStore => {
return gridStore.write(data);
}).then(gridStore => {
return gridStore.close();
});
}
deleteFile(file... | createFile | identifier_name |
handlers.py | """ Handlers for OpenID Connect provider. """
from django.conf import settings
from django.core.cache import cache
from courseware.access import has_access
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY
from openedx.core.dj... |
return course_ids
class IDTokenHandler(OpenIDHandler, ProfileHandler, CourseAccessHandler, PermissionsHandler):
""" Configure the ID Token handler for the LMS. """
def claim_instructor_courses(self, data):
# Don't return list of courses unless they are requested as essential.
if dat... | course_keys = CourseOverview.get_all_course_keys()
# Global staff have access to all courses. Filter courses for non-global staff.
if not GlobalStaff().has_user(user):
course_keys = [course_key for course_key in course_keys if has_access(user, access_type, course_key)]
... | conditional_block |
handlers.py | """ Handlers for OpenID Connect provider. """
from django.conf import settings
from django.core.cache import cache
from courseware.access import has_access
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY
from openedx.core.dj... | return self.find_courses(data['user'], CourseInstructorRole.ROLE, data.get('values'))
def claim_staff_courses(self, data):
"""
Claim `staff_courses` with list of course_ids for which the user
has staff privileges.
"""
return self.find_courses(data['user'], CourseSt... | user has instructor privileges.
"""
| random_line_split |
handlers.py | """ Handlers for OpenID Connect provider. """
from django.conf import settings
from django.core.cache import cache
from courseware.access import has_access
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY
from openedx.core.dj... | (self, user, access_type):
# Check the application cache and update if not present. The application
# cache is useful since there are calls to different endpoints in close
# succession, for example the id_token and user_info endpoints.
key = '-'.join([str(self.__class__), str(user.id), ... | _get_courses_with_access_type | identifier_name |
handlers.py | """ Handlers for OpenID Connect provider. """
from django.conf import settings
from django.core.cache import cache
from courseware.access import has_access
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY
from openedx.core.dj... |
class ProfileHandler(object):
""" Basic OpenID Connect `profile` scope handler with `locale` claim. """
def scope_profile(self, _data):
""" Add specialized claims. """
return ['name', 'locale']
def claim_name(self, data):
""" User displayable full name. """
user = data['... | """ Permissions scope handler """
def scope_permissions(self, _data):
return ['administrator']
def claim_administrator(self, data):
"""
Return boolean indicating user's administrator status.
For our purposes an administrator is any user with is_staff set to True.
"""
... | identifier_body |
main.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (file: string): Promise<boolean> {
return new Promise<boolean>((resolve, _reject) => {
fs.exists(file, (value) => {
resolve(value);
});
});
}
async function readFile(file: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
fs.readFile(file, (err, data) => {
if (err) {
rejec... | exists | identifier_name |
main.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
return `${script} - ${shortPath}`;
}
function getNpmCommandLine(cmd: string): string {
if (vscode.workspace.getConfiguration('npm').get<boolean>('runSilent')) {
return `npm --silent ${cmd}`;
}
return `npm ${cmd}`;
}
let kind: NpmTaskDefinition = {
type: 'npm',
script: script
};
let taskName =... | random_line_split | |
main.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
function isNotPreOrPostScript(script: string): boolean {
return !(script.startsWith('pre') || script.startsWith('post'));
}
async function provideNpmScripts(): Promise<vscode.Task[]> {
let emptyTasks: vscode.Task[] = [];
let allTasks: vscode.Task[] = [];
let folders = vscode.workspace.workspaceFolders;
if (!fo... | {
for (let testName of testNames) {
if (name === testName) {
return true;
}
}
return false;
} | identifier_body |
inputevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public | use crate::dom::bindings::codegen::Bindings::InputEventBinding::{self, InputEventMethods};
use crate::dom::bindings::codegen::Bindings::UIEventBinding::UIEventBinding::UIEventMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::{Dom... | * 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/. */
| random_line_split |
inputevent.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/. */
use crate::dom::bindings::codegen::Bindings::InputEventBinding::{self, InputEventMethods};
use crate::dom::bindin... |
}
| {
self.uievent.IsTrusted()
} | identifier_body |
inputevent.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/. */
use crate::dom::bindings::codegen::Bindings::InputEventBinding::{self, InputEventMethods};
use crate::dom::bindin... | (&self) -> bool {
self.uievent.IsTrusted()
}
}
| IsTrusted | identifier_name |
mount.rs | use util::*;
use hyper::status::StatusCode;
use hyper::client::Response;
fn | <F>(path: &str, f: F) where F: FnOnce(&mut Response) {
run_example("mount", |port| {
let url = format!("http://localhost:{}{}", port, path);
let ref mut res = response_for(&url);
f(res)
})
}
#[test]
fn trims_the_prefix() {
with_path("/test/foo", |res| {
let s = read_body_to_... | with_path | identifier_name |
mount.rs | use util::*;
use hyper::status::StatusCode;
use hyper::client::Response;
fn with_path<F>(path: &str, f: F) where F: FnOnce(&mut Response) {
run_example("mount", |port| {
let url = format!("http://localhost:{}{}", port, path);
let ref mut res = response_for(&url);
f(res)
})
}
#[test]
f... | with_path("/static/files/a", |res| {
let s = read_body_to_string(res);
assert_eq!(s, "No static file with path '/a'!");
});
} | random_line_split | |
mount.rs | use util::*;
use hyper::status::StatusCode;
use hyper::client::Response;
fn with_path<F>(path: &str, f: F) where F: FnOnce(&mut Response) {
run_example("mount", |port| {
let url = format!("http://localhost:{}{}", port, path);
let ref mut res = response_for(&url);
f(res)
})
}
#[test]
f... | {
// depends on `works_with_another_middleware` passing
with_path("/static/files/a", |res| {
let s = read_body_to_string(res);
assert_eq!(s, "No static file with path '/a'!");
});
} | identifier_body | |
seed.rs | // Copyright 2015 The Noise-rs Developers.
//
// 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 ... |
#[inline(always)]
pub fn get2<T: Signed + PrimInt + NumCast>(&self, pos: math::Point2<T>) -> usize {
let y: usize = math::cast(pos[1] & math::cast(0xff));
self.values[self.get1(pos[0]) ^ y] as usize
}
#[inline(always)]
pub fn get3<T: Signed + PrimInt + NumCast>(&self, pos: math::P... | {
let x: usize = math::cast(x & math::cast(0xff));
self.values[x] as usize
} | identifier_body |
seed.rs | // Copyright 2015 The Noise-rs Developers.
//
// 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 ... | /// # Examples
///
/// ```rust
/// extern crate noise;
/// extern crate rand;
///
/// use noise::Seed;
///
/// # fn main() {
/// let seed = rand::random::<Seed>();
/// # }
/// ```
///
/// ```rust
/// extern crate noise;
/// extern crate rand;
///
/... |
impl Rand for Seed {
/// Generates a random seed.
/// | random_line_split |
seed.rs | // Copyright 2015 The Noise-rs Developers.
//
// 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 ... | () {
let _ = perlin3::<f32>(&random(), &[1.0, 2.0, 3.0]);
}
#[test]
fn test_negative_params() {
let _ = perlin3::<f32>(&Seed::new(0), &[-1.0, 2.0, 3.0]);
}
}
| test_random_seed | identifier_name |
html_table_import.js | var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/* Tabulator v4.0.2 (c) Oliver Folkerd */
var Ht... |
// //check for tablator inline options
this._extractOptions(header, col);
for (var i in attributes) {
var attrib = attributes[i],
name;
if ((typeof attrib === "undefined" ? "undefined" : _typeof(attrib)) == "object" && attrib.name && attrib.name.indexOf("tabulator-") === 0) {
name = attrib.na... | //check for tablator inline options
attributes = header.attributes; | random_line_split |
html_table_import.js | var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/* Tabulator v4.0.2 (c) Oliver Folkerd */
var Ht... |
};
//generate blank headers
HtmlTableImport.prototype._generateBlankHeaders = function (headers, rows) {
for (var index = 0; index < headers.length; index++) {
var header = headers[index],
col = { title: "", field: "col" + index };
this.fieldIndex[index] = col.field;
var width = header.getAttribute("wi... | {
var header = headers[index],
exists = false,
col = this._findCol(header.textContent),
width,
attributes;
if (col) {
exists = true;
} else {
col = { title: header.textContent.trim() };
}
if (!col.field) {
col.field = header.textContent.trim().toLowerCase().replace(" ", "_")... | conditional_block |
mod.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use criterion::{Bencher, Criterion};
use kvproto::deadlock::*;
use rand::prelude::*;
use tikv::server::lock_manager::deadlock::DetectTable;
use tikv_util::time::Duration;
struct DetectGenerator {
rng: ThreadRng,
range: u64,
timestamp: u64,... |
fn bench_dense_detect_without_cleanup(c: &mut Criterion) {
let mut group = c.benchmark_group("bench_dense_detect_without_cleanup");
let ranges = vec![
10,
100,
1_000,
10_000,
100_000,
1_000_000,
10_000_000,
100_000_000,
];
for range in r... | {
let mut detect_table = DetectTable::new(cfg.ttl);
let mut generator = DetectGenerator::new(cfg.range);
b.iter(|| {
for entry in generator.generate(cfg.n) {
detect_table.detect(
entry.get_txn().into(),
entry.get_wait_for_txn().into(),
entr... | identifier_body |
mod.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use criterion::{Bencher, Criterion};
use kvproto::deadlock::*;
use rand::prelude::*;
use tikv::server::lock_manager::deadlock::DetectTable;
use tikv_util::time::Duration;
struct DetectGenerator {
rng: ThreadRng,
range: u64,
timestamp: u64,... | () {
let mut criterion = Criterion::default().configure_from_args().sample_size(10);
bench_dense_detect_without_cleanup(&mut criterion);
bench_dense_detect_with_cleanup(&mut criterion);
criterion.final_summary();
}
| main | identifier_name |
mod.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use criterion::{Bencher, Criterion};
use kvproto::deadlock::*;
use rand::prelude::*;
use tikv::server::lock_manager::deadlock::DetectTable;
use tikv_util::time::Duration;
struct DetectGenerator {
rng: ThreadRng,
range: u64,
timestamp: u64,... | entries
}
}
#[derive(Debug)]
struct Config {
n: u64,
range: u64,
ttl: Duration,
}
fn bench_detect(b: &mut Bencher, cfg: &Config) {
let mut detect_table = DetectTable::new(cfg.ttl);
let mut generator = DetectGenerator::new(cfg.range);
b.iter(|| {
for entry in generator.gener... | random_line_split | |
mod.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use criterion::{Bencher, Criterion};
use kvproto::deadlock::*;
use rand::prelude::*;
use tikv::server::lock_manager::deadlock::DetectTable;
use tikv_util::time::Duration;
struct DetectGenerator {
rng: ThreadRng,
range: u64,
timestamp: u64,... | else {
self.timestamp - self.range
},
self.timestamp + self.range,
);
}
entry.set_wait_for_txn(wait_for_txn);
entry.set_key_hash(self.rng.gen());
entries.push(entry);
});
self... | {
0
} | conditional_block |
HTTPFileSystem.ts | import { v2 as webdav } from 'webdav-server'
import { Readable, Writable, Transform } from 'stream'
import * as request from 'request'
export class Resource
{
props : webdav.IPropertyManager;
locks : webdav.ILockManager;
constructor(data ?: Resource)
{
this.props = new webdav.LocalPropertyMana... | this.url = url;
}
protected findResource(path : webdav.Path)
{
const sPath = path.toString();
const r = this.resources[sPath];
if(!r)
return this.resources[sPath] = new Resource();
return r;
}
_openReadStream(path : webdav.Path, info : webdav.Ope... | this.resources = {}; | random_line_split |
HTTPFileSystem.ts | import { v2 as webdav } from 'webdav-server'
import { Readable, Writable, Transform } from 'stream'
import * as request from 'request'
export class Resource
{
props : webdav.IPropertyManager;
locks : webdav.ILockManager;
constructor(data ?: Resource)
{
this.props = new webdav.LocalPropertyMana... | (fs : HTTPFileSystem, callback : webdav.ReturnCallback<any>) : void
{
callback(null, {
url: fs.url,
resources: fs.resources
});
}
unserialize(serializedData : any, callback : webdav.ReturnCallback<HTTPFileSystem>) : void
{
const fs = new HTTPFileSystem(se... | serialize | identifier_name |
main.rs | fn main() {
// defining-structs
{
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
// 实例
let user1 = User {
email: String::from("someone@example.com"),
username: String::fr... | let sq = Rectangle::square(3);
println!("sq is {:?}", sq);
}
// 每个结构体都允许拥有多个 impl 块
}
} | th: size, height: size }
}
}
| identifier_body |
main.rs | fn main() {
// defining-structs
{
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
// 实例
let user1 = User {
email: String::from("someone@example.com"),
username: String::fr... | email: String::from("another@example.com"),
username: String::from("anotherusername567"),
..user1
};
// 使用没有命名字段的元组结构体来创建不同的类型
// 元组结构体(tuple structs)
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
let black = Color(0, 0, 0)... | // 可以简写为
let user2 = User { | random_line_split |
main.rs | fn main() {
// defining-structs
{
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
// 实例
let user1 = User {
email: String::from("someone@example.com"),
username: String::fr... | ight: u32,
}
impl Rectangle {
fn square(size: u32) -> Rectangle {
Rectangle { width: size, height: size }
}
}
let sq = Rectangle::square(3);
println!("sq is {:?}", sq);
}
// 每个结构体都允许拥有多个 im... | he | identifier_name |
logreportwriters.py | # Copyright 2008-2012 Nokia Siemens Networks Oyj
#
# 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... | (self, line):
JsResultWriter(self._output).write(self._model, self._config)
class LogWriter(_LogReportWriter):
def write(self, path, config):
self._write_file(path, config, LOG)
if self._js_model.split_results:
self._write_split_logs(splitext(path)[0])
def _write_split_lo... | write | identifier_name |
logreportwriters.py | # Copyright 2008-2012 Nokia Siemens Networks Oyj
#
# 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... | self._write_file(path, config, REPORT) | identifier_body | |
logreportwriters.py | # Copyright 2008-2012 Nokia Siemens Networks Oyj
#
# 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... |
def _write_split_log(self, index, keywords, strings, path):
with utf8open(path, 'wb') as outfile:
writer = SplitLogWriter(outfile)
writer.write(keywords, strings, index, basename(path))
class ReportWriter(_LogReportWriter):
def write(self, path, config):
self._write_... | index += 1 # enumerate accepts start index only in Py 2.6+
self._write_split_log(index, keywords, strings, '%s-%d.js' % (base, index)) | conditional_block |
logreportwriters.py | # Copyright 2008-2012 Nokia Siemens Networks Oyj
#
# 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... |
class _LogReportWriter(object):
def __init__(self, js_model):
self._js_model = js_model
def _write_file(self, path, config, template):
outfile = codecs.open(path, 'wb', encoding='UTF-8')\
if isinstance(path, basestring) else path # unit test hook
with outfile:
... |
from robot.htmldata import HtmlFileWriter, ModelWriter, LOG, REPORT
from robot.utils import utf8open
from .jswriter import JsResultWriter, SplitLogWriter | random_line_split |
update.rs | use crate::{
self as exercise,
errors::Result,
structs::{LabeledTest, LabeledTestItem},
};
use failure::format_err;
use std::{collections::HashSet, fs, path::Path};
enum DiffType {
NEW,
UPDATED,
}
fn generate_diff_test(
case: &LabeledTest,
diff_type: &DiffType,
use_maplit: bool,
) -> R... | Ok(())
}
pub fn update_exercise(exercise_name: &str, use_maplit: bool) -> Result<()> {
if !exercise::exercise_exists(exercise_name) {
return Err(
format_err!("exercise with the name '{}' does not exist", exercise_name).into(),
);
}
let tests_content = exercise::get_tests_co... | random_line_split | |
update.rs | use crate::{
self as exercise,
errors::Result,
structs::{LabeledTest, LabeledTestItem},
};
use failure::format_err;
use std::{collections::HashSet, fs, path::Path};
enum DiffType {
NEW,
UPDATED,
}
fn generate_diff_test(
case: &LabeledTest,
diff_type: &DiffType,
use_maplit: bool,
) -> R... | (
case: &LabeledTestItem,
diffs: &mut HashSet<String>,
tests_content: &str,
use_maplit: bool,
) -> Result<()> {
match case {
LabeledTestItem::Single(case) => generate_diffs(case, &tests_content, diffs, use_maplit)?,
LabeledTestItem::Array(group) => {
for case in &group.ca... | get_diffs | identifier_name |
update.rs | use crate::{
self as exercise,
errors::Result,
structs::{LabeledTest, LabeledTestItem},
};
use failure::format_err;
use std::{collections::HashSet, fs, path::Path};
enum DiffType {
NEW,
UPDATED,
}
fn generate_diff_test(
case: &LabeledTest,
diff_type: &DiffType,
use_maplit: bool,
) -> R... | ;
if diffs.insert(generate_diff_test(case, &diff_type, use_maplit)?) {
match diff_type {
DiffType::NEW => println!("New test case detected: {}.", description_formatted),
DiffType::UPDATED => println!("Updated test case: {}.", description_formatted),
}
}
let property... | {
DiffType::UPDATED
} | conditional_block |
update.rs | use crate::{
self as exercise,
errors::Result,
structs::{LabeledTest, LabeledTestItem},
};
use failure::format_err;
use std::{collections::HashSet, fs, path::Path};
enum DiffType {
NEW,
UPDATED,
}
fn generate_diff_test(
case: &LabeledTest,
diff_type: &DiffType,
use_maplit: bool,
) -> R... |
fn generate_diff_property(property: &str) -> Result<String> {
Ok(format!(
"//{}\n{}",
"NEW",
exercise::generate_property_body(property)?
))
}
fn generate_diffs(
case: &LabeledTest,
tests_content: &str,
diffs: &mut HashSet<String>,
use_maplit: bool,
) -> Result<()> {
... | {
Ok(format!(
"//{}\n{}",
match diff_type {
DiffType::NEW => "NEW",
DiffType::UPDATED => "UPDATED",
},
exercise::generate_test_function(case, use_maplit)?
))
} | identifier_body |
tradchinese.rs | // This is a part of rust-encoding.
// Copyright (c) 2013-2015, Kang Seonghoon.
// See README.md and LICENSE.txt for details.
//! Legacy traditional Chinese encodings.
use std::convert::Into;
use std::default::Default;
use util::StrCharIndex;
use index_tradchinese as index;
use types::*;
/**
* Big5-2003 with common... | (&mut self, _output: &mut ByteWriter) -> Option<CodecError> {
None
}
}
/// A decoder for Big5-2003 with HKSCS-2008 extension.
#[derive(Clone, Copy)]
struct BigFive2003HKSCS2008Decoder {
st: bigfive2003::State,
}
impl BigFive2003HKSCS2008Decoder {
pub fn new() -> Box<RawDecoder> {
Box::new(... | raw_finish | identifier_name |
tradchinese.rs | // This is a part of rust-encoding.
// Copyright (c) 2013-2015, Kang Seonghoon.
// See README.md and LICENSE.txt for details.
//! Legacy traditional Chinese encodings.
use std::convert::Into;
use std::default::Default;
use util::StrCharIndex;
use index_tradchinese as index;
use types::*;
/**
* Big5-2003 with common... |
}
impl RawEncoder for BigFive2003Encoder {
fn from_self(&self) -> Box<RawEncoder> { BigFive2003Encoder::new() }
fn is_ascii_compatible(&self) -> bool { true }
fn raw_feed(&mut self, input: &str, output: &mut ByteWriter) -> (usize, Option<CodecError>) {
output.writer_hint(input.len());
fo... | { Box::new(BigFive2003Encoder) } | identifier_body |
tradchinese.rs | // This is a part of rust-encoding.
// Copyright (c) 2013-2015, Kang Seonghoon.
// See README.md and LICENSE.txt for details.
//! Legacy traditional Chinese encodings.
use std::convert::Into;
use std::default::Default;
use util::StrCharIndex;
use index_tradchinese as index;
use types::*;
/**
* Big5-2003 with common... | assert_feed_ok!(d, [], [0xa4], "");
assert_feed_ok!(d, [0xa4, 0xb5, 0xd8], [0xa5], "\u{4e2d}\u{83ef}");
assert_feed_ok!(d, [0xc1, 0xb0, 0xea], [], "\u{6c11}\u{570b}");
assert_feed_ok!(d, [0x31, 0xa3, 0xe1, 0x2f, 0x6d], [], "1\u{20ac}/m");
assert_feed_ok!(d, [0xf9, 0xfe], [], "\u{... | assert_feed_ok!(d, [0x41], [], "A");
assert_feed_ok!(d, [0x42, 0x43], [], "BC");
assert_feed_ok!(d, [], [], "");
assert_feed_ok!(d, [0xa4, 0xa4, 0xb5, 0xd8, 0xa5, 0xc1, 0xb0, 0xea], [],
"\u{4e2d}\u{83ef}\u{6c11}\u{570b}"); | random_line_split |
tradchinese.rs | // This is a part of rust-encoding.
// Copyright (c) 2013-2015, Kang Seonghoon.
// See README.md and LICENSE.txt for details.
//! Legacy traditional Chinese encodings.
use std::convert::Into;
use std::default::Default;
use util::StrCharIndex;
use index_tradchinese as index;
use types::*;
/**
* Big5-2003 with common... | else {
let ptr = index::big5::backward(ch as u32);
if ptr == 0xffff {
return (i, Some(CodecError {
upto: j as isize, cause: "unrepresentable character".into()
}));
}
let lead = ptr / 157 + 0x... | {
output.write_byte(ch as u8);
} | conditional_block |
dstr-async-gen-meth-ary-ptrn-rest-obj-prop-id.js | // This file was procedurally generated from the following sources:
// - src/dstr-binding/ary-ptrn-rest-obj-prop-id.case
// - src/dstr-binding/default/cls-expr-async-gen-meth.template
/*---
description: Rest element containing an object binding pattern (class expression method)
esid: sec-class-definitions-runtime-seman... | a. If IsStatic of m is false, then
i. Let status be the result of performing
PropertyDefinitionEvaluation for m with arguments proto and
false.
[...]
Runtime Semantics: PropertyDefinitionEvaluation
AsyncGeneratorMethod :
async [no LineTerminator h... | 14.5.14 Runtime Semantics: ClassDefinitionEvaluation
21. For each ClassElement m in order from methods | random_line_split |
dstr-async-gen-meth-ary-ptrn-rest-obj-prop-id.js | // This file was procedurally generated from the following sources:
// - src/dstr-binding/ary-ptrn-rest-obj-prop-id.case
// - src/dstr-binding/default/cls-expr-async-gen-meth.template
/*---
description: Rest element containing an object binding pattern (class expression method)
esid: sec-class-definitions-runtime-seman... | ([...{ 0: v, 1: w, 2: x, 3: y, length: z }]) {
assert.sameValue(v, 7);
assert.sameValue(w, 8);
assert.sameValue(x, 9);
assert.sameValue(y, undefined);
assert.sameValue(z, 3);
assert.sameValue(length, "outer", "the length prop is not set as a binding name");
callCount = callCount + 1;
}
};... | method | identifier_name |
dstr-async-gen-meth-ary-ptrn-rest-obj-prop-id.js | // This file was procedurally generated from the following sources:
// - src/dstr-binding/ary-ptrn-rest-obj-prop-id.case
// - src/dstr-binding/default/cls-expr-async-gen-meth.template
/*---
description: Rest element containing an object binding pattern (class expression method)
esid: sec-class-definitions-runtime-seman... |
};
new C().method([7, 8, 9]).next().then(() => {
assert.sameValue(callCount, 1, 'invoked exactly once');
}).then($DONE, $DONE);
| {
assert.sameValue(v, 7);
assert.sameValue(w, 8);
assert.sameValue(x, 9);
assert.sameValue(y, undefined);
assert.sameValue(z, 3);
assert.sameValue(length, "outer", "the length prop is not set as a binding name");
callCount = callCount + 1;
} | identifier_body |
show_template_tester.py | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.actions import InterfaceAction
from calibre.gui2.dialogs.template_dialog import TemplateDialog
from cal... | self.previous_text = t.rule[1]
self.first_time = False | conditional_block | |
show_template_tester.py | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.actions import InterfaceAction
from calibre.gui2.dialogs.template_dialog import TemplateDialog
from cal... | (self, *args):
view = self.gui.current_view()
if view is not self.gui.library_view:
return error_dialog(self.gui, _('No template tester available'),
_('Template tester is not available for books '
'on the device.')).exec_()
rows = view.selectionMode... | show_template_editor | identifier_name |
show_template_tester.py | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.actions import InterfaceAction
from calibre.gui2.dialogs.template_dialog import TemplateDialog
from cal... | name = 'Template tester'
action_spec = (_('Template tester'), 'debug.png', None, '')
dont_add_to = frozenset(['context-menu-device'])
action_type = 'current'
def genesis(self):
self.previous_text = _('Enter a template to test using data from the selected book')
self.first_time = True
... | identifier_body | |
show_template_tester.py | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.actions import InterfaceAction
from calibre.gui2.dialogs.template_dialog import TemplateDialog
from cal... | if index.isValid():
db = view.model().db
t = TemplateDialog(self.gui, self.previous_text,
mi=db.get_metadata(index.row(), index_is_id=False, get_cover=False),
text_is_placeholder=self.first_time)
t.setWindowTitle(_('Template tester'))
... | random_line_split | |
comment.ts | import unit = require('tests/tsunit');
import test = require('tests/test');
import common = require('../common');
import Comment = require('../comment');
import Rating = require('../rating');
import RatingCommunicator = require('tests/testratingcommunicator');
import DiscussionCommunicator = require('tests/testdiscuss... | var viewModel = new Comment.ViewModel();
var communicator = new DiscussionCommunicator();
communicator.rating = new RatingCommunicator.Stub();
var controller = new Comment.Controller(model, viewModel, communicator);
communicator.rating.submitLikeRating = (ratableId: number, rating: string, then: () => void... | export class Main extends unit.TestClass {
handleSelectLikeRatingCommand() {
var counter = new common.Counter();
var model = new Comment.Model(); | random_line_split |
comment.ts | import unit = require('tests/tsunit');
import test = require('tests/test');
import common = require('../common');
import Comment = require('../comment');
import Rating = require('../rating');
import RatingCommunicator = require('tests/testratingcommunicator');
import DiscussionCommunicator = require('tests/testdiscuss... | extends unit.TestClass {
handleSelectLikeRatingCommand() {
var counter = new common.Counter();
var model = new Comment.Model();
var viewModel = new Comment.ViewModel();
var communicator = new DiscussionCommunicator();
communicator.rating = new RatingCommunicator.Stub();
var controller = new Comment.Contro... | Main | identifier_name |
page.tsx | import * as React from 'react';
import { Link } from 'react-router-dom';
import { MemberEntity, RepositoryEntity } from '../../model';
import { MemberHeader } from './memberHeader';
import { MemberRow } from './memberRow';
import {RepoHeader} from '../repos/repoHeader';
import {RepoRow} from '../repos/repoRow';
int... |
public componentDidMount() {
this.props.fetchMembers();
this.props.fetchRepos();
}
public render() {
return (
<div className="row">
<div className="col-5">
<div className="row">
<h2> Members Page</h2>
<Link to="/member">New Member</Link>
</div>
... | {
super(props);
this.state = {
members: [],
repos:[]
};
} | identifier_body |
page.tsx | import * as React from 'react';
import { Link } from 'react-router-dom';
import { MemberEntity, RepositoryEntity } from '../../model';
import { MemberHeader } from './memberHeader';
import { MemberRow } from './memberRow';
import {RepoHeader} from '../repos/repoHeader';
import {RepoRow} from '../repos/repoRow';
int... | </div>
<div className="col-5">
<h2> Repo Page</h2>
<table className="table" id="repos_table">
<thead>
<RepoHeader />
</thead>
<tbody>
{
this.props.repos.map((repo) =>
<RepoRow
key={repo... | }
</tbody>
</table> | random_line_split |
page.tsx | import * as React from 'react';
import { Link } from 'react-router-dom';
import { MemberEntity, RepositoryEntity } from '../../model';
import { MemberHeader } from './memberHeader';
import { MemberRow } from './memberRow';
import {RepoHeader} from '../repos/repoHeader';
import {RepoRow} from '../repos/repoRow';
int... | (props) {
super(props);
this.state = {
members: [],
repos:[]
};
}
public componentDidMount() {
this.props.fetchMembers();
this.props.fetchRepos();
}
public render() {
return (
<div className="row">
<div className="col-5">
<div className="row">
... | constructor | identifier_name |
Seq.ts | import { WithEquality, Ordering, ToOrderable } from "./Comparison";
import { HashMap } from "./HashMap";
import { HashSet } from "./HashSet";
import { Option } from "./Option";
import { Collection } from "./Collection";
import { Stream } from "./Stream";
/**
* IterableArray can take a type and apply iterable to its
... | reverse(): Seq<T>;
/**
* Takes a predicate; returns a pair of collections.
* The first one is the longest prefix of this collection
* which satisfies the predicate, and the second collection
* is the remainder of the collection.
*
* Vector.of(1,2,3,4,5,6).span(x => x <3)
*... | * => Vector.of(3,2,1)
*/ | random_line_split |
emitente.py | from base import Entidade
from pynfe.utils.flags import CODIGO_BRASIL
class | (Entidade):
# Dados do Emitente
# - Nome/Razao Social (obrigatorio)
razao_social = str()
# - Nome Fantasia
nome_fantasia = str()
# - CNPJ (obrigatorio)
cnpj = str()
# - Inscricao Estadual (obrigatorio)
inscricao_estadual = str()
# - CNAE Fiscal
cnae_fiscal = str()
# ... | Emitente | identifier_name |
emitente.py | from base import Entidade
from pynfe.utils.flags import CODIGO_BRASIL
class Emitente(Entidade):
# Dados do Emitente
# - Nome/Razao Social (obrigatorio)
razao_social = str()
# - Nome Fantasia
nome_fantasia = str()
# - CNPJ (obrigatorio)
cnpj = str()
# - Inscricao Estadual (obrigatorio... |
# - Codigo Municipio (opt)
endereco_cod_municipio = str()
# - Telefone
endereco_telefone = str()
# Logotipo
logotipo = None
def __str__(self):
return self.cnpj | # - Municipio (obrigatorio)
endereco_municipio = str() | random_line_split |
emitente.py | from base import Entidade
from pynfe.utils.flags import CODIGO_BRASIL
class Emitente(Entidade):
# Dados do Emitente
# - Nome/Razao Social (obrigatorio)
| razao_social = str()
# - Nome Fantasia
nome_fantasia = str()
# - CNPJ (obrigatorio)
cnpj = str()
# - Inscricao Estadual (obrigatorio)
inscricao_estadual = str()
# - CNAE Fiscal
cnae_fiscal = str()
# - Inscricao Municipal
inscricao_municipal = str()
# - Inscricao Estadua... | identifier_body | |
external_event.py | # Copyright 2014 Red Hat, Inc.
#
# 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 a... | (obj_base.NovaObject,
obj_base.NovaObjectDictCompat):
# Version 1.0: Initial version
# Supports network-changed and vif-plugged
VERSION = '1.0'
fields = {
'instance_uuid': fields.UUIDField(),
'name': fields.EnumField(valid_values=EVENT_NAMES),
... | InstanceExternalEvent | identifier_name |
external_event.py | # Copyright 2014 Red Hat, Inc.
#
# 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 a... |
@property
def key(self):
return self.make_key(self.name, self.tag)
| if tag is not None:
return '%s-%s' % (name, tag)
else:
return name | identifier_body |
external_event.py | # Copyright 2014 Red Hat, Inc.
#
# 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 a... |
from nova.objects import base as obj_base
from nova.objects import fields
EVENT_NAMES = [
# Network has changed for this instance, rebuild info_cache
'network-changed',
# VIF plugging notifications, tag is port_id
'network-vif-plugged',
'network-vif-unplugged',
]
EVENT_STATUSES = ['failed', 'co... | # under the License. | random_line_split |
external_event.py | # Copyright 2014 Red Hat, Inc.
#
# 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 a... |
else:
return name
@property
def key(self):
return self.make_key(self.name, self.tag)
| return '%s-%s' % (name, tag) | conditional_block |
borrowck-loan-rcvr.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | impl methods for point {
fn impurem(&self) {
}
fn blockm(&self, f: ||) { f() }
}
fn a() {
let mut p = point {x: 3, y: 4};
// Here: it's ok to call even though receiver is mutable, because we
// can loan it out.
p.impurem();
// But in this case we do not honor the loan:
p.blockm(|... | fn impurem(&self);
fn blockm(&self, f: ||);
}
| random_line_split |
borrowck-loan-rcvr.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
} | identifier_body | |
borrowck-loan-rcvr.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
}
| main | identifier_name |
typedParser.ts | import { IParser } from './iParser'
import { ParseFailure, ParseResult, ParseSuccess } from './parseResult'
export interface TypedValue {}
export interface TypedConstructor<T extends TypedValue> {
new (value: any): T
}
export class TypedParser<V, T extends TypedValue> implements IParser<T> {
ctor: TypedConstruct... | {
return new TypedParser<V, T>(ctor, parser)
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.