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 |
|---|---|---|---|---|
genesis_builder.py | # -*- coding: utf-8 -*-
from ethereum.utils import sha3, encode_hex, denoms
from raiden.utils import privatekey_to_address
from raiden.tests.utils.blockchain import GENESIS_STUB
CLUSTER_NAME = 'raiden'
def | (seeds):
"""Create private keys and addresses for all seeds.
"""
return {
seed: dict(
privatekey=encode_hex(sha3(seed)),
address=encode_hex(privatekey_to_address(sha3(seed)))
) for seed in seeds}
def mk_genesis(accounts, initial_alloc=denoms.ether * 100000000):
... | generate_accounts | identifier_name |
genesis_builder.py | # -*- coding: utf-8 -*-
from ethereum.utils import sha3, encode_hex, denoms
from raiden.utils import privatekey_to_address | def generate_accounts(seeds):
"""Create private keys and addresses for all seeds.
"""
return {
seed: dict(
privatekey=encode_hex(sha3(seed)),
address=encode_hex(privatekey_to_address(sha3(seed)))
) for seed in seeds}
def mk_genesis(accounts, initial_alloc=denoms.eth... | from raiden.tests.utils.blockchain import GENESIS_STUB
CLUSTER_NAME = 'raiden'
| random_line_split |
build.rs | // Copyright 2017 The Xyrosource Team.
//
// 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except acco... |
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let version_file = Path::new(&out_dir).join("version.rs");
let mut fil = File::create(&version_file).unwrap();
let cargo_version = env!("CARGO_PKG_VERSION").to_owned();
... | // https://github.com/simias/pockystation/blob/master/build.rs | random_line_split |
build.rs | // Copyright 2017 The Xyrosource Team.
//
// 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except acco... | {
let out_dir = env::var("OUT_DIR").unwrap();
let version_file = Path::new(&out_dir).join("version.rs");
let mut fil = File::create(&version_file).unwrap();
let cargo_version = env!("CARGO_PKG_VERSION").to_owned();
writeln!(fil, "pub const VERSION: &'static str = \
\"{}\";", cargo... | identifier_body | |
build.rs | // Copyright 2017 The Xyrosource Team.
//
// 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except acco... | () {
let out_dir = env::var("OUT_DIR").unwrap();
let version_file = Path::new(&out_dir).join("version.rs");
let mut fil = File::create(&version_file).unwrap();
let cargo_version = env!("CARGO_PKG_VERSION").to_owned();
writeln!(fil, "pub const VERSION: &'static str = \
\"{}\";", ca... | main | identifier_name |
rotate.js | module.exports = rotate
/**
* Rotates a mat2 by the given angle
*
* @alias mat2.rotate
* @param {mat2} out the receiving matrix
* @param {mat2} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat2} out
*/
function rotate(out, a, rad) {
var a0 = a[0], a1 = a[1], a2 =... | return out
} | out[2] = a0 * -s + a2 * c
out[3] = a1 * -s + a3 * c | random_line_split |
rotate.js | module.exports = rotate
/**
* Rotates a mat2 by the given angle
*
* @alias mat2.rotate
* @param {mat2} out the receiving matrix
* @param {mat2} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat2} out
*/
function | (out, a, rad) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3]
var s = Math.sin(rad)
var c = Math.cos(rad)
out[0] = a0 * c + a2 * s
out[1] = a1 * c + a3 * s
out[2] = a0 * -s + a2 * c
out[3] = a1 * -s + a3 * c
return out
}
| rotate | identifier_name |
rotate.js | module.exports = rotate
/**
* Rotates a mat2 by the given angle
*
* @alias mat2.rotate
* @param {mat2} out the receiving matrix
* @param {mat2} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat2} out
*/
function rotate(out, a, rad) | {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3]
var s = Math.sin(rad)
var c = Math.cos(rad)
out[0] = a0 * c + a2 * s
out[1] = a1 * c + a3 * s
out[2] = a0 * -s + a2 * c
out[3] = a1 * -s + a3 * c
return out
} | identifier_body | |
json.js | /*
* ______ _____ _____ _ _____________ _________________ ____________
* | ___ \ _ / __ \| | / /_ _| ___ \ ___| ___| ___| | ___ \ ___ \
* | |_/ / | | | / \/| |/ / | | | |_/ / |__ | |_ | |_ | |_/ / |_/ /
* | /| | | | | | \ | | | /| __|| _| | _| | ___ \ ___ \
* | |\ \\ \_/ / \__/\... | case 'number':
obj[ key ] = property.default || 0
}
}
return obj
}
module.exports = function ( template ) {
template = createFromSchema( template )
return {
create: function ( obj ) {
return new Promise( function ( resolve ) {
resolve( _.defaults( obj, template ) )
})
},
omit: function... | random_line_split | |
json.js | /*
* ______ _____ _____ _ _____________ _________________ ____________
* | ___ \ _ / __ \| | / /_ _| ___ \ ___| ___| ___| | ___ \ ___ \
* | |_/ / | | | / \/| |/ / | | | |_/ / |__ | |_ | |_ | |_/ / |_/ /
* | /| | | | | | \ | | | /| __|| _| | _| | ___ \ ___ \
* | |\ \\ \_/ / \__/\... | }
module.exports = function ( template ) {
template = createFromSchema( template )
return {
create: function ( obj ) {
return new Promise( function ( resolve ) {
resolve( _.defaults( obj, template ) )
})
},
omit: function () {
var args = Array.prototype.slice.call( arguments )
return functi... | var obj = {}
if ( !schema || !schema.properties ) return obj
var properties = schema.properties
for ( var key in properties ) {
if ( !properties.hasOwnProperty( key ) ) continue
var property = properties[ key ]
switch ( property.type.toLowerCase() ) {
case 'object':
obj[ key ] = createFromSchema( prope... | identifier_body |
json.js | /*
* ______ _____ _____ _ _____________ _________________ ____________
* | ___ \ _ / __ \| | / /_ _| ___ \ ___| ___| ___| | ___ \ ___ \
* | |_/ / | | | / \/| |/ / | | | |_/ / |__ | |_ | |_ | |_/ / |_/ /
* | /| | | | | | \ | | | /| __|| _| | _| | ___ \ ___ \
* | |\ \\ \_/ / \__/\... | schema ) {
var obj = {}
if ( !schema || !schema.properties ) return obj
var properties = schema.properties
for ( var key in properties ) {
if ( !properties.hasOwnProperty( key ) ) continue
var property = properties[ key ]
switch ( property.type.toLowerCase() ) {
case 'object':
obj[ key ] = createFromSc... | eateFromSchema( | identifier_name |
trader.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
import yaml
import logging
import threading
from ybk.lighttrade.sysframe import Client as SysframeClient
log = logging.getLogger('trader')
configfile = open(os.path.join(os.path.dirname(__file__), 'trading.yaml'), encoding='utf-8')
config = yaml.loa... | Client(front_url=d['front_url'],
tradeweb_url=d['tradeweb_url'])
setattr(self.client, 'exchange', exchange)
self.client.login(username, password)
self.traders[signature] = self
else:
old = self.traders[signa... | _url']]
self.client = | conditional_block |
trader.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
import yaml
import logging
import threading
from ybk.lighttrade.sysframe import Client as SysframeClient
log = logging.getLogger('trader')
configfile = open(os.path.join(os.path.dirname(__file__), 'trading.yaml'), encoding='utf-8')
config = yaml.loa... | def __init__(self, exchange, username=None, password=None):
""" 登陆并缓存Trader Object """
with lock:
d = config[exchange]
if d['system'] == 'sysframe':
Client = SysframeClient
elif d['system'] == 'winner':
raise NotImplementedError
... | random_line_split | |
trader.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
import yaml
import logging
import threading
from ybk.lighttrade.sysframe import Client as SysframeClient
log = logging.getLogger('trader')
configfile = open(os.path.join(os.path.dirname(__file__), 'trading.yaml'), encoding='utf-8')
config = yaml.loa... | pass
| t0 + self.client.time_offset + self.client.latency * 3
if __name__ == '__main__':
| identifier_body |
trader.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
import yaml
import logging
import threading
from ybk.lighttrade.sysframe import Client as SysframeClient
log = logging.getLogger('trader')
configfile = open(os.path.join(os.path.dirname(__file__), 'trading.yaml'), encoding='utf-8')
config = yaml.loa... | xchange, username=None, password=None):
""" 登陆并缓存Trader Object """
with lock:
d = config[exchange]
if d['system'] == 'sysframe':
Client = SysframeClient
elif d['system'] == 'winner':
raise NotImplementedError
if username is... | (self, e | identifier_name |
poly.rs | use crate::geometry::*;
use std::f64::consts;
use std::iter::{Repeat, repeat};
/// Refers to an implementation of a polygon
pub trait Poly : TwoDTransformable {
fn get_corners(&self) -> Vec<Point>;
fn set_corners(&mut self, corners: Vec<Point>);
// Normals face outwards
fn normals(&self) -> Vec<Point... | (&self, index: usize) -> Option<Line> {
self.sides_iter().nth(index).and_then(|(beg, end)| {Some(Line::new(beg, end))})
}
fn sides_iter<'a>(&'a self) -> Box<dyn Iterator<Item=(Point, Point)> + 'a> {
let corners_it_shift = self.get_corners().into_iter().cycle().skip(1);
Box::new(self.get... | get_side | identifier_name |
poly.rs | use crate::geometry::*;
use std::f64::consts;
use std::iter::{Repeat, repeat};
/// Refers to an implementation of a polygon
pub trait Poly : TwoDTransformable {
fn get_corners(&self) -> Vec<Point>;
fn set_corners(&mut self, corners: Vec<Point>);
// Normals face outwards
fn normals(&self) -> Vec<Point... |
fn total_sides(&self) -> usize {
self.get_corners().len()
}
fn get_corner_lines(&self, other: &dyn Poly) -> Vec<Line> {
self.get_corners().into_iter()
.zip(other.get_corners().into_iter())
.map(|(beg, end)| { Line::new(beg, end) })
.collect()
}
fn get_shift... | } | random_line_split |
poly.rs | use crate::geometry::*;
use std::f64::consts;
use std::iter::{Repeat, repeat};
/// Refers to an implementation of a polygon
pub trait Poly : TwoDTransformable {
fn get_corners(&self) -> Vec<Point>;
fn set_corners(&mut self, corners: Vec<Point>);
// Normals face outwards
fn normals(&self) -> Vec<Point... |
fn get_shift(&self, other: &dyn Poly) -> Point {
other.get_corners()[0] - self.get_corners()[0]
}
}
pub fn get_at_time<T: Poly + Sized + Clone>(poly: &T, shift: Point, time: f64) -> T {
let mut out = poly.clone();
out.shift_by(time * shift);
out
}
pub fn get_shifted<T: Poly + Sized + Clo... | {
self.get_corners().into_iter()
.zip(other.get_corners().into_iter())
.map(|(beg, end)| { Line::new(beg, end) })
.collect()
} | identifier_body |
logreader.py | __author__ = 'bdeutsch'
import re
import numpy as np
import pandas as pd
# List cards drawn by me and played by opponent
def get_cards(filename):
# Open the file
with open(filename) as f:
mycards = []
oppcards = []
for line in f:
# Generate my revealed card list
... |
n = re.search('name=(.+)id.+to OPPOSING PLAY(?! \(Hero)', line)
if n:
oppcards.append(n.group(1))
for item in mycards:
print item
print '\n'
for item in oppcards:
print item
# make a list of card IDs and names
def get_ids():
# Create an empty l... | mycards.append(m.group(1)) | conditional_block |
logreader.py | __author__ = 'bdeutsch'
import re
import numpy as np
import pandas as pd
# List cards drawn by me and played by opponent
def get_cards(filename):
# Open the file
with open(filename) as f:
mycards = []
oppcards = []
for line in f:
# Generate my revealed card list
... | d["Name"] = np.nan
#print d
return d
# make a list of card names only if followed by id
def get_names():
with open('test_game') as f:
for line in f:
# Find the entity ids
m = re.search('[\[ ]name=([\w ]+?) id=', line)
if m:
print m.group(1)... | idlist = []
with open('test_game') as f:
# For each line
for line in f:
# Find the entity ids
m = re.search('[\[ ]id=(\d+) ', line)
# if one is found
if m:
# Check that we haven't found it yet, convert to an integer
id =... | identifier_body |
logreader.py | __author__ = 'bdeutsch'
import re
import numpy as np
import pandas as pd
# List cards drawn by me and played by opponent
def get_cards(filename):
# Open the file
with open(filename) as f:
mycards = []
oppcards = []
for line in f:
# Generate my revealed card list
... | (df):
with open('test_game') as f:
namedict = {}
for line in f:
# Find combinations of entities and names
m = re.search('[\[ ]name=([\w ]+?) id=(\d+)', line)
if m:
ent_id = int(m.group(2))
name = m.group(1)
df.ix[ent... | get_ids_names | identifier_name |
logreader.py | __author__ = 'bdeutsch'
import re
import numpy as np
import pandas as pd
# List cards drawn by me and played by opponent
def get_cards(filename):
# Open the file
with open(filename) as f:
mycards = []
oppcards = []
for line in f:
# Generate my revealed card list
... |
for item in mycards:
print item
print '\n'
for item in oppcards:
print item
# make a list of card IDs and names
def get_ids():
# Create an empty list of IDs
idlist = []
with open('test_game') as f:
# For each line
for line in f:
# Find the entity ids... |
n = re.search('name=(.+)id.+to OPPOSING PLAY(?! \(Hero)', line)
if n:
oppcards.append(n.group(1)) | random_line_split |
build-sentence-video.exercise.ts | import { sample } from '../../sample';
import {
AbstractExercise,
ExerciseFixture,
ExercisePropsFixture
} from './abstract-exercise.interface';
export interface BuildSentenceVideoProps {
/* tslint:disable-next-line:no-any */
sentence: any;
}
export type BuildSentenceVideoState = string[];
export type Build... | );
super({ sentence });
this.sentence = props.sentence;
}
public getInitialState(): BuildSentenceVideoState {
return [];
}
public getFeedback(
currentSentence: BuildSentenceVideoState
): BuildSentenceVideoFeedback {
return undefined;
}
public isCorrect(currentSentence: BuildSe... | const sentence = sample(
props.sentence.split(' '),
props.sentence.split(' ').length | random_line_split |
build-sentence-video.exercise.ts | import { sample } from '../../sample';
import {
AbstractExercise,
ExerciseFixture,
ExercisePropsFixture
} from './abstract-exercise.interface';
export interface BuildSentenceVideoProps {
/* tslint:disable-next-line:no-any */
sentence: any;
}
export type BuildSentenceVideoState = string[];
export type Build... | (
currentSentence: BuildSentenceVideoState
): BuildSentenceVideoFeedback {
return undefined;
}
public isCorrect(currentSentence: BuildSentenceVideoState) {
return currentSentence.join(' ') === this.sentence;
}
}
| getFeedback | identifier_name |
rpc.rs | use crate::{
agent::{Agent, AgentId},
group::{Group, GroupError, GroupSettings},
handle::OpId,
};
use libp2p::PeerId;
use serde::{Deserialize, Serialize};
use std::{
borrow::Borrow,
convert::{TryFrom, TryInto},
fmt::{Debug, Display},
};
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize)]
#... |
pub(crate) fn new_group(group: Group) -> Resource {
Resource(ResourceKind::Group(group))
}
/// Create a resource of agent kind. Returns both the identifier (key) and the resource
/// handle.
pub(crate) fn agent(agent_id: AgentId, peer_id: PeerId) -> (ResourceIdentifier, Agent) {
l... | {
Resource(ResourceKind::Agent(agent))
} | identifier_body |
rpc.rs | use crate::{
agent::{Agent, AgentId},
group::{Group, GroupError, GroupSettings},
handle::OpId,
};
use libp2p::PeerId;
use serde::{Deserialize, Serialize};
use std::{
borrow::Borrow,
convert::{TryFrom, TryInto},
fmt::{Debug, Display},
};
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize)]
#... |
impl ResourceIdentifier {
const KIND_SIZE: usize = 1;
const KEY_SIZE: usize = std::mem::size_of::<u128>();
/// This key represents a group resource kind.
pub(crate) fn group(id: &Uuid) -> ResourceIdentifier {
let id = id.as_u128().to_be_bytes();
let kind = ResourceKeyKind::GroupId as u... | random_line_split | |
rpc.rs | use crate::{
agent::{Agent, AgentId},
group::{Group, GroupError, GroupSettings},
handle::OpId,
};
use libp2p::PeerId;
use serde::{Deserialize, Serialize};
use std::{
borrow::Borrow,
convert::{TryFrom, TryInto},
fmt::{Debug, Display},
};
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize)]
#... | (agent: Agent) -> Resource {
Resource(ResourceKind::Agent(agent))
}
pub(crate) fn new_group(group: Group) -> Resource {
Resource(ResourceKind::Group(group))
}
/// Create a resource of agent kind. Returns both the identifier (key) and the resource
/// handle.
pub(crate) fn agent... | new_agent | identifier_name |
KeyParser.ts | /**
* KeyParser.ts
*
* Simple parsing logic to take vim key bindings / chords,
* and return a normalized object.
*/
export interface IKey {
character: string
shift: boolean
alt: boolean
control: boolean
meta: boolean
}
export interface IKeyChord {
chord: IKey[]
}
export const parseKeysFr... | const firstChord = parsedKeys.chord[0]
const chordParts: string[] = []
if (firstChord.meta) {
chordParts.push("meta")
}
if (firstChord.control) {
chordParts.push("control")
}
if (firstChord.alt) {
chordParts.push("alt")
}
if (firstChord.shift) {
c... | random_line_split | |
KeyParser.ts | /**
* KeyParser.ts
*
* Simple parsing logic to take vim key bindings / chords,
* and return a normalized object.
*/
export interface IKey {
character: string
shift: boolean
alt: boolean
control: boolean
meta: boolean
}
export interface IKeyChord {
chord: IKey[]
}
export const parseKeysFr... |
if (firstChord.alt) {
chordParts.push("alt")
}
if (firstChord.shift) {
chordParts.push("shift")
}
chordParts.push(firstChord.character)
return chordParts
}
| {
chordParts.push("control")
} | conditional_block |
events.d.ts | export interface Disposable {
/**
* Dispose this object.
*/
dispose(): any;
}
/**
* Represents a typed event.
*/
export interface Event<T> {
| * @param listener The listener function will be call when the event happens.
* @param thisArgs The 'this' which will be used when calling the event listener.
* @param disposables An array to which a {{IDisposable}} will be added. The
* @return
*/
(listener: (e: T) => any, thisArgs?: any... | /**
*
| random_line_split |
events.d.ts | export interface Disposable {
/**
* Dispose this object.
*/
dispose(): any;
}
/**
* Represents a typed event.
*/
export interface Event<T> {
/**
*
* @param listener The listener function will be call when the event happens.
* @param thisArgs The 'this' which will be u... | <T> {
private _options;
private static _noop;
private _event;
private _callbacks;
constructor(_options?: EmitterOptions);
/**
* For the public to allow to subscribe
* to events from this Emitter
*/
event: Event<T>;
/**
* To be kept private to fire an event... | Emitter | identifier_name |
part_of_speech.py | from py2neo import neo4j
from nltk.corpus import wordnet as wn
from collections import defaultdict
import operator
#this routine will scan each word in the phrase, and if it has a hyphenation, attach that information in a node via the edge
#it will also attach both sides of the hypenation as new nodes
def | (graph_db):
#get all word nodes from db
word_nodes_query = neo4j.CypherQuery(graph_db, 'MATCH (n) WHERE n.type="word" RETURN (n)')
word_nodes = word_nodes_query.execute()
words = [node.values[0]['name'] for node in word_nodes.data]
for i in range(0, len(words)):
syns = wn.synsets(words[i])
... | analyze | identifier_name |
part_of_speech.py | from py2neo import neo4j
from nltk.corpus import wordnet as wn
from collections import defaultdict
import operator
#this routine will scan each word in the phrase, and if it has a hyphenation, attach that information in a node via the edge
#it will also attach both sides of the hypenation as new nodes
def analyze(gr... | pos = max(pos_count.iteritems(), key=operator.itemgetter(1))[0]
graph_db.create({"type": "partofspeech", "name": pos, "points": 0},
(word_nodes.data[i][0], "POS", 0, {"points": 0})) | conditional_block | |
part_of_speech.py | from py2neo import neo4j
from nltk.corpus import wordnet as wn
from collections import defaultdict
import operator
#this routine will scan each word in the phrase, and if it has a hyphenation, attach that information in a node via the edge
#it will also attach both sides of the hypenation as new nodes
def analyze(gr... | word_nodes_query = neo4j.CypherQuery(graph_db, 'MATCH (n) WHERE n.type="word" RETURN (n)')
word_nodes = word_nodes_query.execute()
words = [node.values[0]['name'] for node in word_nodes.data]
for i in range(0, len(words)):
syns = wn.synsets(words[i])
#to determine the part of speech, take th... | identifier_body | |
part_of_speech.py | from py2neo import neo4j
from nltk.corpus import wordnet as wn
from collections import defaultdict
import operator
#this routine will scan each word in the phrase, and if it has a hyphenation, attach that information in a node via the edge
#it will also attach both sides of the hypenation as new nodes
def analyze(gr... | words = [node.values[0]['name'] for node in word_nodes.data]
for i in range(0, len(words)):
syns = wn.synsets(words[i])
#to determine the part of speech, take the majority pos from all synsets
pos_count = defaultdict(int)
for s in syns:
pos_count[s.pos] += 1
i... | word_nodes = word_nodes_query.execute() | random_line_split |
article.js | import size from 'lodash/size';
import map from 'lodash/map';
import React from 'react';
import PropTypes from 'prop-types';
import validateURL from 'react-proptypes-url-validator';
import { Link } from 'react-router';
import FontAwesome from 'react-fontawesome';
import Button from 'react-bootstrap/lib/Button';
import ... | pAdvEl.style.padding = '10px 0';
pAdvEl.innerHTML = this.getParagraphAdv();
targetEl.parentElement.insertBefore(pAdvEl, targetEl);
//setTimeout(() => {
(adsbygoogle = window.adsbygoogle || []).push({});
//}, 200);
}
}
goBack = () => {
const pathname = browserHistory.ge... | const pEls = content.getElementsByTagName('p');
const totalP = pEls.length;
if (totalP > 2 && !window.wgLazyAddBlockerDetected) {
const targetEl = pEls[Math.round(totalP * 0.7)];
const pAdvEl = document.createElement('div'); | random_line_split |
article.js | import size from 'lodash/size';
import map from 'lodash/map';
import React from 'react';
import PropTypes from 'prop-types';
import validateURL from 'react-proptypes-url-validator';
import { Link } from 'react-router';
import FontAwesome from 'react-fontawesome';
import Button from 'react-bootstrap/lib/Button';
import ... | () {
const { isLoading } = this.props;
if (isLoading) {
return this.renderLoading();
}
return (
<Row>
<Col lg={10} lgOffset={1}>
<article styleName="article" >
{ this.renderHeader() }
{ this.renderError() }
{ this.renderArticle() }
... | render | identifier_name |
article.js | import size from 'lodash/size';
import map from 'lodash/map';
import React from 'react';
import PropTypes from 'prop-types';
import validateURL from 'react-proptypes-url-validator';
import { Link } from 'react-router';
import FontAwesome from 'react-fontawesome';
import Button from 'react-bootstrap/lib/Button';
import ... |
}
createAdvertiseIfIsPossible = (content) => {
const pEls = content.getElementsByTagName('p');
const totalP = pEls.length;
if (totalP > 2 && !window.wgLazyAddBlockerDetected) {
const targetEl = pEls[Math.round(totalP * 0.7)];
const pAdvEl = document.createElement('div');
pAdvEl.styl... | {
this.articleContentEl = el;
const {contentEl} = this.props.article;
this.createAdvertiseIfIsPossible(contentEl);
el.appendChild(contentEl);
} | conditional_block |
socket.service.ts | import { Injectable } from '@angular/core';
import { Subject, Observable, Observer } from 'rxjs';
import * as SocketIO from 'socket.io-client';
import { SocketMessageType } from './socketMessageType.enum';
@Injectable()
export class SocketService {
private socket: any;
private socketSubject: Subject<any>;
constr... |
}
subcribe(messageType: SocketMessageType, message: any): void {
this.socketSubject.next({
type: messageType,
message: message
});
}
}
| {
this.socket.emit(SocketMessageType[messageType], message);
} | conditional_block |
socket.service.ts | import { Injectable } from '@angular/core';
import { Subject, Observable, Observer } from 'rxjs';
import * as SocketIO from 'socket.io-client';
import { SocketMessageType } from './socketMessageType.enum';
@Injectable()
export class SocketService {
private socket: any;
private socketSubject: Subject<any>;
constr... |
subcribe(messageType: SocketMessageType, message: any): void {
this.socketSubject.next({
type: messageType,
message: message
});
}
}
| {
if (this.socket) {
this.socket.emit(SocketMessageType[messageType], message);
}
} | identifier_body |
socket.service.ts | import { Injectable } from '@angular/core';
import { Subject, Observable, Observer } from 'rxjs';
import * as SocketIO from 'socket.io-client';
import { SocketMessageType } from './socketMessageType.enum';
@Injectable()
export class SocketService {
private socket: any;
private socketSubject: Subject<any>;
| () {
this.socket = undefined;
this.socketSubject = new Subject<any>();
}
connect(): Observable<any> {
if (!this.socket) {
this.socket = SocketIO('http://192.168.1.141:3000');
}
this.socket.on(SocketMessageType[SocketMessageType.USERLIST], (msg) => this.subcribe(SocketMessageType.USERLIST, msg))
this.s... | constructor | identifier_name |
socket.service.ts | import { Injectable } from '@angular/core';
import { Subject, Observable, Observer } from 'rxjs';
import * as SocketIO from 'socket.io-client';
import { SocketMessageType } from './socketMessageType.enum';
@Injectable()
export class SocketService {
private socket: any;
private socketSubject: Subject<any>;
constr... | this.socket.on(SocketMessageType[SocketMessageType.CALLING], (msg) => this.subcribe(SocketMessageType.CALLING, msg))
this.socket.on(SocketMessageType[SocketMessageType.CANCEL], (msg) => this.subcribe(SocketMessageType.CANCEL, msg))
this.socket.on(SocketMessageType[SocketMessageType.CONFIRM], (msg) => this.subcrib... | random_line_split | |
addPermissionLevel.ts | import { RoleDefinition } from "gd-sprest-def/lib/SP";
import { IaddPermissionLevel, IaddPermissionLevelProps } from "../../../@types/helper/methods";
import { Site } from "../../lib";
declare var SP;
/**
* Adds a permission level to the current or specified web.
*/
export const addPermissionLevel: IaddPermissionLev... | }
});
} | // Reject the request
reject("The 'SP' core library is not available."); | random_line_split |
addPermissionLevel.ts | import { RoleDefinition } from "gd-sprest-def/lib/SP";
import { IaddPermissionLevel, IaddPermissionLevelProps } from "../../../@types/helper/methods";
import { Site } from "../../lib";
declare var SP;
/**
* Adds a permission level to the current or specified web.
*/
export const addPermissionLevel: IaddPermissionLev... | let roleDef = ctx.get_site().get_rootWeb().get_roleDefinitions().add(roleDefInfo);
ctx.load(roleDef);
// Execute the request
ctx.executeQueryAsync(() => {
// Get the role definition
Site(props.WebUrl).RootWeb().RoleDefinitions().getById(ro... | {
// Set the context and get the role definitions
let ctx = props.WebUrl ? new SP.ClientContext(props.WebUrl) : SP.ClientContext.get_current();
// Set the base permissions
let basePermissions = new SP.BasePermissions();
let permissions = props.Permissions || ... | conditional_block |
paytoedit.py | ) 2012 thomasv@gitorious
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, s... | (self, is_max):
if self.payto_address:
if is_max:
amount = '!'
else:
amount = self.amount_edit.get_amount()
_type, addr = self.payto_address
self.outputs = [(_type, addr, amount)]
return self.outputs[:]
def lines(self... | get_outputs | identifier_name |
paytoedit.py | ) 2012 thomasv@gitorious
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, s... |
self.is_alias = True
address = data.get('address')
name = data.get('name')
new_url = key + ' <' + address + '>'
self.setText(new_url)
self.previous_payto = new_url
#if self.win.config.get('openalias_autoadd') == 'checked':
self.win.contacts[key] = ('ope... | return | conditional_block |
paytoedit.py | C) 2012 thomasv@gitorious
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, ... | return
try:
self.payto_address = self.parse_output(data)
except:
pass
if self.payto_address:
self.win.lock_amount(False)
return
is_max = False
for i, line in enumerate(lines):
... | self.scan_f(data) | random_line_split |
paytoedit.py | ) 2012 thomasv@gitorious
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, s... |
address = data.get('address')
name = data.get('name')
new_url = key + ' <' + address + '>'
self.setText(new_url)
self.previous_payto = new_url
#if self.win.config.get('openalias_autoadd') == 'checked':
self.win.contacts[key] = ('openalias', name)
self.wi... | self.is_alias = False
if self.hasFocus():
return
if self.is_multiline(): # only supports single line entries atm
return
if self.is_pr:
return
key = str(self.toPlainText())
if key == self.previous_payto:
return
self.previous... | identifier_body |
local_ptr.rs | turns out this causes
// trouble with green threads and lots of optimizations turned on. The
// following case study was done on linux x86_64, but I would imagine that
// other platforms are similar.
//
// On linux, the instruction sequence for loading the tls pointer global
// looks like:
... | maybe_tls_key | identifier_name | |
local_ptr.rs | , the
/// pointer is returned.
pub struct Borrowed<T> {
val: *const (),
}
#[unsafe_destructor]
impl<T> Drop for Borrowed<T> {
fn drop(&mut self) {
unsafe {
if self.val.is_null() {
rtabort!("Aiee, returning null borrowed object!");
}
let val: Box<T> = ... | tls::destroy(RT_TLS_KEY);
}
/// Give a pointer to thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn put<T>(sched: Box<T>) {
let key = tls_key();
let void_ptr: *mut u8 = mem::transmute(sched);
t... | random_line_split | |
local_ptr.rs | the
/// pointer is returned.
pub struct Borrowed<T> {
val: *const (),
}
#[unsafe_destructor]
impl<T> Drop for Borrowed<T> {
fn drop(&mut self) {
unsafe {
if self.val.is_null() {
rtabort!("Aiee, returning null borrowed object!");
}
let val: Box<T> = m... |
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn take<T>() -> Box<T> {
let key = tls_key();
let void_ptr: *mut u8 = tls::get(key);
if void_ptr.is_null() {
... | {
let key = tls_key();
let void_ptr: *mut u8 = mem::transmute(sched);
tls::set(key, void_ptr);
} | identifier_body |
decorators.py | from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect, Http404
def no_permissions_redirect(request):
np_page = reverse('no_permissions')
return HttpResponseRedirect(np_page) if request.method == 'GET' else HttpResponse("Missing qualifications")
def check_and_... | def org_member_required(view_func):
def shim(request, org, *args, **kwargs):
check_and_set_org(request, org)
if not hasattr(request, 'couch_user') or not\
(request.couch_user.is_member_of_org(org) or request.couch_user.is_superuser):
return no_permissions_redirect(request)
... | return shim
| random_line_split |
decorators.py | from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect, Http404
def no_permissions_redirect(request):
np_page = reverse('no_permissions')
return HttpResponseRedirect(np_page) if request.method == 'GET' else HttpResponse("Missing qualifications")
def check_and_... |
req.organization = organization
def org_admin_required(view_func):
def shim(request, org, *args, **kwargs):
check_and_set_org(request, org)
if not hasattr(request, 'couch_user') or not \
(request.couch_user.is_org_admin(org) or request.couch_user.is_superuser):
return no_pe... | raise Http404 | conditional_block |
decorators.py | from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect, Http404
def no_permissions_redirect(request):
np_page = reverse('no_permissions')
return HttpResponseRedirect(np_page) if request.method == 'GET' else HttpResponse("Missing qualifications")
def check_and_... | (view_func):
def shim(request, org, *args, **kwargs):
check_and_set_org(request, org)
if not hasattr(request, 'couch_user') or not\
(request.couch_user.is_member_of_org(org) or request.couch_user.is_superuser):
return no_permissions_redirect(request)
else:
ret... | org_member_required | identifier_name |
decorators.py | from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect, Http404
def no_permissions_redirect(request):
np_page = reverse('no_permissions')
return HttpResponseRedirect(np_page) if request.method == 'GET' else HttpResponse("Missing qualifications")
def check_and_... |
return shim
def org_member_required(view_func):
def shim(request, org, *args, **kwargs):
check_and_set_org(request, org)
if not hasattr(request, 'couch_user') or not\
(request.couch_user.is_member_of_org(org) or request.couch_user.is_superuser):
return no_permissions_redire... | check_and_set_org(request, org)
if not hasattr(request, 'couch_user') or not \
(request.couch_user.is_org_admin(org) or request.couch_user.is_superuser):
return no_permissions_redirect(request)
else:
return view_func(request, org, *args, **kwargs) | identifier_body |
comparison.py | import ecj
import scipy
import numpy
import operator
import networkx as nx
#from progressbar import ProgressBar, Percentage
numpy.random.RandomState()
import bfutils as bfu
import numpy as np
import gmpy as gmp
def num2CG(num,n):
"""num2CG - converts a number whose binary representaion encodes edge
presence/a... | G = num2CG(scipy.random.randint(2**(n**2)),n)
while (len(ecj.scc(G)) > 1) or gcd4scc(G)>1:
G = num2CG(scipy.random.randint(2**(n**2)),n)
return G
def SM_fixed(Gstar,G, iter=5):
compat = []
for j in range(0,iter):
if Gstar == ecj.undersample(G,j):
compat.append(j)
ret... | return False
def randSCC(n): | random_line_split |
comparison.py | import ecj
import scipy
import numpy
import operator
import networkx as nx
#from progressbar import ProgressBar, Percentage
numpy.random.RandomState()
import bfutils as bfu
import numpy as np
import gmpy as gmp
def num2CG(num,n):
"""num2CG - converts a number whose binary representaion encodes edge
presence/a... | (SCC):
g = graph2nx(SCC)
return ecj.listgcd(map(lambda x: len(x)-1, nx.simple_cycles(g)))
def compatibleAtU(uGstar):
compat = []
n = len(uGstar)
numG = 2**(n**2)
#pbar = Percentage()
for i in range(1,numG):
G = num2CG(i,n)
#pbar.update(i+1)
if len(ecj.scc(G)) > 1: co... | gcd4scc | identifier_name |
comparison.py | import ecj
import scipy
import numpy
import operator
import networkx as nx
#from progressbar import ProgressBar, Percentage
numpy.random.RandomState()
import bfutils as bfu
import numpy as np
import gmpy as gmp
def num2CG(num,n):
"""num2CG - converts a number whose binary representaion encodes edge
presence/a... |
return True
def graph2nx(G):
g = nx.DiGraph()
for v in G:
g.add_edges_from([(v,x) for x in G[v] if (0,1) in G[v][x]])
return g
def nx2graph(G):
g = {str(n+1):{} for n in G}
for n in G:
g['%i' % (n+1)] = {'%i' % (x+1):set([(0,1)]) for x in G[n]}
return g
def gcd4scc(SCC):
... | return False | conditional_block |
comparison.py | import ecj
import scipy
import numpy
import operator
import networkx as nx
#from progressbar import ProgressBar, Percentage
numpy.random.RandomState()
import bfutils as bfu
import numpy as np
import gmpy as gmp
def num2CG(num,n):
"""num2CG - converts a number whose binary representaion encodes edge
presence/a... |
def graph2nx(G):
g = nx.DiGraph()
for v in G:
g.add_edges_from([(v,x) for x in G[v] if (0,1) in G[v][x]])
return g
def nx2graph(G):
g = {str(n+1):{} for n in G}
for n in G:
g['%i' % (n+1)] = {'%i' % (x+1):set([(0,1)]) for x in G[n]}
return g
def gcd4scc(SCC):
g = graph2nx(... | n = len(G)
for v in G:
if sum([(0,1) in G[v][w] for w in G[v]]) < n: return False
if sum([(2,0) in G[v][w] for w in G[v]]) < n-1: return False
return True | identifier_body |
exceptions.py | # Copyright (c) 2014 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | pass
class DslSyntaxError(Exception):
pass
class PropertyAccessError(Exception):
pass
class AmbiguousPropertyNameError(PropertyAccessError):
def __init__(self, name):
super(AmbiguousPropertyNameError, self).__init__(
'Found more that one property "%s"' % name)
class NoWriteAc... | random_line_split | |
exceptions.py | # Copyright (c) 2014 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | (self, name):
super(AmbiguousMethodName, self).__init__(
'Found more that one method "%s"' % name)
class DslContractSyntaxError(Exception):
pass
class ContractViolationException(Exception):
pass
class ValueIsMissingError(Exception):
pass
class DslSyntaxError(Exception):
pass
... | __init__ | identifier_name |
exceptions.py | # Copyright (c) 2014 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
class BreakException(InternalFlowException):
pass
class ContinueException(InternalFlowException):
pass
class DslInvalidOperationError(Exception):
pass
class NoMethodFound(Exception):
def __init__(self, name):
super(NoMethodFound, self).__init__('Method "%s" is not found' % name)
class... | def __init__(self, value):
self._value = value
@property
def value(self):
return self._value | identifier_body |
serialize.rs | extern crate serde;
use super::{Split, SplitHandle};
use rect::Rect;
gen_handle!("SplitHandle", SplitHandle, SplitHandleVisitor);
// Serialization
impl serde::ser::Serialize for Split {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::ser::Serializer {
serializer.seriali... | <'a> {
value: &'a Split
}
impl<'a> serde::ser::MapVisitor for SplitMapVisitor<'a> {
fn visit<S>(&mut self, serializer: &mut S) -> Result<Option<()>, S::Error> where S: serde::Serializer {
try!(serializer.serialize_struct_elt("children", &self.value.children));
try!(serializer.serialize_struct_e... | SplitMapVisitor | identifier_name |
serialize.rs | extern crate serde;
use super::{Split, SplitHandle};
use rect::Rect;
gen_handle!("SplitHandle", SplitHandle, SplitHandleVisitor);
// Serialization
impl serde::ser::Serialize for Split {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::ser::Serializer |
}
struct SplitMapVisitor<'a> {
value: &'a Split
}
impl<'a> serde::ser::MapVisitor for SplitMapVisitor<'a> {
fn visit<S>(&mut self, serializer: &mut S) -> Result<Option<()>, S::Error> where S: serde::Serializer {
try!(serializer.serialize_struct_elt("children", &self.value.children));
try!(ser... | {
serializer.serialize_struct("Split", SplitMapVisitor { value: self }).map(|_| ())
} | identifier_body |
serialize.rs | extern crate serde;
use super::{Split, SplitHandle}; | use rect::Rect;
gen_handle!("SplitHandle", SplitHandle, SplitHandleVisitor);
// Serialization
impl serde::ser::Serialize for Split {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::ser::Serializer {
serializer.serialize_struct("Split", SplitMapVisitor { value: self }).m... | random_line_split | |
ImageCellRenderer.spec.ts | /*
* Copyright 2017 TWO SIGMA OPEN SOURCE, LLC
*
* 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 appl... | expect(cellRenderer).to.have.property('drawImage');
expect(cellRenderer.drawImage).to.be.a('Function');
});
it('should implement resizeCell method', () => {
expect(cellRenderer).to.have.property('resizeCell');
expect(cellRenderer.resizeCell).to.be.a('Function');
});
}); | it('should be an instance of CellRenderer', () => {
expect(cellRenderer).to.be.an.instanceof(CellRenderer);
});
it('should implement drawImage method', () => { | random_line_split |
fixtures.py | from datetime import datetime
from pymongo import MongoClient
import pytest
from mongoframes import *
__all__ = [
# Frames
'Dragon',
'Inventory',
'Lair',
'ComplexDragon',
'MonitoredDragon',
# Fixtures
'mongo_client',
'example_dataset_one',
'example_dataset_many'
]
# Cla... |
class ComplexDragon(Dragon):
_fields = Dragon._fields | {
'dob',
'lair',
'traits',
'misc'
}
_default_projection = {
'lair': {
'$ref': Lair,
'inventory': {'$sub': Inventory}
}
}
class MonitoredDragon(Dragon):
_f... | 'inventory'
} | random_line_split |
fixtures.py | from datetime import datetime
from pymongo import MongoClient
import pytest
from mongoframes import *
__all__ = [
# Frames
'Dragon',
'Inventory',
'Lair',
'ComplexDragon',
'MonitoredDragon',
# Fixtures
'mongo_client',
'example_dataset_one',
'example_dataset_many'
]
# Cla... |
# Fred
castle = Lair(
name='Castle',
inventory=Inventory(
gold=2000,
skulls=200
)
)
castle.insert()
fred = ComplexDragon(
name='Fred',
dob=datetime(1980, 7, 12),
breed='Fire-drake',
lair=castle,
traits=... | """Create an example set of data that can be used in testing"""
# Burt
cave = Lair(
name='Cave',
inventory=Inventory(
gold=1000,
skulls=100
)
)
cave.insert()
burt = ComplexDragon(
name='Burt',
dob=datetime(1979, 6, 11),
... | identifier_body |
fixtures.py | from datetime import datetime
from pymongo import MongoClient
import pytest
from mongoframes import *
__all__ = [
# Frames
'Dragon',
'Inventory',
'Lair',
'ComplexDragon',
'MonitoredDragon',
# Fixtures
'mongo_client',
'example_dataset_one',
'example_dataset_many'
]
# Cla... | (request):
"""Create an example set of data that can be used in testing"""
# Burt
cave = Lair(
name='Cave',
inventory=Inventory(
gold=1000,
skulls=100
)
)
cave.insert()
burt = ComplexDragon(
name='Burt',
dob=datetime(1979,... | example_dataset_many | identifier_name |
iddocs.js | Iddocs = new Meteor.Collection('iddocs');
Iddocs.helpers({
update(modifier) {
modifier.updatedAt = new Date();
return Meteor.call('updateDoc', this._id, modifier);
},
approve() {
return this.update({ status: 'APPROVED' });
},
reject(reason) {
return this.update({ status: 'REJECTED', statusRea... | case 'image/bmp':
case 'image/gif':
case 'image/pjpeg':
case 'image/tiff':
case 'image/x-tiff':
return 'IMAGE';
case 'application/pdf':
case 'application/msword':
case 'application/rtf':
case 'application/x-rtf':
case 'text/richtext':
return '... | case 'image/png': | random_line_split |
iddocs.js |
Iddocs = new Meteor.Collection('iddocs');
Iddocs.helpers({
update(modifier) {
modifier.updatedAt = new Date();
return Meteor.call('updateDoc', this._id, modifier);
},
approve() {
return this.update({ status: 'APPROVED' });
},
reject(reason) {
return this.update({ status: 'REJECTED', statusRe... | ,
filetype() {
switch (this.mimetype) {
case 'image/jpeg':
case 'image/png':
case 'image/bmp':
case 'image/gif':
case 'image/pjpeg':
case 'image/tiff':
case 'image/x-tiff':
return 'IMAGE';
case 'application/pdf':
case 'application/msword':
case ... | {
return Docs.findOne(this.fileId);
} | identifier_body |
iddocs.js |
Iddocs = new Meteor.Collection('iddocs');
Iddocs.helpers({
update(modifier) {
modifier.updatedAt = new Date();
return Meteor.call('updateDoc', this._id, modifier);
},
approve() {
return this.update({ status: 'APPROVED' });
},
reject(reason) {
return this.update({ status: 'REJECTED', statusRe... | () {
return Meteor.users.findOne({ _id: this.userId });
},
file() {
return Docs.findOne(this.fileId);
},
filetype() {
switch (this.mimetype) {
case 'image/jpeg':
case 'image/png':
case 'image/bmp':
case 'image/gif':
case 'image/pjpeg':
case 'image/tiff':
cas... | owner | identifier_name |
subsetOf.ts | import { Collection, CollectionConstructor } from '../collection';
import { define, tools } from '../object-plus';
import { AggregatedType, ChainableAttributeSpec, Record, type } from '../record';
import { ItemsBehavior, transactionApi } from '../transactions';
import { CollectionReference, parseReference } from './com... |
}
function toArray( elements ){
return elements ? (
Array.isArray( elements ) ? elements : [ elements ]
) : [];
} | {
const isRoot = transactionApi.begin( collection );
// Save elements to resolve in future...
collection.refs = elements.slice();
transactionApi.markAsDirty( collection, options );
// And throw the 'changes' event.
isRoot && transactionApi.commit( collection );... | conditional_block |
subsetOf.ts | import { Collection, CollectionConstructor } from '../collection';
import { define, tools } from '../object-plus'; |
type RecordsIds = ( string | number )[];
export function subsetOf<X extends CollectionConstructor<R>, R extends Record>( this : void, masterCollection : CollectionReference, T? : X ) : ChainableAttributeSpec<X>{
const CollectionClass = T || Collection,
// Lazily define class for subset collection, if it'... | import { AggregatedType, ChainableAttributeSpec, Record, type } from '../record';
import { ItemsBehavior, transactionApi } from '../transactions';
import { CollectionReference, parseReference } from './commons'; | random_line_split |
subsetOf.ts | import { Collection, CollectionConstructor } from '../collection';
import { define, tools } from '../object-plus';
import { AggregatedType, ChainableAttributeSpec, Record, type } from '../record';
import { ItemsBehavior, transactionApi } from '../transactions';
import { CollectionReference, parseReference } from './com... | (){ return this.refs || this.models; }
constructor( recordsOrIds?, options? ){
super( [], options, subsetOfBehavior );
this.refs = toArray( recordsOrIds );
}
// Remove should work fine as it already accepts ids. Add won't...
add( a_elements, options = {} ){
... | __inner_state__ | identifier_name |
subsetOf.ts | import { Collection, CollectionConstructor } from '../collection';
import { define, tools } from '../object-plus';
import { AggregatedType, ChainableAttributeSpec, Record, type } from '../record';
import { ItemsBehavior, transactionApi } from '../transactions';
import { CollectionReference, parseReference } from './com... |
toggleAll() : Record[] {
return this.length ? this.reset() : this.addAll();
}
}
// Clean up all custom item events to prevent memory leaks.
SubsetOfCollection.prototype._itemEvents = void 0;
return SubsetOfCollection;
}
function resolveRefs( master, elements ){
const... | {
if( this.resolvedWith ){
this.set( this.resolvedWith.models );
return this.models;
}
throw new Error( "Cannot add elemens because the subset collection is not resolved yet." );
} | identifier_body |
asl.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for Apple System Log file parser."""
import unittest
from plaso.formatters import asl as _ # pylint: disable=unused-import
from plaso.lib import timelib
from plaso.parsers import asl
from tests.parsers import test_lib
class AslParserTest(test_lib.ParserTestCase):... | (self):
"""Sets up the needed objects used throughout the test."""
self._parser = asl.AslParser()
def testParse(self):
"""Tests the Parse function."""
test_file = self._GetTestFilePath([u'applesystemlog.asl'])
event_queue_consumer = self._ParseFile(self._parser, test_file)
event_objects = sel... | setUp | identifier_name |
asl.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for Apple System Log file parser."""
import unittest
from plaso.formatters import asl as _ # pylint: disable=unused-import
from plaso.lib import timelib
from plaso.parsers import asl
from tests.parsers import test_lib
class AslParserTest(test_lib.ParserTestCase):... | self.assertEqual(event_object.group_id, 205)
self.assertEqual(event_object.read_uid, 205)
self.assertEqual(event_object.read_gid, 0xffffffff)
self.assertEqual(event_object.level, 4)
# Note that "compatiblity" is spelt incorrectly in the actual message being
# tested here.
expected_message =... | """Tests the Parse function."""
test_file = self._GetTestFilePath([u'applesystemlog.asl'])
event_queue_consumer = self._ParseFile(self._parser, test_file)
event_objects = self._GetEventObjectsFromQueue(event_queue_consumer)
self.assertEqual(len(event_objects), 2)
event_object = event_objects[0]
... | identifier_body |
asl.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for Apple System Log file parser."""
import unittest
from plaso.formatters import asl as _ # pylint: disable=unused-import
from plaso.lib import timelib
from plaso.parsers import asl
from tests.parsers import test_lib
class AslParserTest(test_lib.ParserTestCase):... | unittest.main() | conditional_block | |
asl.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for Apple System Log file parser."""
import unittest
from plaso.formatters import asl as _ # pylint: disable=unused-import
from plaso.lib import timelib
from plaso.parsers import asl
from tests.parsers import test_lib
class AslParserTest(test_lib.ParserTestCase):... | u'2013-11-25 09:45:35.705481')
self.assertEqual(event_object.timestamp, expected_timestamp)
self.assertEqual(event_object.record_position, 442)
self.assertEqual(event_object.message_id, 101406)
self.assertEqual(event_object.computer_name, u'DarkTemplar-2.local')
self.assertEqual(event_objec... |
expected_timestamp = timelib.Timestamp.CopyFromString( | random_line_split |
util.rs | use super::engine::{Action, Round};
use super::state::GameState;
use crate::cards::BasicCard;
pub fn format_hand(hand: &[BasicCard], gs: &GameState) -> String {
let mut cards: Vec<_> = hand.iter().collect();
cards.sort_by(|a, b| gs.display_order(a, b));
let sc: Vec<_> = cards.iter().map(|x| format!("{}", ... |
pub fn format_round(round: &Round) -> String {
format!(
"{}{}\n",
&format_state(round.get_state()),
round.get_phase().format(round.get_state())
)
}
pub fn format_action(action: &Action) -> String {
format!("Player {} plays {}.", action.player + 1, action.card)
}
| {
format!(
"Player 1: Score {}, Hand: {}\nPlayer 2: Score {}, Hand: {}\nTrump: {}\n",
gs.score[0],
&format_hand(&gs.hands[0], gs),
gs.score[1],
&format_hand(&gs.hands[1], gs),
gs.trump
)
} | identifier_body |
util.rs | use super::engine::{Action, Round};
use super::state::GameState;
use crate::cards::BasicCard;
pub fn format_hand(hand: &[BasicCard], gs: &GameState) -> String {
let mut cards: Vec<_> = hand.iter().collect();
cards.sort_by(|a, b| gs.display_order(a, b));
let sc: Vec<_> = cards.iter().map(|x| format!("{}", ... | gs.score[0],
&format_hand(&gs.hands[0], gs),
gs.score[1],
&format_hand(&gs.hands[1], gs),
gs.trump
)
}
pub fn format_round(round: &Round) -> String {
format!(
"{}{}\n",
&format_state(round.get_state()),
round.get_phase().format(round.get_state())
... | }
pub fn format_state(gs: &GameState) -> String {
format!(
"Player 1: Score {}, Hand: {}\nPlayer 2: Score {}, Hand: {}\nTrump: {}\n", | random_line_split |
util.rs | use super::engine::{Action, Round};
use super::state::GameState;
use crate::cards::BasicCard;
pub fn format_hand(hand: &[BasicCard], gs: &GameState) -> String {
let mut cards: Vec<_> = hand.iter().collect();
cards.sort_by(|a, b| gs.display_order(a, b));
let sc: Vec<_> = cards.iter().map(|x| format!("{}", ... | (action: &Action) -> String {
format!("Player {} plays {}.", action.player + 1, action.card)
}
| format_action | identifier_name |
setup.py | #
# setup.py
#
# Copyright (c) 2017 Junpei Kawamoto
#
# This file is part of rgmining-tripadvisor-dataset.
#
# rgmining-tripadvisor-dataset 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 t... |
setup(
name="rgmining-tripadvisor-dataset",
use_scm_version=True,
author="Junpei Kawamoto",
author_email="kawamoto.junpei@gmail.com",
description="Trip Advisor dataset for Review Graph Mining Project",
long_description=read("README.rst"),
url="https://github.com/rgmining/tripadvisor",
... | """Read a package list from a given file path.
Args:
filepath: file path of the package list.
Returns:
a list of package names.
"""
with open(filepath) as fp:
return [pkg_name.strip() for pkg_name in fp.readlines()] | identifier_body |
setup.py | #
# setup.py
#
# Copyright (c) 2017 Junpei Kawamoto
#
# This file is part of rgmining-tripadvisor-dataset.
#
# rgmining-tripadvisor-dataset 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 t... | (self):
"""Before executing run command, download data files.
"""
for f in self.data_files:
if not isinstance(f, tuple):
continue
for i, u in enumerate(f[1]):
base = path.basename(u)
f[1][i] = path.join(sys.prefix, f[0], bas... | run | identifier_name |
setup.py | #
# setup.py
#
# Copyright (c) 2017 Junpei Kawamoto
#
# This file is part of rgmining-tripadvisor-dataset.
#
# rgmining-tripadvisor-dataset 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 t... | return [pkg_name.strip() for pkg_name in fp.readlines()]
setup(
name="rgmining-tripadvisor-dataset",
use_scm_version=True,
author="Junpei Kawamoto",
author_email="kawamoto.junpei@gmail.com",
description="Trip Advisor dataset for Review Graph Mining Project",
long_description=read("READ... | """
with open(filepath) as fp: | random_line_split |
setup.py | #
# setup.py
#
# Copyright (c) 2017 Junpei Kawamoto
#
# This file is part of rgmining-tripadvisor-dataset.
#
# rgmining-tripadvisor-dataset 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 t... |
return distutils.command.install_data.install_data.run(self)
def load_requires_from_file(filepath):
"""Read a package list from a given file path.
Args:
filepath: file path of the package list.
Returns:
a list of package names.
"""
with open(filepath) as fp:
return [... | f[1][i] = urllib.urlretrieve(u, base)[0] | conditional_block |
11.13.2-11-s.js | // Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this n... | () {
"use strict";
try {
eval("_11_13_2_11 |= 1;");
return false;
} catch (e) {
return e instanceof ReferenceError;
}
}
runTestCase(testcase);
| testcase | identifier_name |
11.13.2-11-s.js | // Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this n... | runTestCase(testcase); | random_line_split | |
11.13.2-11-s.js | // Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this n... |
runTestCase(testcase);
| {
"use strict";
try {
eval("_11_13_2_11 |= 1;");
return false;
} catch (e) {
return e instanceof ReferenceError;
}
} | identifier_body |
fetch.py | import re
from time import sleep
from .settings import settings
def | (raw_text):
regex = re.compile(r"@([\w\.]+)")
regex.findall(raw_text)
return regex.findall(raw_text)
def get_parsed_hashtags(raw_text):
regex = re.compile(r"#(\w+)")
regex.findall(raw_text)
return regex.findall(raw_text)
def fetch_mentions(raw_test, dict_obj):
if not settings.fetch_menti... | get_parsed_mentions | identifier_name |
fetch.py | import re
from time import sleep
from .settings import settings
def get_parsed_mentions(raw_text):
regex = re.compile(r"@([\w\.]+)")
regex.findall(raw_text)
return regex.findall(raw_text)
def get_parsed_hashtags(raw_text):
regex = re.compile(r"#(\w+)")
regex.findall(raw_text)
return regex.f... |
like_info_btn = browser.find_one(".EDfFK ._0mzm-.sqdOP")
like_info_btn.click()
likers = {}
liker_elems_css_selector = ".Igw0E ._7UhW9.xLCgt a"
likers_elems = list(browser.find(liker_elems_css_selector))
last_liker = None
while likers_elems:
for ele in likers_elems:
like... | return | conditional_block |
fetch.py | import re
from time import sleep
from .settings import settings
def get_parsed_mentions(raw_text):
regex = re.compile(r"@([\w\.]+)")
regex.findall(raw_text)
return regex.findall(raw_text)
def get_parsed_hashtags(raw_text):
regex = re.compile(r"#(\w+)")
regex.findall(raw_text)
return regex.f... | else:
break
dict_post["img_urls"] = list(img_urls)
def fetch_likes_plays(browser, dict_post):
if not settings.fetch_likes_plays:
return
likes = None
el_likes = browser.find_one(".Nm9Fw > * > span")
el_see_likes = browser.find_one(".vcOH2")
if el_see_likes is not N... | sleep(0.3) | random_line_split |
fetch.py | import re
from time import sleep
from .settings import settings
def get_parsed_mentions(raw_text):
regex = re.compile(r"@([\w\.]+)")
regex.findall(raw_text)
return regex.findall(raw_text)
def get_parsed_hashtags(raw_text):
regex = re.compile(r"#(\w+)")
regex.findall(raw_text)
return regex.f... | )
def fetch_likers(browser, dict_post):
if not settings.fetch_likers:
return
like_info_btn = browser.find_one(".EDfFK ._0mzm-.sqdOP")
like_info_btn.click()
likers = {}
liker_elems_css_selector = ".Igw0E ._7UhW9.xLCgt a"
likers_elems = list(browser.find(liker_elems_css_selector))
... | if not settings.fetch_likes_plays:
return
likes = None
el_likes = browser.find_one(".Nm9Fw > * > span")
el_see_likes = browser.find_one(".vcOH2")
if el_see_likes is not None:
el_plays = browser.find_one(".vcOH2 > span")
dict_post["views"] = int(el_plays.text.replace(",", "").re... | identifier_body |
test_node.py | import unittest
from golem.network.p2p.node import Node
def is_ip_address(address):
|
class TestNode(unittest.TestCase):
def test_str(self):
n = Node(node_name="Blabla", key="ABC")
self.assertNotIn("at", str(n))
self.assertNotIn("at", "{}".format(n))
self.assertIn("Blabla", str(n))
self.assertIn("Blabla", "{}".format(n))
self.assertIn("ABC", str(n))... | """
Check if @address is correct IP address
:param address: Address to be checked
:return: True if is correct, false otherwise
"""
from ipaddress import ip_address, AddressValueError
try:
# will raise error in case of incorrect address
ip_address(unicode(address))
return ... | identifier_body |
test_node.py | import unittest
from golem.network.p2p.node import Node
def is_ip_address(address):
"""
Check if @address is correct IP address
:param address: Address to be checked
:return: True if is correct, false otherwise
"""
from ipaddress import ip_address, AddressValueError
try:
# will rai... | assert is_ip_address(address) | conditional_block | |
test_node.py | import unittest
from golem.network.p2p.node import Node
def | (address):
"""
Check if @address is correct IP address
:param address: Address to be checked
:return: True if is correct, false otherwise
"""
from ipaddress import ip_address, AddressValueError
try:
# will raise error in case of incorrect address
ip_address(unicode(address))
... | is_ip_address | identifier_name |
test_node.py | import unittest
from golem.network.p2p.node import Node
def is_ip_address(address):
"""
Check if @address is correct IP address
:param address: Address to be checked
:return: True if is correct, false otherwise
"""
from ipaddress import ip_address, AddressValueError
try:
# will rai... | n = Node(node_name="Blabla", key="ABC")
self.assertNotIn("at", str(n))
self.assertNotIn("at", "{}".format(n))
self.assertIn("Blabla", str(n))
self.assertIn("Blabla", "{}".format(n))
self.assertIn("ABC", str(n))
self.assertIn("ABC", "{}".format(n))
def test_co... | return False
class TestNode(unittest.TestCase):
def test_str(self): | random_line_split |
app.py | # -*- coding: utf-8 -*-
# (c) 2015 Andreas Motl, Elmyra UG <andreas.motl@elmyra.de>
from kotori.version import __VERSION__
from pyramid.config import Configurator
def | (global_config, **settings):
"""This function returns a Pyramid WSGI application."""
settings['SOFTWARE_VERSION'] = __VERSION__
config = Configurator(settings=settings)
# Addons
config.include('pyramid_jinja2')
# http://docs.pylonsproject.org/projects/pyramid-jinja2/en/latest/#adding-or-overr... | main | identifier_name |
app.py | # -*- coding: utf-8 -*-
# (c) 2015 Andreas Motl, Elmyra UG <andreas.motl@elmyra.de>
from kotori.version import __VERSION__
from pyramid.config import Configurator
def main(global_config, **settings):
| """This function returns a Pyramid WSGI application."""
settings['SOFTWARE_VERSION'] = __VERSION__
config = Configurator(settings=settings)
# Addons
config.include('pyramid_jinja2')
# http://docs.pylonsproject.org/projects/pyramid-jinja2/en/latest/#adding-or-overriding-a-renderer
config.add_j... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.