file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
actions.js | /*
*
* FileContainer actions
*
*/
import {
DEFAULT_ACTION,
UPDATE_FILE_INFO,
RECEIVE_FILE_ID,
UPDATE_BY_FILE_ID,
NEW_CONTAINER_ACTION,
ADD_NEW_ROW,
EDIT_ROW,
MAKE_SAVE_METADATA_ACTION,
MAKE_SAVE_METADATA_FROM_BACKEND,
DONT_SHOW_METADATA_FOR_DIRECTORY,
} from './constants';
// import { ADD_NEW_C... |
export function makeSaveMetaDataFromBackendAction( fileInfo ) {
return {
type: MAKE_SAVE_METADATA_FROM_BACKEND,
fileInfo,
};
}
export function makeDontShowMetaDataForDirectoryAction( ) {
return {
type: DONT_SHOW_METADATA_FOR_DIRECTORY,
}
}
| {
return {
type: MAKE_SAVE_METADATA_ACTION,
};
} | identifier_body |
actions.js | /*
*
* FileContainer actions
*
*/
import {
DEFAULT_ACTION,
UPDATE_FILE_INFO,
RECEIVE_FILE_ID,
UPDATE_BY_FILE_ID,
NEW_CONTAINER_ACTION,
ADD_NEW_ROW,
EDIT_ROW,
MAKE_SAVE_METADATA_ACTION,
MAKE_SAVE_METADATA_FROM_BACKEND,
DONT_SHOW_METADATA_FOR_DIRECTORY,
} from './constants';
// import { ADD_NEW_C... | () {
return {
type: MAKE_SAVE_METADATA_ACTION,
};
}
export function makeSaveMetaDataFromBackendAction( fileInfo ) {
return {
type: MAKE_SAVE_METADATA_FROM_BACKEND,
fileInfo,
};
}
export function makeDontShowMetaDataForDirectoryAction( ) {
return {
type: DONT_SHOW_METADATA_FOR_DIRECTORY,
}
... | makeSaveMetaDataAction | identifier_name |
actions.js | /*
*
* FileContainer actions
*
*/
import {
DEFAULT_ACTION,
UPDATE_FILE_INFO,
RECEIVE_FILE_ID,
UPDATE_BY_FILE_ID,
NEW_CONTAINER_ACTION,
ADD_NEW_ROW,
EDIT_ROW,
MAKE_SAVE_METADATA_ACTION,
MAKE_SAVE_METADATA_FROM_BACKEND,
DONT_SHOW_METADATA_FOR_DIRECTORY,
} from './constants';
// import { ADD_NEW_C... | type: UPDATE_BY_FILE_ID,
fileInfo,
};
}
export function makeNewContainerAction(container) {
return {
type: NEW_CONTAINER_ACTION,
container,
};
}
export function makeChangeNewRowAction(row){
return {
type: ADD_NEW_ROW,
row,
};
}
export function makeEditRowAction(row,cellName,cellValu... | }
export function updateFileById({ fileInfo }) {
return { | random_line_split |
valid.js | private
* 对控件内的字段域进行验证的视图
*/
var ValidView = function(){
};
ValidView.prototype = {
/**
* 获取错误信息的容器
* @protected
* @return {jQuery}
*/
getErrorsContainer : function(){
var _self = this,
errorContainer = _self.get('errorContainer');
if(errorContainer){
if(BUI.isString(errorContai... | f.get('children');
if(deep){
BUI.each(children,function(item){
if(item.clearErrors){
if(item.field){
item.clearErrors(reset);
}else{
item.clearErrors(reset,deep);
}
}
});
}
_self.set('error',null);
_self.get('view').c... | deep;
var _self = this,
children = _sel | conditional_block |
valid.js | private
* 对控件内的字段域进行验证的视图
*/
var ValidView = function(){
};
ValidView.prototype = {
/**
* 获取错误信息的容器
* @protected
* @return {jQuery}
*/
getErrorsContainer : function(){
var _self = this,
errorContainer = _self.get('errorContainer');
if(errorContainer){
if(BUI.isString(errorContai... | }
//如果仅显示第一条错误记录
if(_self.get('showOneError')){
if(errors && errors.length){
_self.showError(errors[0],errorTpl,errorsContainer);
}
return ;
}
BUI.each(errors,function(error){
if(error){
_self.showError(error,errorTpl,errorsContainer);
}
});
},
... | return ; | random_line_split |
createEpisodeTest.js | 'use strict';
const sinon = require('sinon'),
q = require('q'),
mockery = require('mockery'),
_ = require('lodash'),
should = require('chai').should();
describe('Create episode', () => {
const idsGeneratorStub = () => '123';
it('Should call the next callback', done => {
let deferred = q.defer();
let promi... | () {
persistEpisodeInStorage.calledOnce.should.equal(true);
persistEpisodeInStorage.args[0][0].should.equal(bookId);
persistEpisodeInStorage.args[0][1].should.deep.equal(_.assign({id: idsGeneratorStub()}, mockedRequest.body));
done();
}
});
afterEach(() => {
mockery.deregisterAll();
mockery.disabl... | checkResponse | identifier_name |
createEpisodeTest.js | 'use strict';
const sinon = require('sinon'),
q = require('q'),
mockery = require('mockery'),
_ = require('lodash'),
should = require('chai').should();
describe('Create episode', () => {
const idsGeneratorStub = () => '123';
it('Should call the next callback', done => {
let deferred = q.defer();
let promi... |
});
afterEach(() => {
mockery.deregisterAll();
mockery.disable();
});
});
function getCreateEpisodeMiddleware(idsMock, persistEpisodeInStorage) {
mockery.registerMock('../idsGenerator/generateId.js', idsMock);
mockery.registerMock('./persistEpisodeInStorage.js', persistEpisodeInStorage);
mockery.enable({... | {
persistEpisodeInStorage.calledOnce.should.equal(true);
persistEpisodeInStorage.args[0][0].should.equal(bookId);
persistEpisodeInStorage.args[0][1].should.deep.equal(_.assign({id: idsGeneratorStub()}, mockedRequest.body));
done();
} | identifier_body |
createEpisodeTest.js | 'use strict';
const sinon = require('sinon'),
q = require('q'),
mockery = require('mockery'),
_ = require('lodash'),
should = require('chai').should();
describe('Create episode', () => {
const idsGeneratorStub = () => '123';
it('Should call the next callback', done => {
let deferred = q.defer();
let promi... | done();
}
deferred.resolve();
});
it('Should store the scenario data and id', done => {
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const bookId = 'abc1234';
const mockedRequest = mockRequest(boo... | const body = responseSpy.args[0][1];
body.should.deep.equal({id: idsGeneratorStub()}); | random_line_split |
authors.service.ts | import getIndex from './helpers/get_index';
import {name as filterServiceName} from './filter.service';
import {Author, AuthorWithID} from './interfaces/author';
import {AuthorsServiceCtor, FilterServiceInstance} from './interfaces/services';
const AuthorsService: AuthorsServiceCtor = function AuthorsService(filterSe... | else {
return this.getAuthors().then((authors: Array<AuthorWithID>) => {
return authors[getIndex(id, authors)];
});
}
};
AuthorsService.prototype.updateAuthor = function (author: AuthorWithID): any {
return this.$http({
method: 'PUT',
url: this.baseUrl + author._id,
data: author
}).the... | {
return this.$q.resolve(this.data[getIndex(id, this.data)]);
} | conditional_block |
authors.service.ts | import getIndex from './helpers/get_index';
import {name as filterServiceName} from './filter.service';
import {Author, AuthorWithID} from './interfaces/author';
import {AuthorsServiceCtor, FilterServiceInstance} from './interfaces/services';
const AuthorsService: AuthorsServiceCtor = function AuthorsService(filterSe... | AuthorsService.prototype.addAuthor = function (author: Author) {
return this.$http({
method: 'POST',
url: this.baseUrl,
data: author
}).then((response) => {
this.data.push(response.data);
});
};
AuthorsService.prototype.deleteAuthor = function (id: number): any {
return this.$http({
method:... | random_line_split | |
introspection.py | from django.contrib.gis.gdal import OGRGeomType
from django.db.backends.postgresql.introspection import DatabaseIntrospection
class GeoIntrospectionError(Exception):
pass
class PostGISIntrospection(DatabaseIntrospection):
# Reverse dictionary for PostGIS geometry types not populated until
# introspectio... | identification integers for the PostGIS geometry and/or
geography types (if supported).
"""
field_types = [
('geometry', 'GeometryField'),
# The value for the geography type is actually a tuple
# to pass in the `geography=True` keyword to the field
... | ]
def get_postgis_types(self):
"""
Return a dictionary with keys that are the PostgreSQL object | random_line_split |
introspection.py | from django.contrib.gis.gdal import OGRGeomType
from django.db.backends.postgresql.introspection import DatabaseIntrospection
class GeoIntrospectionError(Exception):
pass
class PostGISIntrospection(DatabaseIntrospection):
# Reverse dictionary for PostGIS geometry types not populated until
# introspectio... | # definition.
('geography', ('GeometryField', {'geography': True})),
]
postgis_types = {}
# The OID integers associated with the geometry type may
# be different across versions; hence, this is why we have
# to query the PostgreSQL pg_type table correspon... | postgis_types_reverse = {}
ignored_tables = DatabaseIntrospection.ignored_tables + [
'geography_columns',
'geometry_columns',
'raster_columns',
'spatial_ref_sys',
'raster_overviews',
]
def get_postgis_types(self):
"""
Return a dictionary with keys th... | identifier_body |
introspection.py | from django.contrib.gis.gdal import OGRGeomType
from django.db.backends.postgresql.introspection import DatabaseIntrospection
class GeoIntrospectionError(Exception):
pass
class PostGISIntrospection(DatabaseIntrospection):
# Reverse dictionary for PostGIS geometry types not populated until
# introspectio... |
# OGRGeomType does not require GDAL and makes it easy to convert
# from OGC geom type name to Django field.
field_type = OGRGeomType(row[2]).django
# Getting any GeometryField keyword arguments that are not the default.
dim = row[0]
srid = row[1... | raise Exception('Could not find a geometry or geography column for "%s"."%s"' %
(table_name, geo_col)) | conditional_block |
introspection.py | from django.contrib.gis.gdal import OGRGeomType
from django.db.backends.postgresql.introspection import DatabaseIntrospection
class GeoIntrospectionError(Exception):
pass
class PostGISIntrospection(DatabaseIntrospection):
# Reverse dictionary for PostGIS geometry types not populated until
# introspectio... | (self, data_type, description):
if not self.postgis_types_reverse:
# If the PostGIS types reverse dictionary is not populated, do so
# now. In order to prevent unnecessary requests upon connection
# initialization, the `data_types_reverse` dictionary is not updated
... | get_field_type | identifier_name |
ir_exports.py | # -*- coding: utf-8 -*-
# Copyright 2015-2016 Jairo Llopis <jairo.llopis@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import _, api, fields, models
from openerp.exceptions import ValidationError
class IrExports(models.Model):
_inherit = 'ir.exports'
name =... | inverse="_inverse_model_id",
help="Database model to export.")
@api.multi
@api.depends("resource")
def _compute_model_id(self):
"""Get the model from the resource."""
for s in self:
s.model_id = self._get_model_id(s.resource)
@api.multi
@api.onchange("mo... | "Model",
store=True,
domain=[("transient", "=", False)],
compute="_compute_model_id", | random_line_split |
ir_exports.py | # -*- coding: utf-8 -*-
# Copyright 2015-2016 Jairo Llopis <jairo.llopis@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import _, api, fields, models
from openerp.exceptions import ValidationError
class IrExports(models.Model):
_inherit = 'ir.exports'
name =... |
@api.model
def _get_model_id(self, resource):
"""Return a model object from its technical name.
:param str resource:
Technical name of the model, like ``ir.model``.
"""
return self.env["ir.model"].search([("model", "=", resource)])
@api.model
def create(se... | s.export_fields = False | conditional_block |
ir_exports.py | # -*- coding: utf-8 -*-
# Copyright 2015-2016 Jairo Llopis <jairo.llopis@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import _, api, fields, models
from openerp.exceptions import ValidationError
class IrExports(models.Model):
_inherit = 'ir.exports'
name =... | (self):
"""Void fields if model is changed in a view."""
for s in self:
s.export_fields = False
@api.model
def _get_model_id(self, resource):
"""Return a model object from its technical name.
:param str resource:
Technical name of the model, like ``ir.mo... | _onchange_resource | identifier_name |
ir_exports.py | # -*- coding: utf-8 -*-
# Copyright 2015-2016 Jairo Llopis <jairo.llopis@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import _, api, fields, models
from openerp.exceptions import ValidationError
class IrExports(models.Model):
_inherit = 'ir.exports'
name =... |
@api.multi
@api.onchange("resource")
def _onchange_resource(self):
"""Void fields if model is changed in a view."""
for s in self:
s.export_fields = False
@api.model
def _get_model_id(self, resource):
"""Return a model object from its technical name.
:... | """Get the resource from the model."""
for s in self:
s.resource = s.model_id.model | identifier_body |
unique-pinned-nocopy-2.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 ... | () {
let i = @mut 0;
{
let j = ~r(i);
}
assert_eq!(*i, 1);
}
| main | identifier_name |
unique-pinned-nocopy-2.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 ... |
fn r(i: @mut int) -> r {
r {
i: i
}
}
pub fn main() {
let i = @mut 0;
{
let j = ~r(i);
}
assert_eq!(*i, 1);
} | } | random_line_split |
unique-pinned-nocopy-2.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 ... |
}
fn r(i: @mut int) -> r {
r {
i: i
}
}
pub fn main() {
let i = @mut 0;
{
let j = ~r(i);
}
assert_eq!(*i, 1);
}
| {
unsafe {
*(self.i) = *(self.i) + 1;
}
} | identifier_body |
polar.py | 1]))
def _Del(m):
return int0(npmatrix(diag(xrange(1, int(m)), k=1)[:-1]))
class _CD_RPN:
def __init__(self):
self.coeffs = [(npmatrix((-1,)), npmatrix((-1,)))]
self.rpn = [(rpncalc.RPNProgram([-1]), rpncalc.RPNProgram([-1]))]
# In case this class is utilized by multiple threads.
... | if len(cm_rpn):
cm_rpn.extend([v2, mul])
cm_rpn.extend(npoly_rpn)
cm_rpn.append(add)
else:
cm_rpn.extend(npoly_rpn)
for row in array(D[::-1]):
npoly... | oly_rpn.extend([n2, mul])
| conditional_block |
polar.py | and $d_{m}$.
# If they already exist in cache, just return what is there.
with self.lock:
if len(self.coeffs) <= m:
# Need to generate coefficients for $c_{m}$ and $d_{m}$.
# Fetch the coefficients for $c_{m-1}$ and $d_{m-1}$.
C, D = self.getc... | # | identifier_name | |
polar.py | cm_rpn.extend(npoly_rpn)
for row in array(D[::-1]):
npoly_rpn = []
for coeff in row[::-1]:
if coeff:
if len(npoly_rpn):
npoly_rpn.extend([n2, mul])
... | (self.Ff, axis=0)
return self.F
| identifier_body | |
polar.py | 1]))
def _Del(m):
return int0(npmatrix(diag(xrange(1, int(m)), k=1)[:-1]))
class _CD_RPN:
def __init__(self):
self.coeffs = [(npmatrix((-1,)), npmatrix((-1,)))]
self.rpn = [(rpncalc.RPNProgram([-1]), rpncalc.RPNProgram([-1]))]
# In case this class is utilized by multiple threads.
... | dm_rpn.extend(npoly_rpn)
dm_rpn.append(add)
else:
dm_rpn.extend(npoly_rpn)
self.rpn.append(
(rpncalc.RPNProgram(cm_rpn), rpncalc.RPNProgram(dm_rpn)))
return self.rpn[m]
class Sde... | elif len(npoly_rpn):
npoly_rpn.extend([n2, mul])
if len(dm_rpn):
dm_rpn.extend([v2, mul]) | random_line_split |
tableButton.js | //ButtonTable is a very very special case, because I am still not sure why it is a table :-)
// alternate design is to make it a field. Filed looks more logical, but table is more convenient at this time.
// we will review this design later and decide, meanwhile here is the ButtonPane table that DOES NOT inherit from A... | //for convenience, get the buttons into a collection indexed by name
var btnsToEnable = {};
for (var i = 1; i < n; i++)
{
var row = data[i];
if (hasFlag)
{
var flag = row[1];
if (!flag || flag == '0')
continue;
}
btnsToEnabl... | if (n <= 1) return;
//if the table has its second column, it is interpreted as Yes/No for enable. 0 or empty string is No, everything else is Yes
var hasFlag = data[0].length > 1;
| random_line_split |
insc.py | # coding: utf-8
if DefLANG in ("RU", "UA"):
AnsBase_temp = tuple([line.decode("utf-8") for line in (
"\nВсего входов - %d\nВремя последнего входа - %s\nПоследняя роль - %s", # 0
"\nВремя последнего выхода - %s\nПричина выхода - %s", # 1
"\nНики: %s", # 2
"Нет статистики.", # 3
"«%s» сидит здесь - %s.", # 4
... | # 1
"\nNicks: %s", # 2
"No statistics.", # 3
"'%s' spent here - %s.", # 4
"You spent here - %s.", # 5
"No such user here." # 6
) | conditional_block | |
insc.py | # coding: utf-8
if DefLANG in ("RU", "UA"):
AnsBase_temp = tuple([line.decode("utf-8") for line in (
"\nВсего входов - %d\nВремя последнего входа - %s\nПоследняя роль - %s", # 0
"\nВремя последнего выхода - %s\nПричина выхода - %s", # 1
"\nНики: %s", # 2
"Нет статистики.", # 3
"«%s» сидит здесь - %s.", # 4
... | "Здесь нет такого юзера." # 6
)])
else:
AnsBase_temp = (
"\nTotal joins - %d\nThe Last join-time - %s\nThe last role - %s", # 0
"\nThe last leave-time - %s\nExit reason - %s", # 1
"\nNicks: %s", # 2
"No statistics.", # 3
"'%s' spent here - %s.", # 4
"You spent here - %s.", # 5
"No such user here." # 6... | random_line_split | |
legacy_test_runner.ts | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../core/common/common-legacy.js';
import '../models/text_utils/text_utils-legacy.js';
import '../core/host/host-legacy.js';
import '../core/protoc... | {
// @ts-ignore
testRunner.dumpAsText();
// @ts-ignore
testRunner.waitUntilDone();
} | conditional_block | |
legacy_test_runner.ts | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../core/common/common-legacy.js';
import '../models/text_utils/text_utils-legacy.js';
import '../core/host/host-legacy.js';
import '../core/protoc... | import '../ui/legacy/components/inline_editor/inline_editor-legacy.js';
import '../core/root/root-legacy.js';
import '../core/sdk/sdk-legacy.js';
import './test_runner/test_runner.js';
// @ts-ignore
if (self.testRunner) {
// @ts-ignore
testRunner.dumpAsText();
// @ts-ignore
testRunner.waitUntilDone();
} | import '../ui/legacy/components/data_grid/data_grid-legacy.js';
import '../third_party/diff/diff-legacy.js';
import '../models/extensions/extensions-legacy.js';
import '../models/formatter/formatter-legacy.js'; | random_line_split |
type_infer.rs | /*
类型推导引擎不仅仅在初始化期间分析右值的类型,
还会通过分析变量在后面是 怎么使用的来推导该变量的类型
*/
fn main() {
// 借助类型标注,编译器知道 `elem` 具有 u8 类型
let elem = 5u8;
// 创建一个空 vector(可增长数组)。
let m | ut vec = Vec::new();
// 此时编译器并未知道 `vec` 的确切类型,它只知道 `vec` 是一个含有某种类型
// 的 vector(`Vec<_>`)。
// 将 `elem` 插入 vector。
vec.push(elem);
// Aha!现在编译器就知道了 `vec` 是一个含有 `u8` 类型的 vector(`Vec<u8>`)
// 试一试 ^ 尝试将 `vec.push(elem)` 那行注释掉
println!("{:?}", vec);
}
| identifier_body | |
type_infer.rs | /*
类型推导引擎不仅仅在初始化期间分析右值的类型,
还会通过分析变量在后面是 怎么使用的来推导该变量的类型
*/
fn main() {
// 借助类型标注,编译器知道 `elem` 具有 u8 类型
let elem = 5u8;
// 创建一个空 vector(可增长数组)。
| t mut vec = Vec::new();
// 此时编译器并未知道 `vec` 的确切类型,它只知道 `vec` 是一个含有某种类型
// 的 vector(`Vec<_>`)。
// 将 `elem` 插入 vector。
vec.push(elem);
// Aha!现在编译器就知道了 `vec` 是一个含有 `u8` 类型的 vector(`Vec<u8>`)
// 试一试 ^ 尝试将 `vec.push(elem)` 那行注释掉
println!("{:?}", vec);
}
| le | identifier_name |
type_infer.rs | /*
类型推导引擎不仅仅在初始化期间分析右值的类型,
还会通过分析变量在后面是 怎么使用的来推导该变量的类型 | // 创建一个空 vector(可增长数组)。
let mut vec = Vec::new();
// 此时编译器并未知道 `vec` 的确切类型,它只知道 `vec` 是一个含有某种类型
// 的 vector(`Vec<_>`)。
// 将 `elem` 插入 vector。
vec.push(elem);
// Aha!现在编译器就知道了 `vec` 是一个含有 `u8` 类型的 vector(`Vec<u8>`)
// 试一试 ^ 尝试将 `vec.push(elem)` 那行注释掉
println!("{:?}", vec);
} | */
fn main() {
// 借助类型标注,编译器知道 `elem` 具有 u8 类型
let elem = 5u8;
| random_line_split |
entity.py | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | self, obj):
return reverse(
"entity_read",
kwargs={'entity_version_id': obj.id}
)
| et_select_url( | identifier_name |
entity.py | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | eturn reverse(
"entity_read",
kwargs={'entity_version_id': obj.id}
)
| identifier_body | |
entity.py | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | acronym = django_filters.CharFilter(
lookup_expr='icontains', label=_("Acronym"),
widget=TextInput(attrs={'style': "text-transform:uppercase"})
)
title = django_filters.CharFilter(lookup_expr='icontains', label=_("Title"), )
class Meta:
model = EntityVersion
fields = ["e... | class EntityVersionFilter(django_filters.FilterSet): | random_line_split |
a4.rs | fn main() { // Declaración de vectores o arrays
let vector1 = vec!["primer lemento","segundo elemento","tercer elemento"] ; // Se utiliza "vec!" para declarar una apuntador de variable como vector.
let mut vector2: Vec<&str> = Vec::new(); // Declaración de un vector vacío con el tipo de elementos que va a con... | println!("primer elemento vector 1: {} y tercer elemento vector 2: {}", vector1[0], vector2[2]); // También se puede consultar el índice de uno de los elementos del vector usando "[X]" junto al nombre del vecto, dónde X es el número de la posición del elemento.
} | vector2 = vec!["Primero","Segundo"]; // Se agregan elementos al vector sobreescribiendolo gracias a "mut".
vector2.push("Tercero"); // Agrega un elemento al final del vector.
println!("primer vector 1: {:?} y segundo vector: {:?}", vector1, vector2); // Forma de ver en consola un vector no olvidar el ":?" entr... | random_line_split |
a4.rs | fn main() | { // Declaración de vectores o arrays
let vector1 = vec!["primer lemento","segundo elemento","tercer elemento"] ; // Se utiliza "vec!" para declarar una apuntador de variable como vector.
let mut vector2: Vec<&str> = Vec::new(); // Declaración de un vector vacío con el tipo de elementos que va a contener, en ... | identifier_body | |
a4.rs | fn | () { // Declaración de vectores o arrays
let vector1 = vec!["primer lemento","segundo elemento","tercer elemento"] ; // Se utiliza "vec!" para declarar una apuntador de variable como vector.
let mut vector2: Vec<&str> = Vec::new(); // Declaración de un vector vacío con el tipo de elementos que va a contener, ... | main | identifier_name |
DIAMOND_results_filter.py | #!/usr/lib/python2.7
##########################################################################
#
# Copyright (C) 2015-2016 Sam Westreich
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation;
#
# T... |
else:
db_org = line.split("[", 1)
db_org = db_org[1].split()
try:
db_org = str(db_org[0]) + " " + str(db_org[1])
except IndexError:
db_org = line.strip().split("[", 1)
db_org = db_org[1][:-1]
db_error_counter += 1
db_org = re.sub('[^a-zA-Z0-9-_*. ]', '', db_org)
# add to... | splitline = line.split("[")
db_org = splitline[line.count("[")].strip()[:-1]
if db_org[0].isdigit():
split_db_org = db_org.split()
try:
db_org = split_db_org[1] + " " + split_db_org[2]
except IndexError:
try:
db_org = split_db_org[1]
except IndexError:
db_org = sp... | conditional_block |
DIAMOND_results_filter.py | #!/usr/lib/python2.7
##########################################################################
#
# Copyright (C) 2015-2016 Sam Westreich
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation;
#
# T... | (usage_term):
for idx, elem in enumerate(sys.argv):
this_elem = elem
next_elem = sys.argv[(idx + 1) % len(sys.argv)]
if elem == usage_term:
return next_elem
# loading starting file
if "-I" in sys.argv:
infile_name = string_find("-I")
else:
sys.exit ("WARNING: infile must be specified using '-I' flag.")
#... | string_find | identifier_name |
DIAMOND_results_filter.py | #!/usr/lib/python2.7
##########################################################################
#
# Copyright (C) 2015-2016 Sam Westreich
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation;
#
# T... |
# loading starting file
if "-I" in sys.argv:
infile_name = string_find("-I")
else:
sys.exit ("WARNING: infile must be specified using '-I' flag.")
# optional outfile of specific organism results
if "-SO" in sys.argv:
target_org = string_find("-SO")
if '"' in target_org:
for idx, elem in enumerate(sys.argv):
... | for idx, elem in enumerate(sys.argv):
this_elem = elem
next_elem = sys.argv[(idx + 1) % len(sys.argv)]
if elem == usage_term:
return next_elem | identifier_body |
DIAMOND_results_filter.py | #!/usr/lib/python2.7
##########################################################################
#
# Copyright (C) 2015-2016 Sam Westreich
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation;
#
# T... | # optional outfile of specific organism results
if "-SO" in sys.argv:
target_org = string_find("-SO")
if '"' in target_org:
for idx, elem in enumerate(sys.argv):
this_elem = elem
next_elem = sys.argv[(idx + 1) % len(sys.argv)]
second_elem = sys.argv[(idx + 2) % len(sys.argv)]
if elem == "-SO":
targ... | else:
sys.exit ("WARNING: infile must be specified using '-I' flag.")
| random_line_split |
colors.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
""" Convenience functions for generating distinct colors.
Usage:
>>> generate_colors(4)
[(1.0, 0.0, 0.0), (0.5, 1.0, 0.0), (0.0, 1.0, 1.0), (0.5, 0.0, 1.0)]
"""
from __future__ import division
__author__ = 'Maarten Versteegh'
import math
def _hsv_to_rgb(h,f):
"""Conver... | (n):
"""Generate n distinct colors as rgb triples
Arguments:
n : int
number of colors to generate
Returns:
List of rgb triples
"""
hues = [360/n*i for i in range(n)]
hs = [(math.floor(hue/60) % 6) for hue in hues]
fs = [(hue/60 - math.floor(hue / 60)) for hue in hues]
ret... | generate_colors | identifier_name |
colors.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
""" Convenience functions for generating distinct colors.
Usage:
>>> generate_colors(4)
[(1.0, 0.0, 0.0), (0.5, 1.0, 0.0), (0.0, 1.0, 1.0), (0.5, 0.0, 1.0)]
"""
from __future__ import division
__author__ = 'Maarten Versteegh'
import math
def _hsv_to_rgb(h,f):
"""Conver... |
elif h == 4:
return f, p, v
elif h == 5:
return v, p, 1-f
def generate_colors(n):
"""Generate n distinct colors as rgb triples
Arguments:
n : int
number of colors to generate
Returns:
List of rgb triples
"""
hues = [360/n*i for i in range(n)]
hs = [(math... | return p, 1-f, v | conditional_block |
colors.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
""" Convenience functions for generating distinct colors.
Usage:
>>> generate_colors(4)
[(1.0, 0.0, 0.0), (0.5, 1.0, 0.0), (0.0, 1.0, 1.0), (0.5, 0.0, 1.0)]
"""
from __future__ import division
__author__ = 'Maarten Versteegh'
import math
def _hsv_to_rgb(h,f):
|
def generate_colors(n):
"""Generate n distinct colors as rgb triples
Arguments:
n : int
number of colors to generate
Returns:
List of rgb triples
"""
hues = [360/n*i for i in range(n)]
hs = [(math.floor(hue/60) % 6) for hue in hues]
fs = [(hue/60 - math.floor(hue / 60)) for... | """Convert a color specified by h-value and f-value to rgb triple
"""
v = 1.0
p = 0.0
if h == 0:
return v, f, p
elif h == 1:
return 1-f, v, p
elif h == 2:
return p, v, f
elif h == 3:
return p, 1-f, v
elif h == 4:
return f, p, v
elif h == 5:
... | identifier_body |
colors.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
""" Convenience functions for generating distinct colors.
Usage:
>>> generate_colors(4)
[(1.0, 0.0, 0.0), (0.5, 1.0, 0.0), (0.0, 1.0, 1.0), (0.5, 0.0, 1.0)]
"""
from __future__ import division
__author__ = 'Maarten Versteegh'
import math
def _hsv_to_rgb(h,f):
"""Conver... |
Arguments:
n : int
number of colors to generate
Returns:
List of rgb triples
"""
hues = [360/n*i for i in range(n)]
hs = [(math.floor(hue/60) % 6) for hue in hues]
fs = [(hue/60 - math.floor(hue / 60)) for hue in hues]
return [_hsv_to_rgb(h,f) for h,f in zip(hs,fs)] | def generate_colors(n):
"""Generate n distinct colors as rgb triples | random_line_split |
NoteMouseHandler.ts | import { observeDrag } from "../../../helpers/observeDrag"
import RootStore from "../../../stores/RootStore"
import {
getPencilActionForMouseDown,
getPencilActionForMouseUp,
getPencilCursorForMouseMove,
} from "./PencilMouseHandler"
import {
getSelectionActionForMouseDown,
getSelectionCursorForMouseMoven,
} f... | // 共通の action
// Common Action
// wheel drag to start scrolling
if (e.button === 1) {
return dragScrollAction
}
// 右ダブルクリック
// Right Double-click
if (e.button === 2 && e.detail % 2 === 0) {
return changeToolAction
}
switch (this.rootStore.pianoRollStore.mouseMode) ... | actionForMouseDown(e: MouseEvent): MouseGesture | null { | random_line_split |
NoteMouseHandler.ts | import { observeDrag } from "../../../helpers/observeDrag"
import RootStore from "../../../stores/RootStore"
import {
getPencilActionForMouseDown,
getPencilActionForMouseUp,
getPencilCursorForMouseMove,
} from "./PencilMouseHandler"
import {
getSelectionActionForMouseDown,
getSelectionCursorForMouseMoven,
} f... | (rootStore: RootStore) {
this.rootStore = rootStore
this.onMouseDown = this.onMouseDown.bind(this)
this.onMouseMove = this.onMouseMove.bind(this)
this.onMouseUp = this.onMouseUp.bind(this)
}
// mousedown 以降に行う MouseAction を返す
// Returns a MouseAction to do after MouseDown
actionForMouseDown(e: ... | constructor | identifier_name |
CodeModal.tsx | import MonacoEditor from '@monaco-editor/react';
import classNames from 'classnames';
import React, { useEffect, useState } from 'react';
import { AutoSizer } from 'react-virtualized';
// @ts-ignore
import Rodal from 'rodal';
import { ValueType } from 'tweek-client';
import { isStringValidJson } from '../../../services... | const editLineNum = lineCount > 1 ? lineCount - 1 : lineCount;
editor.setPosition({
lineNumber: editLineNum,
column: model.getLineMaxColumn(editLineNum),
});
editor.revealLine(lineCoun... | const model = editor.getModel();
if (model) {
const lineCount = model.getLineCount(); | random_line_split |
CodeModal.tsx | import MonacoEditor from '@monaco-editor/react';
import classNames from 'classnames';
import React, { useEffect, useState } from 'react';
import { AutoSizer } from 'react-virtualized';
// @ts-ignore
import Rodal from 'rodal';
import { ValueType } from 'tweek-client';
import { isStringValidJson } from '../../../services... |
editor.focus();
}, 500);
}}
/>
</div>
)}
</AutoSizer>
)}
<div className="rodal-button-container">
<button
disabled={value === initialValue || !isStringValidJson(value, valueType)}
... | {
const lineCount = model.getLineCount();
const editLineNum = lineCount > 1 ? lineCount - 1 : lineCount;
editor.setPosition({
lineNumber: editLineNum,
column: model.getLineMaxColumn(editLineNum),
... | conditional_block |
debug_node.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Injector } from '../di';
import { Predicate } from '../facade/collection';
import { RenderDebugInfo } from '... | extends DebugNode {
name: string;
properties: {
[key: string]: any;
};
attributes: {
[key: string]: string;
};
classes: {
[key: string]: boolean;
};
styles: {
[key: string]: string;
};
childNodes: DebugNode[];
nativeElement: any;
construct... | DebugElement | identifier_name |
debug_node.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Injector } from '../di';
import { Predicate } from '../facade/collection';
import { RenderDebugInfo } from '... | export declare function getAllDebugNodes(): DebugNode[];
export declare function indexDebugNode(node: DebugNode): void;
export declare function removeDebugNodeFromIndex(node: DebugNode): void; | */
export declare function getDebugNode(nativeNode: any): DebugNode; | random_line_split |
different-category-comparison.test.js | /**
* @license Copyright 2019 Google Inc. 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 applicable law or a... | });
it('should upload the second report', async () => {
const compareUpload = await state.page.$('.report-upload-box--compare input[type=file]');
if (!compareUpload) throw new Error('Missing compare upload box');
await compareUpload.uploadFile(getTestLHRPath('7.0.0', 'coursehero', 'b'));
... | random_line_split | |
ProjOpen.js | /**
* File: app/project/ProjOpen.js
* Author: liusha | grid: null,
initComponent: function() {
var me = this;
me.openStore = Ext.create('xdfn.project.store.ProjOpenJsonStore');
me.rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
errorSummary: false
});
me.callParent(arguments);
... | */
Ext.define('xdfn.project.ProjOpen', {
extend: 'xdfn.project.ui.ProjOpen',
| random_line_split |
ProjOpen.js | /**
* File: app/project/ProjOpen.js
* Author: liusha
*/
Ext.define('xdfn.project.ProjOpen', {
extend: 'xdfn.project.ui.ProjOpen',
grid: null,
initComponent: function() {
var me = this;
me.openStore = Ext.create('xdfn.project.store.ProjOpenJsonStore');
me.... | },
success: function(response, opts) {
me.rowEditing.cancelEdit();
var i = store.indexOf(rows[0]);
store.remove(rows);
var count = store.getCount();
if (count > 0) {
... | g.cancelEdit();
var i = store.indexOf(rows[0]);
store.remove(rows);
var count = store.getCount();
if (count > 0) {
sm.select((i == count)? --i : i);
}
return;
}
Ext.MessageBox.confirm('提示', '... | conditional_block |
server.sitemap.ts | // tslint:disable:no-require-imports
import { writeFile } from 'fs'
const sitemapGenerator = require('sitemap-generator')
export const sitemap = (host: string) => new Promise<string>((resolve, reject) => {
const generator = new sitemapGenerator(host)
// Avoid infinite loop during initial creation
generator.cra... |
generator.on('clienterror', (err: any) => {
return reject(err)
})
console.log(`starting sitemap crawler on ${host}`)
generator.start()
}) | } else {
return reject('Failed to generate sitemap.xml')
}
}) | random_line_split |
server.sitemap.ts | // tslint:disable:no-require-imports
import { writeFile } from 'fs'
const sitemapGenerator = require('sitemap-generator')
export const sitemap = (host: string) => new Promise<string>((resolve, reject) => {
const generator = new sitemapGenerator(host)
// Avoid infinite loop during initial creation
generator.cra... |
})
generator.on('clienterror', (err: any) => {
return reject(err)
})
console.log(`starting sitemap crawler on ${host}`)
generator.start()
})
| {
return reject('Failed to generate sitemap.xml')
} | conditional_block |
index.ts | import { NextApiRequest, NextApiResponse } from 'next'
| import { formatAmountForStripe } from '../../../utils/stripe-helpers'
import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-node#configuration
apiVersion: '2020-03-02',
})
export default async function handler(
req: NextApiRequest,
res: Nex... | import { CURRENCY, MIN_AMOUNT, MAX_AMOUNT } from '../../../config' | random_line_split |
index.ts | import { NextApiRequest, NextApiResponse } from 'next'
import { CURRENCY, MIN_AMOUNT, MAX_AMOUNT } from '../../../config'
import { formatAmountForStripe } from '../../../utils/stripe-helpers'
import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-... | (
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === 'POST') {
const amount: number = req.body.amount
try {
// Validate the amount that was passed from the client.
if (!(amount >= MIN_AMOUNT && amount <= MAX_AMOUNT)) {
throw new Error('Invalid amount.')
}
// C... | handler | identifier_name |
index.ts | import { NextApiRequest, NextApiResponse } from 'next'
import { CURRENCY, MIN_AMOUNT, MAX_AMOUNT } from '../../../config'
import { formatAmountForStripe } from '../../../utils/stripe-helpers'
import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-... | success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/donate-with-checkout`,
}
const checkoutSession: Stripe.Checkout.Session = await stripe.checkout.sessions.create(
params
)
res.status(200).json(checkoutSession... | {
if (req.method === 'POST') {
const amount: number = req.body.amount
try {
// Validate the amount that was passed from the client.
if (!(amount >= MIN_AMOUNT && amount <= MAX_AMOUNT)) {
throw new Error('Invalid amount.')
}
// Create Checkout Sessions from body params.
co... | identifier_body |
index.ts | import { NextApiRequest, NextApiResponse } from 'next'
import { CURRENCY, MIN_AMOUNT, MAX_AMOUNT } from '../../../config'
import { formatAmountForStripe } from '../../../utils/stripe-helpers'
import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-... |
}
| {
res.setHeader('Allow', 'POST')
res.status(405).end('Method Not Allowed')
} | conditional_block |
unique-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
TheA { x: i64, y: i64 },
TheB (i64, i32, i32),
}
// This is a special case since it does not have the implicit discriminant field.
enum Univariant {
TheOnlyCase(i64)
}
fn main() {
// In order to avoid endianness trouble all of the following test values consist of a single
// repeated byte. Thi... | ABC | identifier_name |
unique-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | // 0b0001000100010001 = 4369
// 0b00010001 = 17
let the_b: Box<_> = box ABC::TheB (0, 286331153, 286331153);
let univariant: Box<_> = box Univariant::TheOnlyCase(123234);
zzz(); // #break
}
fn zzz() {()} | // 0b00010001000100010001000100010001 = 286331153 | random_line_split |
vertex.rs | //! Vertex data structures.
use cgmath::{Point2,Point3,Vector2};
#[cfg(test)]
use std::mem;
use common::color::Color4;
#[derive(Debug, Clone, Copy, PartialEq)]
/// An untextured rendering vertex, with position and color.
pub struct ColoredVertex {
/// The 3-d position of this vertex in world space.
pub position:... | };
[
vtx(min.x, min.y), vtx(max.x, max.y), vtx(min.x, max.y),
vtx(min.x, min.y), vtx(max.x, min.y), vtx(max.x, max.y),
]
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
/// A point in the world with corresponding texture data.
///
/// The texture position is [0, 1].
pub struct TextureVertex {... | /// Generates two colored triangles, representing a square, at z=0.
/// The bounds of the square is represented by `b`.
pub fn square(min: Point2<f32>, max: Point2<f32>, color: Color4<f32>) -> [ColoredVertex; 6] {
let vtx = |x, y| {
ColoredVertex { position: Point3::new(x, y, 0.0), color: color } | random_line_split |
vertex.rs | //! Vertex data structures.
use cgmath::{Point2,Point3,Vector2};
#[cfg(test)]
use std::mem;
use common::color::Color4;
#[derive(Debug, Clone, Copy, PartialEq)]
/// An untextured rendering vertex, with position and color.
pub struct ColoredVertex {
/// The 3-d position of this vertex in world space.
pub position:... |
}
#[derive(Debug, Clone, Copy, PartialEq)]
/// A point in the world with corresponding texture data.
///
/// The texture position is [0, 1].
pub struct TextureVertex {
/// The position of this vertex in the world.
pub world_position: Point3<f32>,
/// The position of this vertex on a texture. The range of vali... | {
let vtx = |x, y| {
ColoredVertex { position: Point3::new(x, y, 0.0), color: color }
};
[
vtx(min.x, min.y), vtx(max.x, max.y), vtx(min.x, max.y),
vtx(min.x, min.y), vtx(max.x, min.y), vtx(max.x, max.y),
]
} | identifier_body |
vertex.rs | //! Vertex data structures.
use cgmath::{Point2,Point3,Vector2};
#[cfg(test)]
use std::mem;
use common::color::Color4;
#[derive(Debug, Clone, Copy, PartialEq)]
/// An untextured rendering vertex, with position and color.
pub struct ColoredVertex {
/// The 3-d position of this vertex in world space.
pub position:... | {
/// The position of this vertex in the world.
pub world_position: Point3<f32>,
/// The position of this vertex on a texture. The range of valid values
/// in each dimension is [0, 1].
pub texture_position: Vector2<f32>,
}
| TextureVertex | identifier_name |
plugin.js | /**
* @license
* Copyright (c) 2016 The {life-parser} Project Authors. All rights reserved.
* This code may only be used under the MIT style license found at http://100dayproject.github.io/LICENSE.txt
* The complete set of authors may be found at http://100dayproject.github.io/AUTHORS.txt
* The complete set of con... | command: 'insertMedia',
toolbar: 'insert'
});
}
}); | });
editor.ui.addButton('crab_media', {
label: 'CrabJS: Insert Media', | random_line_split |
geeks_events.js | /* This is where are handled "live" events of the application.
*/
var events = require('events')
, URL = require('url')
, io = require('socket.io')
, extend = require('nodetk/utils').extend
, error = require('./utils').error
;
var emitter = exports.emitter = new events.EventEmitter();
emitter.on('CREATE... | emitter.on('UPDATE:Geek', function(ids, data_) {
var data = extend({}, data_);
ids.forEach(function(id) {
data.id = id;
websocket_listener.broadcast({event: "UpdateGeek", data: data});
});
});
// TODO: events to deletion of geeks
// ----------------------------------
emitter.on('DELETE:Geek', function(i... | });
| random_line_split |
observeOn-spec.ts | import * as Rx from '../../dist/cjs/Rx';
import { expect } from 'chai';
import marbleTestingSignature = require('../helpers/marble-testing'); // tslint:disable-line:no-require-imports
declare const { asDiagram };
declare const hot: typeof marbleTestingSignature.hot;
declare const expectObservable: typeof marbleTesting... | const sub = '^ ! ';
const expected = '--a-- ';
const unsub = ' ! ';
const result = e1
.mergeMap((x: string) => Observable.of(x))
.observeOn(rxTestScheduler)
.mergeMap((x: string) => Observable.of(x));
expectObservable(result, unsub).toBe(expected);
ex... | it('should not break unsubscription chains when the result is unsubscribed explicitly', () => {
const e1 = hot('--a--b--|'); | random_line_split |
observeOn-spec.ts | import * as Rx from '../../dist/cjs/Rx';
import { expect } from 'chai';
import marbleTestingSignature = require('../helpers/marble-testing'); // tslint:disable-line:no-require-imports
declare const { asDiagram };
declare const hot: typeof marbleTestingSignature.hot;
declare const expectObservable: typeof marbleTesting... | else {
observer.next(i++);
this.schedule();
}
});
})
.observeOn(Rx.Scheduler.asap)
.subscribe(
x => {
const observeOnSubscriber = subscription._subscriptions[0];
expect(observeOnSubscriber._subscriptions.length).to.equal(2); // 1 for the con... | {
observer.complete();
} | conditional_block |
messages_ua.js | /*
| required: "Це поле необхідно заповнити.",
remote: "Будь ласка, введіть правильне значення.",
email: "Будь ласка, введіть коректну адресу електронної пошти.",
url: "Будь ласка, введіть коректний URL.",
date: "Будь ласка, введіть коректну дату.",
dateISO: "Будь ласка, введіть коректну дату у ... | * Translated default messages for the jQuery validation plugin.
* Localex: UA (Ukrainian)
*/
jQuery.extend(jQuery.validator.messages, {
| random_line_split |
addCrewSlot.js | $(document).ready(function(){
var nbSlots = 1;
var roles = [];
$('.captain-role option').each(function(){
roles.push([$(this).val(), $(this).text()]);
});
$(".crew-slots").append(generateDivSlot(nbSlots));
$('#add_slot').click(function(){
nbSlots++;
$(".crew-slots").... | var crewSlot = $(this).parent("div");
$('#' + crewSlot.attr('id')).remove();
renameCrewSlotDiv();
})
function generateDivSlot(nbSlots)
{
var str = "<div id=slot" + nbSlots + " class='crew-slot'>";
str += " <label for='crew-role'>Slot " + nbSlots + " : </lab... |
$(document).on('click', '.remove-slot', function(){ | random_line_split |
addCrewSlot.js | $(document).ready(function(){
var nbSlots = 1;
var roles = [];
$('.captain-role option').each(function(){
roles.push([$(this).val(), $(this).text()]);
});
$(".crew-slots").append(generateDivSlot(nbSlots));
$('#add_slot').click(function(){
nbSlots++;
$(".crew-slots").... |
function renameCrewSlotDiv()
{
var slotNum = 0;
$(".crew-slot").each(function(){
slotNum++;
$(this).attr('id', 'slot' + slotNum);
$(this).find("label").text("Slot " + slotNum + " : ");
})
nbSlots = slotNum;
}
})
| {
var str = "<div id=slot" + nbSlots + " class='crew-slot'>";
str += " <label for='crew-role'>Slot " + nbSlots + " : </label>";
str += " <select name='crew-role[]'>";
$(roles).each(function(){
str += " <option value='" + $(this)[0] + "'>" + $(this)[1] ... | identifier_body |
addCrewSlot.js | $(document).ready(function(){
var nbSlots = 1;
var roles = [];
$('.captain-role option').each(function(){
roles.push([$(this).val(), $(this).text()]);
});
$(".crew-slots").append(generateDivSlot(nbSlots));
$('#add_slot').click(function(){
nbSlots++;
$(".crew-slots").... | ()
{
var slotNum = 0;
$(".crew-slot").each(function(){
slotNum++;
$(this).attr('id', 'slot' + slotNum);
$(this).find("label").text("Slot " + slotNum + " : ");
})
nbSlots = slotNum;
}
})
| renameCrewSlotDiv | identifier_name |
addCrewSlot.js | $(document).ready(function(){
var nbSlots = 1;
var roles = [];
$('.captain-role option').each(function(){
roles.push([$(this).val(), $(this).text()]);
});
$(".crew-slots").append(generateDivSlot(nbSlots));
$('#add_slot').click(function(){
nbSlots++;
$(".crew-slots").... |
str += "<br />";
str += "</div>";
return str;
}
function renameCrewSlotDiv()
{
var slotNum = 0;
$(".crew-slot").each(function(){
slotNum++;
$(this).attr('id', 'slot' + slotNum);
$(this).find("label").text("Slot " + slotN... | {
str += " <button type='button' class='btn btn-default btn-xs remove-slot'>";
str += " <span class='glyphicon glyphicon-remove' aria-hidden='true'></span>";
str += " </button>";
} | conditional_block |
db.py | # -*- coding: utf-8 -*-
#########################################################################
## This scaffolding model makes your app work on Google App Engine too
## File is released under public domain and you can use without limitations
#########################################################################
... |
## create all tables needed by auth if not custom tables
auth.define_tables(username=False, signature=False)
## configure email
mail = auth.settings.mailer
mail.settings.server = 'logging' if request.is_local else myconf.get('smtp.server')
mail.settings.sender = myconf.get('smtp.sender')
mail.settings.login = myconf.... | from gluon.tools import Auth, Service, PluginManager
auth = Auth(db, host=myconf.get('host.name'))
service = Service()
plugins = PluginManager() | random_line_split |
db.py | # -*- coding: utf-8 -*-
#########################################################################
## This scaffolding model makes your app work on Google App Engine too
## File is released under public domain and you can use without limitations
#########################################################################
... |
else:
## connect to Google BigTable (optional 'google:datastore://namespace')
db = DAL('google:datastore+ndb')
## store sessions and tickets there
session.connect(request, response, db=db)
## or store session in Memcache, Redis, etc.
## from gluon.contrib.memdb import MEMDB
## from google.a... | db = DAL(myconf.get('db.uri'),
pool_size = myconf.get('db.pool_size'),
migrate_enabled = myconf.get('db.migrate'),
check_reserved = ['all']) | conditional_block |
coin-block-chain-info.module.ts | import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { RouterModule } from '@angular/router';
import { BlockchainSharedModule } from '../../shared';
import {
CoinBlockChainInfoService,
CoinBlockChainInfoPopupService,
CoinBlockChainInfoComponent,
CoinBlockChainInfoDetailComponent,
... | {}
| BlockchainCoinBlockChainInfoModule | identifier_name |
coin-block-chain-info.module.ts | import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { RouterModule } from '@angular/router';
import { BlockchainSharedModule } from '../../shared';
import {
CoinBlockChainInfoService,
CoinBlockChainInfoPopupService,
CoinBlockChainInfoComponent,
CoinBlockChainInfoDetailComponent,
... | CoinBlockChainInfoPopupComponent,
CoinBlockChainInfoDeleteDialogComponent,
CoinBlockChainInfoDeletePopupComponent,
],
providers: [
CoinBlockChainInfoService,
CoinBlockChainInfoPopupService,
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class BlockchainCoinBlockCh... | CoinBlockChainInfoDeletePopupComponent,
],
entryComponents: [
CoinBlockChainInfoComponent,
CoinBlockChainInfoDialogComponent, | random_line_split |
webpack.config.prod.js | var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: [
'./app/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/dist/'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new ... | preLoaders: [
{
test: /\.tsx?$/,
exclude: /(node_modules)/,
loader: 'source-map'
}
],
loaders: [{
test: /\.scss$/,
include: /src/,
loaders: [
'style',
'css',
'autoprefixer?browsers=last 3 versions',
'sass?outputSty... | random_line_split | |
distinct_clause.rs | use crate::backend::Backend;
use crate::query_builder::*;
use crate::query_dsl::order_dsl::ValidOrderingForDistinct;
use crate::result::QueryResult; |
#[derive(Debug, Clone, Copy, QueryId)]
pub struct NoDistinctClause;
#[derive(Debug, Clone, Copy, QueryId)]
pub struct DistinctClause;
impl<DB: Backend> QueryFragment<DB> for NoDistinctClause {
fn walk_ast(&self, _: AstPass<DB>) -> QueryResult<()> {
Ok(())
}
}
impl<DB: Backend> QueryFragment<DB> for D... | random_line_split | |
distinct_clause.rs | use crate::backend::Backend;
use crate::query_builder::*;
use crate::query_dsl::order_dsl::ValidOrderingForDistinct;
use crate::result::QueryResult;
#[derive(Debug, Clone, Copy, QueryId)]
pub struct | ;
#[derive(Debug, Clone, Copy, QueryId)]
pub struct DistinctClause;
impl<DB: Backend> QueryFragment<DB> for NoDistinctClause {
fn walk_ast(&self, _: AstPass<DB>) -> QueryResult<()> {
Ok(())
}
}
impl<DB: Backend> QueryFragment<DB> for DistinctClause {
fn walk_ast(&self, mut out: AstPass<DB>) -> Que... | NoDistinctClause | identifier_name |
icon-picker.tsx | import React from 'react';
import { FieldProps } from 'formik';
import { Text, BorderBox, FilterList } from '@primer/components';
import { iconThemes } from '@renderer/icons';
const IconPicker: React.FC<FieldProps> = ({ field, form }): JSX.Element => {
const currentIconTheme = iconThemes.find(
(iconTheme) => ic... | onClick={(): void => form.setFieldValue('iconTheme', name)}
>
<img
src={icons.contributed}
style={{
height: 16,
marginRight: 10,
position: 'relative',
top: 2,
}}
/>
... | random_line_split | |
chunk.rs | use std::io;
use std::fmt;
use std::ops::{Deref, DerefMut};
use ::aux::ReadExt;
static NAME_LENGTH: u32 = 8;
pub struct Root<R> {
pub name: String,
input: R,
buffer: Vec<u8>,
position: u32,
}
impl<R: io::Seek> Root<R> {
pub fn tell(&mut self) -> u32 {
self.input.seek(io::SeekFrom::Current... |
pub fn ignore(self) {
let left = self.end_pos - self.root.get_pos();
self.root.skip(left)
}
}
impl<'a, R: io::Read> Drop for Chunk<'a, R> {
fn drop(&mut self) {
debug!("Leaving chunk");
assert!(!self.has_more())
}
}
impl<'a, R: io::Read> Deref for Chunk<'a, R> {
t... | {
self.root.get_pos() < self.end_pos
} | identifier_body |
chunk.rs | use std::io;
use std::fmt;
use std::ops::{Deref, DerefMut};
use ::aux::ReadExt;
static NAME_LENGTH: u32 = 8;
pub struct Root<R> {
pub name: String,
input: R,
buffer: Vec<u8>,
position: u32,
}
impl<R: io::Seek> Root<R> {
pub fn tell(&mut self) -> u32 {
self.input.seek(io::SeekFrom::Current... | }
} | }
impl<'a, R: io::Read> DerefMut for Chunk<'a, R> {
fn deref_mut(&mut self) -> &mut Root<R> {
self.root | random_line_split |
chunk.rs | use std::io;
use std::fmt;
use std::ops::{Deref, DerefMut};
use ::aux::ReadExt;
static NAME_LENGTH: u32 = 8;
pub struct Root<R> {
pub name: String,
input: R,
buffer: Vec<u8>,
position: u32,
}
impl<R: io::Seek> Root<R> {
pub fn tell(&mut self) -> u32 {
self.input.seek(io::SeekFrom::Current... | (&mut self) -> u8 {
self.position += 1;
self.input.read_u8().unwrap()
}
pub fn read_u32(&mut self) -> u32 {
self.position += 4;
self.input.read_u32().unwrap()
}
pub fn read_bool(&mut self) -> bool {
self.position += 1;
self.input.read_u8().unwrap() != 0
... | read_u8 | identifier_name |
urls.py | """effcalculator URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cl... | url(r'^', include('frontend.urls'))
] | urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include('api.urls')), | random_line_split |
do.ts | import Operator from '../Operator';
import Observer from '../Observer';
import Subscriber from '../Subscriber';
import noop from '../util/noop';
import tryCatch from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
import bindCallback from '../util/bindCallback';
export default function _do<T>(nex... | (destination: Observer<T>, next: (x: T) => void, error: (e: any) => void, complete: () => void) {
super(destination);
this.__next = next;
this.__error = error;
this.__complete = complete;
}
_next(x) {
const result = tryCatch(this.__next)(x);
if (result === errorObject) {
this.destinat... | constructor | identifier_name |
do.ts | import Operator from '../Operator';
import Observer from '../Observer'; | import {errorObject} from '../util/errorObject';
import bindCallback from '../util/bindCallback';
export default function _do<T>(next?: (x: T) => void, error?: (e: any) => void, complete?: () => void) {
return this.lift(new DoOperator(next || noop, error || noop, complete || noop));
}
class DoOperator<T, R> impleme... | import Subscriber from '../Subscriber';
import noop from '../util/noop';
import tryCatch from '../util/tryCatch'; | random_line_split |
do.ts | import Operator from '../Operator';
import Observer from '../Observer';
import Subscriber from '../Subscriber';
import noop from '../util/noop';
import tryCatch from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
import bindCallback from '../util/bindCallback';
export default function _do<T>(nex... |
_next(x) {
const result = tryCatch(this.__next)(x);
if (result === errorObject) {
this.destination.error(errorObject.e);
} else {
this.destination.next(x);
}
}
_error(e) {
const result = tryCatch(this.__error)(e);
if (result === errorObject) {
this.destination.error(er... | {
super(destination);
this.__next = next;
this.__error = error;
this.__complete = complete;
} | identifier_body |
do.ts | import Operator from '../Operator';
import Observer from '../Observer';
import Subscriber from '../Subscriber';
import noop from '../util/noop';
import tryCatch from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
import bindCallback from '../util/bindCallback';
export default function _do<T>(nex... |
}
_error(e) {
const result = tryCatch(this.__error)(e);
if (result === errorObject) {
this.destination.error(errorObject.e);
} else {
this.destination.error(e);
}
}
_complete() {
const result = tryCatch(this.__complete)();
if (result === errorObject) {
this.destinati... | {
this.destination.next(x);
} | conditional_block |
xwrapper.rs | use libc::*;
use std::ffi::{CString, CStr};
use std::ptr;
use xlib::{ Display, Pixmap, Window, XClassHint, XCreateSimpleWindow, XDefaultScreen, XDefaultScreenOfDisplay, XGetSelectionOwner, XID, XInternAtom, XOpenDisplay, XRootWindowOfScreen, XSetSelectionOwner, XSizeHints };
use x11::xrender::{ XRenderCreatePicture, ... | }
pub fn intern_atom(xserver: &XServer, name: &str) -> XID {
return unsafe { XInternAtom(xserver.display, name.as_ptr() as *mut c_char, 0) };
}
pub fn null_xrender_picture_attributes() -> XRenderPictureAttributes {
return XRenderPictureAttributes {
repeat: 0,
alpha_map: XNone,
alpha_x_origin: 0,
... | {
WindowSettings {
opacity: intern_atom(xserver, "_NET_WM_WINDOW_OPACITY"),
type_atom: intern_atom(xserver, "_NET_WM_WINDOW_TYPE"),
is_desktop: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DESKTOP"),
is_dock: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DOCK"),
is_toolbar: intern_atom(xserver, "_NET_WM... | identifier_body |
xwrapper.rs | use libc::*;
use std::ffi::{CString, CStr};
use std::ptr;
use xlib::{ Display, Pixmap, Window, XClassHint, XCreateSimpleWindow, XDefaultScreen, XDefaultScreenOfDisplay, XGetSelectionOwner, XID, XInternAtom, XOpenDisplay, XRootWindowOfScreen, XSetSelectionOwner, XSizeHints };
use x11::xrender::{ XRenderCreatePicture, ... | (xserver: &XServer) -> WindowSettings {
WindowSettings {
opacity: intern_atom(xserver, "_NET_WM_WINDOW_OPACITY"),
type_atom: intern_atom(xserver, "_NET_WM_WINDOW_TYPE"),
is_desktop: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DESKTOP"),
is_dock: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DOCK"),
is_... | find_window_settings | identifier_name |
xwrapper.rs | use libc::*;
use std::ffi::{CString, CStr};
use std::ptr;
use xlib::{ Display, Pixmap, Window, XClassHint, XCreateSimpleWindow, XDefaultScreen, XDefaultScreenOfDisplay, XGetSelectionOwner, XID, XInternAtom, XOpenDisplay, XRootWindowOfScreen, XSetSelectionOwner, XSizeHints };
use x11::xrender::{ XRenderCreatePicture, ... | dither: XNone,
component_alpha: 0,
}
}
//
// Side-Effecting Stuff
//
pub fn register_compositing_window_manager(xserver: &XServer, wm_name: &CStr) -> bool {
let screen = unsafe { XDefaultScreen(xserver.display) };
let reg_atom_name = CString::new(format!("_NET_WM_CM_S{}", screen)).unwrap();
let reg_at... | graphics_exposures: 0,
subwindow_mode: 0,
poly_edge: 0,
poly_mode: 0, | random_line_split |
xwrapper.rs | use libc::*;
use std::ffi::{CString, CStr};
use std::ptr;
use xlib::{ Display, Pixmap, Window, XClassHint, XCreateSimpleWindow, XDefaultScreen, XDefaultScreenOfDisplay, XGetSelectionOwner, XID, XInternAtom, XOpenDisplay, XRootWindowOfScreen, XSetSelectionOwner, XSizeHints };
use x11::xrender::{ XRenderCreatePicture, ... | ,
_ => panic!(format!("Don't know how to query for {} extension", name)),
}
}
}
pub struct WindowSettings {
pub opacity: XID,
pub type_atom: XID,
pub is_desktop: XID,
pub is_dock: XID,
pub is_toolbar: XID,
pub is_menu: XID,
pub is_util: XID,
pub is_splash: XID,
pub is_dialog: XID,
pub i... | {
panic!("No XShape extension!");
} | conditional_block |
list.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
${helpers.single_keyword("list-style-position", "outside inside", animatable=False)}
// TODO(pcwalton): Implement the full set of counter styles per CSS-COUNTER-STYLES [1] 6.1:
//
// decimal-leading-zero, armenian, upper-armenian, lower-armenian, georgian, lower-roman,
// upper-roman
//
// TODO(bholley): Miss... |
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("List", inherited=True) %> | random_line_split |
list.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("List", inherited=True) %>
${help... | } else {
Err(())
}
}
</%helpers:longhand>
| {
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(SpecifiedValue(Vec::new()))
}
let mut quotes = Vec::new();
loop {
let first = match input.next() {
Ok(Token::QuotedString(value)) => value.into_owned(),
... | identifier_body |
list.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("List", inherited=True) %>
${help... | (pub Vec<(String,String)>);
}
impl ComputedValueAsSpecified for SpecifiedValue {}
impl NoViewportPercentage for SpecifiedValue {}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut first = true;
for pair in &se... | T | identifier_name |
template_installer.rs | // Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// ... | ));
}
let template_string = {
if version.major >= 7 {
crate::resource::get_string("elasticsearch/template-es7x.json").ok_or_else(|| {
anyhow!(
"Failed to find template for Elasticsearch version {}",
version.version
... | {
debug!("Checking for template \"{}\"", template);
match client.get_template(template).await {
Err(err) => {
warn!("Failed to check if template {} exists: {}", template, err);
}
Ok(None) => {
debug!("Did not find template for \"{}\", will install", template);
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.