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 |
|---|---|---|---|---|
syntax_iterators.py | from typing import Union, Iterator
from ...symbols import NOUN, PROPN, PRON
from ...errors import Errors
from ...tokens import Doc, Span
def noun_chunks(doclike: Union[Doc, Span]) -> Iterator[Span]:
| prev_end = word.right_edge.i
yield word.left_edge.i, word.right_edge.i + 1, np_label
elif word.dep == conj:
head = word.head
while head.dep == conj and head.head.i < head.i:
head = head.head
# If the head is an NP, and we're coordinated... | """
Detect base noun phrases from a dependency parse. Works on both Doc and Span.
"""
# fmt: off
labels = ["nsubj", "nsubj:pass", "obj", "iobj", "ROOT", "appos", "nmod", "nmod:poss"]
# fmt: on
doc = doclike.doc # Ensure works on both Doc and Span.
if not doc.has_annotation("DEP"):
r... | identifier_body |
syntax_iterators.py | from typing import Union, Iterator
from ...symbols import NOUN, PROPN, PRON
from ...errors import Errors
from ...tokens import Doc, Span
def noun_chunks(doclike: Union[Doc, Span]) -> Iterator[Span]:
"""
Detect base noun phrases from a dependency parse. Works on both Doc and Span.
"""
# fmt: off
l... | while head.dep == conj and head.head.i < head.i:
head = head.head
# If the head is an NP, and we're coordinated to it, we're an NP
if head.dep in np_deps:
prev_end = word.right_edge.i
yield word.left_edge.i, word.right_edge.i + 1, np_la... | if word.dep in np_deps:
prev_end = word.right_edge.i
yield word.left_edge.i, word.right_edge.i + 1, np_label
elif word.dep == conj:
head = word.head | random_line_split |
syntax_iterators.py | from typing import Union, Iterator
from ...symbols import NOUN, PROPN, PRON
from ...errors import Errors
from ...tokens import Doc, Span
def | (doclike: Union[Doc, Span]) -> Iterator[Span]:
"""
Detect base noun phrases from a dependency parse. Works on both Doc and Span.
"""
# fmt: off
labels = ["nsubj", "nsubj:pass", "obj", "iobj", "ROOT", "appos", "nmod", "nmod:poss"]
# fmt: on
doc = doclike.doc # Ensure works on both Doc and Sp... | noun_chunks | identifier_name |
lib.rs | crate serde;
#[macro_use]
extern crate serde_derive;
use std::cmp::{self, max, min};
use std::fmt;
use std::iter;
use std::marker::PhantomData;
use std::ops;
pub trait Int:
Copy
+ ops::Add<Self, Output=Self>
+ ops::Sub<Self, Output=Self>
+ cmp::Ord
{
fn zero() -> Self;
fn one() -> Self;
f... | (self) -> usize { self }
}
/// Implements a range index type with operator overloads
#[macro_export]
macro_rules! int_range_index {
($(#[$attr:meta])* struct $Self_:ident($T:ty)) => (
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)]
$(#[$attr])*
pub struct $Self_(pub $T);
... | get | identifier_name |
lib.rs | fn zero() -> isize { 0 }
#[inline]
fn one() -> isize { 1 }
#[inline]
fn max_value() -> isize { ::std::isize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<isize> { num_traits::NumCast::from(n) }
}
impl Int for usize {
#[inline]
fn zero() -> usize { 0 }
#[inline]
fn one() ... | {
Range::empty()
} | conditional_block | |
lib.rs | crate serde;
#[macro_use]
extern crate serde_derive;
use std::cmp::{self, max, min};
use std::fmt;
use std::iter;
use std::marker::PhantomData;
use std::ops;
pub trait Int:
Copy
+ ops::Add<Self, Output=Self>
+ ops::Sub<Self, Output=Self>
+ cmp::Ord
{
fn zero() -> Self;
fn one() -> Self;
f... | self.length() == Int::zero()
}
/// Shift the entire range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - +============+ - - - - - | - - - ->
/// |
/// <- o ... | }
/// `true` if the offset from the beginning to the end of the range is zero.
#[inline]
pub fn is_empty(&self) -> bool { | random_line_split |
lib.rs | crate serde;
#[macro_use]
extern crate serde_derive;
use std::cmp::{self, max, min};
use std::fmt;
use std::iter;
use std::marker::PhantomData;
use std::ops;
pub trait Int:
Copy
+ ops::Add<Self, Output=Self>
+ ops::Sub<Self, Output=Self>
+ cmp::Ord
{
fn zero() -> Self;
fn one() -> Self;
f... |
#[inline]
fn one() -> usize { 1 }
#[inline]
fn max_value() -> usize { ::std::usize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<usize> { Some(n) }
}
/// An index type to be used by a `Range`
pub trait RangeIndex: Int + fmt::Debug {
type Index;
fn new(x: Self::Index) -> Self;
... | { 0 } | identifier_body |
challenge.service.ts | import { Injectable } from '@angular/core';
import {BaseCrudService} from "./base-crud.service";
import {Observable} from "rxjs/Observable";
import {Ladder, LadderUser} from "./ladder.service";
import {User} from "./users.service";
@Injectable()
export class ChallengeService extends BaseCrudService<Challenge> {
url... |
}
export interface LadderNode extends Ladder {
above: LadderUser[],
below: LadderUser[]
}
export interface Challenge {
id: number;
name: string;
created: Date;
status: string; // PROPOSED, ACCEPTED, REJECTED, CLOSED
dateTime: Date;
dateTimeEnd: Date;
challengerId: number;
challengedId: number;
... | {
return this.http.get<LadderNode[]>(this.url);
} | identifier_body |
challenge.service.ts | import { Injectable } from '@angular/core';
import {BaseCrudService} from "./base-crud.service";
import {Observable} from "rxjs/Observable";
import {Ladder, LadderUser} from "./ladder.service";
import {User} from "./users.service";
@Injectable()
export class ChallengeService extends BaseCrudService<Challenge> {
url... | name: string;
created: Date;
status: string; // PROPOSED, ACCEPTED, REJECTED, CLOSED
dateTime: Date;
dateTimeEnd: Date;
challengerId: number;
challengedId: number;
scoreChallenger: number;
scoreChallenged: number;
} | random_line_split | |
challenge.service.ts | import { Injectable } from '@angular/core';
import {BaseCrudService} from "./base-crud.service";
import {Observable} from "rxjs/Observable";
import {Ladder, LadderUser} from "./ladder.service";
import {User} from "./users.service";
@Injectable()
export class ChallengeService extends BaseCrudService<Challenge> {
url... | (ladder : Ladder, challenge : Challenge): Observable<Challenge> {
return this.http.post<Challenge>(this.url + "/" + ladder.id, challenge);
}
public putChallenge(challenge : Challenge) {
return this.http.put<Challenge>(this.url + "/" + challenge.id, challenge);
}
public getAvailableChallenges() {
r... | postChallenge | identifier_name |
highlight.rs | // Copyright 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-MIT or ... | (src: &str, class: Option<&str>, id: Option<&str>) -> String {
debug!("highlighting: ================\n{}\n==============", src);
let sess = parse::new_parse_sess();
let fm = parse::string_to_filemap(&sess,
src.to_string(),
"<stdin>... | highlight | identifier_name |
highlight.rs | // Copyright 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-MIT or ... | t::LIT_BYTE(..) | t::LIT_BINARY(..) | t::LIT_BINARY_RAW(..) |
t::LIT_CHAR(..) | t::LIT_STR(..) | t::LIT_STR_RAW(..) => "string",
// number literals
t::LIT_INTEGER(..) | t::LIT_FLOAT(..) => "number",
// keywords are also included in the identifier set
... | }
}
// text literals | random_line_split |
highlight.rs | // Copyright 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-MIT or ... |
/// Exhausts the `lexer` writing the output into `out`.
///
/// The general structure for this method is to iterate over each token,
/// possibly giving it an HTML span with a class specifying what flavor of token
/// it's used. All source code emission is done as slices from the source map,
/// not from the tokens t... | {
debug!("highlighting: ================\n{}\n==============", src);
let sess = parse::new_parse_sess();
let fm = parse::string_to_filemap(&sess,
src.to_string(),
"<stdin>".to_string());
let mut out = io::MemWriter::new();
... | identifier_body |
work.en.ts | export const work_en = `
# [Meituan-Dianping](http://meituan.com/)
## Web Frontend Developer
## 2015.10 - now
### Take part in developing the web applications for Meituan Dianping restaurant menu order business, including hybrid web applications, PC web applications.
### Designed and developed the client side code for... | ### Embedded software development. Developed the tcp/udp server and client on pc and cortex m3 using the lwip protocal.
`; |
# [Changchun Institute of Applied Chemistry](http://www.ciac.jl.cn/)
## Software Development Intern
## 2013.04 - 2013.09 | random_line_split |
model_eval.py | import os
import argparse
import re
import numpy as np
from model import *
np.random.seed(1337)
def get_engine(address = "postgresql+pg8000://script@localhost:5432/ccfd"):
# disk_engine = create_engine('sqlite:///'+data_dir+db_name,convert_unicode=True)
# disk_engine.raw_connection().connection.text_factory =... |
def eval_best_val(table):
#populate dictionary
directory = ModelLoader.w_dir.format(table=table)
print 'evaluating path @'
for root, dirs, files in os.walk(directory):
names = {}
for f in files:
# print f
m = re.search('\.[0-9]+-',f)
name_end = m.s... | m = re.search('-[0-9]+\.[0-9]+\.hdf5',f_name)
start = m.span()[0]+1
end = m.span()[1]-5
return float(f_name[start:end]) | identifier_body |
model_eval.py | import os
import argparse
import re
import numpy as np
from model import *
np.random.seed(1337)
def get_engine(address = "postgresql+pg8000://script@localhost:5432/ccfd"):
# disk_engine = create_engine('sqlite:///'+data_dir+db_name,convert_unicode=True)
# disk_engine.raw_connection().connection.text_factory =... |
print '=======================AUC============================'
return data_little_enc_eval.auc_list
def parse_args():
parser = argparse.ArgumentParser(prog='Model Evaluator')
parser.add_argument('-t','--table',required=True)
parser.add_argument('-i','--id',default=1)
args = parser.parse_args()... | for trans_mode in options:
print '################## USER:{user_mode}--------TRANS:{trans_mode}###############'.format(user_mode=user_mode,trans_mode=trans_mode)
eval_list = data_little_enc_eval.evaluate_model(user_mode,trans_mode,title,add_info=add_info)
print '#####################... | conditional_block |
model_eval.py | import os
import argparse
import re
import numpy as np
from model import *
np.random.seed(1337)
def get_engine(address = "postgresql+pg8000://script@localhost:5432/ccfd"):
# disk_engine = create_engine('sqlite:///'+data_dir+db_name,convert_unicode=True)
# disk_engine.raw_connection().connection.text_factory =... | table_auth = 'auth_enc'
auth_enc_eval = Evaluator(model, table_auth, disk_engine)
options = ['train','test']
py.sign_in('bottydim', 'o1kuyms9zv')
print '=======================DATA LITTLE============================'
for user_mode in options:
for trans_mode in options:
print... | disk_engine = get_engine()
ml = ModelLoader(table,arch_path=arch,w_path=w_path)
model = ml.model
data_little_enc_eval = Evaluator(model, table, disk_engine) | random_line_split |
model_eval.py | import os
import argparse
import re
import numpy as np
from model import *
np.random.seed(1337)
def get_engine(address = "postgresql+pg8000://script@localhost:5432/ccfd"):
# disk_engine = create_engine('sqlite:///'+data_dir+db_name,convert_unicode=True)
# disk_engine.raw_connection().connection.text_factory =... | (self, *args, **kwargs):
ModelOperator.__init__(self, *args, **kwargs)
# self.disk_engine = disk_engine
# self.model = model
# self.table = table
# self.auc_list = []
# self.encoders = load_encoders()
# if 'events_tbl' in kwargs:
# self.events_tbl = kw... | __init__ | identifier_name |
task-comm-7.rs | // run-pass
#![allow(unused_must_use)]
#![allow(unused_assignments)]
// ignore-emscripten no threads support
use std::sync::mpsc::{channel, Sender};
use std::thread;
pub fn main() |
fn test00_start(c: &Sender<isize>, start: isize,
number_of_messages: isize) {
let mut i: isize = 0;
while i < number_of_messages { c.send(start + i).unwrap(); i += 1; }
}
fn test00() {
let mut r: isize = 0;
let mut sum: isize = 0;
let (tx, rx) = channel();
let number_of_messag... | { test00(); } | identifier_body |
task-comm-7.rs | // run-pass
#![allow(unused_must_use)]
#![allow(unused_assignments)]
// ignore-emscripten no threads support
use std::sync::mpsc::{channel, Sender}; | use std::thread;
pub fn main() { test00(); }
fn test00_start(c: &Sender<isize>, start: isize,
number_of_messages: isize) {
let mut i: isize = 0;
while i < number_of_messages { c.send(start + i).unwrap(); i += 1; }
}
fn test00() {
let mut r: isize = 0;
let mut sum: isize = 0;
let (... | random_line_split | |
task-comm-7.rs | // run-pass
#![allow(unused_must_use)]
#![allow(unused_assignments)]
// ignore-emscripten no threads support
use std::sync::mpsc::{channel, Sender};
use std::thread;
pub fn main() { test00(); }
fn test00_start(c: &Sender<isize>, start: isize,
number_of_messages: isize) {
let mut i: isize = 0;
... | () {
let mut r: isize = 0;
let mut sum: isize = 0;
let (tx, rx) = channel();
let number_of_messages: isize = 10;
let tx2 = tx.clone();
let t1 = thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 0, number_of_messages);
});
let tx2 = tx.clone();
let t2 = thread::s... | test00 | identifier_name |
RULE_9_2_D_use_reentrant_function.py | """
Use reentrant functions. Do not use not reentrant functions.(ctime, strtok, toupper)
== Violation ==
void A() {
k = ctime(); <== Violation. ctime() is not the reenterant function.
j = strok(blar blar); <== Violation. strok() is not the reenterant function.
}
== Good ==
void A() {... | def test4(self):
self.Analyze("thisfile.c",
"""
void ctime () {
}
""")
self.ExpectSuccess(__name__)
def test5(self):
self.Analyze("thisfile.c",
"""
void func1()
{
k = help.ctime ()
}
""")
self.ExpectSuccess(__name__)
... | """)
self.ExpectSuccess(__name__)
| random_line_split |
RULE_9_2_D_use_reentrant_function.py | """
Use reentrant functions. Do not use not reentrant functions.(ctime, strtok, toupper)
== Violation ==
void A() {
k = ctime(); <== Violation. ctime() is not the reenterant function.
j = strok(blar blar); <== Violation. strok() is not the reenterant function.
}
== Good ==
void A() {... | (self):
self.Analyze("thisfile.c",
"""
void ctime () {
}
""")
self.ExpectSuccess(__name__)
def test5(self):
self.Analyze("thisfile.c",
"""
void func1()
{
k = help.ctime ()
}
""")
self.ExpectSuccess(__name__)
def te... | test4 | identifier_name |
RULE_9_2_D_use_reentrant_function.py | """
Use reentrant functions. Do not use not reentrant functions.(ctime, strtok, toupper)
== Violation ==
void A() {
k = ctime(); <== Violation. ctime() is not the reenterant function.
j = strok(blar blar); <== Violation. strok() is not the reenterant function.
}
== Good ==
void A() {... | """)
self.ExpectSuccess(__name__)
def test3(self):
self.Analyze("thisfile.c",
"""
void ctime() {
}
""")
self.ExpectSuccess(__name__)
def test4(self):
self.Analyze("thisfile.c",
"""
void ctime () {
}
""")
self.Ex... | def setUpRule(self):
ruleManager.AddFunctionScopeRule(RunRule)
def test1(self):
self.Analyze("thisfile.c",
"""
void func1()
{
k = ctime()
}
""")
self.ExpectError(__name__)
def test2(self):
self.Analyze("thisfile.c",
"... | identifier_body |
RULE_9_2_D_use_reentrant_function.py | """
Use reentrant functions. Do not use not reentrant functions.(ctime, strtok, toupper)
== Violation ==
void A() {
k = ctime(); <== Violation. ctime() is not the reenterant function.
j = strok(blar blar); <== Violation. strok() is not the reenterant function.
}
== Good ==
void A() {... |
nsiqcppstyle_reporter.Error(t, __name__,
"Do not use not reentrant function(%s)." % t.value)
ruleManager.AddFunctionScopeRule(RunRule)
##########################################################################
# Unit Test
#################... | return | conditional_block |
vibrance.rs | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by app... | B = b;
float Rc = R * (Rt + S) + G * Gt + B * Bt;
float Gc = R * Rt + G * (Gt + S) + B * Bt;
float Bc = R * Rt + G * Gt + B * (Bt + S);
out->r = rsClamp(Rc, 0, 255);
out->g = rsClamp(Gc, 0, 255);
out->b = rsClamp(Bc, 0, 255);
}
void prepareVibrance() {
Vib = vibrance/100.f;
S =... | R = r;
G = g; | random_line_split |
SeatgeekSVG.tsx | import React from 'react';
export default function SeatgeekSVG() | {
return (
<svg viewBox="20 554 299 228" width="24" height="24">
<g>
<path d="M71.3,578.6c0,0,37.5-24.6,98.2-24.6s98.2,24.6,98.2,24.6l-24.6,130.4H95.8L71.3,578.6z" />
<path d="M71.3,737.8c0,0,38.2,17.5,98.2,17.5s98.2-17.5,98.2-17.5v27.8c0,0-38.9,16.4-98.2,16.4 s-98.2-16.4-98.2-16.4V737.8z" /... | identifier_body | |
SeatgeekSVG.tsx | import React from 'react';
export default function | () {
return (
<svg viewBox="20 554 299 228" width="24" height="24">
<g>
<path d="M71.3,578.6c0,0,37.5-24.6,98.2-24.6s98.2,24.6,98.2,24.6l-24.6,130.4H95.8L71.3,578.6z" />
<path d="M71.3,737.8c0,0,38.2,17.5,98.2,17.5s98.2-17.5,98.2-17.5v27.8c0,0-38.9,16.4-98.2,16.4 s-98.2-16.4-98.2-16.4V737.8z... | SeatgeekSVG | identifier_name |
SeatgeekSVG.tsx | import React from 'react';
export default function SeatgeekSVG() {
return (
<svg viewBox="20 554 299 228" width="24" height="24">
<g>
<path d="M71.3,578.6c0,0,37.5-24.6,98.2-24.6s98.2,24.6,98.2,24.6l-24.6,130.4H95.8L71.3,578.6z" />
<path d="M71.3,737.8c0,0,38.2,17.5,98.2,17.5s98.2-17.5,98.2... | <path d="M269.9,719.8v-46.4c0-7.5,6.1-13.6,13.6-13.6H319v24.6H296v35.5H269.9z" />
</g>
</svg>
);
} | <path d="M69.1,719.8v-46.4c0-7.5-6.1-13.6-13.6-13.6H20v24.6h22.9v35.5H69.1z" /> | random_line_split |
message.rs | use std::str;
use std::str::FromStr;
use std::ascii::AsciiExt;
use IterListHeader;
use Error::{ForbiddenHeader, MissingHeader};
pub trait Message {
fn get_header(&self, &str) -> Option<&Vec<Vec<u8>>>;
fn contains_header(&self, &str) -> bool;
fn get_value_header(&self, name: &str) -> Option<&[u8]> {
... |
}
| {
if let Some(values) = self.get_list_header("Transfer-Encoding") {
for value in values {
if value.eq_ignore_ascii_case(b"chunked") {
return true
}
}
}
false
} | identifier_body |
message.rs | use std::str;
use std::str::FromStr;
use std::ascii::AsciiExt;
use IterListHeader;
use Error::{ForbiddenHeader, MissingHeader};
pub trait Message {
fn get_header(&self, &str) -> Option<&Vec<Vec<u8>>>;
fn contains_header(&self, &str) -> bool;
fn | (&self, name: &str) -> Option<&[u8]> {
let value_header = self.get_header(name);
if value_header.is_none() || value_header.unwrap().len() != 1 {
return None;
}
Some(&value_header.unwrap()[0])
}
fn get_list_header(&self, name: &str) -> Option<IterListHeader> {
... | get_value_header | identifier_name |
message.rs | use std::str;
use std::str::FromStr;
use std::ascii::AsciiExt;
use IterListHeader;
use Error::{ForbiddenHeader, MissingHeader};
pub trait Message {
fn get_header(&self, &str) -> Option<&Vec<Vec<u8>>>;
fn contains_header(&self, &str) -> bool;
fn get_value_header(&self, name: &str) -> Option<&[u8]> {
... | else {
None
}
}
fn content_length(&self) -> ::Result<usize> {
if self.contains_header("Transfer-Encoding") {
return Err(ForbiddenHeader);
}
let value = try!(self.get_value_header("Content-Length").ok_or(MissingHeader));
FromStr::from_str(try!(str... | {
Some(IterListHeader::new(values))
} | conditional_block |
message.rs | use std::str;
use std::str::FromStr;
use std::ascii::AsciiExt;
use IterListHeader;
use Error::{ForbiddenHeader, MissingHeader};
pub trait Message {
fn get_header(&self, &str) -> Option<&Vec<Vec<u8>>>;
fn contains_header(&self, &str) -> bool;
fn get_value_header(&self, name: &str) -> Option<&[u8]> {
... | let value = try!(self.get_value_header("Content-Length").ok_or(MissingHeader));
FromStr::from_str(try!(str::from_utf8(value))).map_err(From::from)
}
fn is_chunked(&self) -> bool {
if let Some(values) = self.get_list_header("Transfer-Encoding") {
for value in values {
... | return Err(ForbiddenHeader);
} | random_line_split |
doctest.py | DoctestTextfile(path, parent)
def _is_setup_py(config, path, parent):
if path.basename != "setup.py":
return False
contents = path.read()
return "setuptools" in contents or "distutils" in contents
def _is_doctest(config, path, parent):
if path.ext in (".txt", ".rst") and parent.session.isin... | (self, failures):
super(MultipleDoctestFailures, self).__init__()
self.failures = failures
def _init_runner_class():
import doctest
class PytestDoctestRunner(doctest.DebugRunner):
"""
Runner to collect failures. Note that the out variable in this case is
a list instea... | __init__ | identifier_name |
doctest.py | _is_doctest(config, path, parent):
if path.ext in (".txt", ".rst") and parent.session.isinitpath(path):
return True
globs = config.getoption("doctestglob") or ["test*.txt"]
for glob in globs:
if path.check(fnmatch=glob):
return True
return False
class ReprFailDoctest(Termi... | else: | random_line_split | |
doctest.py | __(
self, checker=checker, verbose=verbose, optionflags=optionflags
)
self.continue_on_failure = continue_on_failure
def report_failure(self, out, test, example, got):
failure = doctest.DocTestFailure(test, example, got)
if self.continue_on_failur... | raise | conditional_block | |
doctest.py | return DoctestTextfile(path, parent)
def _is_setup_py(config, path, parent):
if path.basename != "setup.py":
return False
contents = path.read()
return "setuptools" in contents or "distutils" in contents
def _is_doctest(config, path, parent):
if path.ext in (".txt", ".rst") and parent.sessi... |
def _get_continue_on_failure(config):
continue_on_failure = config.getvalue("doctest_continue_on_failure")
if continue_on_failure:
# We need to turn off this if we use pdb since we should stop at
# the first failure
if config.getvalue("usepdb"):
continue_on_failure = False... | optionflags_str = parent.config.getini("doctest_optionflags")
flag_lookup_table = _get_flag_lookup()
flag_acc = 0
for flag in optionflags_str:
flag_acc |= flag_lookup_table[flag]
return flag_acc | identifier_body |
lt.js | /*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'image2', 'lt', { | captionPlaceholder: 'Caption', // MISSING
infoTab: 'Vaizdo informacija',
lockRatio: 'Išlaikyti proporciją',
menu: 'Vaizdo savybės',
pathName: 'image', // MISSING
pathNameCaption: 'caption', // MISSING
resetSize: 'Atstatyti dydį',
resizer: 'Click and drag to resize', // MISSING
title: 'Vaizdo savybės',
uploadT... | alt: 'Alternatyvus Tekstas',
btnUpload: 'Siųsti į serverį',
captioned: 'Captioned image', // MISSING | random_line_split |
pytiger2c.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script para ejecutar PyTiger2C desde la linea de comandos.
"""
import os
import sys
import optparse
import subprocess
# Add the directory containing the packages in the source distribution to the path.
# This should be removed when Tiger2C is installed.
PACKAGES_DIR ... | (argv):
"""
Reconoce las opciones especificadas como argumentos.
@type argv: C{list}
@param argv: Lista de argumentos del programa.
@rtype: C{tuple}
@return: Retorna una tupla donde el primer elemento es una estructura
que almacena la información acerca de las opciones especifi... | _parse_args | identifier_name |
pytiger2c.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script para ejecutar PyTiger2C desde la linea de comandos.
"""
import os
import sys
import optparse
import subprocess
# Add the directory containing the packages in the source distribution to the path.
# This should be removed when Tiger2C is installed.
PACKAGES_DIR ... | EXIT_SUCCESS, EXIT_FAILURE = 0, 1
def _parse_args(argv):
"""
Reconoce las opciones especificadas como argumentos.
@type argv: C{list}
@param argv: Lista de argumentos del programa.
@rtype: C{tuple}
@return: Retorna una tupla donde el primer elemento es una estructura
que alma... |
from pytiger2c import __version__, __authors__, tiger2c, tiger2dot
from pytiger2c.errors import PyTiger2CError
| random_line_split |
pytiger2c.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script para ejecutar PyTiger2C desde la linea de comandos.
"""
import os
import sys
import optparse
import subprocess
# Add the directory containing the packages in the source distribution to the path.
# This should be removed when Tiger2C is installed.
PACKAGES_DIR ... | elif len(args) != 1:
parser.error('invalid number of arguments')
else:
return options, args
def main(argv):
"""
Función principal del script.
@type argv: C{list}
@param argv: Lista de argumentos del programa.
@rtype: C{int}
@return: Retorna 0 si no ocurrió nin... | arser.error('missing required --output option')
| conditional_block |
pytiger2c.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script para ejecutar PyTiger2C desde la linea de comandos.
"""
import os
import sys
import optparse
import subprocess
# Add the directory containing the packages in the source distribution to the path.
# This should be removed when Tiger2C is installed.
PACKAGES_DIR ... | prog=os.path.basename(argv[0]))
parser.add_option('-o', '--output', action='store', dest='output', metavar='FILE',
help='write the output to FILE')
parser.add_option('-t', '--output-type', action='store', dest='output_type', metavar='TYPE',
... | """
Reconoce las opciones especificadas como argumentos.
@type argv: C{list}
@param argv: Lista de argumentos del programa.
@rtype: C{tuple}
@return: Retorna una tupla donde el primer elemento es una estructura
que almacena la información acerca de las opciones especificadas
... | identifier_body |
focusable.js | /*!
* jQuery UI Focusable 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: :focusable Selector
//>>group: Core
//>>description: Selects elements which can be focused.
//>>docs: http://api.j... |
if ( /^(input|select|textarea|button|object)$/.test( nodeName ) ) {
focusableIfVisible = !element.disabled;
if ( focusableIfVisible ) {
// Form controls within a disabled fieldset are disabled.
// However, controls within the fieldset's legend do not get disabled.
// Since controls generally ... | {
map = element.parentNode;
mapName = map.name;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap='#" + mapName + "']" );
return img.length > 0 && img.is( ":visible" );
} | conditional_block |
focusable.js | /*!
* jQuery UI Focusable 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: :focusable Selector
//>>group: Core
//>>description: Selects elements which can be focused.
//>>docs: http://api.j... | ( element ) {
var visibility = element.css( "visibility" );
while ( visibility === "inherit" ) {
element = element.parent();
visibility = element.css( "visibility" );
}
return visibility !== "hidden";
}
$.extend( $.expr[ ":" ], {
focusable: function( element ) {
return $.ui.focusable( element, $.... | visible | identifier_name |
focusable.js | /*!
* jQuery UI Focusable 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: :focusable Selector
//>>group: Core
//>>description: Selects elements which can be focused.
//>>docs: http://api.j... |
$.extend( $.expr[ ":" ], {
focusable: function( element ) {
return $.ui.focusable( element, $.attr( element, "tabindex" ) != null );
}
} );
return $.ui.focusable;
} ) );
| {
var visibility = element.css( "visibility" );
while ( visibility === "inherit" ) {
element = element.parent();
visibility = element.css( "visibility" );
}
return visibility !== "hidden";
} | identifier_body |
focusable.js | /*!
* jQuery UI Focusable 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: :focusable Selector
//>>group: Core
//>>description: Selects elements which can be focused.
//>>docs: http://api.j... | fieldset = $( element ).closest( "fieldset" )[ 0 ];
if ( fieldset ) {
focusableIfVisible = !fieldset.disabled;
}
}
} else if ( "a" === nodeName ) {
focusableIfVisible = element.href || hasTabindex;
} else {
focusableIfVisible = hasTabindex;
}
return focusableIfVisible && $( element ).... | random_line_split | |
RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery.graphql.js | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<ff40aed3600a349a81c8d336ef25c383>>
* @flow
* @lightSyntaxTransform
* @nogrep
*/
/* eslint-disabl... |
module.exports = ((node/*: any*/)/*: Query<
RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$variables,
RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$data,
>*/);
| {
(node/*: any*/).hash = "dc18b1545e059ab74a8a0209a0c58b60";
} | conditional_block |
RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery.graphql.js | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<ff40aed3600a349a81c8d336ef25c383>>
* @flow
* @lightSyntaxTransform
* @nogrep
*/
/* eslint-disabl... | "args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
(v2/*: any*/),
(v3/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"cacheID": "0731919b754e27166d990aec021f2e80",
"id": ... | "selections": [
{
"alias": null, | random_line_split |
ExcelColumns.py | import string
def fillChars(chars):
for i in string.ascii_lowercase:
chars.append(i)
def getColumnNumber():
columnNumber=int(raw_input("Please input cell number: "))
return columnNumber
def printColumns(chars):
printBlank=True
counter=1
for c0 in chars... |
def computeColumn(columnNumber,column):
if columnNumber==0:
return column
print 'overloading'
base=26
col=columnNumber % base
columnNumber/=base
if col==0:
col=base
columnNumber=columnNumber-1
column.insert(0,col)
return computeColumn(columnNumber,column)... | base=26
column=[]
while columnNumber>0:
col=columnNumber % base
columnNumber/=base
if col==0:
col=base
columnNumber=columnNumber-1
column.insert(0,col)
return column | identifier_body |
ExcelColumns.py | import string
def fillChars(chars):
for i in string.ascii_lowercase:
chars.append(i)
def getColumnNumber():
columnNumber=int(raw_input("Please input cell number: "))
return columnNumber
def printColumns(chars):
printBlank=True
counter=1
for c0 in chars... | (columnNumber):
base=26
column=[]
while columnNumber>0:
col=columnNumber % base
columnNumber/=base
if col==0:
col=base
columnNumber=columnNumber-1
column.insert(0,col)
return column
def computeColumn(columnNumber,column):
if ... | computeColumn | identifier_name |
ExcelColumns.py | import string
def fillChars(chars):
for i in string.ascii_lowercase:
chars.append(i)
def getColumnNumber():
columnNumber=int(raw_input("Please input cell number: "))
return columnNumber
def printColumns(chars):
printBlank=True
counter=1
for c0 in chars... |
def computeColumn(columnNumber):
base=26
column=[]
while columnNumber>0:
col=columnNumber % base
columnNumber/=base
if col==0:
col=base
columnNumber=columnNumber-1
column.insert(0,col)
return column
def computeColumn(columnNumb... | if aColumn % 26 ==1:
print
print counter,':',
print getEquivalentColumn(computeColumnRecursive(aColumn,[])),
counter+=1
aColumn+=1 | conditional_block |
ExcelColumns.py | import string
def fillChars(chars):
for i in string.ascii_lowercase:
chars.append(i)
def getColumnNumber():
columnNumber=int(raw_input("Please input cell number: "))
return columnNumber
def printColumns(chars):
printBlank=True
counter=1
for c0 in chars... | else:
start2=1
for c2 in chars[start2:]:
print counter,':',
for c3 in chars[1:]:
print c0+c1+c2+c3,
counter += 1
print
raw_input("pause for a while")
def printColumns2(col... | if printBlank:
start2=0
printBlank=False | random_line_split |
fd-generation-list-form.js | import { getOwner } from '@ember/application';
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import { get } from '@ember/object';
import ListFormController from 'ember-flexberry/controllers/list-form';
export default ListFormController.extend({
/**
Name of related ... |
},
/**
Method to get type and attributes of a component,
which will be embeded in object-list-view cell.
@method getCellComponent.
@param {Object} attr Attribute of projection property related to current table cell.
@param {String} bindingPath Path to model property related to current table c... | {
let _this = this;
_this.get('appState').loading();
let stagePk = _this.get('currentProjectContext').getCurrentStage();
let adapter = getOwner(this).lookup('adapter:application');
adapter.callFunction('Generate', { project: stagePk.toString() }, null, { withCredentials: true },
(re... | identifier_body |
fd-generation-list-form.js | import { getOwner } from '@ember/application';
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import { get } from '@ember/object';
import ListFormController from 'ember-flexberry/controllers/list-form';
export default ListFormController.extend({
/**
Name of related ... | () {
let _this = this;
_this.get('appState').loading();
let stagePk = _this.get('currentProjectContext').getCurrentStage();
let adapter = getOwner(this).lookup('adapter:application');
adapter.callFunction('Generate', { project: stagePk.toString() }, null, { withCredentials: true },
... | generationStartButtonClick | identifier_name |
fd-generation-list-form.js | import { getOwner } from '@ember/application';
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import { get } from '@ember/object';
import ListFormController from 'ember-flexberry/controllers/list-form';
export default ListFormController.extend({
/**
Name of related ... | generationStartButtonClick() {
let _this = this;
_this.get('appState').loading();
let stagePk = _this.get('currentProjectContext').getCurrentStage();
let adapter = getOwner(this).lookup('adapter:application');
adapter.callFunction('Generate', { project: stagePk.toString() }, null, { w... | random_line_split | |
fd-generation-list-form.js | import { getOwner } from '@ember/application';
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import { get } from '@ember/object';
import ListFormController from 'ember-flexberry/controllers/list-form';
export default ListFormController.extend({
/**
Name of related ... |
return this._super(...arguments);
},
});
| {
return {
componentName: 'object-list-view-cell',
componentProperties: {
dateFormat: 'DD.MM.YYYY, HH:mm:ss'
}
};
} | conditional_block |
storage.py | import contextlib
import gc
import multiprocessing
import os
from memsql_loader.util.apsw_storage import APSWStorage
from memsql_loader.util import paths
MEMSQL_LOADER_DB = 'memsql_loader.db'
def get_loader_db_path():
return os.path.join(paths.get_data_dir(), MEMSQL_LOADER_DB)
# IMPORTANT NOTE: This class canno... | # object in __new__. However, we may have closed this object's
# connections in fork_wrapper above; in that case, we want to set
# up new database connections.
if not LoaderStorage._initialized:
super(LoaderStorage, self).__init__(get_loader_db_path())
... |
def __init__(self):
with LoaderStorage._instance_lock:
# Since this is a singleton object, we don't want to call the
# parent object's __init__ if we've already instantiated this | random_line_split |
storage.py | import contextlib
import gc
import multiprocessing
import os
from memsql_loader.util.apsw_storage import APSWStorage
from memsql_loader.util import paths
MEMSQL_LOADER_DB = 'memsql_loader.db'
def get_loader_db_path():
return os.path.join(paths.get_data_dir(), MEMSQL_LOADER_DB)
# IMPORTANT NOTE: This class canno... |
@classmethod
def drop_database(cls):
with cls._instance_lock:
if os.path.isfile(get_loader_db_path()):
os.remove(get_loader_db_path())
if os.path.isfile(get_loader_db_path() + '-shm'):
os.remove(get_loader_db_path() + '-shm')
if os.pa... | with cls._instance_lock:
if cls._instance is None:
cls._instance = super(LoaderStorage, cls).__new__(
cls, *args, **kwargs)
cls._initialized = False
return cls._instance | identifier_body |
storage.py | import contextlib
import gc
import multiprocessing
import os
from memsql_loader.util.apsw_storage import APSWStorage
from memsql_loader.util import paths
MEMSQL_LOADER_DB = 'memsql_loader.db'
def get_loader_db_path():
return os.path.join(paths.get_data_dir(), MEMSQL_LOADER_DB)
# IMPORTANT NOTE: This class canno... |
return cls._instance
@classmethod
def drop_database(cls):
with cls._instance_lock:
if os.path.isfile(get_loader_db_path()):
os.remove(get_loader_db_path())
if os.path.isfile(get_loader_db_path() + '-shm'):
os.remove(get_loader_db_path... | cls._instance = super(LoaderStorage, cls).__new__(
cls, *args, **kwargs)
cls._initialized = False | conditional_block |
storage.py | import contextlib
import gc
import multiprocessing
import os
from memsql_loader.util.apsw_storage import APSWStorage
from memsql_loader.util import paths
MEMSQL_LOADER_DB = 'memsql_loader.db'
def get_loader_db_path():
return os.path.join(paths.get_data_dir(), MEMSQL_LOADER_DB)
# IMPORTANT NOTE: This class canno... | (cls, *args, **kwargs):
with cls._instance_lock:
if cls._instance is None:
cls._instance = super(LoaderStorage, cls).__new__(
cls, *args, **kwargs)
cls._initialized = False
return cls._instance
@classmethod
def drop_database(cl... | __new__ | identifier_name |
transliterator.ts | export default {
translitePrimer: new Map([
['А', 'A'], ['а', 'a'], ['Б', 'B'], ['б', 'b'], ['В', 'V'], ['в', 'v'], ['Г', 'G'], ['г', 'g'],
['Д', 'D'], ['д', 'd'], ['Е', 'E'], ['е', 'e'], ['Ё', 'Yo'], ['ё', 'yo'], ['Ж', 'Zh'], ['ж', 'zh'],
['З', 'Z'], ['з', 'z'], ['И', 'I'... | nput) => {
oldShema[input.key] = input;
return oldShema;
}, initObject);
},
mapOldSchemaToNew(oldShema, initArray = []) {
initArray.length = 0;
return Object.entries(oldShema).reduce((newSchema, keyValue) => {
const key = keyValue[0];
cons... | duce((oldShema, i | identifier_name |
transliterator.ts | export default {
translitePrimer: new Map([
['А', 'A'], ['а', 'a'], ['Б', 'B'], ['б', 'b'], ['В', 'V'], ['в', 'v'], ['Г', 'G'], ['г', 'g'],
['Д', 'D'], ['д', 'd'], ['Е', 'E'], ['е', 'e'], ['Ё', 'Yo'], ['ё', 'yo'], ['Ж', 'Zh'], ['ж', 'zh'],
['З', 'Z'], ['з', 'z'], ['И', 'I'... | del, transliteratedFields = {name: 'alias'}, schema = {}) {
const computed = model.computed = model.computed || {};
const required = function(name) {
return function(fields) {
if (fields[name]) {
return fields[name];
}
retu... | this.translitePrimer.forEach((value, key) => {
const err = Core.form.repository.validators.systemName()(value);
this.__translitToSystemName[key] = err ? '' : value;
});
}
return this.__translitToSystemName;
},
extendComputed(mo | conditional_block |
transliterator.ts | export default {
translitePrimer: new Map([
['А', 'A'], ['а', 'a'], ['Б', 'B'], ['б', 'b'], ['В', 'V'], ['в', 'v'], ['Г', 'G'], ['г', 'g'],
['Д', 'D'], ['д', 'd'], ['Е', 'E'], ['е', 'e'], ['Ё', 'Yo'], ['ё', 'yo'], ['Ж', 'Zh'], ['ж', 'zh'],
['З', 'Z'], ['з', 'z'], ['И', 'I'... | if (computed[name] && !computed[name].transliteratedFieldsClass) {
console.warn(`Transliterator: computed is not fully extended, computed[${name}] is exist in model!`);
return;
}
if (computed[alias] && !computed[alias].transliteratedFieldsClass) {
... | const required = function(name) {
return function(fields) {
if (fields[name]) {
return fields[name];
}
return this.previous(name);
};
};
const getTranslite = (name, alias) =>
(fields) => {
... | identifier_body |
transliterator.ts | export default {
translitePrimer: new Map([
['А', 'A'], ['а', 'a'], ['Б', 'B'], ['б', 'b'], ['В', 'V'], ['в', 'v'], ['Г', 'G'], ['г', 'g'],
['Д', 'D'], ['д', 'd'], ['Е', 'E'], ['е', 'e'], ['Ё', 'Yo'], ['ё', 'yo'], ['Ж', 'Zh'], ['ж', 'zh'],
['З', 'Z'], ['з', 'z'], ['И', 'I'... |
setOptionsToFieldsOfNewSchema(newSchema, transliteratedFields, inputSettings) {
this.setOptionsToComputedTransliteratedFields(this.mapNewSchemaToOld(newSchema), transliteratedFields, inputSettings);
return newSchema;
},
isShemaNew(schema) {
return Array.isArray(schema);
},
... | });
return schema;
}, | random_line_split |
parser-postfix-exp-assign.js | * You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See... | {
try {
eval(tests[i]);
assert(false);
} catch (e) {
assert(e instanceof SyntaxError);
}
} | conditional_block | |
parser-postfix-exp-assign.js | *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distribut... | 'var a = 0B11; a++ = 42',
'var a = 0b11; a-- = 42',
'var a = 0B11; a-- = 42',
// OctalIntegerLiteral
'var a = 0o66; a++ = 42',
'var a = 0O66; a++ = 42',
'var a = 0o66; a-- = 42',
'var a = 0O66; a-- = 42',
// HexIntegerLiteral
'var a = 0xFF; a++ = 42',
'var a = 0xFF; a++ = 42',
'var a = 0xFF; a... | 'var a = 1.23e4; a-- = 42',
// BinaryIntegerLiteral
'var a = 0b11; a++ = 42', | random_line_split |
vc.py | env.get('HOST_ARCH')
if not host_platform:
host_platform = platform.machine()
# TODO(2.5): the native Python platform.machine() function returns
# '' on all Python versions before 2.6, after which it also uses
# PROCESSOR_ARCHITECTURE.
if not host_platform:
host... | (msvc_version):
msvc_version_numeric = ''.join([x for x in msvc_version if x in string_digits + '.'])
t = msvc_version_numeric.split(".")
if not len(t) == 2:
raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
try:
maj = int(t[0])
min = int(t[1])
... | msvc_version_to_maj_min | identifier_name |
vc.py | MSVC_VERSION documentation in Tool/msvc.xml.
_VCVER = ["15.0", "14.0", "14.0Exp", "12.0", "12.0Exp", "11.0", "11.0Exp", "10.0", "10.0Exp", "9.0", "9.0Exp","8.0", "8.0Exp","7.1", "7.0", "6.0"]
_VCVER_TO_PRODUCT_DIR = {
'15.0' : [
r'Microsoft\VisualStudio\SxS\VS7\15.0'],
'14.0' : [
... | stdout = common.get_output(script, args)
script_env_stdout_cache[cache_key] = stdout | conditional_block | |
vc.py | .0)
Note
----
This only check whether a given version *may* support the given (host,
target), not that the toolchain is actually present on the machine.
"""
# We assume that any Visual Studio version supports x86 as a target
if host_target[1] != "x86":
maj, min = msvc_version_to_maj... | random_line_split | ||
vc.py |
class BatchFileExecutionError(VisualCException):
pass
# Dict to 'canonalize' the arch
_ARCH_TO_CANONICAL = {
"amd64" : "amd64",
"emt64" : "amd64",
"i386" : "x86",
"i486" : "x86",
"i586" : "x86",
"i686" : "x86",
"ia64" : "ia64",
"itanium" : "ia64"... | pass | identifier_body | |
SelectEventPlugin-test.js | /**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
var React;
var ReactDOM;
var ReactDOMComponentTree;
var ReactTestUtils;
var SelectEventPlugin;
... |
var cb = jest.fn();
var rendered = ReactTestUtils.renderIntoDocument(
<WithSelect onSelect={cb} />,
);
var node = ReactDOM.findDOMNode(rendered);
node.selectionStart = 0;
node.selectionEnd = 0;
node.focus();
var focus = extract(node, 'topFocus');
expect(focus).toBe(null);
... | class WithSelect extends React.Component {
render() {
return <input type="text" onSelect={this.props.onSelect} />;
}
} | random_line_split |
SelectEventPlugin-test.js | /**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
var React;
var ReactDOM;
var ReactDOMComponentTree;
var ReactTestUtils;
var SelectEventPlugin;
... | extends React.Component {
render() {
return <input type="text" />;
}
}
var rendered = ReactTestUtils.renderIntoDocument(<WithoutSelect />);
var node = ReactDOM.findDOMNode(rendered);
node.focus();
// It seems that .focus() isn't triggering this event in our test
// environ... | WithoutSelect | identifier_name |
executor.rs | use serde::{Serialize, Deserialize};
use std::mem;
use std::fmt::Debug;
use std::sync::mpsc::{Sender, Receiver};
use std::collections::HashMap;
use amy;
use slog;
use time::Duration;
use ferris::{Wheel, CopyWheel, Resolution};
use envelope::Envelope;
use pid::Pid;
use process::Process;
use node_id::NodeId;
use msg::Msg... | <T> {
pid: Pid,
node: NodeId,
envelopes: Vec<Envelope<T>>,
processes: HashMap<Pid, Box<Process<T>>>,
service_senders: HashMap<Pid, amy::Sender<Envelope<T>>>,
tx: Sender<ExecutorMsg<T>>,
rx: Receiver<ExecutorMsg<T>>,
cluster_tx: Sender<ClusterMsg<T>>,
timer_wheel: CopyWheel<(Pid, Opti... | Executor | identifier_name |
executor.rs | use serde::{Serialize, Deserialize};
use std::mem;
use std::fmt::Debug;
use std::sync::mpsc::{Sender, Receiver};
use std::collections::HashMap;
use amy;
use slog;
use time::Duration;
use ferris::{Wheel, CopyWheel, Resolution};
use envelope::Envelope;
use pid::Pid;
use process::Process;
use node_id::NodeId;
use msg::Msg... | match msg {
ExecutorMsg::Envelope(envelope) => {
self.metrics.received_envelopes += 1;
self.route(envelope);
},
ExecutorMsg::Start(pid, process) => self.start(pid, process),
ExecutorMsg::Stop(pid) => self... | ///
///This call blocks the current thread indefinitely.
pub fn run(mut self) {
while let Ok(msg) = self.rx.recv() { | random_line_split |
executor.rs | use serde::{Serialize, Deserialize};
use std::mem;
use std::fmt::Debug;
use std::sync::mpsc::{Sender, Receiver};
use std::collections::HashMap;
use amy;
use slog;
use time::Duration;
use ferris::{Wheel, CopyWheel, Resolution};
use envelope::Envelope;
use pid::Pid;
use process::Process;
use node_id::NodeId;
use msg::Msg... |
/// Route envelopes to local or remote processes
///
/// Retrieve any envelopes from processes handling local messages and put them on either the
/// executor or the cluster channel depending upon whether they are local or remote.
///
/// Note that all envelopes sent to an executor are sent fr... | {
for (pid, c_id) in self.timer_wheel.expire() {
let envelope = Envelope::new(pid, self.pid.clone(), Msg::Timeout, c_id);
let _ = self.route_to_process(envelope);
}
} | identifier_body |
gcthread.rs | //! Garbage collection thread
use std::any::Any;
use std::cmp::min;
use std::mem::size_of;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use num_cpus;
use scoped_pool::Pool;
use appthread::AppThread;
use constants::{MAJOR_COLLECT_THRESHOLD, MAX_SLEEP_DUR, MIN_SLEEP_DUR};
use heap::{CollectOps, Obje... | 3
}
} | pub fn ptr_shift() -> i32 {
if size_of::<usize>() == 32 {
2
} else { | random_line_split |
gcthread.rs | //! Garbage collection thread
use std::any::Any;
use std::cmp::min;
use std::mem::size_of;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use num_cpus;
use scoped_pool::Pool;
use appthread::AppThread;
use constants::{MAJOR_COLLECT_THRESHOLD, MAX_SLEEP_DUR, MIN_SLEEP_DUR};
use heap::{CollectOps, Obje... |
// TODO: base this call on a duration since last call?
let young_count = gc.minor_collection(&mut pool);
// do a major collection if the young count reaches a threshold and we're not just trying
// to keep up with the app threads
// TODO: force a major collection every n minut... | {
// reset next sleep duration on receiving no entries
sleep_dur = MIN_SLEEP_DUR;
} | conditional_block |
gcthread.rs | //! Garbage collection thread
use std::any::Any;
use std::cmp::min;
use std::mem::size_of;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use num_cpus;
use scoped_pool::Pool;
use appthread::AppThread;
use constants::{MAJOR_COLLECT_THRESHOLD, MAX_SLEEP_DUR, MIN_SLEEP_DUR};
use heap::{CollectOps, Obje... |
/// Wait for the GC thread to finish. On success, returns the object that implements
/// `StatsLogger` for the calling thread to examine.
pub fn join(self) -> Result<S, Box<Any + Send + 'static>> {
self.handle.join()
}
}
/// Main GC thread loop.
fn gc_thread<S, T>(num_threads: usize, rx_chan... | {
AppThread::spawn_from_gc(self.tx_chan.clone(), f)
} | identifier_body |
gcthread.rs | //! Garbage collection thread
use std::any::Any;
use std::cmp::min;
use std::mem::size_of;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use num_cpus;
use scoped_pool::Pool;
use appthread::AppThread;
use constants::{MAJOR_COLLECT_THRESHOLD, MAX_SLEEP_DUR, MIN_SLEEP_DUR};
use heap::{CollectOps, Obje... | <S: StatsLogger> {
/// This is cloned and given to app threads.
tx_chan: JournalSender,
/// The GC thread's handle to join on.
handle: thread::JoinHandle<S>,
}
impl GcThread<DefaultLogger> {
/// Spawn a GC thread with default parameters: a `ParHeap` and a `DefaultLogger` parallelized
/// acro... | GcThread | identifier_name |
test_pep8.py | #!/usr/bin/env python
import os.path
import unittest
import pep8 | SRC_PATH = os.path.dirname(os.path.dirname(__file__))
EXCLUDE = ['.svn', 'CVS', '.bzr', '.hg', '.git',
'Paste-1.7.5.1-py2.6.egg', 'PasteDeploy-1.5.0-py2.6.egg', 'data']
class AdhocracyStyleGuide(pep8.StyleGuide):
def ignore_code(self, code):
IGNORED = [
'E111', # indentation is not... | random_line_split | |
test_pep8.py | #!/usr/bin/env python
import os.path
import unittest
import pep8
SRC_PATH = os.path.dirname(os.path.dirname(__file__))
EXCLUDE = ['.svn', 'CVS', '.bzr', '.hg', '.git',
'Paste-1.7.5.1-py2.6.egg', 'PasteDeploy-1.5.0-py2.6.egg', 'data']
class AdhocracyStyleGuide(pep8.StyleGuide):
def | (self, code):
IGNORED = [
'E111', # indentation is not a multiple of four
'E121', # continuation line indentation is not a multiple of four
'E122', # continuation line missing indentation or outdented
'E123', # closing bracket does not match indentation of ope... | ignore_code | identifier_name |
test_pep8.py | #!/usr/bin/env python
import os.path
import unittest
import pep8
SRC_PATH = os.path.dirname(os.path.dirname(__file__))
EXCLUDE = ['.svn', 'CVS', '.bzr', '.hg', '.git',
'Paste-1.7.5.1-py2.6.egg', 'PasteDeploy-1.5.0-py2.6.egg', 'data']
class AdhocracyStyleGuide(pep8.StyleGuide):
| 'E501', # line too long
'E701', # multiple statements on one line
'E702', # multiple statements on one line
'E711', # comparison to None should be 'if cond is None:'
'E712', # comparison to True should be 'if cond is True:' or
# 'if c... | def ignore_code(self, code):
IGNORED = [
'E111', # indentation is not a multiple of four
'E121', # continuation line indentation is not a multiple of four
'E122', # continuation line missing indentation or outdented
'E123', # closing bracket does not match ind... | identifier_body |
asignacion-punto-juego.component.ts |
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { SelectionModel } from '@angular/cdk/collections';
import {MatTableDataSource} from '@angular/material/table';
import Swal from 'sweetalert2';
// Clases
import { Alumno, Equipo, Juego, Punto, AsignacionPuntosJuego} from '../../../clase... |
ngOnInit() {
console.log('Inicio el componente');
this.grupoId = this.sesion.DameGrupo().id;
this.juego = this.sesion.DameJuego();
this.profesorId = this.sesion.DameProfesor().id;
console.log(this.juego);
// traigo los tipos de puntos entre los que se puede seleccionar
this.peticionesA... | {} | identifier_body |
asignacion-punto-juego.component.ts |
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { SelectionModel } from '@angular/cdk/collections';
import {MatTableDataSource} from '@angular/material/table';
import Swal from 'sweetalert2';
// Clases
import { Alumno, Equipo, Juego, Punto, AsignacionPuntosJuego} from '../../../clase... | {
if (this.IsAllSelected()) {
this.selection.clear(); // Desactivamos todos
} else {
// activamos todos
this.dataSource.data.forEach(row => this.selection.select(row));
}
}
// Esta función decide si el boton de aceptar los tipos de puntos
// debe estar activo (si hay al menosuna fila... | terToggle() | identifier_name |
asignacion-punto-juego.component.ts | import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { SelectionModel } from '@angular/cdk/collections';
import {MatTableDataSource} from '@angular/material/table';
import Swal from 'sweetalert2';
// Clases
import { Alumno, Equipo, Juego, Punto, AsignacionPuntosJuego} from '../../../clases... |
tiposPuntos: Punto[];
seleccionados: boolean[];
displayedColumns: string[] = ['select', 'nombrePunto', 'descripcionPunto'];
selection = new SelectionModel<Punto>(true, []);
juego: Juego;
dataSource;
puntosSeleccionados: Punto[] = [];
botonTablaDesactivado = false;
puntoAleatorio: Punto;
constr... | grupoId: number;
profesorId: number;
// tslint:disable-next-line:ban-types
isDisabled: Boolean = true; | random_line_split |
asignacion-punto-juego.component.ts |
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { SelectionModel } from '@angular/cdk/collections';
import {MatTableDataSource} from '@angular/material/table';
import Swal from 'sweetalert2';
// Clases
import { Alumno, Equipo, Juego, Punto, AsignacionPuntosJuego} from '../../../clase... | }
// Esta función decide si el boton de aceptar los tipos de puntos
// debe estar activo (si hay al menosuna fila seleccionada)
HaSeleccionado() {
if (this.selection.selected.length === 0) {
return false;
} else {
return true;
}
}
AgregarTiposPuntosAlJuego() {
console.log ('Vamos ... | // activamos todos
this.dataSource.data.forEach(row => this.selection.select(row));
}
| conditional_block |
index-2.js | 24,26";
w["hat"]="0,2,5,8,11,14,19,21,25";
w["have"]="11,20,25,26";
w["head"]="14";
w["header"]="3";
w["horizon"]="10";
w["host"]="5,6,10,15,16,20,22,24,26";
w["host0"]="20,22";
w["host1"]="20,22";
w["host2"]="22";
w["host3"]="22";
w["host_id"]="20";
w["host_uuid"]="3";
w["hostnam"]="13,24";
w["howev"]="26";
w["hpet"]=... | w["neutron-metadata-ag"]="25"; | random_line_split | |
proxy_crawler.py | import asyncio
from itertools import compress
import traceback
from proxypool.rules.rule_base import CrawlerRuleBase
from proxypool.utils import page_download, page_download_phantomjs, logger, Result
class ProxyCrawler(object):
"""Crawl proxies according to the rules."""
def __init__(self, proxies, rules=No... | filters = zip(*filters)
selector = map(lambda x: x == rule.filters, filters)
proxies = compress(proxies, selector)
for proxy in proxies:
await self._proxies.put(proxy) # put proxies in Queue to validate
@staticmethod
def _url_generator(rule):
""... | ips = page.xpath(rule.ip_xpath)
ports = page.xpath(rule.port_xpath)
if not ips or not ports:
logger.warning('{2} crawler could not get ip(len={0}) or port(len={1}), please check the xpaths or network'.
format(len(ips), len(ports), rule.__rule_name__))
return
... | identifier_body |
proxy_crawler.py | import asyncio
from itertools import compress
import traceback
from proxypool.rules.rule_base import CrawlerRuleBase
from proxypool.utils import page_download, page_download_phantomjs, logger, Result
class ProxyCrawler(object):
"""Crawl proxies according to the rules."""
def __init__(self, proxies, rules=No... | self._pages = asyncio.Queue()
self._rules = rules if rules else CrawlerRuleBase.__subclasses__()
async def _parse_page(self):
while 1:
page = await self._pages.get()
await self._parse_proxy(page.rule, page.content)
self._pages.task_done()
async def... | self._stop_flag = asyncio.Event() # stop flag for crawler, not for validator | random_line_split |
proxy_crawler.py | import asyncio
from itertools import compress
import traceback
from proxypool.rules.rule_base import CrawlerRuleBase
from proxypool.utils import page_download, page_download_phantomjs, logger, Result
class ProxyCrawler(object):
"""Crawl proxies according to the rules."""
def __init__(self, proxies, rules=No... |
elif rule.next_page_xpath:
if page is None:
break
next_page = page.xpath(rule.next_page_xpath)
if next_page:
yield
page = yield Result(rule.next_page_host + str(next_page[0]).strip(), rule)
... | yield
yield Result(rule.urls_format.format(rule.start_url, i), rule) | conditional_block |
proxy_crawler.py | import asyncio
from itertools import compress
import traceback
from proxypool.rules.rule_base import CrawlerRuleBase
from proxypool.utils import page_download, page_download_phantomjs, logger, Result
class | (object):
"""Crawl proxies according to the rules."""
def __init__(self, proxies, rules=None):
"""Crawler init.
Args:
proxies: aysncio.Queue object
rules: crawler rules of each proxy web, should be iterable object
flag: stop flag for page downloading
... | ProxyCrawler | identifier_name |
main.rs | use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;
use std::collections::HashMap;
extern crate regex;
use regex::Regex;
enum Ineq {
Equals(i32),
GreaterThan(i32),
LessThan(i32),
}
// --------------------------------------------------------
fn find_sue... |
let reader = BufReader::new(file);
let lines = reader.lines();
let re = Regex::new(r"(?P<key>[:alpha:]+): (?P<value>\d+)").unwrap();
let mut sue_num = 0;
let mut sue_no_conflict = -1i32;
for line in lines {
let text = line.unwrap();
sue_num += 1;
let mut has_conflict = false;
for cap in re.... | random_line_split | |
main.rs |
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;
use std::collections::HashMap;
extern crate regex;
use regex::Regex;
enum Ineq {
Equals(i32),
GreaterThan(i32),
LessThan(i32),
}
// --------------------------------------------------------
fn find_su... |
},
_ => {},
}
}
if !has_conflict {
println!("Sue {} has no conflicts", sue_num);
sue_no_conflict = sue_num;
}
}
sue_no_conflict
}
// --------------------------------------------------------
fn main() {
println!("Running part 1...");
let mut sue_stats_exact = HashMap::new();
sue_stats... | {
has_conflict = true;
} | conditional_block |
main.rs |
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;
use std::collections::HashMap;
extern crate regex;
use regex::Regex;
enum | {
Equals(i32),
GreaterThan(i32),
LessThan(i32),
}
// --------------------------------------------------------
fn find_sue (constraints: &HashMap<&str, Ineq>, filename: &str) -> i32 {
let path = Path::new(filename);
let display = path.display();
// Open the path in read-only mode, returns `io::Result<Fi... | Ineq | identifier_name |
ascii_chars_increasing.rs | use malachite_base::chars::exhaustive::ascii_chars_increasing;
#[test]
fn | () {
assert_eq!(
ascii_chars_increasing().collect::<String>(),
"\u{0}\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}\u{7}\u{8}\t\n\u{b}\u{c}\r\u{e}\u{f}\u{10}\u{11}\u{12}\
\u{13}\u{14}\u{15}\u{16}\u{17}\u{18}\u{19}\u{1a}\u{1b}\u{1c}\u{1d}\u{1e}\u{1f} !\"#$%&\'()*\
+,-./0123456789:;<=>?@ABCDEFGHIJKLMN... | test_ascii_chars_increasing | identifier_name |
ascii_chars_increasing.rs | use malachite_base::chars::exhaustive::ascii_chars_increasing;
#[test]
fn test_ascii_chars_increasing() | {
assert_eq!(
ascii_chars_increasing().collect::<String>(),
"\u{0}\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}\u{7}\u{8}\t\n\u{b}\u{c}\r\u{e}\u{f}\u{10}\u{11}\u{12}\
\u{13}\u{14}\u{15}\u{16}\u{17}\u{18}\u{19}\u{1a}\u{1b}\u{1c}\u{1d}\u{1e}\u{1f} !\"#$%&\'()*\
+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQ... | identifier_body | |
ascii_chars_increasing.rs | use malachite_base::chars::exhaustive::ascii_chars_increasing;
#[test]
fn test_ascii_chars_increasing() {
assert_eq!(
ascii_chars_increasing().collect::<String>(),
"\u{0}\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}\u{7}\u{8}\t\n\u{b}\u{c}\r\u{e}\u{f}\u{10}\u{11}\u{12}\
\u{13}\u{14}\u{15}\u{16}\u{17}\u{18... | );
assert_eq!(ascii_chars_increasing().count(), 1 << 7);
} | random_line_split | |
51_N-Queens.py | class Solution(object):
def | (self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
def search(cur):
if cur == n:
add_answer()
else:
for i in range(n):
ok = True
rows[cur] = i
for j in range(... | solveNQueens | identifier_name |
51_N-Queens.py | class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
def search(cur):
if cur == n:
add_answer()
else:
for i in range(n):
ok = True
rows[... |
else:
return True
def add_answer():
ans = []
for num in rows:
res_str = ""
for i in range(n):
if i == num:
res_str += "Q"
else:
res_str +... | return False | conditional_block |
51_N-Queens.py | class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
def search(cur):
if cur == n:
add_answer()
else:
for i in range(n):
ok = True
rows[... | ans.append(res_str)
result.append(ans)
result = []
rows = [0] * n
search(0)
return result
print Solution().solveNQueens(4) | if i == num:
res_str += "Q"
else:
res_str += "." | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.