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 |
|---|---|---|---|---|
hotkeysDialog.tsx | /*
* Copyright 2016 Palantir Technologies, Inc. All rights reserved.
*
* Licensed under the terms of the LICENSE file distributed with this project.
*/
import * as classNames from "classnames";
import * as React from "react";
import * as ReactDOM from "react-dom";
import { Classes } from "../../common";
import { ... |
}
/**
* Because hotkeys can be registered globally and locally and because
* event ordering cannot be guaranteed, we use this debouncing method to
* allow all hotkey listeners to fire and add their hotkeys to the dialog.
*
* 10msec after the last listener adds their hotkeys, we render... | {
ReactDOM.unmountComponentAtNode(this.container);
this.container.remove();
delete this.container;
} | conditional_block |
text.py | class CharacterSubstitutions(object):
character_substitutions = dict()
def standard_text_from_block(block, offset, max_length):
str = ''
for i in range(offset, offset + max_length):
c = block[i]
if c == 0:
return str
else:
str += chr(c - 0x30)
return str... | byte_list = []
text_pos = 0
while text_pos < len(text):
c = text[text_pos]
if c == '[':
end_bracket_pos = text.find(']', text_pos)
if end_bracket_pos == -1:
raise ValueError("String contains '[' at position {} but no subsequent ']': {}".format(
... | random_line_split | |
text.py | class CharacterSubstitutions(object):
character_substitutions = dict()
def standard_text_from_block(block, offset, max_length):
str = ''
for i in range(offset, offset + max_length):
c = block[i]
if c == 0:
return str
else:
str += chr(c - 0x30)
return str... | (text, max_length):
# First, substitute all of the characters
if CharacterSubstitutions.character_substitutions:
for k, v in CharacterSubstitutions.character_substitutions.items():
text = text.replace(k, v)
byte_list = []
text_pos = 0
while text_pos < len(text):
c = text... | standard_text_to_byte_list | identifier_name |
text.py | class CharacterSubstitutions(object):
character_substitutions = dict()
def standard_text_from_block(block, offset, max_length):
str = ''
for i in range(offset, offset + max_length):
c = block[i]
if c == 0:
return str
else:
str += chr(c - 0x30)
return str... | byte_list = standard_text_to_byte_list(text, max_length)
block[offset:offset+len(byte_list)] = byte_list | identifier_body | |
text.py | class CharacterSubstitutions(object):
character_substitutions = dict()
def standard_text_from_block(block, offset, max_length):
str = ''
for i in range(offset, offset + max_length):
c = block[i]
if c == 0:
return str
else:
str += chr(c - 0x30)
return str... |
try:
bracket_byte_value = int(bracket_byte, 16)
except ValueError as e:
raise ValueError("String contains invalid hex number '{}': {}".format(
bracket_byte, text
), e)
byte_list.append(... | raise ValueError("String contains invalid hex number '{}', must be two digits: {}".format(
bracket_byte, text
)) | conditional_block |
DetailsLine.tsx | import * as React from 'react';
import { Responsive } from '@visx/visx';
import { Typography, Box } from '@mui/material';
import makeStyles from '@mui/styles/makeStyles';
const useStyles = makeStyles((theme) => ({
lineText: {
fontSize: theme.typography.body2.fontSize,
overflow: 'hidden',
textOverflow: ... | interface Props {
line?: JSX.Element | string;
}
const DetailsLine = ({ line }: Props): JSX.Element => {
const classes = useStyles();
return (
<Responsive.ParentSize parentSizeStyles={{ height: 'auto' }}>
{({ width }): JSX.Element => (
<Typography component="div">
<Box
cl... | },
}));
| random_line_split |
no_method_suggested_traits.rs | // Copyright 2015 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 PubPub for u32 {}
impl PubPub for i32 {}
}
pub mod bar {
trait PubPriv {
fn method(&self);
}
}
mod qux {
pub trait PrivPub {
fn method(&self);
}
}
mod quz {
trait PrivPriv {
fn method(&self);
}
}
mod reexport {
pub trait Reexported {
fn m... | {} | identifier_body |
no_method_suggested_traits.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) {}
fn method3(&self) {}
}
impl PubPub for u32 {}
impl PubPub for i32 {}
}
pub mod bar {
trait PubPriv {
fn method(&self);
}
}
mod qux {
pub trait PrivPub {
fn method(&self);
}
}
mod quz {
trait PrivPriv {
fn method(&self);
}
}
mod reexport {... | method | identifier_name |
no_method_suggested_traits.rs | // Copyright 2015 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 | // except according to those terms.
pub use reexport::Reexported;
pub mod foo {
pub trait PubPub {
fn method(&self) {}
fn method3(&self) {}
}
impl PubPub for u32 {}
impl PubPub for i32 {}
}
pub mod bar {
trait PubPriv {
fn method(&self);
}
}
mod qux {
pub trait Pr... | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
ConstFunc.ts | import Func from './Func';
import { ConstBranch, ConstSet, ConstRef, Return } from '~/runtime/instructions';
import Translator from './Translator';
import TranslationVisitor from './TranslationVisitor';
import { ConstantDeclaration } from '~/syntax';
export default class ConstFunc extends Func {
ast: ConstantDecl... | (translator: Translator) {
// every constant has a special global reference created for it
const constRef = translator.newConstantRef();
// a const branch is a special constant memoization branch that will branch only if the constant has been initialized
const branch = this.addInstructio... | translate | identifier_name |
ConstFunc.ts | import Func from './Func';
import { ConstBranch, ConstSet, ConstRef, Return } from '~/runtime/instructions';
import Translator from './Translator';
import TranslationVisitor from './TranslationVisitor';
import { ConstantDeclaration } from '~/syntax';
export default class ConstFunc extends Func {
ast: ConstantDecl... | this.addInstruction(new Return(localRef));
}
getStackEntry() {
const { startLine: line, startColumn: column } = this.ast.locations.self;
return `${this.ast.prettyName()} (${this.modulePath}:${line}:${column})`;
}
} | random_line_split | |
ConstFunc.ts | import Func from './Func';
import { ConstBranch, ConstSet, ConstRef, Return } from '~/runtime/instructions';
import Translator from './Translator';
import TranslationVisitor from './TranslationVisitor';
import { ConstantDeclaration } from '~/syntax';
export default class ConstFunc extends Func {
ast: ConstantDecl... |
getStackEntry() {
const { startLine: line, startColumn: column } = this.ast.locations.self;
return `${this.ast.prettyName()} (${this.modulePath}:${line}:${column})`;
}
} | {
// every constant has a special global reference created for it
const constRef = translator.newConstantRef();
// a const branch is a special constant memoization branch that will branch only if the constant has been initialized
const branch = this.addInstruction(new ConstBranch({ const... | identifier_body |
tags-on-commits-list.tsx | import React from 'dom-chef';
import cache from 'webext-storage-cache';
import select from 'select-dom';
import {TagIcon} from '@primer/octicons-react';
import arrayUnion from 'array-union';
import * as pageDetect from 'github-url-detection';
import features from '.';
import * as api from '../github-helpers/api';
impo... | else {
result[commit] = newTags[commit];
}
}
return result;
}
function isTagTarget(target: CommonTarget): target is TagTarget {
return 'tagger' in target;
}
async function getTags(lastCommit: string, after?: string): Promise<CommitTags> {
const {repository} = await api.v4(`
repository() {
refs(
fi... | {
result[commit] = arrayUnion(result[commit], newTags[commit]);
} | conditional_block |
tags-on-commits-list.tsx | import React from 'dom-chef';
import cache from 'webext-storage-cache';
import select from 'select-dom';
import {TagIcon} from '@primer/octicons-react';
import arrayUnion from 'array-union';
import * as pageDetect from 'github-url-detection';
import features from '.';
import * as api from '../github-helpers/api';
impo... |
function isTagTarget(target: CommonTarget): target is TagTarget {
return 'tagger' in target;
}
async function getTags(lastCommit: string, after?: string): Promise<CommitTags> {
const {repository} = await api.v4(`
repository() {
refs(
first: 100,
refPrefix: "refs/tags/",
orderBy: {
field: TAG_... | {
const result: CommitTags = {...oldTags};
for (const commit in newTags) {
if (result[commit]) {
result[commit] = arrayUnion(result[commit], newTags[commit]);
} else {
result[commit] = newTags[commit];
}
}
return result;
} | identifier_body |
tags-on-commits-list.tsx | import React from 'dom-chef';
import cache from 'webext-storage-cache';
import select from 'select-dom';
import {TagIcon} from '@primer/octicons-react';
import arrayUnion from 'array-union';
import * as pageDetect from 'github-url-detection';
import features from '.';
import * as api from '../github-helpers/api'; | import {buildRepoURL, getRepo} from '../github-helpers';
type CommitTags = Record<string, string[]>;
interface BaseTarget {
commitResourcePath: string;
}
type TagTarget = {
tagger: {
date: Date;
};
} & BaseTarget;
type CommitTarget = {
committedDate: Date;
} & BaseTarget;
type CommonTarget = TagTarget | Comm... | import {getCommitHash} from './mark-merge-commits-in-list'; | random_line_split |
tags-on-commits-list.tsx | import React from 'dom-chef';
import cache from 'webext-storage-cache';
import select from 'select-dom';
import {TagIcon} from '@primer/octicons-react';
import arrayUnion from 'array-union';
import * as pageDetect from 'github-url-detection';
import features from '.';
import * as api from '../github-helpers/api';
impo... | (lastCommit: string, after?: string): Promise<CommitTags> {
const {repository} = await api.v4(`
repository() {
refs(
first: 100,
refPrefix: "refs/tags/",
orderBy: {
field: TAG_COMMIT_DATE,
direction: DESC
}
${after ? `, after: "${after}"` : ''}
) {
pageInfo {
hasNextPage
... | getTags | identifier_name |
serde_json.rs | //! [`ToSql`] and [`FromSql`] implementation for JSON `Value`.
use serde_json::Value;
use crate::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
use crate::Result;
/// Serialize JSON `Value` to text.
impl ToSql for Value {
#[inline]
fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
... | fn checked_memory_handle() -> Result<Connection> {
let db = Connection::open_in_memory()?;
db.execute_batch("CREATE TABLE foo (t TEXT, b BLOB)")?;
Ok(db)
}
#[test]
fn test_json_value() -> Result<()> {
let db = checked_memory_handle()?;
let json = r#"{"foo": 13, ... | random_line_split | |
serde_json.rs | //! [`ToSql`] and [`FromSql`] implementation for JSON `Value`.
use serde_json::Value;
use crate::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
use crate::Result;
/// Serialize JSON `Value` to text.
impl ToSql for Value {
#[inline]
fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
... | () -> Result<()> {
let db = checked_memory_handle()?;
let json = r#"{"foo": 13, "bar": "baz"}"#;
let data: serde_json::Value = serde_json::from_str(json).unwrap();
db.execute(
"INSERT INTO foo (t, b) VALUES (?, ?)",
&[&data as &dyn ToSql, &json.as_bytes()],
... | test_json_value | identifier_name |
serde_json.rs | //! [`ToSql`] and [`FromSql`] implementation for JSON `Value`.
use serde_json::Value;
use crate::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
use crate::Result;
/// Serialize JSON `Value` to text.
impl ToSql for Value {
#[inline]
fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
... |
#[test]
fn test_json_value() -> Result<()> {
let db = checked_memory_handle()?;
let json = r#"{"foo": 13, "bar": "baz"}"#;
let data: serde_json::Value = serde_json::from_str(json).unwrap();
db.execute(
"INSERT INTO foo (t, b) VALUES (?, ?)",
&[&data as ... | {
let db = Connection::open_in_memory()?;
db.execute_batch("CREATE TABLE foo (t TEXT, b BLOB)")?;
Ok(db)
} | identifier_body |
images.collection.ts | import { MongoObservable } from 'meteor-rxjs';
import { Meteor } from 'meteor/meteor';
import { UploadFS } from 'meteor/jalik:ufs';
import { Thumb, Image } from "../models/image.model";
export const Images = new MongoObservable.Collection<Image>('images');
export const Thumbs = new MongoObservable.Collection<Thumb>('t... | },
transformWrite(from, to, fileId, file) {
// Resize to 32x32
from.pipe(to); // this returns the raw data
// TODO:fix thumbnail generation
// gm(from, file.name)
// .resize(32, 32)
// .gravity('Center')
// .extent(32, 32)
// .quality(75)
// .stream()
// .pipe(... | }),
transformRead (from, to, fileId, file, request) {
from.pipe(to); // this returns the raw data | random_line_split |
images.collection.ts | import { MongoObservable } from 'meteor-rxjs';
import { Meteor } from 'meteor/meteor';
import { UploadFS } from 'meteor/jalik:ufs';
import { Thumb, Image } from "../models/image.model";
export const Images = new MongoObservable.Collection<Image>('images');
export const Thumbs = new MongoObservable.Collection<Thumb>('t... |
});
export const ImagesStore = new UploadFS.store.GridFS({
collection: Images.collection,
name: 'images',
filter: new UploadFS.Filter({
contentTypes: ['image/*']
}),
copyTo: [
ThumbsStore
],
permissions: new UploadFS.StorePermissions({
insert: loggedIn,
update: loggedIn,
remove: logg... | {
// Resize to 32x32
from.pipe(to); // this returns the raw data
// TODO:fix thumbnail generation
// gm(from, file.name)
// .resize(32, 32)
// .gravity('Center')
// .extent(32, 32)
// .quality(75)
// .stream()
// .pipe(to);
} | identifier_body |
images.collection.ts | import { MongoObservable } from 'meteor-rxjs';
import { Meteor } from 'meteor/meteor';
import { UploadFS } from 'meteor/jalik:ufs';
import { Thumb, Image } from "../models/image.model";
export const Images = new MongoObservable.Collection<Image>('images');
export const Thumbs = new MongoObservable.Collection<Thumb>('t... | (from, to, fileId, file) {
// Resize to 32x32
from.pipe(to); // this returns the raw data
// TODO:fix thumbnail generation
// gm(from, file.name)
// .resize(32, 32)
// .gravity('Center')
// .extent(32, 32)
// .quality(75)
// .stream()
// .pipe(to);
}
});
export c... | transformWrite | identifier_name |
webglbuffer.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use canvas_traits::{CanvasMsg, CanvasWebGLMsg... | self.is_deleted.set(true);
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteBuffer(self.id))).unwrap();
}
}
} | Ok(())
}
pub fn delete(&self) {
if !self.is_deleted.get() { | random_line_split |
webglbuffer.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use canvas_traits::{CanvasMsg, CanvasWebGLMsg... |
}
}
| {
self.is_deleted.set(true);
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteBuffer(self.id))).unwrap();
} | conditional_block |
webglbuffer.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use canvas_traits::{CanvasMsg, CanvasWebGLMsg... | (&self) -> u32 {
self.id
}
// NB: Only valid buffer targets come here
pub fn bind(&self, target: u32) -> WebGLResult<()> {
if let Some(previous_target) = self.target.get() {
if target != previous_target {
return Err(WebGLError::InvalidOperation);
}
... | id | identifier_name |
uniq-cc-generic.rs | // Copyright 2012-2013 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... |
pub fn main() {
let v = empty_pointy();
v.a = p(v);
}
| {
return @mut Pointy {
a : none,
d : make_uniq_closure(~"hi")
}
} | identifier_body |
uniq-cc-generic.rs | // Copyright 2012-2013 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... | use std::ptr;
enum maybe_pointy {
none,
p(@mut Pointy),
}
struct Pointy {
a : maybe_pointy,
d : ~fn() -> uint,
}
fn make_uniq_closure<A:Send>(a: A) -> ~fn() -> uint {
let result: ~fn() -> uint = || ptr::to_unsafe_ptr(&a) as uint;
result
}
fn empty_pointy() -> @mut Pointy {
return @mut Po... | // option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
uniq-cc-generic.rs | // Copyright 2012-2013 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... | {
a : maybe_pointy,
d : ~fn() -> uint,
}
fn make_uniq_closure<A:Send>(a: A) -> ~fn() -> uint {
let result: ~fn() -> uint = || ptr::to_unsafe_ptr(&a) as uint;
result
}
fn empty_pointy() -> @mut Pointy {
return @mut Pointy {
a : none,
d : make_uniq_closure(~"hi")
}
}
pub fn mai... | Pointy | identifier_name |
test_dynamic_repeated_get_set.rs | use protobuf::reflect::FileDescriptor;
use protobuf::reflect::ReflectValueBox;
use super::test_dynamic_repeated_get_set_pb;
fn dynamic_file_descriptor() -> FileDescriptor {
FileDescriptor::new_dynamic(
test_dynamic_repeated_get_set_pb::file_descriptor()
.proto()
.clone(),
V... | do_test_repeated(&test_dynamic_repeated_get_set_pb::file_descriptor());
} | fn dynamic_repeated() { | random_line_split |
test_dynamic_repeated_get_set.rs | use protobuf::reflect::FileDescriptor;
use protobuf::reflect::ReflectValueBox;
use super::test_dynamic_repeated_get_set_pb;
fn dynamic_file_descriptor() -> FileDescriptor {
FileDescriptor::new_dynamic(
test_dynamic_repeated_get_set_pb::file_descriptor()
.proto()
.clone(),
V... | () {
do_test_repeated(&test_dynamic_repeated_get_set_pb::file_descriptor());
}
| dynamic_repeated | identifier_name |
test_dynamic_repeated_get_set.rs | use protobuf::reflect::FileDescriptor;
use protobuf::reflect::ReflectValueBox;
use super::test_dynamic_repeated_get_set_pb;
fn dynamic_file_descriptor() -> FileDescriptor {
FileDescriptor::new_dynamic(
test_dynamic_repeated_get_set_pb::file_descriptor()
.proto()
.clone(),
V... | {
do_test_repeated(&test_dynamic_repeated_get_set_pb::file_descriptor());
} | identifier_body | |
settings.py | import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEBUG = True
ALLOWED_HOSTS = []
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'django_netjsongraph.db',
}
}
SECRET_KEY = 'fn)t*+$)ugeyip6-#txyy$5wf2ervc0d2n#h)qb)y5@ly$t*@w'
INSTALLED_APPS = [
... | 'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler',
},
'main_log': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler',
'formatter': 'verbose',
'filename': os.path.join(BASE_DIR, 'error... | },
'mail_admins': {
'level': 'ERROR', | random_line_split |
quiz-game.component.ts | import { Component, ElementRef, Input, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { BehaviorSubject } from 'rxjs';
import { Question, Quiz, QuizAnswer, QuizResult, QuestionAnswer } from '../../../shared/quiz/quiz';
import { QuizService } from '../../../shared/quiz... | (): void {
this.index++;
this.question = this.innerQuiz.questions[this.index];
this.actionsSubject.next(Action.START);
}
getImageURL(imagePath: string): string {
const index = imagePath.lastIndexOf('/');
const imageId = imagePath.substring(index + 1);
return 'api/images/' + imageId;
}
}
| changeQuestion | identifier_name |
quiz-game.component.ts | import { Component, ElementRef, Input, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { BehaviorSubject } from 'rxjs';
import { Question, Quiz, QuizAnswer, QuizResult, QuestionAnswer } from '../../../shared/quiz/quiz';
import { QuizService } from '../../../shared/quiz... |
this.selectAnswer(value);
this.answerRef.nativeElement.focus();
this.quizGameForm.reset();
}
selectAnswer(answer: string): void {
const questionAnswer = new QuestionAnswer();
questionAnswer.answers.push(answer);
this.quizAnswer.questionAnswers.push(questionAnswer);
if (this.index + 1 <... | {
value = '';
} | conditional_block |
quiz-game.component.ts | import { Component, ElementRef, Input, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { BehaviorSubject } from 'rxjs';
import { Question, Quiz, QuizAnswer, QuizResult, QuestionAnswer } from '../../../shared/quiz/quiz';
import { QuizService } from '../../../shared/quiz... |
}
| {
const index = imagePath.lastIndexOf('/');
const imageId = imagePath.substring(index + 1);
return 'api/images/' + imageId;
} | identifier_body |
quiz-game.component.ts | import { Component, ElementRef, Input, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { BehaviorSubject } from 'rxjs';
import { Question, Quiz, QuizAnswer, QuizResult, QuestionAnswer } from '../../../shared/quiz/quiz';
import { QuizService } from '../../../shared/quiz... | constructor(private fb: FormBuilder, private quizService: QuizService) {
this.quizGameForm = this.fb.group({
answer: '',
});
this.seconds = 10;
this.result = null;
this.index = -1;
this.question = null;
this.quizAnswer = new QuizAnswer();
this.innerQuiz = { id: -1, questions: [] ... | actionsSubject = new BehaviorSubject<Action>(Action.STOP);
seconds: number;
| random_line_split |
htmlmodelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLModElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLModElem... | #[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLModElement> {
let element = HTMLModElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLModElementBinding::Wrap)
... | random_line_split | |
htmlmodelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLModElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLModElem... | {
htmlelement: HTMLElement
}
impl HTMLModElementDerived for EventTarget {
fn is_htmlmodelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLModElement)))
}
}
impl HTMLModElement {
fn new_inherited(localName: ... | HTMLModElement | identifier_name |
htmlmodelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLModElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLModElem... |
}
| {
let element = HTMLModElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLModElementBinding::Wrap)
} | identifier_body |
admin.py | '''
This file is part of pyShop
pyShop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
pyShop is distributed in the hope that it will be us... |
admin.site.register(Product, ProductAdmin)
| '''Contains the admin panel settings for product objects
Currently set to display the name and catergory,
be filterable by catergory
and searchable via name and description.'''
list_display = ('name', 'catergory')
list_filter = ['catergory']
search_fields = ['name', 'description'] | identifier_body |
admin.py | ''' | This file is part of pyShop
pyShop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
pyShop is distributed in the hope that it will be useful... | random_line_split | |
admin.py | '''
This file is part of pyShop
pyShop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
pyShop is distributed in the hope that it will be us... | (admin.ModelAdmin):
'''Contains the admin panel settings for product objects
Currently set to display the name and catergory,
be filterable by catergory
and searchable via name and description.'''
list_display = ('name', 'catergory')
list_filter = ['catergory']
search_fields = ['name', 'description']
admin.site... | ProductAdmin | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import os
from django.core.exceptions import ImproperlyConfigured
from sho... | # Backward compatibility: Find from current directory, if
# LOCAL_SETTINGS_FILE environment variables is unset
if local_settings_file is None:
cand = os.path.join(os.path.dirname(__file__), 'local_settings.py')
if os.path.exists(cand):
local_settings_file = cand
# Load local... | local_settings_file = os.getenv('LOCAL_SETTINGS_FILE')
| random_line_split |
__init__.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import os
from django.core.exceptions import ImproperlyConfigured
from sho... | raise ImproperlyConfigured('No configure in local_settings')
local_configure = local_settings_ns['configure']
local_configure(setup)
return setup
globals().update(Setup.configure(configure))
| base_settings.configure(setup)
local_settings_file = os.getenv('LOCAL_SETTINGS_FILE')
# Backward compatibility: Find from current directory, if
# LOCAL_SETTINGS_FILE environment variables is unset
if local_settings_file is None:
cand = os.path.join(os.path.dirname(__file__), 'local_settings.py... | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import os
from django.core.exceptions import ImproperlyConfigured
from sho... | (setup):
base_settings.configure(setup)
local_settings_file = os.getenv('LOCAL_SETTINGS_FILE')
# Backward compatibility: Find from current directory, if
# LOCAL_SETTINGS_FILE environment variables is unset
if local_settings_file is None:
cand = os.path.join(os.path.dirname(__file__), 'loca... | configure | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import os
from django.core.exceptions import ImproperlyConfigured
from sho... |
return setup
globals().update(Setup.configure(configure))
| local_settings_ns = {
'__file__': local_settings_file,
}
with open(local_settings_file, 'rb') as fp:
compiled = compile(fp.read(), local_settings_file, 'exec')
exec(compiled, local_settings_ns)
if 'configure' not in local_settings_ns:
raise Imprope... | conditional_block |
nevergrad_example.py | """This test checks that Nevergrad is functional.
It also checks that it is usable with a separate scheduler.
"""
import ray
from ray.tune import run
from ray.tune.schedulers import AsyncHyperBandScheduler
from ray.tune.suggest.nevergrad import NevergradSearch
def easy_objective(config, reporter):
import time
... | # With nevergrad v0.2.0+ the following is also possible:
# from nevergrad import instrumentation as inst
# instrumentation = inst.Instrumentation(
# height=inst.var.Array(1).bounded(0, 200).asfloat(),
# width=inst.var.OrderedDiscrete([0, 10, 20, 30, 40, 50]))
# parameter_names = None # ... | import argparse
from nevergrad.optimization import optimizerlib
parser = argparse.ArgumentParser()
parser.add_argument(
"--smoke-test", action="store_true", help="Finish quickly for testing")
args, _ = parser.parse_known_args()
ray.init()
config = {
"num_samples": 10 if args.sm... | conditional_block |
nevergrad_example.py | """This test checks that Nevergrad is functional.
It also checks that it is usable with a separate scheduler.
"""
import ray
from ray.tune import run
from ray.tune.schedulers import AsyncHyperBandScheduler
from ray.tune.suggest.nevergrad import NevergradSearch
def | (config, reporter):
import time
time.sleep(0.2)
for i in range(config["iterations"]):
reporter(
timesteps_total=i,
mean_loss=(config["height"] - 14)**2 - abs(config["width"] - 3))
time.sleep(0.02)
if __name__ == "__main__":
import argparse
from nevergrad.opt... | easy_objective | identifier_name |
nevergrad_example.py | """This test checks that Nevergrad is functional.
It also checks that it is usable with a separate scheduler.
"""
import ray
from ray.tune import run
from ray.tune.schedulers import AsyncHyperBandScheduler
from ray.tune.suggest.nevergrad import NevergradSearch
def easy_objective(config, reporter):
import time
... | import argparse
from nevergrad.optimization import optimizerlib
parser = argparse.ArgumentParser()
parser.add_argument(
"--smoke-test", action="store_true", help="Finish quickly for testing")
args, _ = parser.parse_known_args()
ray.init()
config = {
"num_samples": 10 if arg... |
if __name__ == "__main__": | random_line_split |
nevergrad_example.py | """This test checks that Nevergrad is functional.
It also checks that it is usable with a separate scheduler.
"""
import ray
from ray.tune import run
from ray.tune.schedulers import AsyncHyperBandScheduler
from ray.tune.suggest.nevergrad import NevergradSearch
def easy_objective(config, reporter):
|
if __name__ == "__main__":
import argparse
from nevergrad.optimization import optimizerlib
parser = argparse.ArgumentParser()
parser.add_argument(
"--smoke-test", action="store_true", help="Finish quickly for testing")
args, _ = parser.parse_known_args()
ray.init()
config = {
... | import time
time.sleep(0.2)
for i in range(config["iterations"]):
reporter(
timesteps_total=i,
mean_loss=(config["height"] - 14)**2 - abs(config["width"] - 3))
time.sleep(0.02) | identifier_body |
AnnotationList.tsx | with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you 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... | (
`Are you sure you want to delete ${annotationCurrentlyDeleting?.short_descr}?`,
)}
onConfirm={() => {
if (annotationCurrentlyDeleting) {
handleAnnotationDelete(annotationCurrentlyDeleting);
}
}}
onHide={() => setAnnotationCurren... | t | identifier_name |
AnnotationList.tsx | with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you 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... | );
};
// get the Annotation Layer
useEffect(() => {
fetchAnnotationLayer();
}, [fetchAnnotationLayer]);
const initialSort = [{ id: 'short_descr', desc: true }];
const columns = useMemo(
() => [
{
accessor: 'short_descr',
Header: t('Label'),
},
{
access... | t('There was an issue deleting the selected annotations: %s', errMsg),
),
), | random_line_split |
AnnotationList.tsx | this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you 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/LICE... |
onHide={() => setAnnotationCurrentlyDeleting(null)}
open
title={t('Delete Annotation?')}
/>
)}
<ConfirmStatusChange
title={t('Please confirm')}
description={t(
'Are you sure you want to delete the selected annotations?',
)}
onC... | {() => {
if (annotationCurrentlyDeleting) {
handleAnnotationDelete(annotationCurrentlyDeleting);
}
}} | identifier_body |
AnnotationList.tsx | this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you 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/LICE... |
}}
onHide={() => setAnnotationCurrentlyDeleting(null)}
open
title={t('Delete Annotation?')}
/>
)}
<ConfirmStatusChange
title={t('Please confirm')}
description={t(
'Are you sure you want to delete the selected annotations?',
)... | {
handleAnnotationDelete(annotationCurrentlyDeleting);
} | conditional_block |
pipeNamingRule.js | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Lint = require("tslint");
var sprintf_js_1 =... |
Rule.prototype.apply = function (sourceFile) {
return this.applyWithWalker(new ClassMetadataWalker(sourceFile, this));
};
Rule.prototype.validateName = function (name) {
return this.validator(name);
};
Rule.prototype.validatePrefix = function (prefix) {
return this.prefixChe... | {
var _this = _super.call(this, ruleName, value, disabledIntervals) || this;
if (value[1] === 'camelCase') {
_this.validator = selectorValidator_1.SelectorValidator.camelCase;
}
if (value.length > 2) {
_this.hasPrefix = true;
var prefixExpression = (va... | identifier_body |
pipeNamingRule.js | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Lint = require("tslint");
var sprintf_js_1 =... | (sourceFile, rule) {
var _this = _super.call(this, sourceFile, rule.getOptions()) || this;
_this.rule = rule;
return _this;
}
ClassMetadataWalker.prototype.visitNg2Pipe = function (controller, decorator) {
var className = controller.name.text;
this.validateProperties(clas... | ClassMetadataWalker | identifier_name |
pipeNamingRule.js | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Lint = require("tslint");
var sprintf_js_1 =... | var args = baseExpr.arguments || [];
return args[0];
};
ClassMetadataWalker.prototype.validateProperty = function (className, property) {
var propName = property.initializer.text;
var isValidName = this.rule.validateName(propName);
var isValidPrefix = (this.rule.hasPrefix... | var baseExpr = pipe.expression || {}; | random_line_split |
tag_map.py | # encoding: utf8
from __future__ import unicode_literals
from ..symbols import *
TAG_MAP = {
# Explanation of Unidic tags:
# https://www.gavo.t.u-tokyo.ac.jp/~mine/japanese/nlp+slp/UNIDIC_manual.pdf
# Universal Dependencies Mapping:
# http://universaldependencies.org/ja/overview/morphology.html
#... | "感動詞,一般,*,*": {POS: INTJ},
# this is specifically for unicode full-width space
"空白,*,*,*": {POS: X},
"形状詞,一般,*,*":{POS: ADJ},
"形状詞,タリ,*,*":{POS: ADJ},
"形状詞,助動詞語幹,*,*":{POS: ADJ},
"形容詞,一般,*,*":{POS: ADJ},
"形容詞,非自立可能,*,*":{POS: AUX}, # XXX ADJ if alone, AUX otherwise
"助詞,格助詞,*,*"... |
"記号,一般,*,*":{POS: PUNCT}, # this includes characters used to represent sounds like ドレミ
"記号,文字,*,*":{POS: PUNCT}, # this is for Greek and Latin characters used as sumbols, as in math
"感動詞,フィラー,*,*": {POS: INTJ}, | random_line_split |
dramafever.py | # coding: utf-8
from __future__ import unicode_literals
import itertools
from .amp import AMPIE
from ..compat import (
compat_HTTPError,
compat_urlparse,
)
from ..utils import (
ExtractorError,
clean_html,
int_or_none,
sanitized_Request,
urlencode_postdata
)
class DramaFeverBaseIE(AMPIE)... |
class DramaFeverIE(DramaFeverBaseIE):
IE_NAME = 'dramafever'
_VALID_URL = r'https?://(?:www\.)?dramafever\.com/drama/(?P<id>[0-9]+/[0-9]+)(?:/|$)'
_TESTS = [{
'url': 'http://www.dramafever.com/drama/4512/1/Cooking_with_Shin/',
'info_dict': {
'id': '4512.1',
'ext': ... | error = self._html_search_regex(
r'(?s)class="hidden-xs prompt"[^>]*>(.+?)<',
response, 'error message', default=None)
if error:
raise ExtractorError('Unable to login: %s' % error, expected=True)
raise ExtractorError('Unable to log in') | conditional_block |
dramafever.py | # coding: utf-8
from __future__ import unicode_literals
import itertools
from .amp import AMPIE
from ..compat import (
compat_HTTPError,
compat_urlparse,
)
from ..utils import (
ExtractorError,
clean_html,
int_or_none,
sanitized_Request,
urlencode_postdata
)
class DramaFeverBaseIE(AMPIE)... | self._LOGIN_URL, urlencode_postdata(login_form))
response = self._download_webpage(
request, None, 'Logging in as %s' % username)
if all(logout_pattern not in response
for logout_pattern in ['href="/accounts/logout/"', '>Log out<']):
error = self._html... | random_line_split | |
dramafever.py | # coding: utf-8
from __future__ import unicode_literals
import itertools
from .amp import AMPIE
from ..compat import (
compat_HTTPError,
compat_urlparse,
)
from ..utils import (
ExtractorError,
clean_html,
int_or_none,
sanitized_Request,
urlencode_postdata
)
class DramaFeverBaseIE(AMPIE)... |
def _login(self):
(username, password) = self._get_login_info()
if username is None:
return
login_form = {
'username': username,
'password': password,
}
request = sanitized_Request(
self._LOGIN_URL, urlencode_postdata(login_f... | _LOGIN_URL = 'https://www.dramafever.com/accounts/login/'
_NETRC_MACHINE = 'dramafever'
_CONSUMER_SECRET = 'DA59dtVXYLxajktV'
_consumer_secret = None
def _get_consumer_secret(self):
mainjs = self._download_webpage(
'http://www.dramafever.com/static/51afe95/df2014/scripts/main.js',... | identifier_body |
dramafever.py | # coding: utf-8
from __future__ import unicode_literals
import itertools
from .amp import AMPIE
from ..compat import (
compat_HTTPError,
compat_urlparse,
)
from ..utils import (
ExtractorError,
clean_html,
int_or_none,
sanitized_Request,
urlencode_postdata
)
class DramaFeverBaseIE(AMPIE)... | (self):
mainjs = self._download_webpage(
'http://www.dramafever.com/static/51afe95/df2014/scripts/main.js',
None, 'Downloading main.js', fatal=False)
if not mainjs:
return self._CONSUMER_SECRET
return self._search_regex(
r"var\s+cs\s*=\s*'([^']+)'"... | _get_consumer_secret | identifier_name |
hmacsha256sign-tests.js | //
// Copyright (c) Microsoft and contributors. 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 requi... | //
var should = require('should');
// Test includes
var testutil = require('../util/util');
// Lib includes
var HmacSha256Sign = testutil.libRequire('common/lib/services/hmacsha256sign');
var sharedkey;
describe('hmacsha256sign', function () {
it('should sign correctly', function (done) {
var hmacSha256Sign... | // distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License. | random_line_split |
bin_spike.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
"""
import numpy as np
from numpy import ma
def bin_spike(x, l):
""" | Maybe use pstsd instead?
Dummy way to avoid warnings when x[ini:fin] are all masked.
Improve this in the future.
"""
assert x.ndim == 1, "I'm not ready to deal with multidimensional x"
assert l%2 == 0, "l must be an even integer"
N = len(x)
bin = ma.masked_all(N)
# bin... |
l is the number of points used for comparison, thus l=2 means that each
point will be compared only against the previous and following
measurements. l=2 is is probably not a good choice, too small.
| random_line_split |
bin_spike.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
"""
import numpy as np
from numpy import ma
def bin_spike(x, l):
"""
l is the number of points used for comparison, thus l=2 means that each
point will be compared only against t... |
return bin
class Bin_Spike(object):
def __init__(self, data, varname, cfg, autoflag=True):
self.data = data
self.varname = varname
self.cfg = cfg
self.set_features()
if autoflag:
self.test()
def keys(self):
return self.features.keys() + \
... | bin[i] = x[i] - ma.median(x[ini:fin])
# bin_std[i] = (np.append(x[ini:i], x[i+1:fin+1])).std()
bin[i] /= (np.append(x[ini:i], x[i+1:fin+1])).std() | conditional_block |
bin_spike.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
"""
import numpy as np
from numpy import ma
def bin_spike(x, l):
"""
l is the number of points used for comparison, thus l=2 means that each
point will be compared only against t... |
def test(self):
self.flags = {}
try:
threshold = self.cfg['threshold']
except:
print("Deprecated cfg format. It should contain a threshold item.")
threshold = self.cfg
try:
flag_good = self.cfg['flag_good']
flag_bad = sel... | self.features = {'bin_spike': bin_spike(self.data[self.varname],
self.cfg['l'])} | identifier_body |
bin_spike.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
"""
import numpy as np
from numpy import ma
def bin_spike(x, l):
"""
l is the number of points used for comparison, thus l=2 means that each
point will be compared only against t... | (self, data, varname, cfg, autoflag=True):
self.data = data
self.varname = varname
self.cfg = cfg
self.set_features()
if autoflag:
self.test()
def keys(self):
return self.features.keys() + \
["flag_%s" % f for f in self.flags.keys()]
def... | __init__ | identifier_name |
IceLance.tsx | import React from 'react';
import SPELLS from 'common/SPELLS';
import { SpellLink } from 'interface';
import { formatPercentage } from 'common/format';
import Statistic from 'parser/ui/Statistic';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';... |
onFingersStackChange(event: ChangeBuffStackEvent) {
// FoF overcaps don't show as a refreshbuff, instead they are a stack lost followed immediately by a gain
const stackChange = event.stacksGained;
if (stackChange > 0) {
this.totalFingersProcs += stackChange;
} else if (this.iceLanceCastTimest... | {
const damageTarget = encodeTargetString(event.targetID, event.targetInstance);
if (this.iceLanceTargetId !== damageTarget) {
return;
}
//If the player has Glacial Fragments, Blizzard is active (checking its CD because the spell lasts as long as it's cooldown), and the target is in a Blizzard, t... | identifier_body |
IceLance.tsx | import React from 'react';
import SPELLS from 'common/SPELLS';
import { SpellLink } from 'interface';
import { formatPercentage } from 'common/format';
import Statistic from 'parser/ui/Statistic';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';... |
this.hadFingersProc = false;
if (this.selectedCombatant.hasBuff(SPELLS.FINGERS_OF_FROST.id)) {
this.hadFingersProc = true;
}
}
onDamage(event: DamageEvent) {
const damageTarget = encodeTargetString(event.targetID, event.targetInstance);
if (this.iceLanceTargetId !== damageTarget) {
... | {
this.iceLanceTargetId = encodeTargetString(event.targetID, event.targetInstance);
} | conditional_block |
IceLance.tsx | import React from 'react';
import SPELLS from 'common/SPELLS';
import { SpellLink } from 'interface';
import { formatPercentage } from 'common/format';
import Statistic from 'parser/ui/Statistic';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';... | }
}
onFingersStackChange(event: ChangeBuffStackEvent) {
// FoF overcaps don't show as a refreshbuff, instead they are a stack lost followed immediately by a gain
const stackChange = event.stacksGained;
if (stackChange > 0) {
this.totalFingersProcs += stackChange;
} else if (this.iceLanceC... |
const enemy = this.enemies.getEntity(event);
if (enemy && !SHATTER_DEBUFFS.some(effect => enemy.hasBuff(effect.id, event.timestamp)) && !this.hadFingersProc) {
this.nonShatteredCasts += 1; | random_line_split |
IceLance.tsx | import React from 'react';
import SPELLS from 'common/SPELLS';
import { SpellLink } from 'interface';
import { formatPercentage } from 'common/format';
import Statistic from 'parser/ui/Statistic';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';... | () {
return 1 - (this.nonShatteredCasts / this.abilityTracker.getAbility(SPELLS.ICE_LANCE.id).casts);
}
get fingersProcUtilizationThresholds() {
return {
actual: 1 - (this.wastedFingersProcs / this.totalFingersProcs) || 0,
isLessThan: {
minor: 0.95,
average: 0.85,
major:... | shatteredPercent | identifier_name |
mod.rs | //! Parse an ICAL calendar.
//!
//! Wrap the result of the `PropertyParser` into components.
//!
//! Each component contains properties (ie: `Property`) or sub-components.
//!
//! * The `VcardParser` return `IcalCalendar` objects.
//!
//! # Examples
//!
//!
//! ```toml
//! [dependencies.ical]
//! version = "0.3.*"
//! ... | //! for line in reader {
//! println!("{:?}", line);
//! }
//! ```
pub mod component;
// Sys mods.
use std::cell::RefCell;
use std::io::BufRead;
// Internal mods
use crate::line::LineReader;
use crate::parser::{Component, ParserError};
use crate::property::PropertyParser;
/// Reader returning `IcalCalendar` obj... | //! let buf = BufReader::new(File::open("./tests/ressources/ical_input.ics")
//! .unwrap());
//!
//! let reader = ical::IcalParser::new(buf);
//! | random_line_split |
mod.rs | //! Parse an ICAL calendar.
//!
//! Wrap the result of the `PropertyParser` into components.
//!
//! Each component contains properties (ie: `Property`) or sub-components.
//!
//! * The `VcardParser` return `IcalCalendar` objects.
//!
//! # Examples
//!
//!
//! ```toml
//! [dependencies.ical]
//! version = "0.3.*"
//! ... | <B> {
line_parser: RefCell<PropertyParser<B>>,
}
impl<B: BufRead> IcalParser<B> {
/// Return a new `IcalParser` from a `Reader`.
pub fn new(reader: B) -> IcalParser<B> {
let line_reader = LineReader::new(reader);
let line_parser = PropertyParser::new(line_reader);
IcalParser {
... | IcalParser | identifier_name |
mod.rs | //! Parse an ICAL calendar.
//!
//! Wrap the result of the `PropertyParser` into components.
//!
//! Each component contains properties (ie: `Property`) or sub-components.
//!
//! * The `VcardParser` return `IcalCalendar` objects.
//!
//! # Examples
//!
//!
//! ```toml
//! [dependencies.ical]
//! version = "0.3.*"
//! ... |
}
| {
match self.check_header() {
Ok(res) => {
if res == None {
return None;
}
}
Err(err) => return Some(Err(err)),
};
let mut calendar = component::IcalCalendar::new();
let result = match calendar.parse... | identifier_body |
Ready.ts | import { Arr } from '@ephox/katamari';
import { SugarElement } from '../node/SugarElement';
import * as DomEvent from './DomEvent';
const documentReady = (f: () => void): void => {
/*
* We only use this in one place, so creating one listener per ready request is more optimal than managing
* a single event wit... |
};
const image = (image: SugarElement<HTMLImageElement>): Promise<SugarElement<HTMLImageElement>> => new Promise((resolve, reject) => {
const loaded = () => {
destroy();
resolve(image);
};
const listeners = [
DomEvent.bind(image, 'load', loaded),
DomEvent.bind(image, 'error', () => {
destr... | {
// Note that this fires when DOM manipulation is allowed, but before all resources are
// available. This is the best practice but might be a bit weird.
const listener = DomEvent.bind(SugarElement.fromDom(document), 'DOMContentLoaded', () => { // IE9 minimum
f();
listener.unbind();
});
} | conditional_block |
Ready.ts | import { Arr } from '@ephox/katamari';
import { SugarElement } from '../node/SugarElement';
import * as DomEvent from './DomEvent';
const documentReady = (f: () => void): void => {
/*
* We only use this in one place, so creating one listener per ready request is more optimal than managing
* a single event wit... | f();
listener.unbind();
});
}
};
const image = (image: SugarElement<HTMLImageElement>): Promise<SugarElement<HTMLImageElement>> => new Promise((resolve, reject) => {
const loaded = () => {
destroy();
resolve(image);
};
const listeners = [
DomEvent.bind(image, 'load', loaded),
Do... | } else {
// Note that this fires when DOM manipulation is allowed, but before all resources are
// available. This is the best practice but might be a bit weird.
const listener = DomEvent.bind(SugarElement.fromDom(document), 'DOMContentLoaded', () => { // IE9 minimum | random_line_split |
signin.component.ts | import {Component, Input, Output, EventEmitter} from '@angular/core';
import { Alien } from '../../../models/index';
import { AuthService } from '../../../services/auth.service';
import { Router } from '@angular/router';
import {DisplayService} from '../../../services/display.service';
import {Config} from '../../../co... | })
.catch((err) => {
this.handleErrorLogin(err);
});
}
private handleErrorLogin(err) {
const errorCode = err.json()[0].errorCode;
if (errorCode === 'Unauthorized') {
this.error = 'Les données que vous avez entré sont incorrects';
setTimeout(() => {this.error = '';}, 40... | this.error = 'Bienvenue '.concat(alien.json().nickname).concat(' !'); | random_line_split |
signin.component.ts | import {Component, Input, Output, EventEmitter} from '@angular/core';
import { Alien } from '../../../models/index';
import { AuthService } from '../../../services/auth.service';
import { Router } from '@angular/router';
import {DisplayService} from '../../../services/display.service';
import {Config} from '../../../co... | }
displayLogin() {
return this.swipeValue;
}
swip() {
var btnclick = document.querySelector('#SingIn-animat').classList;
btnclick.add('SingIn-animat');
this.onSwipe.emit(!this.swipeValue);
setTimeout(() => {
btnclick.remove('SingIn-animat');
}, 1000);
}
}
| const errors = JSON.parse(err._body);
this.error = errors[0]['message'][Config.getSelectedErrorsLanguage()];
setTimeout(() => {this.error = '';}, 4000);
}
| conditional_block |
signin.component.ts | import {Component, Input, Output, EventEmitter} from '@angular/core';
import { Alien } from '../../../models/index';
import { AuthService } from '../../../services/auth.service';
import { Router } from '@angular/router';
import {DisplayService} from '../../../services/display.service';
import {Config} from '../../../co... |
private handleErrorLogin(err) {
const errorCode = err.json()[0].errorCode;
if (errorCode === 'Unauthorized') {
this.error = 'Les données que vous avez entré sont incorrects';
setTimeout(() => {this.error = '';}, 4000);
} else {
const errors = JSON.parse(err._body);
this.error = e... | {
this.alien.email = this.alien.email.toLowerCase();
this.auth.login(this.alien)
.then((alien) => {
this.auth.setAlienInLocalStorage(alien.json().user);
this.displayService.setShowHeader(true);
this.router.navigate(['/home']);
this.error = 'Bienvenue '.concat(alien.json().n... | identifier_body |
signin.component.ts | import {Component, Input, Output, EventEmitter} from '@angular/core';
import { Alien } from '../../../models/index';
import { AuthService } from '../../../services/auth.service';
import { Router } from '@angular/router';
import {DisplayService} from '../../../services/display.service';
import {Config} from '../../../co... | {
var btnclick = document.querySelector('#SingIn-animat').classList;
btnclick.add('SingIn-animat');
this.onSwipe.emit(!this.swipeValue);
setTimeout(() => {
btnclick.remove('SingIn-animat');
}, 1000);
}
}
| ip() | identifier_name |
chat-message.component.ts | import { animate, keyframes, style, transition, trigger } from '@angular/animations';
import { AfterViewInit, ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core';
import { ChatMessage } from '@udonarium/chat-message';
import { ImageFile } from '@udonarium/core/file-storage/image-file';
import { Ch... |
discloseMessage() {
this.chatMessage.tag = this.chatMessage.tag.replace('secret', '');
}
} | ngAfterViewInit() {
} | random_line_split |
chat-message.component.ts | import { animate, keyframes, style, transition, trigger } from '@angular/animations';
import { AfterViewInit, ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core';
import { ChatMessage } from '@udonarium/chat-message';
import { ImageFile } from '@udonarium/core/file-storage/image-file';
import { Ch... |
}
| {
this.chatMessage.tag = this.chatMessage.tag.replace('secret', '');
} | identifier_body |
chat-message.component.ts | import { animate, keyframes, style, transition, trigger } from '@angular/animations';
import { AfterViewInit, ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core';
import { ChatMessage } from '@udonarium/chat-message';
import { ImageFile } from '@udonarium/core/file-storage/image-file';
import { Ch... | () {
}
discloseMessage() {
this.chatMessage.tag = this.chatMessage.tag.replace('secret', '');
}
}
| ngAfterViewInit | identifier_name |
ll.ui.slickslide.1.0.0.js | $(document).ready(function(){
var currentPosition = 0;
var slideWidth = 560;
var slides = $('.slide');
var numberOfSlides = slides.length;
// Remove scrollbar in JS
$('#slidesContainer').css('overflow', 'hidden');
// Wrap all .slides with #slideInner div
slides
.wrapAll('<div id="slideInner"></div... | else{ $('#leftControl').show() }
// Hide right arrow if position is last slide
if(position==numberOfSlides-1){ $('#rightControl').hide() } else{ $('#rightControl').show() }
}
}); | { $('#leftControl').hide() } | conditional_block |
ll.ui.slickslide.1.0.0.js | $(document).ready(function(){
var currentPosition = 0;
var slideWidth = 560;
var slides = $('.slide');
var numberOfSlides = slides.length;
// Remove scrollbar in JS
$('#slidesContainer').css('overflow', 'hidden');
// Wrap all .slides with #slideInner div
slides
.wrapAll('<div id="slideInner"></div... |
}); | {
// Hide left arrow if position is first slide
if(position==0){ $('#leftControl').hide() } else{ $('#leftControl').show() }
// Hide right arrow if position is last slide
if(position==numberOfSlides-1){ $('#rightControl').hide() } else{ $('#rightControl').show() }
} | identifier_body |
ll.ui.slickslide.1.0.0.js | $(document).ready(function(){
var currentPosition = 0;
var slideWidth = 560;
var slides = $('.slide');
var numberOfSlides = slides.length;
// Remove scrollbar in JS
$('#slidesContainer').css('overflow', 'hidden');
// Wrap all .slides with #slideInner div
slides
.wrapAll('<div id="slideInner"></div... |
// Insert controls in the DOM
$('#slideshow')
.prepend('<span class="control" id="leftControl">Clicking moves left</span>')
.append('<span class="control" id="rightControl">Clicking moves right</span>');
// Hide left arrow control on first load
manageControls(currentPosition);
// Create event liste... | 'width' : slideWidth
});
// Set #slideInner width equal to total width of all slides
$('#slideInner').css('width', slideWidth * numberOfSlides); | random_line_split |
ll.ui.slickslide.1.0.0.js | $(document).ready(function(){
var currentPosition = 0;
var slideWidth = 560;
var slides = $('.slide');
var numberOfSlides = slides.length;
// Remove scrollbar in JS
$('#slidesContainer').css('overflow', 'hidden');
// Wrap all .slides with #slideInner div
slides
.wrapAll('<div id="slideInner"></div... | (position){
// Hide left arrow if position is first slide
if(position==0){ $('#leftControl').hide() } else{ $('#leftControl').show() }
// Hide right arrow if position is last slide
if(position==numberOfSlides-1){ $('#rightControl').hide() } else{ $('#rightControl').show() }
}
}); | manageControls | identifier_name |
mediaViewer.js | const React = require('react')
const SUPPORTED_VIDEO_EXTENSIONS = [
'm4v',
'mkv',
'mov',
'mp4', |
const SUPPORTED_AUDIO_EXTENSIONS = [
'aac',
'mp3',
'ogg',
'wav',
'm4a'
]
module.exports = class MediaViewer extends React.Component {
render () {
const torrent = this.props.torrent
const ix = this.props.ix
const file = torrent.files[ix]
const fileExt = file && getExtension(file.name)
c... | 'ogv',
'webm'
] | random_line_split |
mediaViewer.js | const React = require('react')
const SUPPORTED_VIDEO_EXTENSIONS = [
'm4v',
'mkv',
'mov',
'mp4',
'ogv',
'webm'
]
const SUPPORTED_AUDIO_EXTENSIONS = [
'aac',
'mp3',
'ogg',
'wav',
'm4a'
]
module.exports = class MediaViewer extends React.Component {
render () | }
return (
<div className='mediaViewer'>
{content}
</div>
)
}
}
// Given 'foo.txt', returns 'txt'
// Given eg. null, undefined, '', or 'README', returns null
function getExtension (filename) {
if (!filename) return null
const ix = filename.lastIndexOf('.')
if (ix < 0) return n... | {
const torrent = this.props.torrent
const ix = this.props.ix
const file = torrent.files[ix]
const fileExt = file && getExtension(file.name)
const isVideo = SUPPORTED_VIDEO_EXTENSIONS.includes(fileExt)
const isAudio = SUPPORTED_AUDIO_EXTENSIONS.includes(fileExt)
const fileURL = torrent.serve... | identifier_body |
mediaViewer.js | const React = require('react')
const SUPPORTED_VIDEO_EXTENSIONS = [
'm4v',
'mkv',
'mov',
'mp4',
'ogv',
'webm'
]
const SUPPORTED_AUDIO_EXTENSIONS = [
'aac',
'mp3',
'ogg',
'wav',
'm4a'
]
module.exports = class MediaViewer extends React.Component {
| () {
const torrent = this.props.torrent
const ix = this.props.ix
const file = torrent.files[ix]
const fileExt = file && getExtension(file.name)
const isVideo = SUPPORTED_VIDEO_EXTENSIONS.includes(fileExt)
const isAudio = SUPPORTED_AUDIO_EXTENSIONS.includes(fileExt)
const fileURL = torrent.s... | render | identifier_name |
list.js | /************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko
* Website: http://www.espocrm.com
*
* EspoCRM is free software: you can redistribute it and... | Espo.define('Views.ScheduledJob.List', 'Views.List', function (Dep) {
return Dep.extend({
searchPanel: false,
setup: function () {
Dep.prototype.setup.call(this);
this.createView('search', 'Base', {
el: '#main > .search-container',
template: 'scheduled-job.cronjob'
});
},
a... | * GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/ | random_line_split |
validators.py | from django.core.exceptions import ValidationError
from pyparsing import ParseBaseException
from django.core.validators import MaxLengthValidator
class ParamValidator(object):
def __init__(self, file_support=False):
self._file_support = file_support
def __call__(self, value):
# Impor... | (MaxLengthValidator):
def clean(self, x):
return len(str(x))
class ParamFormFieldValidator(object):
def __init__(self, param):
self._param = param
def __call__(self, value):
try:
self._param.validate(value)
except ValueError as err:
raise Val... | ParamLengthValidator | identifier_name |
validators.py | from django.core.exceptions import ValidationError
from pyparsing import ParseBaseException
from django.core.validators import MaxLengthValidator
class ParamValidator(object):
def __init__(self, file_support=False):
self._file_support = file_support
def __call__(self, value):
# Impor... | # Error while creating Param
raise ValidationError(str(err))
class ParamLengthValidator(MaxLengthValidator):
def clean(self, x):
return len(str(x))
class ParamFormFieldValidator(object):
def __init__(self, param):
self._param = param
def __call__(self, va... | except ParseBaseException as err:
# Parser Error
raise ValidationError(str(err))
except ValueError as err: | random_line_split |
validators.py | from django.core.exceptions import ValidationError
from pyparsing import ParseBaseException
from django.core.validators import MaxLengthValidator
class ParamValidator(object):
def __init__(self, file_support=False):
self._file_support = file_support
def __call__(self, value):
# Impor... |
class ParamFormFieldValidator(object):
def __init__(self, param):
self._param = param
def __call__(self, value):
try:
self._param.validate(value)
except ValueError as err:
raise ValidationError(err)
except TypeError as err:
raise Validati... | def clean(self, x):
return len(str(x)) | identifier_body |
plupload.js | (function($) {
Drupal.plupload = Drupal.plupload || {};
/**
* Attaches the Plupload behavior to each FileField Sources Plupload form element.
*/
Drupal.behaviors.filefield_sources_plupload = {
attach: function (context, settings) {
$(".filefield-source-plupload .plupload-element", context).once('ffs-... | $submit.bind('click', function(e) {
e.preventDefault();
uploader.bind('StateChanged', function() {
if (uploader.total.uploaded == uploader.files.length) {
// Custom ajax trigger
$submit.trigger('pud_update');
}
});
if (uploader.... | }
}
});
| random_line_split |
plupload.js | (function($) {
Drupal.plupload = Drupal.plupload || {};
/**
* Attaches the Plupload behavior to each FileField Sources Plupload form element.
*/
Drupal.behaviors.filefield_sources_plupload = {
attach: function (context, settings) {
$(".filefield-source-plupload .plupload-element", context).once('ffs-... |
});
$submit.bind('click', function(e) {
e.preventDefault();
uploader.bind('StateChanged', function() {
if (uploader.total.uploaded == uploader.files.length) {
// Custom ajax trigger
$submit.trigger('pud_update');
}
});
... | {
// Remove files exceeding the cardinality setting.
if (uploader.files.length >= pluploadSettings.cardinality) {
var i = 0;
for (i=0;i<uploader.files.length;i++) {
if (i >= pluploadSettings.cardinality) {
uploader.removeFile(uploader.files... | conditional_block |
model_store.py | the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding: utf-8
"""Model zoo for pre-trained models."""
__all__ = ['get_model_file', 'pur... | sha1_hash = _model_sha1[name]
if os.path.exists(file_path):
if check_sha1(file_path, sha1_hash):
return file_path
else:
logging.warning('Mismatch in the content of model file detected. Downloading again.')
else:
logging.info('Model file not found. Downloading ... | random_line_split | |
model_store.py | the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding: utf-8
"""Model zoo for pre-trained models."""
__all__ = ['get_model_file', 'pur... | file_path = os.path.join(root, file_name+'.params')
sha1_hash = _model_sha1[name]
if os.path.exists(file_path):
if check_sha1(file_path, sha1_hash):
return file_path
else:
logging.warning('Mismatch in the content of model file detected. Downloading again.')
else:
... | r"""Return location for the pretrained on local file system.
This function will download from online model zoo when model cannot be found or has mismatch.
The root directory will be created if it doesn't exist.
Parameters
----------
name : str
Name of the model.
root : str, default $MX... | identifier_body |
model_store.py | the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding: utf-8
"""Model zoo for pre-trained models."""
__all__ = ['get_model_file', 'pur... | (name, root=os.path.join(base.data_dir(), 'models')):
r"""Return location for the pretrained on local file system.
This function will download from online model zoo when model cannot be found or has mismatch.
The root directory will be created if it doesn't exist.
Parameters
----------
name : ... | get_model_file | identifier_name |
model_store.py | specific language governing permissions and limitations
# under the License.
# coding: utf-8
"""Model zoo for pre-trained models."""
__all__ = ['get_model_file', 'purge']
import os
import zipfile
import logging
import tempfile
import uuid
import shutil
from ..utils import download, check_sha1, replace_file
from ... ... | repo_url = repo_url + '/' | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.